[Commits] Rev 3793: MDEV-4702 - Reduce usage of LOCK_open in lp:~maria-captains/maria/10.0

Sergey Vojtovich svoj at mariadb.org
Wed Aug 14 11:49:06 EEST 2013


At lp:~maria-captains/maria/10.0

------------------------------------------------------------
revno: 3793
revision-id: svoj at mariadb.org-20130814084850-b6gi2ipymsn4n2me
parent: sergii at pisem.net-20130813140210-0wt1bg53gu8cj37i
committer: Sergey Vojtovich <svoj at mariadb.org>
branch nick: 10.0-mdev4702
timestamp: Wed 2013-08-14 12:48:50 +0400
message:
  MDEV-4702 - Reduce usage of LOCK_open
  
  Following variables do not require LOCK_open protection anymore:
  - table_def_cache (renamed to tdc_hash) is protected by rw-lock
    LOCK_tdc_hash;
  - table_def_shutdown_in_progress doesn't need LOCK_open protection;
  - last_table_id use atomics;
  - TABLE_SHARE::ref_count (renamed to TABLE_SHARE::tdc.ref_count)
    is protected by TABLE_SHARE::tdc.LOCK_table_share;
  - TABLE_SHARE::next, ::prev (renamed to tdc.next and tdc.prev),
    oldest_unused_share, end_of_unused_share are protected by
    LOCK_unused_shares;
  - TABLE_SHARE::m_flush_tickets (renamed to tdc.m_flush_tickets)
    is protected by TABLE_SHARE::tdc.LOCK_table_share;
  - refresh_version (renamed to tdc_version) use atomics.
=== modified file 'libmysqld/CMakeLists.txt'
--- a/libmysqld/CMakeLists.txt	2013-07-21 14:39:19 +0000
+++ b/libmysqld/CMakeLists.txt	2013-08-14 08:48:50 +0000
@@ -102,6 +102,7 @@ SET(SQL_EMBEDDED_SOURCES emb_qcache.cc l
            ../sql/my_apc.cc ../sql/my_apc.h
 	   ../sql/rpl_gtid.cc
            ../sql/compat56.cc
+           ../sql/table_cache.cc
            ${GEN_SOURCES}
            ${MYSYS_LIBWRAP_SOURCE}
 )

=== modified file 'mysql-test/r/mysqld--help.result'
--- a/mysql-test/r/mysqld--help.result	2013-08-13 11:35:36 +0000
+++ b/mysql-test/r/mysqld--help.result	2013-08-14 08:48:50 +0000
@@ -927,6 +927,9 @@
  The number of cached table definitions
  --table-open-cache=# 
  The number of cached open tables
+ --table-open-cache-instances=# 
+ MySQL 5.6 compatible option. Not used or needed in
+ MariaDB
  --tc-heuristic-recover=name 
  Decision to use in heuristic recover process. Possible
  values are COMMIT or ROLLBACK.
@@ -1258,6 +1261,7 @@ sysdate-is-now FALSE
 table-cache 400
 table-definition-cache 400
 table-open-cache 400
+table-open-cache-instances 1
 tc-heuristic-recover COMMIT
 thread-cache-size 0
 thread-pool-idle-timeout 60

=== modified file 'mysql-test/suite/perfschema/r/dml_setup_instruments.result'
--- a/mysql-test/suite/perfschema/r/dml_setup_instruments.result	2013-07-21 14:39:19 +0000
+++ b/mysql-test/suite/perfschema/r/dml_setup_instruments.result	2013-08-14 08:48:50 +0000
@@ -20,15 +20,15 @@ where name like 'Wait/Synch/Rwlock/sql/%
 order by name limit 10;
 NAME	ENABLED	TIMED
 wait/synch/rwlock/sql/LOCK_dboptions	YES	YES
+wait/synch/rwlock/sql/LOCK_flush	YES	YES
 wait/synch/rwlock/sql/LOCK_grant	YES	YES
 wait/synch/rwlock/sql/LOCK_system_variables_hash	YES	YES
 wait/synch/rwlock/sql/LOCK_sys_init_connect	YES	YES
 wait/synch/rwlock/sql/LOCK_sys_init_slave	YES	YES
+wait/synch/rwlock/sql/LOCK_tdc	YES	YES
 wait/synch/rwlock/sql/LOGGER::LOCK_logger	YES	YES
 wait/synch/rwlock/sql/MDL_context::LOCK_waiting_for	YES	YES
 wait/synch/rwlock/sql/MDL_lock::rwlock	YES	YES
-wait/synch/rwlock/sql/Query_cache_query::lock	YES	YES
-wait/synch/rwlock/sql/THR_LOCK_servers	YES	YES
 select * from performance_schema.setup_instruments
 where name like 'Wait/Synch/Cond/sql/%'
   and name not in (

=== added file 'mysql-test/suite/sys_vars/r/table_open_cache_instances_basic.result'
--- a/mysql-test/suite/sys_vars/r/table_open_cache_instances_basic.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/sys_vars/r/table_open_cache_instances_basic.result	2013-08-14 08:48:50 +0000
@@ -0,0 +1,3 @@
+select @@table_open_cache_instances;
+@@table_open_cache_instances
+1

=== added file 'mysql-test/suite/sys_vars/t/table_open_cache_instances_basic.test'
--- a/mysql-test/suite/sys_vars/t/table_open_cache_instances_basic.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/sys_vars/t/table_open_cache_instances_basic.test	2013-08-14 08:48:50 +0000
@@ -0,0 +1 @@
+select @@table_open_cache_instances;

=== modified file 'sql/CMakeLists.txt'
--- a/sql/CMakeLists.txt	2013-07-21 14:39:19 +0000
+++ b/sql/CMakeLists.txt	2013-08-14 08:48:50 +0000
@@ -91,6 +91,7 @@ SET (SQL_SOURCE
 			   ../sql-common/mysql_async.c
                my_apc.cc my_apc.h
                rpl_gtid.cc
+               table_cache.cc
                ${GEN_SOURCES}
                ${MYSYS_LIBWRAP_SOURCE}
 			   )

=== modified file 'sql/ha_ndbcluster_binlog.cc'
--- a/sql/ha_ndbcluster_binlog.cc	2013-07-21 14:39:19 +0000
+++ b/sql/ha_ndbcluster_binlog.cc	2013-08-14 08:48:50 +0000
@@ -376,9 +376,7 @@ ndbcluster_binlog_open_table(THD *thd, N
     free_table_share(table_share);
     DBUG_RETURN(error);
   }
-  mysql_mutex_lock(&LOCK_open);
-  assign_new_table_id(table_share);
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_assign_new_table_id(table_share);
 
   if (!reopen)
   {

=== modified file 'sql/handler.cc'
--- a/sql/handler.cc	2013-08-12 18:56:35 +0000
+++ b/sql/handler.cc	2013-08-14 08:48:50 +0000
@@ -4718,7 +4718,7 @@ static my_bool discover_handlerton(THD *
     {
       if (error)
       {
-        DBUG_ASSERT(share->error); // get_cached_table_share needs that
+        DBUG_ASSERT(share->error); // tdc_lock_share needs that
         /*
           report an error, unless it is "generic" and a more
           specific one was already reported
@@ -4856,29 +4856,27 @@ bool ha_table_exists(THD *thd, const cha
 
     Table_exists_error_handler no_such_table_handler;
     thd->push_internal_handler(&no_such_table_handler);
-    TABLE_SHARE *share= get_table_share(thd, db, table_name, flags);
+    TABLE_SHARE *share= tdc_acquire_share(thd, db, table_name, flags);
     thd->pop_internal_handler();
 
     if (hton && share)
     {
       *hton= share->db_type();
-      mysql_mutex_lock(&LOCK_open);
-      release_table_share(share);
-      mysql_mutex_unlock(&LOCK_open);
+      tdc_release_share(share);
     }
 
     // the table doesn't exist if we've caught ER_NO_SUCH_TABLE and nothing else
     DBUG_RETURN(!no_such_table_handler.safely_trapped_errors());
   }
 
-  mysql_mutex_lock(&LOCK_open);
-  TABLE_SHARE *share= get_cached_table_share(db, table_name);
-  if (hton && share)
-    *hton= share->db_type();
-  mysql_mutex_unlock(&LOCK_open);
-
+  TABLE_SHARE *share= tdc_lock_share(db, table_name);
   if (share)
+  {
+    if (hton)
+      *hton= share->db_type();
+    tdc_unlock_share(share);
     DBUG_RETURN(TRUE);
+  }
 
   char path[FN_REFLEN + 1];
   size_t path_len = build_table_filename(path, sizeof(path) - 1,

=== modified file 'sql/mysqld.cc'
--- a/sql/mysqld.cc	2013-08-13 11:35:36 +0000
+++ b/sql/mysqld.cc	2013-08-14 08:48:50 +0000
@@ -40,9 +40,7 @@
 #include "hostname.h"     // hostname_cache_free, hostname_cache_init
 #include "sql_acl.h"      // acl_free, grant_free, acl_init,
                           // grant_init
-#include "sql_base.h"     // table_def_free, table_def_init,
-                          // cached_open_tables,
-                          // cached_table_definitions
+#include "sql_base.h"
 #include "sql_test.h"     // mysql_print_status
 #include "item_create.h"  // item_create_cleanup, item_create_init
 #include "sql_servers.h"  // servers_free, servers_init
@@ -473,7 +471,6 @@ int32 thread_count;
 int32 thread_running;
 ulong thread_created;
 ulong back_log, connect_timeout, concurrency, server_id;
-ulong table_cache_size, table_def_size;
 ulong what_to_log;
 ulong slow_launch_time, slave_open_temp_tables;
 ulong open_files_limit, max_binlog_size;
@@ -489,7 +486,6 @@ ulonglong binlog_stmt_cache_size=0;
 ulonglong  max_binlog_stmt_cache_size=0;
 ulonglong query_cache_size=0;
 ulong query_cache_limit=0;
-ulong refresh_version;  /* Increments on each reload */
 ulong executed_events=0;
 query_id_t global_query_id;
 my_atomic_rwlock_t global_query_id_lock;
@@ -843,7 +839,7 @@ PSI_mutex_key key_BINLOG_LOCK_index, key
   key_LOCK_manager,
   key_LOCK_prepared_stmt_count,
   key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status,
-  key_LOCK_system_variables_hash, key_LOCK_table_share, key_LOCK_thd_data,
+  key_LOCK_system_variables_hash, key_LOCK_thd_data,
   key_LOCK_user_conn, key_LOCK_uuid_short_generator, key_LOG_LOCK_log,
   key_master_info_data_lock, key_master_info_run_lock,
   key_master_info_sleep_lock,
@@ -902,7 +898,6 @@ static PSI_mutex_info all_server_mutexes
   { &key_LOCK_server_started, "LOCK_server_started", PSI_FLAG_GLOBAL},
   { &key_LOCK_status, "LOCK_status", PSI_FLAG_GLOBAL},
   { &key_LOCK_system_variables_hash, "LOCK_system_variables_hash", PSI_FLAG_GLOBAL},
-  { &key_LOCK_table_share, "LOCK_table_share", PSI_FLAG_GLOBAL},
   { &key_LOCK_stats, "LOCK_stats", PSI_FLAG_GLOBAL},
   { &key_LOCK_global_user_client_stats, "LOCK_global_user_client_stats", PSI_FLAG_GLOBAL},
   { &key_LOCK_global_table_stats, "LOCK_global_table_stats", PSI_FLAG_GLOBAL},
@@ -1963,14 +1958,14 @@ void clean_up(bool print_message)
     udf_free();
 #endif
   }
-  table_def_start_shutdown();
+  tdc_start_shutdown();
   plugin_shutdown();
   ha_end();
   if (tc_log)
     tc_log->close();
   delegates_destroy();
   xid_cache_free();
-  table_def_free();
+  tdc_deinit();
   mdl_destroy();
   key_caches.delete_elements((void (*)(const char*, uchar*)) free_key_cache);
   wt_end();
@@ -4012,7 +4007,7 @@ static int init_common_variables()
 
     /* MyISAM requires two file handles per table. */
     wanted_files= (10 + max_connections + extra_max_connections +
-                   table_cache_size*2);
+                   tc_size * 2);
     /*
       We are trying to allocate no less than max_connections*5 file
       handles (i.e. we are trying to set the limit so that they will
@@ -4039,20 +4034,19 @@ static int init_common_variables()
         max_connections= (ulong) MY_MIN(files-10-TABLE_OPEN_CACHE_MIN*2,
                                      max_connections);
         /*
-          Decrease table_cache_size according to max_connections, but
+          Decrease tc_size according to max_connections, but
           not below TABLE_OPEN_CACHE_MIN.  Outer MY_MIN() ensures that we
-          never increase table_cache_size automatically (that could
+          never increase tc_size automatically (that could
           happen if max_connections is decreased above).
         */
-        table_cache_size= (ulong) MY_MIN(MY_MAX((files-10-max_connections)/2,
-                                          TABLE_OPEN_CACHE_MIN),
-                                      table_cache_size);
+        tc_size= (ulong) MY_MIN(MY_MAX((files - 10 - max_connections) / 2,
+                                       TABLE_OPEN_CACHE_MIN), tc_size);
 	DBUG_PRINT("warning",
 		   ("Changed limits: max_open_files: %u  max_connections: %ld  table_cache: %ld",
-		    files, max_connections, table_cache_size));
+		    files, max_connections, tc_size));
 	if (global_system_variables.log_warnings)
 	  sql_print_warning("Changed limits: max_open_files: %u  max_connections: %ld  table_cache: %ld",
-			files, max_connections, table_cache_size);
+			files, max_connections, tc_size);
       }
       else if (global_system_variables.log_warnings)
 	sql_print_warning("Could not increase number of max_open_files to more than %u (request: %u)", files, wanted_files);
@@ -4477,7 +4471,7 @@ static int init_server_components()
     all things are initialized so that unireg_abort() doesn't fail
   */
   mdl_init();
-  if (table_def_init() | hostname_cache_init())
+  if (tdc_init() | hostname_cache_init())
     unireg_abort(1);
 
   query_cache_set_min_res_unit(query_cache_min_res_unit);
@@ -5054,8 +5048,8 @@ int mysqld_main(int argc, char **argv)
     if (pfs_param.m_enabled  && !opt_help && !opt_bootstrap)
     {
       /* Add sizing hints from the server sizing parameters. */
-      pfs_param.m_hints.m_table_definition_cache= table_def_size;
-      pfs_param.m_hints.m_table_open_cache= table_cache_size;
+      pfs_param.m_hints.m_table_definition_cache= tdc_size;
+      pfs_param.m_hints.m_table_open_cache= tc_size;
       pfs_param.m_hints.m_max_connections= max_connections;
       pfs_param.m_hints.m_open_files_limit= open_files_limit;
       PSI_hook= initialize_performance_schema(&pfs_param);
@@ -5286,12 +5280,6 @@ int mysqld_main(int argc, char **argv)
 
   execute_ddl_log_recovery();
 
-  /*
-    We must have LOCK_open before LOCK_global_system_variables because
-    LOCK_open is held while sql_plugin.c::intern_sys_var_ptr() is called.
-  */
-  mysql_mutex_record_order(&LOCK_open, &LOCK_global_system_variables);
-
   if (Events::init(opt_noacl || opt_bootstrap))
     unireg_abort(1);
 
@@ -6944,7 +6932,7 @@ struct my_option my_long_options[]=
    0, 0, 0,
     GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
   {"table_cache", 0, "Deprecated; use --table-open-cache instead.",
-   &table_cache_size, &table_cache_size, 0, GET_ULONG,
+   &tc_size, &tc_size, 0, GET_ULONG,
    REQUIRED_ARG, TABLE_OPEN_CACHE_DEFAULT, 1, 512*1024L, 0, 1, 0}
 };
 
@@ -7080,7 +7068,7 @@ static int show_open_tables(THD *thd, SH
 {
   var->type= SHOW_LONG;
   var->value= buff;
-  *((long *)buff)= (long)cached_open_tables();
+  *((long *) buff)= (long) tc_records();
   return 0;
 }
 
@@ -7098,10 +7086,20 @@ static int show_table_definitions(THD *t
 {
   var->type= SHOW_LONG;
   var->value= buff;
-  *((long *)buff)= (long)cached_table_definitions();
+  *((long *) buff)= (long) tdc_records();
   return 0;
 }
 
+
+static int show_flush_commands(THD *thd, SHOW_VAR *var, char *buff)
+{
+  var->type= SHOW_LONG;
+  var->value= buff;
+  *((long *) buff)= (long) tdc_refresh_version();
+  return 0;
+}
+
+
 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
 /* Functions relying on CTX */
 static int show_ssl_ctx_sess_accept(THD *thd, SHOW_VAR *var, char *buff)
@@ -7557,7 +7555,7 @@ SHOW_VAR status_vars[]= {
   {"Feature_timezone",         (char*) offsetof(STATUS_VAR, feature_timezone), SHOW_LONG_STATUS},
   {"Feature_trigger",          (char*) offsetof(STATUS_VAR, feature_trigger), SHOW_LONG_STATUS},
   {"Feature_xml",              (char*) offsetof(STATUS_VAR, feature_xml), SHOW_LONG_STATUS},
-  {"Flush_commands",           (char*) &refresh_version,        SHOW_LONG_NOFLUSH},
+  {"Flush_commands",           (char*) &show_flush_commands, SHOW_SIMPLE_FUNC},
   {"Handler_commit",           (char*) offsetof(STATUS_VAR, ha_commit_count), SHOW_LONG_STATUS},
   {"Handler_delete",           (char*) offsetof(STATUS_VAR, ha_delete_count), SHOW_LONG_STATUS},
   {"Handler_discover",         (char*) offsetof(STATUS_VAR, ha_discover_count), SHOW_LONG_STATUS},
@@ -7890,7 +7888,6 @@ static int mysql_init_variables(void)
   log_error_file_ptr= log_error_file;
   protocol_version= PROTOCOL_VERSION;
   what_to_log= ~ (1L << (uint) COM_TIME);
-  refresh_version= 1L;	/* Increments on each reload */
   denied_connections= 0;
   executed_events= 0;
   global_query_id= thread_id= 1L;

=== modified file 'sql/mysqld.h'
--- a/sql/mysqld.h	2013-08-13 11:35:36 +0000
+++ b/sql/mysqld.h	2013-08-14 08:48:50 +0000
@@ -160,7 +160,6 @@ extern ulonglong query_cache_size;
 extern ulong query_cache_limit;
 extern ulong query_cache_min_res_unit;
 extern ulong slow_launch_threads, slow_launch_time;
-extern ulong table_cache_size, table_def_size;
 extern MYSQL_PLUGIN_IMPORT ulong max_connections;
 extern ulong max_connect_errors, connect_timeout;
 extern my_bool slave_allow_batching;
@@ -248,7 +247,7 @@ extern PSI_mutex_key key_BINLOG_LOCK_ind
   key_LOCK_logger, key_LOCK_manager,
   key_LOCK_prepared_stmt_count,
   key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status,
-  key_LOCK_table_share, key_LOCK_thd_data,
+  key_LOCK_thd_data,
   key_LOCK_user_conn, key_LOG_LOCK_log,
   key_master_info_data_lock, key_master_info_run_lock,
   key_master_info_sleep_lock,

=== modified file 'sql/sql_admin.cc'
--- a/sql/sql_admin.cc	2013-08-12 13:46:35 +0000
+++ b/sql/sql_admin.cc	2013-08-14 08:48:50 +0000
@@ -131,15 +131,13 @@ static int prepare_for_repair(THD *thd,
       DBUG_RETURN(0);
     has_mdl_lock= TRUE;
 
-    share= get_table_share_shortlived(thd, table_list, GTS_TABLE);
+    share= tdc_acquire_share_shortlived(thd, table_list, GTS_TABLE);
     if (share == NULL)
       DBUG_RETURN(0);				// Can't open frm file
 
     if (open_table_from_share(thd, share, "", 0, 0, 0, &tmp_table, FALSE))
     {
-      mysql_mutex_lock(&LOCK_open);
-      release_table_share(share);
-      mysql_mutex_unlock(&LOCK_open);
+      tdc_release_share(share);
       DBUG_RETURN(0);                           // Out of memory
     }
     table= &tmp_table;
@@ -262,11 +260,7 @@ static int prepare_for_repair(THD *thd,
 end:
   thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0);
   if (table == &tmp_table)
-  {
-    mysql_mutex_lock(&LOCK_open);
     closefrm(table, 1);				// Free allocated memory
-    mysql_mutex_unlock(&LOCK_open);
-  }
   /* In case of a temporary table there will be no metadata lock. */
   if (error && has_mdl_lock)
     thd->mdl_context.release_transactional_locks();

=== modified file 'sql/sql_base.cc'
--- a/sql/sql_base.cc	2013-08-12 13:46:35 +0000
+++ b/sql/sql_base.cc	2013-08-14 08:48:50 +0000
@@ -163,153 +163,16 @@ Repair_mrg_table_error_handler::handle_c
   @{
 */
 
-/**
-  LOCK_open protects the following variables/objects:
-
-  end_of_unused_share
-  last_table_id
-  oldest_unused_share
-  refresh_version
-  table_cache_count
-  table_def_cache
-  table_def_shutdown_in_progress
-  unused_tables
-  TABLE::next
-  TABLE::prev
-  TABLE_SHARE::free_tables
-  TABLE_SHARE::m_flush_tickets
-  TABLE_SHARE::next
-  TABLE_SHARE::prev
-  TABLE_SHARE::ref_count
-  TABLE_SHARE::used_tables
-*/
-mysql_mutex_t LOCK_open;
-
-#ifdef HAVE_PSI_INTERFACE
-static PSI_mutex_key key_LOCK_open;
-static PSI_mutex_info all_tdc_mutexes[]= {
-  { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL }
-};
-
-/**
-  Initialize performance schema instrumentation points
-  used by the table cache.
-*/
-
-static void init_tdc_psi_keys(void)
-{
-  const char *category= "sql";
-  int count;
-
-  count= array_elements(all_tdc_mutexes);
-  mysql_mutex_register(category, all_tdc_mutexes, count);
-}
-#endif /* HAVE_PSI_INTERFACE */
-
-
-/**
-   Total number of TABLE instances for tables in the table definition cache
-   (both in use by threads and not in use). This value is accessible to user
-   as "Open_tables" status variable.
-*/
-uint  table_cache_count= 0;
-/**
-   List that contains all TABLE instances for tables in the table definition
-   cache that are not in use by any thread. Recently used TABLE instances are
-   appended to the end of the list. Thus the beginning of the list contains
-   tables which have been least recently used.
-*/
-TABLE *unused_tables;
-HASH table_def_cache;
-static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
-static bool table_def_inited= 0;
-static bool table_def_shutdown_in_progress= 0;
-
 static bool check_and_update_table_version(THD *thd, TABLE_LIST *tables,
                                            TABLE_SHARE *table_share);
 static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry);
 static bool auto_repair_table(THD *thd, TABLE_LIST *table_list);
-static void free_cache_entry(TABLE *entry);
 static bool
 has_write_table_with_auto_increment(TABLE_LIST *tables);
 static bool
 has_write_table_with_auto_increment_and_select(TABLE_LIST *tables);
 static bool has_write_table_auto_increment_not_first_in_pk(TABLE_LIST *tables);
 
-uint cached_open_tables(void)
-{
-  return table_cache_count;
-}
-
-
-#ifdef EXTRA_DEBUG
-static void check_unused(THD *thd)
-{
-  uint count= 0, open_files= 0, idx= 0;
-  TABLE *cur_link, *start_link, *entry;
-  TABLE_SHARE *share;
-
-  if ((start_link=cur_link=unused_tables))
-  {
-    do
-    {
-      if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
-      {
-	DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
-	return; /* purecov: inspected */
-      }
-    } while (count++ < table_cache_count &&
-	     (cur_link=cur_link->next) != start_link);
-    if (cur_link != start_link)
-    {
-      DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
-    }
-  }
-  for (idx=0 ; idx < table_def_cache.records ; idx++)
-  {
-    share= (TABLE_SHARE*) my_hash_element(&table_def_cache, idx);
-
-    TABLE_SHARE::TABLE_list::Iterator it(share->free_tables);
-    while ((entry= it++))
-    {
-      /*
-        We must not have TABLEs in the free list that have their file closed.
-      */
-      DBUG_ASSERT(entry->db_stat && entry->file);
-      /* Merge children should be detached from a merge parent */
-      if (entry->in_use)
-      {
-        /* purecov: begin inspected */
-        DBUG_PRINT("error",("Used table is in share's list of unused tables"));
-        /* purecov: end */
-      }
-      /* extra() may assume that in_use is set */
-      entry->in_use= thd;
-      DBUG_ASSERT(!thd || ! entry->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
-      entry->in_use= 0;
-
-      count--;
-      open_files++;
-    }
-    it.init(share->used_tables);
-    while ((entry= it++))
-    {
-      if (!entry->in_use)
-      {
-        DBUG_PRINT("error",("Unused table is in share's list of used tables")); /* purecov: inspected */
-      }
-      open_files++;
-    }
-  }
-  if (count != 0)
-  {
-    DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
-			count)); /* purecov: inspected */
-  }
-}
-#else
-#define check_unused(A)
-#endif
 
 /**
   Create a table cache/table definition cache key
@@ -337,7 +200,7 @@ static void check_unused(THD *thd)
 uint create_tmp_table_def_key(THD *thd, char *key,
                               const char *db, const char *table_name)
 {
-  uint key_length= create_table_def_key(key, db, table_name);
+  uint key_length= tdc_create_key(key, db, table_name);
   int4store(key + key_length, thd->variables.server_id);
   int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
   key_length+= TMP_TABLE_KEY_EXTRA;
@@ -387,451 +250,6 @@ uint get_table_def_key(const TABLE_LIST
   Functions to handle table definition cache (TABLE_SHARE)
 *****************************************************************************/
 
-extern "C" uchar *table_def_key(const uchar *record, size_t *length,
-                               my_bool not_used __attribute__((unused)))
-{
-  TABLE_SHARE *entry=(TABLE_SHARE*) record;
-  *length= entry->table_cache_key.length;
-  return (uchar*) entry->table_cache_key.str;
-}
-
-
-static void table_def_free_entry(TABLE_SHARE *share)
-{
-  DBUG_ENTER("table_def_free_entry");
-  mysql_mutex_assert_owner(&LOCK_open);
-  if (share->prev)
-  {
-    /* remove from old_unused_share list */
-    *share->prev= share->next;
-    share->next->prev= share->prev;
-  }
-  free_table_share(share);
-  DBUG_VOID_RETURN;
-}
-
-
-bool table_def_init(void)
-{
-  table_def_inited= 1;
-#ifdef HAVE_PSI_INTERFACE
-  init_tdc_psi_keys();
-#endif
-  mysql_mutex_init(key_LOCK_open, &LOCK_open, MY_MUTEX_INIT_FAST);
-  mysql_mutex_record_order(&LOCK_active_mi, &LOCK_open);
-  /*
-    When we delete from the table_def_cache(), the free function
-    table_def_free_entry() is invoked from my_hash_delete(), which calls
-    free_table_share(), which may unload plugins, which can remove status
-    variables and hence takes LOCK_status. Record this locking order here.
-  */
-  mysql_mutex_record_order(&LOCK_open, &LOCK_status);
-  oldest_unused_share= &end_of_unused_share;
-  end_of_unused_share.prev= &oldest_unused_share;
-
-  return my_hash_init(&table_def_cache, &my_charset_bin, table_def_size,
-                      0, 0, table_def_key,
-                      (my_hash_free_key) table_def_free_entry, 0) != 0;
-}
-
-
-/**
-  Notify table definition cache that process of shutting down server
-  has started so it has to keep number of TABLE and TABLE_SHARE objects
-  minimal in order to reduce number of references to pluggable engines.
-*/
-
-void table_def_start_shutdown(void)
-{
-  DBUG_ENTER("table_def_start_shutdown");
-  if (table_def_inited)
-  {
-    mysql_mutex_lock(&LOCK_open);
-    /*
-      Ensure that TABLE and TABLE_SHARE objects which are created for
-      tables that are open during process of plugins' shutdown are
-      immediately released. This keeps number of references to engine
-      plugins minimal and allows shutdown to proceed smoothly.
-    */
-    table_def_shutdown_in_progress= TRUE;
-    mysql_mutex_unlock(&LOCK_open);
-    /* Free all cached but unused TABLEs and TABLE_SHAREs. */
-    close_cached_tables(NULL, NULL, FALSE, LONG_TIMEOUT);
-  }
-  DBUG_VOID_RETURN;
-}
-
-
-void table_def_free(void)
-{
-  DBUG_ENTER("table_def_free");
-  if (table_def_inited)
-  {
-    table_def_inited= 0;
-    /* Free table definitions. */
-    my_hash_free(&table_def_cache);
-    mysql_mutex_destroy(&LOCK_open);
-  }
-  DBUG_VOID_RETURN;
-}
-
-
-uint cached_table_definitions(void)
-{
-  return table_def_cache.records;
-}
-
-
-/*
-  Auxiliary routines for manipulating with per-share used/unused and
-  global unused lists of TABLE objects and table_cache_count counter.
-  Responsible for preserving invariants between those lists, counter
-  and TABLE::in_use member.
-  In fact those routines implement sort of implicit table cache as
-  part of table definition cache.
-*/
-
-
-/**
-   Add newly created TABLE object for table share which is going
-   to be used right away.
-*/
-
-static void table_def_add_used_table(THD *thd, TABLE *table)
-{
-  DBUG_ASSERT(table->in_use == thd);
-  table->s->used_tables.push_front(table);
-  table_cache_count++;
-}
-
-
-/**
-   Prepare used or unused TABLE instance for destruction by removing
-   it from share's and global list.
-*/
-
-static void table_def_remove_table(TABLE *table)
-{
-  if (table->in_use)
-  {
-    /* Remove from per-share chain of used TABLE objects. */
-    table->s->used_tables.remove(table);
-  }
-  else
-  {
-    /* Remove from per-share chain of unused TABLE objects. */
-    table->s->free_tables.remove(table);
-
-    /* And global unused chain. */
-    table->next->prev=table->prev;
-    table->prev->next=table->next;
-    if (table == unused_tables)
-    {
-      unused_tables=unused_tables->next;
-      if (table == unused_tables)
-	unused_tables=0;
-    }
-    check_unused(current_thd);
-  }
-  table_cache_count--;
-}
-
-
-/**
-   Mark already existing TABLE instance as used.
-*/
-
-static void table_def_use_table(THD *thd, TABLE *table)
-{
-  DBUG_ASSERT(!table->in_use);
-
-  /* Unlink table from list of unused tables for this share. */
-  table->s->free_tables.remove(table);
-  /* Unlink able from global unused tables list. */
-  if (table == unused_tables)
-  {						// First unused
-    unused_tables=unused_tables->next;	        // Remove from link
-    if (table == unused_tables)
-      unused_tables=0;
-  }
-  table->prev->next=table->next;		/* Remove from unused list */
-  table->next->prev=table->prev;
-  check_unused(thd);
-  /* Add table to list of used tables for this share. */
-  table->s->used_tables.push_front(table);
-  table->in_use= thd;
-  /* The ex-unused table must be fully functional. */
-  DBUG_ASSERT(table->db_stat && table->file);
-  /* The children must be detached from the table. */
-  DBUG_ASSERT(! table->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
-}
-
-
-/**
-   Mark already existing used TABLE instance as unused.
-*/
-
-static void table_def_unuse_table(TABLE *table)
-{
-  THD *thd __attribute__((unused))= table->in_use;
-  DBUG_ASSERT(table->in_use);
-
-  /* We shouldn't put the table to 'unused' list if the share is old. */
-  DBUG_ASSERT(! table->s->has_old_version());
-
-  table->in_use= 0;
-
-  /* Remove table from the list of tables used in this share. */
-  table->s->used_tables.remove(table);
-  /* Add table to the list of unused TABLE objects for this share. */
-  table->s->free_tables.push_front(table);
-  /* Also link it last in the global list of unused TABLE objects. */
-  if (unused_tables)
-  {
-    table->next=unused_tables;
-    table->prev=unused_tables->prev;
-    unused_tables->prev=table;
-    table->prev->next=table;
-  }
-  else
-    unused_tables=table->next=table->prev=table;
-  check_unused(thd);
-}
-
-
-/*
-  Get TABLE_SHARE for a table.
-
-  get_table_share()
-  thd			Thread handle
-  table_list		Table that should be opened
-  key			Table cache key
-  key_length		Length of key
-  flags   		operation: what to open table or view
-  hash_value            = my_calc_hash(&table_def_cache, key, key_length)
-
-  IMPLEMENTATION
-    Get a table definition from the table definition cache.
-    If it doesn't exist, create a new from the table definition file.
-
-  RETURN
-   0  Error
-   #  Share for table
-*/
-
-TABLE_SHARE *get_table_share(THD *thd, const char *db, const char *table_name,
-                             const char *key, uint key_length, uint flags,
-                             my_hash_value_type hash_value)
-{
-  TABLE_SHARE *share;
-  DBUG_ENTER("get_table_share");
-
-  mysql_mutex_lock(&LOCK_open);
-
-  /* Read table definition from cache */
-  share= (TABLE_SHARE*) my_hash_search_using_hash_value(&table_def_cache,
-                                        hash_value, (uchar*) key, key_length);
-
-  if (!share)
-  {
-    if (!(share= alloc_table_share(db, table_name, key, key_length)))
-      goto err;
-
-    /*
-      We assign a new table id under the protection of LOCK_open.
-      We do this instead of creating a new mutex
-      and using it for the sole purpose of serializing accesses to a
-      static variable, we assign the table id here. We assign it to the
-      share before inserting it into the table_def_cache to be really
-      sure that it cannot be read from the cache without having a table
-      id assigned.
-
-      CAVEAT. This means that the table cannot be used for
-      binlogging/replication purposes, unless get_table_share() has been
-      called directly or indirectly.
-     */
-    assign_new_table_id(share);
-
-    if (my_hash_insert(&table_def_cache, (uchar*) share))
-    {
-      free_table_share(share);
-      goto err;
-    }
-    share->ref_count++;                         // Mark in use
-    share->error= OPEN_FRM_OPEN_ERROR;
-    mysql_mutex_lock(&share->LOCK_share);
-    mysql_mutex_unlock(&LOCK_open);
-
-    /* note that get_table_share() *always* uses discovery */
-    open_table_def(thd, share, flags | GTS_USE_DISCOVERY);
-
-    mysql_mutex_unlock(&share->LOCK_share);
-    mysql_mutex_lock(&LOCK_open);
-
-    if (share->error)
-    {
-      share->ref_count--;
-      (void) my_hash_delete(&table_def_cache, (uchar*) share);
-      goto err;
-    }
-
-    share->m_psi= PSI_CALL_get_table_share(false, share);
-
-    DBUG_PRINT("exit", ("share: 0x%lx  ref_count: %u",
-                        (ulong) share, share->ref_count));
-
-    goto end;
-  }
-
-  /* cannot force discovery of a cached share */
-  DBUG_ASSERT(!(flags & GTS_FORCE_DISCOVERY));
-
-  /* make sure that open_table_def() for this share is not running */
-  mysql_mutex_lock(&share->LOCK_share);
-  mysql_mutex_unlock(&share->LOCK_share);
-
-  /*
-     We found an existing table definition. Return it if we didn't get
-     an error when reading the table definition from file.
-  */
-  if (share->error)
-  {
-    open_table_error(share, share->error, share->open_errno);
-    goto err;
-  }
-
-  if (share->is_view && !(flags & GTS_VIEW))
-  {
-    open_table_error(share, OPEN_FRM_NOT_A_TABLE, ENOENT);
-    goto err;
-  }
-  if (!share->is_view && !(flags & GTS_TABLE))
-  {
-    open_table_error(share, OPEN_FRM_NOT_A_VIEW, ENOENT);
-    goto err;
-  }
-
-  ++share->ref_count;
-
-  if (share->ref_count == 1 && share->prev)
-  {
-    /*
-      Share was not used before and it was in the old_unused_share list
-      Unlink share from this list
-    */
-    DBUG_PRINT("info", ("Unlinking from not used list"));
-    *share->prev= share->next;
-    share->next->prev= share->prev;
-    share->next= 0;
-    share->prev= 0;
-  }
-
-   /* Free cache if too big */
-  while (table_def_cache.records > table_def_size &&
-         oldest_unused_share->next)
-    my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
-
-  DBUG_PRINT("exit", ("share: 0x%lx  ref_count: %u",
-                      (ulong) share, share->ref_count));
-  goto end;
-
-err:
-  mysql_mutex_unlock(&LOCK_open);
-  DBUG_RETURN(0);
-
-end:
-  if (flags & GTS_NOLOCK)
-  {
-    release_table_share(share);
-    /*
-      if GTS_NOLOCK is requested, the returned share pointer cannot be used,
-      the share it points to may go away any moment.
-      But perhaps the caller is only interested to know whether a share or
-      table existed?
-      Let's return an invalid pointer here to catch dereferencing attempts.
-    */
-    share= (TABLE_SHARE*) 1;
-  }
-
-  mysql_mutex_unlock(&LOCK_open);
-  DBUG_RETURN(share);
-}
-
-
-/**
-  Mark that we are not using table share anymore.
-
-  @param  share   Table share
-
-  If the share has no open tables and (we have done a refresh or
-  if we have already too many open table shares) then delete the
-  definition.
-*/
-
-void release_table_share(TABLE_SHARE *share)
-{
-  DBUG_ENTER("release_table_share");
-  DBUG_PRINT("enter",
-             ("share: 0x%lx  table: %s.%s  ref_count: %u  version: %lu",
-              (ulong) share, share->db.str, share->table_name.str,
-              share->ref_count, share->version));
-
-  mysql_mutex_assert_owner(&LOCK_open);
-
-  DBUG_ASSERT(share->ref_count);
-  if (!--share->ref_count)
-  {
-    if (share->has_old_version() || table_def_shutdown_in_progress)
-      my_hash_delete(&table_def_cache, (uchar*) share);
-    else
-    {
-      /* Link share last in used_table_share list */
-      DBUG_PRINT("info",("moving share to unused list"));
-
-      DBUG_ASSERT(share->next == 0);
-      share->prev= end_of_unused_share.prev;
-      *end_of_unused_share.prev= share;
-      end_of_unused_share.prev= &share->next;
-      share->next= &end_of_unused_share;
-
-      if (table_def_cache.records > table_def_size)
-      {
-        /* Delete the least used share to preserve LRU order. */
-        my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
-      }
-    }
-  }
-
-  DBUG_VOID_RETURN;
-}
-
-
-/*
-  Check if table definition exits in cache
-
-  SYNOPSIS
-    get_cached_table_share()
-    db			Database name
-    table_name		Table name
-
-  RETURN
-    0  Not cached
-    #  TABLE_SHARE for table
-*/
-
-TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
-{
-  char key[MAX_DBKEY_LENGTH];
-  uint key_length;
-  mysql_mutex_assert_owner(&LOCK_open);
-
-  key_length= create_table_def_key(key, db, table_name);
-  TABLE_SHARE* share= (TABLE_SHARE*)my_hash_search(&table_def_cache,
-                                                   (uchar*) key, key_length);
-  return !share || share->error ? 0 : share;
-}  
-
-
 /*
   Create a list for all open tables matching SQL expression
 
@@ -852,20 +270,19 @@ TABLE_SHARE *get_cached_table_share(cons
 
 OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
 {
-  int result = 0;
   OPEN_TABLE_LIST **start_list, *open_list;
   TABLE_LIST table_list;
+  TABLE_SHARE *share;
+  TDC_iterator tdc_it;
   DBUG_ENTER("list_open_tables");
 
-  mysql_mutex_lock(&LOCK_open);
   bzero((char*) &table_list,sizeof(table_list));
   start_list= &open_list;
   open_list=0;
 
-  for (uint idx=0 ; result == 0 && idx < table_def_cache.records; idx++)
+  tdc_it.init();
+  while ((share= tdc_it.next()))
   {
-    TABLE_SHARE *share= (TABLE_SHARE *)my_hash_element(&table_def_cache, idx);
-
     if (db && my_strcasecmp(system_charset_info, db, share->db.str))
       continue;
     if (wild && wild_compare(share->table_name.str, wild, 0))
@@ -890,14 +307,16 @@ OPEN_TABLE_LIST *list_open_tables(THD *t
 		  share->db.str)+1,
 	   share->table_name.str);
     (*start_list)->in_use= 0;
-    TABLE_SHARE::TABLE_list::Iterator it(share->used_tables);
+    mysql_mutex_lock(&LOCK_open);
+    TABLE_SHARE::TABLE_list::Iterator it(share->tdc.used_tables);
     while (it++)
       ++(*start_list)->in_use;
+    mysql_mutex_unlock(&LOCK_open);
     (*start_list)->locked= 0;                   /* Obsolete. */
     start_list= &(*start_list)->next;
     *start_list=0;
   }
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_it.deinit();
   DBUG_RETURN(open_list);
 }
 
@@ -913,39 +332,18 @@ void intern_close_table(TABLE *table)
                         table->s ? table->s->db.str : "?",
                         table->s ? table->s->table_name.str : "?",
                         (long) table));
+  mysql_mutex_assert_not_owner(&LOCK_open);
 
   free_io_cache(table);
   delete table->triggers;
   if (table->file)                              // Not true if placeholder
     (void) closefrm(table, 1);			// close file
   table->alias.free();
-  DBUG_VOID_RETURN;
-}
-
-/*
-  Remove table from the open table cache
-
-  SYNOPSIS
-    free_cache_entry()
-    table		Table to remove
-
-  NOTE
-    We need to have a lock on LOCK_open when calling this
-*/
-
-static void free_cache_entry(TABLE *table)
-{
-  DBUG_ENTER("free_cache_entry");
-
-  /* This should be done before releasing table share. */
-  table_def_remove_table(table);
-
-  intern_close_table(table);
-
   my_free(table);
   DBUG_VOID_RETURN;
 }
 
+
 /* Free resources allocated by filesort() and read_record() */
 
 void free_io_cache(TABLE *table)
@@ -970,9 +368,9 @@ void free_io_cache(TABLE *table)
    @pre Caller should have LOCK_open mutex.
 */
 
-static void kill_delayed_threads_for_table(TABLE_SHARE *share)
+void kill_delayed_threads_for_table(TABLE_SHARE *share)
 {
-  TABLE_SHARE::TABLE_list::Iterator it(share->used_tables);
+  TABLE_SHARE::TABLE_list::Iterator it(share->tdc.used_tables);
   TABLE *tab;
 
   mysql_mutex_assert_owner(&LOCK_open);
@@ -1021,67 +419,48 @@ bool close_cached_tables(THD *thd, TABLE
                          bool wait_for_refresh, ulong timeout)
 {
   bool result= FALSE;
-  bool found= TRUE;
   struct timespec abstime;
   DBUG_ENTER("close_cached_tables");
   DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
 
-  mysql_mutex_lock(&LOCK_open);
   if (!tables)
   {
     /*
       Force close of all open tables.
 
       Note that code in TABLE_SHARE::wait_for_old_version() assumes that
-      incrementing of refresh_version and removal of unused tables and
-      shares from TDC happens atomically under protection of LOCK_open,
-      or putting it another way that TDC does not contain old shares
-      which don't have any tables used.
-    */
-    refresh_version++;
-    DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu",
-                          refresh_version));
+      incrementing of refresh_version is followed by purge of unused table
+      shares.
+    */
+    tdc_increment_refresh_version();
     kill_delayed_threads();
     /*
       Get rid of all unused TABLE and TABLE_SHARE instances. By doing
       this we automatically close all tables which were marked as "old".
     */
-    while (unused_tables)
-      free_cache_entry(unused_tables);
+    tc_purge();
     /* Free table shares which were not freed implicitly by loop above. */
-    while (oldest_unused_share->next)
-      (void) my_hash_delete(&table_def_cache, (uchar*) oldest_unused_share);
+    tdc_purge(true);
   }
   else
   {
     bool found=0;
     for (TABLE_LIST *table= tables; table; table= table->next_local)
     {
-      TABLE_SHARE *share= get_cached_table_share(table->db, table->table_name);
-
-      if (share)
-      {
-        kill_delayed_threads_for_table(share);
-        /* tdc_remove_table() also sets TABLE_SHARE::version to 0. */
-        tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED, table->db,
-                         table->table_name, TRUE);
-	found=1;
-      }
+      /* tdc_remove_table() also sets TABLE_SHARE::version to 0. */
+      found|= tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED, table->db,
+                               table->table_name, TRUE);
     }
     if (!found)
       wait_for_refresh=0;			// Nothing to wait for
   }
 
-  mysql_mutex_unlock(&LOCK_open);
-
   DBUG_PRINT("info", ("open table definitions: %d",
-                      (int) table_def_cache.records));
+                      (int) tdc_records()));
 
   if (!wait_for_refresh)
     DBUG_RETURN(result);
 
-  set_timespec(abstime, timeout);
-
   if (thd->locked_tables_mode)
   {
     /*
@@ -1120,60 +499,61 @@ bool close_cached_tables(THD *thd, TABLE
   /* Wait until all threads have closed all the tables we are flushing. */
   DBUG_PRINT("info", ("Waiting for other threads to close their open tables"));
 
-  while (found && ! thd->killed)
-  {
-    TABLE_SHARE *share;
-    found= FALSE;
-    /*
-      To a self-deadlock or deadlocks with other FLUSH threads
-      waiting on our open HANDLERs, we have to flush them.
-    */
-    mysql_ha_flush(thd);
-    DEBUG_SYNC(thd, "after_flush_unlock");
+  /*
+    To a self-deadlock or deadlocks with other FLUSH threads
+    waiting on our open HANDLERs, we have to flush them.
+  */
+  mysql_ha_flush(thd);
+  DEBUG_SYNC(thd, "after_flush_unlock");
 
-    mysql_mutex_lock(&LOCK_open);
+  if (!tables)
+  {
+    bool found= true;
+    set_timespec(abstime, timeout);
+    while (found && !thd->killed)
+    {
+      TABLE_SHARE *share;
+      TDC_iterator tdc_it;
+      found= false;
 
-    if (!tables)
-    {
-      for (uint idx=0 ; idx < table_def_cache.records ; idx++)
+      tdc_it.init();
+      while ((share= tdc_it.next()))
       {
-        share= (TABLE_SHARE*) my_hash_element(&table_def_cache, idx);
+        mysql_mutex_lock(&share->tdc.LOCK_table_share);
         if (share->has_old_version())
         {
-          found= TRUE;
+          /* wait_for_old_version() will unlock mutex and free share */
+          found= true;
           break;
         }
+        mysql_mutex_unlock(&share->tdc.LOCK_table_share);
       }
-    }
-    else
-    {
-      for (TABLE_LIST *table= tables; table; table= table->next_local)
+      tdc_it.deinit();
+
+      if (found)
       {
-        share= get_cached_table_share(table->db, table->table_name);
-        if (share && share->has_old_version())
+        if (share->wait_for_old_version(thd, &abstime,
+                                        MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL))
         {
-	  found= TRUE;
+          result= TRUE;
           break;
         }
       }
     }
-
-    if (found)
+  }
+  else
+  {
+    for (TABLE_LIST *table= tables; table; table= table->next_local)
     {
-      /*
-        The method below temporarily unlocks LOCK_open and frees
-        share's memory.
-      */
-      if (share->wait_for_old_version(thd, &abstime,
-                                    MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL))
+      if (thd->killed)
+        break;
+      if (tdc_wait_for_old_version(thd, table->db, table->table_name, timeout,
+                                   MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL))
       {
-        mysql_mutex_unlock(&LOCK_open);
         result= TRUE;
-        goto err_with_reopen;
+        break;
       }
     }
-
-    mysql_mutex_unlock(&LOCK_open);
   }
 
 err_with_reopen:
@@ -1204,23 +584,26 @@ bool close_cached_tables(THD *thd, TABLE
 
 bool close_cached_connection_tables(THD *thd, LEX_STRING *connection)
 {
-  uint idx;
   TABLE_LIST tmp, *tables= NULL;
   bool result= FALSE;
+  TABLE_SHARE *share;
+  TDC_iterator tdc_it;
   DBUG_ENTER("close_cached_connections");
   DBUG_ASSERT(thd);
 
   bzero(&tmp, sizeof(TABLE_LIST));
 
-  mysql_mutex_lock(&LOCK_open);
-
-  for (idx= 0; idx < table_def_cache.records; idx++)
+  tdc_it.init();
+  while ((share= tdc_it.next()))
   {
-    TABLE_SHARE *share= (TABLE_SHARE *) my_hash_element(&table_def_cache, idx);
-
+    mysql_mutex_lock(&share->tdc.LOCK_table_share);
     /* Ignore if table is not open or does not have a connect_string */
-    if (!share->connect_string.length || !share->ref_count)
+    if (!share->connect_string.length || !share->tdc.ref_count)
+    {
+      mysql_mutex_unlock(&share->tdc.LOCK_table_share);
       continue;
+    }
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
 
     /* Compare the connection string */
     if (connection &&
@@ -1240,7 +623,7 @@ bool close_cached_connection_tables(THD
     tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp, 
                                        sizeof(TABLE_LIST));
   }
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_it.deinit();
 
   if (tables)
     result= close_cached_tables(thd, tables, FALSE, LONG_TIMEOUT);
@@ -1633,23 +1016,7 @@ void close_thread_table(THD *thd, TABLE
   if (table->file != NULL)
     table->file->unbind_psi();
 
-  mysql_mutex_lock(&LOCK_open);
-
-  if (table->s->has_old_version() || table->needs_reopen() ||
-      table_def_shutdown_in_progress)
-    free_cache_entry(table);
-  else
-  {
-    DBUG_ASSERT(table->file);
-    table_def_unuse_table(table);
-    /*
-      We free the least used table, not the subject table,
-      to keep the LRU order.
-    */
-    if (table_cache_count > table_cache_size)
-      free_cache_entry(unused_tables);
-  }
-  mysql_mutex_unlock(&LOCK_open);
+  tc_release_table(table);
   DBUG_VOID_RETURN;
 }
 
@@ -2588,40 +1955,6 @@ open_table_get_mdl_lock(THD *thd, Open_t
 
 
 /**
-  Check if table's share is being removed from the table definition
-  cache and, if yes, wait until the flush is complete.
-
-  @param thd             Thread context.
-  @param table_list      Table which share should be checked.
-  @param timeout         Timeout for waiting.
-  @param deadlock_weight Weight of this wait for deadlock detector.
-
-  @retval FALSE   Success. Share is up to date or has been flushed.
-  @retval TRUE    Error (OOM, our was killed, the wait resulted
-                  in a deadlock or timeout). Reported.
-*/
-
-static bool
-tdc_wait_for_old_version(THD *thd, const char *db, const char *table_name,
-                         ulong wait_timeout, uint deadlock_weight)
-{
-  TABLE_SHARE *share;
-  bool res= FALSE;
-
-  mysql_mutex_lock(&LOCK_open);
-  if ((share= get_cached_table_share(db, table_name)) &&
-      share->has_old_version())
-  {
-    struct timespec abstime;
-    set_timespec(abstime, wait_timeout);
-    res= share->wait_for_old_version(thd, &abstime, deadlock_weight);
-  }
-  mysql_mutex_unlock(&LOCK_open);
-  return res;
-}
-
-
-/**
   Open a base table.
 
   @param thd            Thread context.
@@ -2659,14 +1992,13 @@ tdc_wait_for_old_version(THD *thd, const
 bool open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
                 Open_table_context *ot_ctx)
 {
-  reg1	TABLE *table;
+  TABLE *table;
   const char *key;
   uint	key_length;
   char	*alias= table_list->alias;
   uint flags= ot_ctx->get_flags();
   MDL_ticket *mdl_ticket;
   TABLE_SHARE *share;
-  my_hash_value_type hash_value;
   uint gts_flags;
   DBUG_ENTER("open_table");
 
@@ -2890,9 +2222,6 @@ bool open_table(THD *thd, TABLE_LIST *ta
     mdl_ticket= table_list->mdl_request.ticket;
   }
 
-  hash_value= my_calc_hash(&table_def_cache, (uchar*) key, key_length);
-
-
   if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)
   {
     if (!ha_table_exists(thd, table_list->db, table_list->table_name))
@@ -2912,8 +2241,8 @@ bool open_table(THD *thd, TABLE_LIST *ta
 
 retry_share:
 
-  share= get_table_share(thd, table_list->db, table_list->table_name,
-                         key, key_length, gts_flags, hash_value);
+  share= tdc_acquire_share(thd, table_list->db, table_list->table_name,
+                           key, key_length, gts_flags, &table);
 
   if (!share)
   {
@@ -2974,18 +2303,14 @@ bool open_table(THD *thd, TABLE_LIST *ta
                      0, table_list, mem_root))
       goto err_lock;
 
-    mysql_mutex_lock(&LOCK_open);
-
     /* TODO: Don't free this */
-    release_table_share(share);
+    tdc_release_share(share);
 
     DBUG_ASSERT(table_list->view);
 
-    mysql_mutex_unlock(&LOCK_open);
     DBUG_RETURN(FALSE);
   }
 
-  mysql_mutex_lock(&LOCK_open);
   if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
   {
     if (share->has_old_version())
@@ -2999,8 +2324,10 @@ bool open_table(THD *thd, TABLE_LIST *ta
         Release our reference to share, wait until old version of
         share goes away and then try to get new version of table share.
       */
-      release_table_share(share);
-      mysql_mutex_unlock(&LOCK_open);
+      if (table)
+        tc_release_table(table);
+      else
+        tdc_release_share(share);
 
       MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
       bool wait_result;
@@ -3026,23 +2353,18 @@ bool open_table(THD *thd, TABLE_LIST *ta
         and try to reopen them. Note: refresh_version is currently
         changed only during FLUSH TABLES.
       */
-      release_table_share(share);
-      mysql_mutex_unlock(&LOCK_open);
+      if (table)
+        tc_release_table(table);
+      else
+        tdc_release_share(share);
       (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
                                            NULL);
       DBUG_RETURN(TRUE);
     }
   }
 
-  if (!share->free_tables.is_empty())
+  if (table)
   {
-    table= share->free_tables.front();
-    table_def_use_table(thd, table);
-
-    /* Release the share as we hold an extra reference to it */
-    release_table_share(share);
-    mysql_mutex_unlock(&LOCK_open);
-
     DBUG_ASSERT(table->file != NULL);
     table->file->rebind_psi();
   }
@@ -3050,12 +2372,6 @@ bool open_table(THD *thd, TABLE_LIST *ta
   {
     enum open_frm_error error;
 
-    /* If we have too many TABLE instances around, try to get rid of them */
-    while (table_cache_count > table_cache_size && unused_tables)
-      free_cache_entry(unused_tables);
-
-    mysql_mutex_unlock(&LOCK_open);
-
     /* make a new table */
     if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
       goto err_lock;
@@ -3089,9 +2405,7 @@ bool open_table(THD *thd, TABLE_LIST *ta
     }
 
     /* Add table to the share's used tables list. */
-    mysql_mutex_lock(&LOCK_open);
-    table_def_add_used_table(thd, table);
-    mysql_mutex_unlock(&LOCK_open);
+    tc_add_table(thd, table);
   }
 
   table->mdl_ticket= mdl_ticket;
@@ -3130,9 +2444,7 @@ bool open_table(THD *thd, TABLE_LIST *ta
   DBUG_RETURN(FALSE);
 
 err_lock:
-  mysql_mutex_lock(&LOCK_open);
-  release_table_share(share);
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_release_share(share);
 
   DBUG_RETURN(TRUE);
 }
@@ -3151,7 +2463,7 @@ bool open_table(THD *thd, TABLE_LIST *ta
 TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name)
 {
   char	key[MAX_DBKEY_LENGTH];
-  uint key_length= create_table_def_key(key, db, table_name);
+  uint key_length= tdc_create_key(key, db, table_name);
 
   for (TABLE *table= list; table ; table=table->next)
   {
@@ -3549,62 +2861,6 @@ Locked_tables_list::reopen_tables(THD *t
 }
 
 
-/*
-  Function to assign a new table map id to a table share.
-
-  PARAMETERS
-
-    share - Pointer to table share structure
-
-  DESCRIPTION
-
-    We are intentionally not checking that share->mutex is locked
-    since this function should only be called when opening a table
-    share and before it is entered into the table_def_cache (meaning
-    that it cannot be fetched by another thread, even accidentally).
-
-  PRE-CONDITION(S)
-
-    share is non-NULL
-    The LOCK_open mutex is locked.
-
-  POST-CONDITION(S)
-
-    share->table_map_id is given a value that with a high certainty is
-    not used by any other table (the only case where a table id can be
-    reused is on wrap-around, which means more than 4 billion table
-    share opens have been executed while one table was open all the
-    time).
-
-    share->table_map_id is not ~0UL.
- */
-static ulong last_table_id= ~0UL;
-
-void assign_new_table_id(TABLE_SHARE *share)
-{
-
-  DBUG_ENTER("assign_new_table_id");
-
-  /* Preconditions */
-  DBUG_ASSERT(share != NULL);
-  mysql_mutex_assert_owner(&LOCK_open);
-
-  ulong tid= ++last_table_id;                   /* get next id */
-  /*
-    There is one reserved number that cannot be used.  Remember to
-    change this when 6-byte global table id's are introduced.
-  */
-  if (unlikely(tid == ~0UL))
-    tid= ++last_table_id;
-  share->table_map_id= tid;
-  DBUG_PRINT("info", ("table_id=%lu", tid));
-
-  /* Post conditions */
-  DBUG_ASSERT(share->table_map_id != ~0UL);
-
-  DBUG_VOID_RETURN;
-}
-
 #ifndef DBUG_OFF
 /* Cause a spurious statement reprepare for debug purposes. */
 static bool inject_reprepare(THD *thd)
@@ -3762,8 +3018,8 @@ bool tdc_open_view(THD *thd, TABLE_LIST
   TABLE_SHARE *share;
   bool err= TRUE;
 
-  if (!(share= get_table_share(thd, table_list->db, table_list->table_name,
-                               cache_key, cache_key_length, GTS_VIEW)))
+  if (!(share= tdc_acquire_share(thd, table_list->db, table_list->table_name,
+                                 cache_key, cache_key_length, GTS_VIEW)))
     return TRUE;
 
   DBUG_ASSERT(share->is_view);
@@ -3790,9 +3046,7 @@ bool tdc_open_view(THD *thd, TABLE_LIST
                     thd->open_options, &not_used, table_list, mem_root);
 
 ret:
-  mysql_mutex_lock(&LOCK_open);
-  release_table_share(share);
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_release_share(share);
 
   return err;
 }
@@ -3857,7 +3111,7 @@ static bool auto_repair_table(THD *thd,
   if (!(entry= (TABLE*)my_malloc(sizeof(TABLE), MYF(MY_WME))))
     return result;
 
-  if (!(share= get_table_share_shortlived(thd, table_list, GTS_TABLE)))
+  if (!(share= tdc_acquire_share_shortlived(thd, table_list, GTS_TABLE)))
     goto end_free;
 
   DBUG_ASSERT(! share->is_view);
@@ -3886,13 +3140,11 @@ static bool auto_repair_table(THD *thd,
     result= FALSE;
   }
 
-  mysql_mutex_lock(&LOCK_open);
-  release_table_share(share);
+  tdc_release_share(share);
   /* Remove the repaired share from the table cache. */
   tdc_remove_table(thd, TDC_RT_REMOVE_ALL,
                    table_list->db, table_list->table_name,
-                   TRUE);
-  mysql_mutex_unlock(&LOCK_open);
+                   FALSE);
 end_free:
   my_free(entry);
   return result;
@@ -4039,9 +3291,9 @@ recover_from_failed_open(THD *thd)
         thd->clear_error();                 // Clear error message
 
         if ((result=
-             !get_table_share(thd, m_failed_table->db,
-                              m_failed_table->table_name,
-                              GTS_TABLE | GTS_FORCE_DISCOVERY | GTS_NOLOCK)))
+             !tdc_acquire_share(thd, m_failed_table->db,
+                                m_failed_table->table_name,
+                                GTS_TABLE | GTS_FORCE_DISCOVERY | GTS_NOLOCK)))
           break;
 
         thd->mdl_context.release_transactional_locks();
@@ -6091,13 +5343,6 @@ TABLE *open_table_uncached(THD *thd, han
                                       MYF(MY_WME))))
     DBUG_RETURN(0);				/* purecov: inspected */
 
-#ifndef DBUG_OFF
-  mysql_mutex_lock(&LOCK_open);
-  DBUG_ASSERT(!my_hash_search(&table_def_cache, (uchar*) cache_key,
-                              key_length));
-  mysql_mutex_unlock(&LOCK_open);
-#endif
-
   share= (TABLE_SHARE*) (tmp_table+1);
   tmp_path= (char*) (share+1);
   saved_cache_key= strmov(tmp_path, path)+1;
@@ -9421,23 +8666,6 @@ my_bool mysql_rm_tmp_tables(void)
 	unireg support functions
 *****************************************************************************/
 
-/*
-  free all unused tables
-
-  NOTE
-    This is called by 'handle_manager' when one wants to periodicly flush
-    all not used tables.
-*/
-
-void tdc_flush_unused_tables()
-{
-  mysql_mutex_lock(&LOCK_open);
-  while (unused_tables)
-    free_cache_entry(unused_tables);
-  mysql_mutex_unlock(&LOCK_open);
-}
-
-
 /**
    A callback to the server internals that is used to address
    special cases of the locking protocol.
@@ -9508,122 +8736,6 @@ bool mysql_notify_thread_having_shared_l
 }
 
 
-/**
-   Remove all or some (depending on parameter) instances of TABLE and
-   TABLE_SHARE from the table definition cache.
-
-   @param  thd          Thread context
-   @param  remove_type  Type of removal:
-                        TDC_RT_REMOVE_ALL     - remove all TABLE instances and
-                                                TABLE_SHARE instance. There
-                                                should be no used TABLE objects
-                                                and caller should have exclusive
-                                                metadata lock on the table.
-                        TDC_RT_REMOVE_NOT_OWN - remove all TABLE instances
-                                                except those that belong to
-                                                this thread. There should be
-                                                no TABLE objects used by other
-                                                threads and caller should have
-                                                exclusive metadata lock on the
-                                                table.
-                        TDC_RT_REMOVE_UNUSED  - remove all unused TABLE
-                                                instances (if there are no
-                                                used instances will also
-                                                remove TABLE_SHARE).
-                        TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE -
-                                                remove all TABLE instances
-                                                except those that belong to
-                                                this thread, but don't mark
-                                                TABLE_SHARE as old. There
-                                                should be no TABLE objects
-                                                used by other threads and
-                                                caller should have exclusive
-                                                metadata lock on the table.
-   @param  db           Name of database
-   @param  table_name   Name of table
-   @param  has_lock     If TRUE, LOCK_open is already acquired
-
-   @note It assumes that table instances are already not used by any
-   (other) thread (this should be achieved by using meta-data locks).
-*/
-
-void tdc_remove_table(THD *thd, enum_tdc_remove_table_type remove_type,
-                      const char *db, const char *table_name,
-                      bool has_lock)
-{
-  char key[MAX_DBKEY_LENGTH];
-  uint key_length;
-  TABLE *table;
-  TABLE_SHARE *share;
-  DBUG_ENTER("tdc_remove_table");
-  DBUG_PRINT("enter",("name: %s  remove_type: %d", table_name, remove_type));
-
-  if (! has_lock)
-    mysql_mutex_lock(&LOCK_open);
-  else
-  {
-    mysql_mutex_assert_owner(&LOCK_open);
-  }
-
-  DBUG_ASSERT(remove_type == TDC_RT_REMOVE_UNUSED ||
-              thd->mdl_context.is_lock_owner(MDL_key::TABLE, db, table_name,
-                                             MDL_EXCLUSIVE));
-
-  key_length= create_table_def_key(key, db, table_name);
-
-  if ((share= (TABLE_SHARE*) my_hash_search(&table_def_cache,(uchar*) key,
-                                            key_length)))
-  {
-    if (share->ref_count)
-    {
-      TABLE_SHARE::TABLE_list::Iterator it(share->free_tables);
-#ifndef DBUG_OFF
-      if (remove_type == TDC_RT_REMOVE_ALL)
-      {
-        DBUG_ASSERT(share->used_tables.is_empty());
-      }
-      else if (remove_type == TDC_RT_REMOVE_NOT_OWN)
-      {
-        TABLE_SHARE::TABLE_list::Iterator it2(share->used_tables);
-        while ((table= it2++))
-        {
-          if (table->in_use != thd)
-          {
-            DBUG_ASSERT(0);
-          }
-        }
-      }
-#endif
-      /*
-        Set share's version to zero in order to ensure that it gets
-        automatically deleted once it is no longer referenced.
-
-        Note that code in TABLE_SHARE::wait_for_old_version() assumes
-        that marking share as old and removal of its unused tables
-        and of the share itself from TDC happens atomically under
-        protection of LOCK_open, or, putting it another way, that
-        TDC does not contain old shares which don't have any tables
-        used.
-      */
-      if (remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE)
-        share->version= 0;
-
-      while ((table= it++))
-        free_cache_entry(table);
-    }
-    else
-    {
-      DBUG_ASSERT(remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE);
-      (void) my_hash_delete(&table_def_cache, (uchar*) share);
-    }
-  }
-
-  if (! has_lock)
-    mysql_mutex_unlock(&LOCK_open);
-  DBUG_VOID_RETURN;
-}
-
-
 int setup_ftfuncs(SELECT_LEX *select_lex)
 {
   List_iterator<Item_func_match> li(*(select_lex->ftfunc_list)),

=== modified file 'sql/sql_base.h'
--- a/sql/sql_base.h	2013-08-12 13:46:35 +0000
+++ b/sql/sql_base.h	2013-08-14 08:48:50 +0000
@@ -20,6 +20,7 @@
 #include "sql_trigger.h"                        /* trg_event_type */
 #include "sql_class.h"                          /* enum_mark_columns */
 #include "mysqld.h"                             /* key_map */
+#include "table_cache.h"
 
 class Item_ident;
 struct Name_resolution_context;
@@ -59,93 +60,9 @@ enum find_item_error_report_type {REPORT
 				  IGNORE_ERRORS, REPORT_EXCEPT_NON_UNIQUE,
                                   IGNORE_EXCEPT_NON_UNIQUE};
 
-enum enum_tdc_remove_table_type {TDC_RT_REMOVE_ALL, TDC_RT_REMOVE_NOT_OWN,
-                                 TDC_RT_REMOVE_UNUSED,
-                                 TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE};
-
-/* bits for last argument to remove_table_from_cache() */
-#define RTFC_NO_FLAG                0x0000
-#define RTFC_OWNED_BY_THD_FLAG      0x0001
-#define RTFC_WAIT_OTHER_THREAD_FLAG 0x0002
-#define RTFC_CHECK_KILLED_FLAG      0x0004
-
-extern HASH table_def_cache;
-
-bool check_dup(const char *db, const char *name, TABLE_LIST *tables);
-extern mysql_mutex_t LOCK_open;
-bool table_cache_init(void);
-void table_cache_free(void);
-bool table_def_init(void);
-void table_def_free(void);
-void table_def_start_shutdown(void);
-void assign_new_table_id(TABLE_SHARE *share);
-uint cached_table_definitions(void);
-uint cached_open_tables(void);
-
-/**
-  Create a table cache key for non-temporary table.
-
-  @param key         Buffer for key (must be at least MAX_DBKEY_LENGTH bytes).
-  @param db          Database name.
-  @param table_name  Table name.
-
-  @return Length of key.
-
-  @sa create_table_def_key(thd, char *, table_list, bool)
-*/
-
-inline uint
-create_table_def_key(char *key, const char *db, const char *table_name)
-{
-  /*
-    In theory caller should ensure that both db and table_name are
-    not longer than NAME_LEN bytes. In practice we play safe to avoid
-    buffer overruns.
-  */
-  return (uint)(strmake(strmake(key, db, NAME_LEN) + 1, table_name,
-                        NAME_LEN) - key + 1);
-}
-
 uint create_tmp_table_def_key(THD *thd, char *key, const char *db,
                               const char *table_name);
 uint get_table_def_key(const TABLE_LIST *table_list, const char **key);
-TABLE_SHARE *get_table_share(THD *thd, const char *db, const char *table_name,
-                             const char *key, uint key_length, uint flags,
-                             my_hash_value_type hash_value);
-void release_table_share(TABLE_SHARE *share);
-TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name);
-
-// convenience helper: call get_table_share() without precomputed hash_value
-static inline TABLE_SHARE *get_table_share(THD *thd, const char *db,
-                                           const char *table_name,
-                                           const char *key, uint key_length,
-                                           uint flags)
-{
-  return get_table_share(thd, db, table_name, key, key_length, flags,
-                my_calc_hash(&table_def_cache, (uchar*) key, key_length));
-}
-
-// convenience helper: call get_table_share() without precomputed cache key
-static inline TABLE_SHARE *get_table_share(THD *thd, const char *db,
-                                           const char *table_name, uint flags)
-{
-  char	key[MAX_DBKEY_LENGTH];
-  uint	key_length;
-  key_length= create_table_def_key(key, db, table_name);
-  return get_table_share(thd, db, table_name, key, key_length, flags);
-}
-
-// convenience helper: call get_table_share() reusing the MDL cache key.
-// NOTE: lifetime of the returned TABLE_SHARE is limited by the
-// lifetime of the TABLE_LIST object!!!
-static inline TABLE_SHARE *get_table_share_shortlived(THD *thd, TABLE_LIST *tl,
-                                                      uint flags)
-{
-  const char *key;
-  uint        key_length= get_table_def_key(tl, &key);
-  return get_table_share(thd, tl->db, tl->table_name, key, key_length, flags);
-}
-
 TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type update,
                    uint lock_flags);
 
@@ -326,6 +243,7 @@ bool lock_tables(THD *thd, TABLE_LIST *t
 int decide_logging_format(THD *thd, TABLE_LIST *tables);
 void free_io_cache(TABLE *entry);
 void intern_close_table(TABLE *entry);
+void kill_delayed_threads_for_table(TABLE_SHARE *share);
 void close_thread_table(THD *thd, TABLE **table_ptr);
 bool close_temporary_tables(THD *thd);
 TABLE_LIST *unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
@@ -361,9 +279,6 @@ void close_all_tables_for_name(THD *thd,
                                ha_extra_function extra,
                                TABLE *skip_table);
 OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild);
-void tdc_remove_table(THD *thd, enum_tdc_remove_table_type remove_type,
-                      const char *db, const char *table_name,
-                      bool has_lock);
 bool tdc_open_view(THD *thd, TABLE_LIST *table_list, const char *alias,
                    const char *cache_key, uint cache_key_length,
                    MEM_ROOT *mem_root, uint flags);
@@ -377,7 +292,6 @@ static inline bool tdc_open_view(THD *th
   return tdc_open_view(thd, table_list, alias, key, key_length, mem_root, flags);
 }
 
-void tdc_flush_unused_tables();
 TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db,
                                   const char *table_name,
                                   bool no_error);
@@ -395,7 +309,6 @@ extern "C" int simple_raw_key_cmp(void*
 extern "C" int count_distinct_walk(void *elem, element_count count, void *arg);
 int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2);
 
-extern TABLE *unused_tables;
 extern Item **not_found_item;
 extern Field *not_found_field;
 extern Field *view_ref_found;

=== modified file 'sql/sql_manager.cc'
--- a/sql/sql_manager.cc	2012-02-15 17:08:08 +0000
+++ b/sql/sql_manager.cc	2013-08-14 08:48:50 +0000
@@ -110,7 +110,7 @@ pthread_handler_t handle_manager(void *a
 
     if (error == ETIMEDOUT || error == ETIME)
     {
-      tdc_flush_unused_tables();
+      tc_purge();
       error = 0;
       reset_flush_time = TRUE;
     }

=== modified file 'sql/sql_parse.cc'
--- a/sql/sql_parse.cc	2013-07-21 14:43:42 +0000
+++ b/sql/sql_parse.cc	2013-08-14 08:48:50 +0000
@@ -1600,8 +1600,8 @@ bool dispatch_command(enum enum_server_c
                         (int) thread_count, (ulong) thd->query_id,
                         current_global_status_var->long_query_count,
                         current_global_status_var->opened_tables,
-                        refresh_version,
-                        cached_open_tables(),
+                        tdc_refresh_version(),
+                        tc_records(),
                         (uint) (queries_per_second1000 / 1000),
                         (uint) (queries_per_second1000 % 1000));
 #ifdef EMBEDDED_LIBRARY

=== modified file 'sql/sql_show.cc'
--- a/sql/sql_show.cc	2013-08-12 12:17:51 +0000
+++ b/sql/sql_show.cc	2013-08-14 08:48:50 +0000
@@ -4424,7 +4424,7 @@ static int fill_schema_table_from_frm(TH
     goto end;
   }
 
-  share= get_table_share_shortlived(thd, &table_list, GTS_TABLE | GTS_VIEW);
+  share= tdc_acquire_share_shortlived(thd, &table_list, GTS_TABLE | GTS_VIEW);
   if (!share)
   {
     res= 0;
@@ -4476,9 +4476,7 @@ static int fill_schema_table_from_frm(TH
 
 
 end_share:
-  mysql_mutex_lock(&LOCK_open);
-  release_table_share(share);
-  mysql_mutex_unlock(&LOCK_open);
+  tdc_release_share(share);
 
 end:
   /*

=== modified file 'sql/sql_table.cc'
--- a/sql/sql_table.cc	2013-08-12 16:32:53 +0000
+++ b/sql/sql_table.cc	2013-08-14 08:48:50 +0000
@@ -2432,7 +2432,7 @@ int mysql_rm_table_no_locks(THD *thd, TA
     {
       char *end;
       /*
-        It could happen that table's share in the table_def_cache
+        It could happen that table's share in the table definition cache
         is the only thing that keeps the engine plugin loaded
         (if it is uninstalled and waits for the ref counter to drop to 0).
 

=== modified file 'sql/sql_test.cc'
--- a/sql/sql_test.cc	2013-07-21 14:39:19 +0000
+++ b/sql/sql_test.cc	2013-08-14 08:48:50 +0000
@@ -20,7 +20,7 @@
 #include "sql_priv.h"
 #include "unireg.h"
 #include "sql_test.h"
-#include "sql_base.h" // table_def_cache, table_cache_count, unused_tables
+#include "sql_base.h" // unused_tables
 #include "sql_show.h" // calc_sum_of_all_status
 #include "sql_select.h"
 #include "keycaches.h"
@@ -78,21 +78,21 @@ print_where(COND *cond,const char *info,
 
 static void print_cached_tables(void)
 {
-  uint idx,count,unused;
+  uint count= 0, unused= 0;
   TABLE_SHARE *share;
   TABLE *start_link, *lnk, *entry;
+  TDC_iterator tdc_it;
 
   compile_time_assert(TL_WRITE_ONLY+1 == array_elements(lock_descriptions));
 
   /* purecov: begin tested */
-  mysql_mutex_lock(&LOCK_open);
   puts("DB             Table                            Version  Thread  Open  Lock");
 
-  for (idx=unused=0 ; idx < table_def_cache.records ; idx++)
+  tdc_it.init();
+  mysql_mutex_lock(&LOCK_open);
+  while ((share= tdc_it.next()))
   {
-    share= (TABLE_SHARE*) my_hash_element(&table_def_cache, idx);
-
-    TABLE_SHARE::TABLE_list::Iterator it(share->used_tables);
+    TABLE_SHARE::TABLE_list::Iterator it(share->tdc.used_tables);
     while ((entry= it++))
     {
       printf("%-14.14s %-32s%6ld%8ld%6d  %s\n",
@@ -100,7 +100,7 @@ static void print_cached_tables(void)
              entry->in_use->thread_id, entry->db_stat ? 1 : 0,
              lock_descriptions[(int)entry->reginfo.lock_type]);
     }
-    it.init(share->free_tables);
+    it.init(share->tdc.free_tables);
     while ((entry= it++))
     {
       unused++;
@@ -109,7 +109,7 @@ static void print_cached_tables(void)
              0L, entry->db_stat ? 1 : 0, "Not in use");
     }
   }
-  count=0;
+  tdc_it.deinit();
   if ((start_link=lnk=unused_tables))
   {
     do
@@ -119,20 +119,18 @@ static void print_cached_tables(void)
 	printf("unused_links isn't linked properly\n");
 	return;
       }
-    } while (count++ < cached_open_tables() && (lnk=lnk->next) != start_link);
+    } while (count++ < tc_records() && (lnk=lnk->next) != start_link);
     if (lnk != start_link)
     {
       printf("Unused_links aren't connected\n");
     }
   }
+  mysql_mutex_unlock(&LOCK_open);
   if (count != unused)
     printf("Unused_links (%d) doesn't match table_def_cache: %d\n", count,
            unused);
-  printf("\nCurrent refresh version: %ld\n",refresh_version);
-  if (my_hash_check(&table_def_cache))
-    printf("Error: Table definition hash table is corrupted\n");
+  printf("\nCurrent refresh version: %ld\n", tdc_refresh_version());
   fflush(stdout);
-  mysql_mutex_unlock(&LOCK_open);
   /* purecov: end */
   return;
 }
@@ -485,7 +483,7 @@ static void display_table_locks(void)
   DYNAMIC_ARRAY saved_table_locks;
 
   (void) my_init_dynamic_array(&saved_table_locks,sizeof(TABLE_LOCK_INFO),
-                               cached_open_tables() + 20, 50,
+                               tc_records() + 20, 50,
                                MYF(MY_THREAD_SPECIFIC));
   mysql_mutex_lock(&THR_LOCK_lock);
   for (list= thr_lock_thread_list; list; list= list_rest(list))
@@ -616,7 +614,7 @@ Open tables:   %10lu\n\
 Open files:    %10lu\n\
 Open streams:  %10lu\n",
 	 tmp.opened_tables,
-	 (ulong) cached_open_tables(),
+	 (ulong) tc_records(),
 	 (ulong) my_file_opened,
 	 (ulong) my_stream_opened);
 

=== modified file 'sql/sys_vars.cc'
--- a/sql/sys_vars.cc	2013-08-13 11:35:36 +0000
+++ b/sql/sys_vars.cc	2013-08-14 08:48:50 +0000
@@ -2675,16 +2675,25 @@ static Sys_var_charptr Sys_system_time_z
 static Sys_var_ulong Sys_table_def_size(
        "table_definition_cache",
        "The number of cached table definitions",
-       GLOBAL_VAR(table_def_size), CMD_LINE(REQUIRED_ARG),
+       GLOBAL_VAR(tdc_size), CMD_LINE(REQUIRED_ARG),
        VALID_RANGE(TABLE_DEF_CACHE_MIN, 512*1024),
        DEFAULT(TABLE_DEF_CACHE_DEFAULT), BLOCK_SIZE(1));
 
 static Sys_var_ulong Sys_table_cache_size(
        "table_open_cache", "The number of cached open tables",
-       GLOBAL_VAR(table_cache_size), CMD_LINE(REQUIRED_ARG),
+       GLOBAL_VAR(tc_size), CMD_LINE(REQUIRED_ARG),
        VALID_RANGE(1, 512*1024), DEFAULT(TABLE_OPEN_CACHE_DEFAULT),
        BLOCK_SIZE(1));
 
+static ulong table_cache_instances;
+static Sys_var_ulong Sys_table_cache_instances(
+       "table_open_cache_instances",
+       "MySQL 5.6 compatible option. Not used or needed in MariaDB",
+       READ_ONLY GLOBAL_VAR(table_cache_instances), CMD_LINE(REQUIRED_ARG),
+       VALID_RANGE(1, 64), DEFAULT(1),
+       BLOCK_SIZE(1), NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(NULL),
+       ON_UPDATE(NULL), NULL);
+
 static Sys_var_ulong Sys_thread_cache_size(
        "thread_cache_size",
        "How many threads we should keep in a cache for reuse",

=== modified file 'sql/table.cc'
--- a/sql/table.cc	2013-08-12 13:46:35 +0000
+++ b/sql/table.cc	2013-08-14 08:48:50 +0000
@@ -31,7 +31,7 @@
 #include "sql_partition.h"       // mysql_unpack_partition,
                                  // fix_partition_func, partition_info
 #include "sql_acl.h"             // *_ACL, acl_getroot_no_password
-#include "sql_base.h"            // release_table_share
+#include "sql_base.h"
 #include "create_options.h"
 #include <m_ctype.h>
 #include "my_md5.h"
@@ -318,23 +318,9 @@ TABLE_SHARE *alloc_table_share(const cha
     /* TEMPORARY FIX: if true, this means this is mysql.gtid_slave_pos table */
     share->is_gtid_slave_pos= FALSE;
     share->table_category= get_table_category(& share->db, & share->table_name);
-    share->version= refresh_version;
     share->open_errno= ENOENT;
-
-    /*
-      Since alloc_table_share() can be called without any locking (for
-      example, ha_create_table... functions), we do not assign a table
-      map id here.  Instead we assign a value that is not used
-      elsewhere, and then assign a table map id inside open_table()
-      under the protection of the LOCK_open mutex.
-    */
-    share->table_map_id= ~0UL;
     share->cached_row_logging_check= -1;
 
-    share->used_tables.empty();
-    share->free_tables.empty();
-    share->m_flush_tickets.empty();
-
     init_sql_alloc(&share->stats_cb.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(0));
 
     memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root));
@@ -342,6 +328,7 @@ TABLE_SHARE *alloc_table_share(const cha
                      &share->LOCK_share, MY_MUTEX_INIT_SLOW);
     mysql_mutex_init(key_TABLE_SHARE_LOCK_ha_data,
                      &share->LOCK_ha_data, MY_MUTEX_INIT_FAST);
+    tdc_init_share(share);
   }
   DBUG_RETURN(share);
 }
@@ -354,7 +341,7 @@ TABLE_SHARE *alloc_table_share(const cha
     init_tmp_table_share()
     thd         thread handle
     share	Share to fill
-    key		Table_cache_key, as generated from create_table_def_key.
+    key		Table_cache_key, as generated from tdc_create_key.
 		must start with db name.    
     key_length	Length of key
     table_name	Table name
@@ -404,11 +391,6 @@ void init_tmp_table_share(THD *thd, TABL
     compatibility checks.
   */
   share->table_map_id= (ulong) thd->query_id;
-
-  share->used_tables.empty();
-  share->free_tables.empty();
-  share->m_flush_tickets.empty();
-
   DBUG_VOID_RETURN;
 }
 
@@ -443,6 +425,7 @@ void TABLE_SHARE::destroy()
   {
     mysql_mutex_destroy(&LOCK_share);
     mysql_mutex_destroy(&LOCK_ha_data);
+    tdc_deinit_share(this);
   }
   my_hash_free(&name_hash);
 
@@ -487,37 +470,7 @@ void free_table_share(TABLE_SHARE *share
 {
   DBUG_ENTER("free_table_share");
   DBUG_PRINT("enter", ("table: %s.%s", share->db.str, share->table_name.str));
-  DBUG_ASSERT(share->ref_count == 0);
-
-  if (share->m_flush_tickets.is_empty())
-  {
-    /*
-      No threads are waiting for this share to be flushed (the
-      share is not old, is for a temporary table, or just nobody
-      happens to be waiting for it). Destroy it.
-    */
-    share->destroy();
-  }
-  else
-  {
-    Wait_for_flush_list::Iterator it(share->m_flush_tickets);
-    Wait_for_flush *ticket;
-    /*
-      We're about to iterate over a list that is used
-      concurrently. Make sure this never happens without a lock.
-    */
-    mysql_mutex_assert_owner(&LOCK_open);
-
-    while ((ticket= it++))
-      (void) ticket->get_ctx()->m_wait.set_status(MDL_wait::GRANTED);
-    /*
-      If there are threads waiting for this share to be flushed,
-      the last one to receive the notification will destroy the
-      share. At this point the share is removed from the table
-      definition cache, so is OK to proceed here without waiting
-      for this thread to do the work.
-    */
-  }
+  share->destroy();
   DBUG_VOID_RETURN;
 }
 
@@ -596,7 +549,7 @@ inline bool is_system_table_name(const c
 
   NOTES
     This function is called when the table definition is not cached in
-    table_def_cache
+    table definition cache
     The data is returned in 'share', which is alloced by
     alloc_table_share().. The code assumes that share is initialized.
 */
@@ -2932,7 +2885,7 @@ int closefrm(register TABLE *table, bool
   if (free_share)
   {
     if (table->s->tmp_table == NO_TMP_TABLE)
-      release_table_share(table->s);
+      tdc_release_share(table->s);
     else
       free_table_share(table->s);
   }
@@ -3775,7 +3728,7 @@ bool TABLE_SHARE::visit_subgraph(Wait_fo
   if (gvisitor->m_lock_open_count++ == 0)
     mysql_mutex_lock(&LOCK_open);
 
-  TABLE_list::Iterator tables_it(used_tables);
+  TABLE_list::Iterator tables_it(tdc.used_tables);
 
   /*
     In case of multiple searches running in parallel, avoid going
@@ -3829,10 +3782,15 @@ bool TABLE_SHARE::visit_subgraph(Wait_fo
   @param abstime         Timeout for waiting as absolute time value.
   @param deadlock_weight Weight of this wait for deadlock detector.
 
-  @pre LOCK_open is write locked, the share is used (has
-       non-zero reference count), is marked for flush and
+  @pre LOCK_table_share is locked, the share is marked for flush and
        this connection does not reference the share.
-       LOCK_open will be unlocked temporarily during execution.
+       LOCK_table_share will be unlocked temporarily during execution.
+
+  It may happen that another FLUSH TABLES thread marked this share
+  for flush, but didn't yet purge it from table definition cache.
+  In this case we may start waiting for a table share that has no
+  references (ref_count == 0). We do this with assumption that this
+  another FLUSH TABLES thread is about to purge this share.
 
   @retval FALSE - Success.
   @retval TRUE  - Error (OOM, deadlock, timeout, etc...).
@@ -3845,19 +3803,14 @@ bool TABLE_SHARE::wait_for_old_version(T
   Wait_for_flush ticket(mdl_context, this, deadlock_weight);
   MDL_wait::enum_wait_status wait_status;
 
-  mysql_mutex_assert_owner(&LOCK_open);
-  /*
-    We should enter this method only when share's version is not
-    up to date and the share is referenced. Otherwise our
-    thread will never be woken up from wait.
-  */
-  DBUG_ASSERT(version != refresh_version && ref_count != 0);
+  mysql_mutex_assert_owner(&tdc.LOCK_table_share);
+  DBUG_ASSERT(has_old_version());
 
-  m_flush_tickets.push_front(&ticket);
+  tdc.m_flush_tickets.push_front(&ticket);
 
   mdl_context->m_wait.reset_status();
 
-  mysql_mutex_unlock(&LOCK_open);
+  mysql_mutex_unlock(&tdc.LOCK_table_share);
 
   mdl_context->will_wait_for(&ticket);
 
@@ -3868,18 +3821,22 @@ bool TABLE_SHARE::wait_for_old_version(T
 
   mdl_context->done_waiting_for();
 
-  mysql_mutex_lock(&LOCK_open);
+  mysql_mutex_lock(&tdc.LOCK_table_share);
 
-  m_flush_tickets.remove(&ticket);
+  tdc.m_flush_tickets.remove(&ticket);
 
-  if (m_flush_tickets.is_empty() && ref_count == 0)
+  if (tdc.m_flush_tickets.is_empty() && tdc.ref_count == 0)
   {
     /*
       If our thread was the last one using the share,
       we must destroy it here.
     */
+    mysql_mutex_unlock(&tdc.LOCK_table_share);
     destroy();
   }
+  else
+    mysql_mutex_unlock(&tdc.LOCK_table_share);
+
 
   /*
     In cases when our wait was aborted by KILL statement,
@@ -3924,7 +3881,7 @@ bool TABLE_SHARE::wait_for_old_version(T
 
 void TABLE::init(THD *thd, TABLE_LIST *tl)
 {
-  DBUG_ASSERT(s->ref_count > 0 || s->tmp_table != NO_TMP_TABLE);
+  DBUG_ASSERT(s->tdc.ref_count > 0 || s->tmp_table != NO_TMP_TABLE);
 
   if (thd->lex->need_correct_ident())
     alias_name_used= my_strcasecmp(table_alias_charset,

=== modified file 'sql/table.h'
--- a/sql/table.h	2013-08-12 13:46:35 +0000
+++ b/sql/table.h	2013-08-14 08:48:50 +0000
@@ -479,7 +479,7 @@ TABLE_CATEGORY get_table_category(const
 
 struct TABLE_share;
 
-extern ulong refresh_version;
+extern ulong tdc_refresh_version(void);
 
 typedef struct st_table_field_type
 {
@@ -599,15 +599,27 @@ struct TABLE_SHARE
   TYPELIB *intervals;			/* pointer to interval info */
   mysql_mutex_t LOCK_ha_data;           /* To protect access to ha_data */
   mysql_mutex_t LOCK_share;             /* To protect TABLE_SHARE */
-  TABLE_SHARE *next, **prev;            /* Link to unused shares */
 
-  /*
-    Doubly-linked (back-linked) lists of used and unused TABLE objects
-    for this share.
-  */
   typedef I_P_List <TABLE, TABLE_share> TABLE_list;
-  TABLE_list used_tables;
-  TABLE_list free_tables;
+  struct
+  {
+    /**
+      Protects ref_count and m_flush_tickets.
+    */
+    mysql_mutex_t LOCK_table_share;
+    TABLE_SHARE *next, **prev;            /* Link to unused shares */
+    uint ref_count;                       /* How many TABLE objects uses this */
+    /**
+      List of tickets representing threads waiting for the share to be flushed.
+    */
+    Wait_for_flush_list m_flush_tickets;
+    /*
+      Doubly-linked (back-linked) lists of used and unused TABLE objects
+      for this share.
+    */
+    TABLE_list used_tables;
+    TABLE_list free_tables;
+  } tdc;
 
   LEX_CUSTRING tabledef_version;
 
@@ -674,7 +686,6 @@ struct TABLE_SHARE
   /** Per-page checksums or not. */
   enum ha_choice page_checksum;
 
-  uint ref_count;                       /* How many TABLE objects uses this */
   uint key_block_size;			/* create key_block_size, if used */
   uint stats_sample_pages;		/* number of pages to sample during
 					stats estimation, if used, otherwise 0. */
@@ -759,11 +770,6 @@ struct TABLE_SHARE
   /** Instrumentation for this table share. */
   PSI_table_share *m_psi;
 
-  /**
-    List of tickets representing threads waiting for the share to be flushed.
-  */
-  Wait_for_flush_list m_flush_tickets;
-
   /*
     Set share's table cache key and update its db and table name appropriately.
 
@@ -835,7 +841,7 @@ struct TABLE_SHARE
   /** Is this table share being expelled from the table definition cache?  */
   inline bool has_old_version() const
   {
-    return version != refresh_version;
+    return version != tdc_refresh_version();
   }
 
   /**

=== added file 'sql/table_cache.cc'
--- a/sql/table_cache.cc	1970-01-01 00:00:00 +0000
+++ b/sql/table_cache.cc	2013-08-14 08:48:50 +0000
@@ -0,0 +1,1280 @@
+/* Copyright (c) 2000, 2012, Oracle and/or its affiliates.
+   Copyright (c) 2010, 2011 Monty Program Ab
+   Copyright (C) 2013 Sergey Vojtovich and MariaDB Foundation
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; version 2 of the License.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
+
+/**
+  @file
+  Table definition cache and table cache implementation.
+
+  Table definition cache actions:
+  - add new TABLE_SHARE object to cache (tdc_acquire_share())
+  - acquire TABLE_SHARE object from cache (tdc_acquire_share())
+  - release TABLE_SHARE object to cache (tdc_release_share())
+  - purge unused TABLE_SHARE objects from cache (tdc_purge())
+  - remove TABLE_SHARE object from cache (tdc_remove_table())
+  - get number of TABLE_SHARE objects in cache (tdc_records())
+
+  Table cache actions:
+  - add new TABLE object to cache (tc_add_table())
+  - acquire TABLE object from cache (tc_acquire_table())
+  - release TABLE object to cache (tc_release_table())
+  - purge unused TABLE objects from cache (tc_purge())
+  - purge unused TABLE objects of a table from cache (tdc_remove_table())
+  - get number of TABLE objects in cache (tc_records())
+
+  Dependencies:
+  - intern_close_table(): frees TABLE object
+  - kill_delayed_threads_for_table()
+  - close_cached_tables(): flush tables on shutdown
+  - alloc_table_share()
+  - free_table_share()
+
+  Table cache invariants:
+  - TABLE_SHARE::used_tables shall not contain objects with TABLE::in_use == 0
+  - TABLE_SHARE::free_tables shall not contain objects with TABLE::in_use != 0
+  - unused_tables shall not contain objects with TABLE::in_use != 0
+  - cached TABLE object must be either in TABLE_SHARE::used_tables or in
+    TABLE_SHARE::free_tables
+*/
+
+#include "my_global.h"
+#include "hash.h"
+#include "table.h"
+#include "sql_base.h"
+
+/** Configuration. */
+ulong tdc_size; /**< Table definition cache threshold for LRU eviction. */
+ulong tc_size; /**< Table cache threshold for LRU eviction. */
+
+/** Data collections. */
+static HASH tdc_hash; /**< Collection of TABLE_SHARE objects. */
+/** Collection of unused TABLE_SHARE objects. */
+static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
+TABLE *unused_tables; /**< Collection of unused TABLE objects. */
+
+static int64 tdc_version;  /* Increments on each reload */ 
+static int64 last_table_id;
+static bool tdc_inited;
+
+static uint tc_count; /**< Number of TABLE objects in table cache. */
+
+
+/**
+  Protects used and unused lists in the TABLE_SHARE object,
+  LRU lists of used TABLEs.
+
+  tc_count
+  unused_tables
+  TABLE::next
+  TABLE::prev
+  TABLE_SHARE::tdc.free_tables
+  TABLE_SHARE::tdc.used_tables
+*/
+
+mysql_mutex_t LOCK_open;
+
+
+/**
+  Protects unused shares list.
+
+  TABLE_SHARE::tdc.prev
+  TABLE_SHARE::tdc.next
+  oldest_unused_share
+  end_of_unused_share
+*/
+
+static mysql_mutex_t LOCK_unused_shares;
+static mysql_rwlock_t LOCK_tdc; /**< Protects tdc_hash. */
+static mysql_rwlock_t LOCK_flush; /**< Sync tc_purge() and tdc_remove_table(). */
+my_atomic_rwlock_t LOCK_tdc_atomics; /**< Protects tdc_version. */
+
+#ifdef HAVE_PSI_INTERFACE
+static PSI_mutex_key key_LOCK_open, key_LOCK_unused_shares,
+                     key_TABLE_SHARE_LOCK_table_share;
+static PSI_mutex_info all_tc_mutexes[]=
+{
+  { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL },
+  { &key_LOCK_unused_shares, "LOCK_unused_shares", PSI_FLAG_GLOBAL },
+  { &key_TABLE_SHARE_LOCK_table_share, "TABLE_SHARE::tdc.LOCK_table_share", 0 }
+};
+
+static PSI_rwlock_key key_rwlock_LOCK_tdc, key_rwlock_LOCK_flush;
+static PSI_rwlock_info all_tc_rwlocks[]=
+{
+  { &key_rwlock_LOCK_tdc, "LOCK_tdc", PSI_FLAG_GLOBAL },
+  { &key_rwlock_LOCK_flush, "LOCK_flush", PSI_FLAG_GLOBAL }
+};
+
+
+static void init_tc_psi_keys(void)
+{
+  const char *category= "sql";
+  int count;
+
+  count= array_elements(all_tc_mutexes);
+  mysql_mutex_register(category, all_tc_mutexes, count);
+
+  count= array_elements(all_tc_rwlocks);
+  mysql_rwlock_register(category, all_tc_rwlocks, count);
+}
+#endif
+
+
+/*
+  Auxiliary routines for manipulating with per-share used/unused and
+  global unused lists of TABLE objects and tc_count counter.
+  Responsible for preserving invariants between those lists, counter
+  and TABLE::in_use member.
+  In fact those routines implement sort of implicit table cache as
+  part of table definition cache.
+*/
+
+
+/**
+  Get number of TABLE objects (used and unused) in table cache.
+
+  @todo Protect tc_count so it is read atomically.
+*/
+
+uint tc_records(void)
+{
+  return tc_count;
+}
+
+
+/**
+  Free all unused TABLE objects.
+
+  While locked:
+  - remove unused objects from TABLE_SHARE::tdc.free_tables lists
+  - reset unused_tables
+  - decrement tc_count
+
+  While unlocked:
+  - free resources related to unused objects
+
+  @note This is called by 'handle_manager' when one wants to
+        periodicly flush all not used tables.
+*/
+
+void tc_purge(void)
+{
+  mysql_mutex_lock(&LOCK_open);
+  if (unused_tables)
+  {
+    TABLE *table= unused_tables, *next;
+    unused_tables->prev->next= 0;
+    do
+    {
+      unused_tables->s->tdc.free_tables.remove(unused_tables);
+      tc_count--;
+    } while ((unused_tables= unused_tables->next));
+    mysql_rwlock_rdlock(&LOCK_flush);
+    mysql_mutex_unlock(&LOCK_open);
+
+    do
+    {
+      next= table->next;
+      intern_close_table(table);
+    } while ((table= next));
+    mysql_rwlock_unlock(&LOCK_flush);
+  }
+  else
+    mysql_mutex_unlock(&LOCK_open);
+}
+
+
+/**
+  Verify consistency of used/unused lists (for debugging).
+*/
+
+#ifdef EXTRA_DEBUG
+static void check_unused(THD *thd)
+{
+  uint count= 0, open_files= 0;
+  TABLE *cur_link, *start_link, *entry;
+  TABLE_SHARE *share;
+  TDC_iterator tdc_it;
+
+  tdc_it.init();
+  mysql_mutex_lock(&LOCK_open);
+  if ((start_link=cur_link=unused_tables))
+  {
+    do
+    {
+      if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
+      {
+	DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
+	return; /* purecov: inspected */
+      }
+    } while (count++ < tc_count &&
+	     (cur_link=cur_link->next) != start_link);
+    if (cur_link != start_link)
+    {
+      DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
+    }
+  }
+  while ((share= tdc_it.next()))
+  {
+    TABLE_SHARE::TABLE_list::Iterator it(share->tdc.free_tables);
+    while ((entry= it++))
+    {
+      /*
+        We must not have TABLEs in the free list that have their file closed.
+      */
+      DBUG_ASSERT(entry->db_stat && entry->file);
+      /* Merge children should be detached from a merge parent */
+      if (entry->in_use)
+      {
+        DBUG_PRINT("error",("Used table is in share's list of unused tables")); /* purecov: inspected */
+      }
+      /* extra() may assume that in_use is set */
+      entry->in_use= thd;
+      DBUG_ASSERT(!thd || !entry->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
+      entry->in_use= 0;
+
+      count--;
+      open_files++;
+    }
+    it.init(share->tdc.used_tables);
+    while ((entry= it++))
+    {
+      if (!entry->in_use)
+      {
+        DBUG_PRINT("error",("Unused table is in share's list of used tables")); /* purecov: inspected */
+      }
+      open_files++;
+    }
+  }
+  mysql_mutex_unlock(&LOCK_open);
+  tdc_it.deinit();
+  if (count != 0)
+  {
+    DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
+                       count)); /* purecov: inspected */
+  }
+}
+#else
+#define check_unused(A)
+#endif
+
+
+/**
+  Remove unused TABLE object from table cache.
+
+  @pre LOCK_open is locked, table is not used.
+
+  While locked:
+  - remove object from TABLE_SHARE::tdc.free_tables
+  - remove object from unused_tables
+
+  @note This is helper routine, supposed to be used by table cache
+  methods only.
+*/
+
+static void tc_remove_table(TABLE *table)
+{
+  mysql_mutex_assert_owner(&LOCK_open);
+  DBUG_ASSERT(!table->in_use);
+  /* Remove from per-share chain of unused TABLE objects. */
+  table->s->tdc.free_tables.remove(table);
+
+  /* And global unused chain. */
+  table->next->prev= table->prev;
+  table->prev->next= table->next;
+  if (table == unused_tables)
+  {
+    unused_tables= unused_tables->next;
+    if (table == unused_tables)
+      unused_tables= 0;
+  }
+  tc_count--;
+}
+
+
+/**
+  Add new TABLE object to table cache.
+
+  @pre TABLE object is used by caller.
+
+  Added object cannot be evicted or acquired.
+
+  While locked:
+  - add object to TABLE_SHARE::tdc.used_tables
+  - increment tc_count
+  - evict LRU object from table cache if we reached threshold
+
+  While unlocked: 
+  - free evicted object
+*/
+
+void tc_add_table(THD *thd, TABLE *table)
+{
+  DBUG_ASSERT(table->in_use == thd);
+  mysql_mutex_lock(&LOCK_open);
+  table->s->tdc.used_tables.push_front(table);
+  tc_count++;
+  /* If we have too many TABLE instances around, try to get rid of them */
+  if (tc_count > tc_size && unused_tables)
+  {
+    TABLE *purge_table= unused_tables;
+    tc_remove_table(purge_table);
+    mysql_rwlock_rdlock(&LOCK_flush);
+    mysql_mutex_unlock(&LOCK_open);
+    intern_close_table(purge_table);
+    mysql_rwlock_unlock(&LOCK_flush);
+    check_unused(thd);
+  }
+  else
+    mysql_mutex_unlock(&LOCK_open);
+}
+
+
+/**
+  Acquire TABLE object from table cache.
+
+  @pre share must be protected against removal.
+
+  Acquired object cannot be evicted or acquired again.
+
+  While locked:
+  - pop object from TABLE_SHARE::tdc.free_tables()
+  - remove share protection
+  - remove object from unused_tables
+  - add object to TABLE_SHARE::tdc.used_tables()
+  - mark object used by thd
+
+  @note share protection is kept if there are no unused objects.
+
+  @return TABLE object, or NULL if no unused objects.
+*/
+
+static TABLE *tc_acquire_table(THD *thd, TABLE_SHARE *share)
+{
+  TABLE *table;
+
+  mysql_mutex_lock(&LOCK_open);
+  if (!(table= share->tdc.free_tables.pop_front()))
+  {
+    mysql_mutex_unlock(&LOCK_open);
+    return 0;
+  }
+  mysql_rwlock_unlock(&LOCK_tdc);
+  DBUG_ASSERT(!table->in_use);
+
+  /* Unlink table from global unused tables list. */
+  if (table == unused_tables)
+  {                                             // First unused
+    unused_tables=unused_tables->next;	        // Remove from link
+    if (table == unused_tables)
+      unused_tables=0;
+  }
+  table->prev->next=table->next;		/* Remove from unused list */
+  table->next->prev=table->prev;
+  table->in_use= thd;
+  /* Add table to list of used tables for this share. */
+  table->s->tdc.used_tables.push_front(table);
+  mysql_mutex_unlock(&LOCK_open);
+
+  /* The ex-unused table must be fully functional. */
+  DBUG_ASSERT(table->db_stat && table->file);
+  /* The children must be detached from the table. */
+  DBUG_ASSERT(! table->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
+  check_unused(thd);
+  return table;
+}
+
+
+/**
+  Release TABLE object to table cache.
+
+  @pre object is used by caller.
+
+  Released object may be evicted or acquired again.
+
+  While locked:
+  - mark object not in use by any thread
+  - remove object from TABLE_SHARE::tdc.used_tables
+  - if object is marked for purge, decrement tc_count
+  - add object to TABLE_SHARE::tdc.free_tables
+  - add object to unused_tables
+  - evict LRU object from table cache if we reached threshold
+
+  While unlocked: 
+  - free evicted/purged object
+
+  @note Another thread may mark share for purge any moment (even
+  after version check). It means to-be-purged object may go to
+  unused lists. This other thread is expected to call tc_purge(),
+  which is synchronized with us on LOCK_open.
+
+  @return
+    @retval true  object purged
+    @retval false object released
+*/
+
+bool tc_release_table(TABLE *table)
+{
+  THD *thd __attribute__((unused))= table->in_use;
+  DBUG_ASSERT(table->in_use);
+  DBUG_ASSERT(table->file);
+
+  mysql_mutex_lock(&LOCK_open);
+  /* Remove table from the list of tables used in this share. */
+  table->s->tdc.used_tables.remove(table);
+  table->in_use= 0;
+  if (table->s->has_old_version() || table->needs_reopen() || !tdc_size)
+  {
+    tc_count--;
+    mysql_rwlock_rdlock(&LOCK_flush);
+    mysql_mutex_unlock(&LOCK_open);
+    intern_close_table(table);
+    mysql_rwlock_unlock(&LOCK_flush);
+    return true;
+  }
+  /* Add table to the list of unused TABLE objects for this share. */
+  table->s->tdc.free_tables.push_front(table);
+  /* Also link it last in the global list of unused TABLE objects. */
+  if (unused_tables)
+  {
+    table->next=unused_tables;
+    table->prev=unused_tables->prev;
+    unused_tables->prev=table;
+    table->prev->next=table;
+  }
+  else
+    unused_tables=table->next=table->prev=table;
+  /*
+    We free the least used table, not the subject table,
+    to keep the LRU order.
+  */
+  if (tc_count > tc_size)
+  {
+    TABLE *purge_table= unused_tables;
+    tc_remove_table(purge_table);
+    mysql_rwlock_rdlock(&LOCK_flush);
+    mysql_mutex_unlock(&LOCK_open);
+    intern_close_table(purge_table);
+    mysql_rwlock_unlock(&LOCK_flush);
+  }
+  else
+    mysql_mutex_unlock(&LOCK_open);
+  check_unused(thd);
+  return false;
+}
+
+
+extern "C" uchar *tdc_key(const uchar *record, size_t *length,
+                          my_bool not_used __attribute__((unused)))
+{
+  TABLE_SHARE *entry= (TABLE_SHARE*) record;
+  *length= entry->table_cache_key.length;
+  return (uchar*) entry->table_cache_key.str;
+}
+
+
+/**
+  Delete share from hash and free share object.
+
+  @return
+    @retval 0 Success
+    @retval 1 Share is referenced
+*/
+
+static int tdc_delete_share_from_hash(TABLE_SHARE *share)
+{
+  DBUG_ENTER("tdc_delete_share_from_hash");
+  mysql_rwlock_wrlock(&LOCK_tdc);
+  mysql_mutex_lock(&share->tdc.LOCK_table_share);
+  if (--share->tdc.ref_count)
+  {
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    mysql_rwlock_unlock(&LOCK_tdc);
+    DBUG_RETURN(1);
+  }
+  my_hash_delete(&tdc_hash, (uchar*) share);
+  /* Notify PFS early, while still locked. */
+  PSI_CALL_release_table_share(share->m_psi);
+  share->m_psi= 0;
+  mysql_rwlock_unlock(&LOCK_tdc);
+
+  if (share->tdc.m_flush_tickets.is_empty())
+  {
+    /* No threads are waiting for this share to be flushed, destroy it. */
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    free_table_share(share);
+  }
+  else
+  {
+    Wait_for_flush_list::Iterator it(share->tdc.m_flush_tickets);
+    Wait_for_flush *ticket;
+    while ((ticket= it++))
+      (void) ticket->get_ctx()->m_wait.set_status(MDL_wait::GRANTED);
+    /*
+      If there are threads waiting for this share to be flushed,
+      the last one to receive the notification will destroy the
+      share. At this point the share is removed from the table
+      definition cache, so is OK to proceed here without waiting
+      for this thread to do the work.
+    */
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+  }
+  DBUG_RETURN(0);
+}
+
+
+/**
+  Initialize table definition cache.
+
+  @retval  0  Success
+  @retval !0  Error
+*/
+
+int tdc_init(void)
+{
+  DBUG_ENTER("tdc_init");
+#ifdef HAVE_PSI_INTERFACE
+  init_tc_psi_keys();
+#endif
+  tdc_inited= true;
+  mysql_mutex_init(key_LOCK_open, &LOCK_open, MY_MUTEX_INIT_FAST);
+  mysql_mutex_record_order(&LOCK_active_mi, &LOCK_open);
+  /*
+    We must have LOCK_open before LOCK_global_system_variables because
+    LOCK_open is held while sql_plugin.cc::intern_sys_var_ptr() is called.
+  */
+  mysql_mutex_record_order(&LOCK_open, &LOCK_global_system_variables);
+  mysql_mutex_init(key_LOCK_unused_shares, &LOCK_unused_shares,
+                   MY_MUTEX_INIT_FAST);
+  mysql_rwlock_init(key_rwlock_LOCK_tdc, &LOCK_tdc);
+  mysql_rwlock_init(key_rwlock_LOCK_flush, &LOCK_flush);
+  my_atomic_rwlock_init(&LOCK_tdc_atomics);
+  oldest_unused_share= &end_of_unused_share;
+  end_of_unused_share.tdc.prev= &oldest_unused_share;
+  tdc_version= 1L;  /* Increments on each reload */
+  DBUG_RETURN(my_hash_init(&tdc_hash, &my_charset_bin, tdc_size, 0, 0, tdc_key,
+                           0, 0));
+}
+
+
+/**
+  Notify table definition cache that process of shutting down server
+  has started so it has to keep number of TABLE and TABLE_SHARE objects
+  minimal in order to reduce number of references to pluggable engines.
+*/
+
+void tdc_start_shutdown(void)
+{
+  DBUG_ENTER("table_def_start_shutdown");
+  if (tdc_inited)
+  {
+    /*
+      Ensure that TABLE and TABLE_SHARE objects which are created for
+      tables that are open during process of plugins' shutdown are
+      immediately released. This keeps number of references to engine
+      plugins minimal and allows shutdown to proceed smoothly.
+    */
+    tdc_size= 0;
+    /* Free all cached but unused TABLEs and TABLE_SHAREs. */
+    close_cached_tables(NULL, NULL, FALSE, LONG_TIMEOUT);
+  }
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Deinitialize table definition cache.
+*/
+
+void tdc_deinit(void)
+{
+  DBUG_ENTER("tdc_deinit");
+  if (tdc_inited)
+  {
+    tdc_inited= false;
+    my_hash_free(&tdc_hash);
+    my_atomic_rwlock_destroy(&LOCK_tdc_atomics);
+    mysql_rwlock_destroy(&LOCK_flush);
+    mysql_rwlock_destroy(&LOCK_tdc);
+    mysql_mutex_destroy(&LOCK_unused_shares);
+    mysql_mutex_destroy(&LOCK_open);
+  }
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Get number of cached table definitions.
+
+  @return Number of cached table definitions
+*/
+
+ulong tdc_records(void)
+{
+  ulong records;
+  DBUG_ENTER("tdc_records");
+  mysql_rwlock_rdlock(&LOCK_tdc);
+  records= tdc_hash.records;
+  mysql_rwlock_unlock(&LOCK_tdc);
+  DBUG_RETURN(records);
+}
+
+
+void tdc_purge(bool all)
+{
+  DBUG_ENTER("tdc_purge");
+  for (;;)
+  {
+    TABLE_SHARE *share;
+    if (!all)
+    {
+      mysql_rwlock_rdlock(&LOCK_tdc);
+      if (tdc_hash.records <= tdc_size)
+      {
+        mysql_rwlock_unlock(&LOCK_tdc);
+        break;
+      }
+      mysql_rwlock_unlock(&LOCK_tdc);
+    }
+
+    mysql_mutex_lock(&LOCK_unused_shares);
+    if (!oldest_unused_share->tdc.next)
+    {
+      mysql_mutex_unlock(&LOCK_unused_shares);
+      break;
+    }
+
+    share= oldest_unused_share;
+    *share->tdc.prev= share->tdc.next;
+    share->tdc.next->tdc.prev= share->tdc.prev;
+    /* Concurrent thread may start using share again, reset prev and next. */
+    share->tdc.prev= 0;
+    share->tdc.next= 0;
+    mysql_mutex_lock(&share->tdc.LOCK_table_share);
+    share->tdc.ref_count++;
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    mysql_mutex_unlock(&LOCK_unused_shares);
+
+    tdc_delete_share_from_hash(share);
+  }
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Prepeare table share for use with table definition cache.
+*/
+
+void tdc_init_share(TABLE_SHARE *share)
+{
+  DBUG_ENTER("tdc_init_share");
+  mysql_mutex_init(key_TABLE_SHARE_LOCK_table_share,
+                   &share->tdc.LOCK_table_share, MY_MUTEX_INIT_FAST);
+  share->tdc.m_flush_tickets.empty();
+  share->tdc.used_tables.empty();
+  share->tdc.free_tables.empty();
+  tdc_assign_new_table_id(share);
+  share->version= tdc_refresh_version();
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Release table definition cache specific resources of table share.
+*/
+
+void tdc_deinit_share(TABLE_SHARE *share)
+{
+  DBUG_ENTER("tdc_deinit_share");
+  DBUG_ASSERT(share->tdc.ref_count == 0);
+  DBUG_ASSERT(share->tdc.m_flush_tickets.is_empty());
+  DBUG_ASSERT(share->tdc.used_tables.is_empty());
+  DBUG_ASSERT(share->tdc.free_tables.is_empty());
+  mysql_mutex_destroy(&share->tdc.LOCK_table_share);
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Lock table share.
+
+  Find table share with given db.table_name in table definition cache. Return
+  locked table share if found.
+
+  Locked table share means:
+  - table share is protected against removal from table definition cache
+  - no other thread can acquire/release table share
+
+  Caller is expected to unlock table share with tdc_unlock_share().
+
+  @retval  0 Share not found
+  @retval !0 Pointer to locked table share 
+*/
+
+TABLE_SHARE *tdc_lock_share(const char *db, const char *table_name)
+{
+  char key[MAX_DBKEY_LENGTH];
+  uint key_length;
+
+  DBUG_ENTER("tdc_lock_share");
+  key_length= tdc_create_key(key, db, table_name);
+
+  mysql_rwlock_rdlock(&LOCK_tdc);
+  TABLE_SHARE* share= (TABLE_SHARE*) my_hash_search(&tdc_hash,
+                                                    (uchar*) key, key_length);
+  if (share && !share->error)
+    mysql_mutex_lock(&share->tdc.LOCK_table_share);
+  else
+    share= 0;
+  mysql_rwlock_unlock(&LOCK_tdc);
+  DBUG_RETURN(share);
+}
+
+
+/**
+  Unlock share locked by tdc_lock_share().
+*/
+
+void tdc_unlock_share(TABLE_SHARE *share)
+{
+  DBUG_ENTER("tdc_unlock_share");
+  mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+  DBUG_VOID_RETURN;
+}
+
+
+/*
+  Get TABLE_SHARE for a table.
+
+  tdc_acquire_share()
+  thd                   Thread handle
+  table_list            Table that should be opened
+  key                   Table cache key
+  key_length            Length of key
+  flags                 operation: what to open table or view
+
+  IMPLEMENTATION
+    Get a table definition from the table definition cache.
+    If it doesn't exist, create a new from the table definition file.
+
+  RETURN
+   0  Error
+   #  Share for table
+*/
+
+TABLE_SHARE *tdc_acquire_share(THD *thd, const char *db, const char *table_name,
+                               const char *key, uint key_length, uint flags,
+                               TABLE **out_table)
+{
+  TABLE_SHARE *share;
+  bool was_unused;
+  my_hash_value_type hash_value;
+  DBUG_ENTER("tdc_acquire_share");
+
+  hash_value= my_calc_hash(&tdc_hash, (uchar*) key, key_length);
+
+  mysql_rwlock_rdlock(&LOCK_tdc);
+  share= (TABLE_SHARE*) my_hash_search_using_hash_value(&tdc_hash, hash_value,
+                                                        (uchar*) key,
+                                                        key_length);
+  if (!share)
+  {
+    TABLE_SHARE *new_share;
+    mysql_rwlock_unlock(&LOCK_tdc);
+
+    if (!(new_share= alloc_table_share(db, table_name, key, key_length)))
+      DBUG_RETURN(0);
+    new_share->error= OPEN_FRM_OPEN_ERROR;
+
+    mysql_rwlock_wrlock(&LOCK_tdc);
+    share= (TABLE_SHARE*) my_hash_search_using_hash_value(&tdc_hash, hash_value,
+                                                          (uchar*) key,
+                                                          key_length);
+    if (!share)
+    {
+      bool need_purge;
+
+      share= new_share;
+      mysql_mutex_lock(&share->tdc.LOCK_table_share);
+      if (my_hash_insert(&tdc_hash, (uchar*) share))
+      {
+        mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+        mysql_rwlock_unlock(&LOCK_tdc);
+        free_table_share(share);
+        DBUG_RETURN(0);
+      }
+      need_purge= tdc_hash.records > tdc_size;
+      mysql_rwlock_unlock(&LOCK_tdc);
+
+      /* note that tdc_acquire_share() *always* uses discovery */
+      open_table_def(thd, share, flags | GTS_USE_DISCOVERY);
+      share->tdc.ref_count++;
+      mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+
+      if (share->error)
+      {
+        tdc_delete_share_from_hash(share);
+        DBUG_RETURN(0);
+      }
+      else if (need_purge)
+        tdc_purge(false);
+      if (out_table)
+        *out_table= 0;
+      share->m_psi= PSI_CALL_get_table_share(false, share);
+      goto end;
+    }
+    free_table_share(new_share);
+  }
+
+  /* cannot force discovery of a cached share */
+  DBUG_ASSERT(!(flags & GTS_FORCE_DISCOVERY));
+
+  if (out_table && (flags & GTS_TABLE))
+  {
+    if ((*out_table= tc_acquire_table(thd, share)))
+    {
+      DBUG_ASSERT(!(flags & GTS_NOLOCK));
+      DBUG_ASSERT(!share->tdc.prev && !share->tdc.next);
+      DBUG_ASSERT(!share->error);
+      DBUG_ASSERT(!share->is_view);
+      DBUG_RETURN(share);
+    }
+  }
+
+  mysql_mutex_lock(&share->tdc.LOCK_table_share);
+  mysql_rwlock_unlock(&LOCK_tdc);
+
+  /*
+     We found an existing table definition. Return it if we didn't get
+     an error when reading the table definition from file.
+  */
+  if (share->error)
+  {
+    open_table_error(share, share->error, share->open_errno);
+    goto err;
+  }
+
+  if (share->is_view && !(flags & GTS_VIEW))
+  {
+    open_table_error(share, OPEN_FRM_NOT_A_TABLE, ENOENT);
+    goto err;
+  }
+  if (!share->is_view && !(flags & GTS_TABLE))
+  {
+    open_table_error(share, OPEN_FRM_NOT_A_VIEW, ENOENT);
+    goto err;
+  }
+
+  was_unused= !share->tdc.ref_count;
+  share->tdc.ref_count++;
+  mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+  if (was_unused)
+  {
+    mysql_mutex_lock(&LOCK_unused_shares);
+    if (share->tdc.prev)
+    {
+      /*
+        Share was not used before and it was in the old_unused_share list
+        Unlink share from this list
+      */
+      DBUG_PRINT("info", ("Unlinking from not used list"));
+      *share->tdc.prev= share->tdc.next;
+      share->tdc.next->tdc.prev= share->tdc.prev;
+      share->tdc.next= 0;
+      share->tdc.prev= 0;
+    } 
+    mysql_mutex_unlock(&LOCK_unused_shares);
+  }
+  DBUG_ASSERT(share->tdc.prev == 0 && share->tdc.next == 0);
+
+end:
+  DBUG_PRINT("exit", ("share: 0x%lx  ref_count: %u",
+                      (ulong) share, share->tdc.ref_count));
+  if (flags & GTS_NOLOCK)
+  {
+    tdc_release_share(share);
+    /*
+      if GTS_NOLOCK is requested, the returned share pointer cannot be used,
+      the share it points to may go away any moment.
+      But perhaps the caller is only interested to know whether a share or
+      table existed?
+      Let's return an invalid pointer here to catch dereferencing attempts.
+    */
+    share= (TABLE_SHARE*) 1;
+  }
+  DBUG_RETURN(share);
+
+err:
+  mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+  DBUG_RETURN(0);
+}
+
+
+/**
+  Release table share acquired by tdc_acquire_share().
+*/
+
+void tdc_release_share(TABLE_SHARE *share)
+{
+  DBUG_ENTER("tdc_release_share");
+  
+  mysql_mutex_lock(&share->tdc.LOCK_table_share);
+  DBUG_PRINT("enter",
+             ("share: 0x%lx  table: %s.%s  ref_count: %u  version: %lu",
+              (ulong) share, share->db.str, share->table_name.str,
+              share->tdc.ref_count, share->version));
+  DBUG_ASSERT(share->tdc.ref_count);
+
+  if (share->tdc.ref_count > 1)
+  {
+    share->tdc.ref_count--;
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    DBUG_VOID_RETURN;
+  }
+  mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+
+  mysql_mutex_lock(&LOCK_unused_shares);
+  mysql_mutex_lock(&share->tdc.LOCK_table_share);
+  if (share->has_old_version())
+  {
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    mysql_mutex_unlock(&LOCK_unused_shares);
+    tdc_delete_share_from_hash(share);
+    DBUG_VOID_RETURN;
+  }
+  if (--share->tdc.ref_count)
+  {
+    mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+    mysql_mutex_unlock(&LOCK_unused_shares);
+    DBUG_VOID_RETURN;
+  }
+  /* Link share last in used_table_share list */
+  DBUG_PRINT("info", ("moving share to unused list"));
+  DBUG_ASSERT(share->tdc.next == 0);
+  share->tdc.prev= end_of_unused_share.tdc.prev;
+  *end_of_unused_share.tdc.prev= share;
+  end_of_unused_share.tdc.prev= &share->tdc.next;
+  share->tdc.next= &end_of_unused_share;
+  mysql_mutex_unlock(&share->tdc.LOCK_table_share);
+  mysql_mutex_unlock(&LOCK_unused_shares);
+
+  /* Delete the least used share to preserve LRU order. */
+  tdc_purge(false);
+  DBUG_VOID_RETURN;
+}
+
+
+static TABLE_SHARE *tdc_delete_share(const char *db, const char *table_name)
+{
+  TABLE_SHARE *share;
+  DBUG_ENTER("tdc_delete_share");
+
+  while ((share= tdc_lock_share(db, table_name)))
+  {
+    share->tdc.ref_count++;
+    if (share->tdc.ref_count > 1)
+    {
+      tdc_unlock_share(share);
+      DBUG_RETURN(share);
+    }
+    tdc_unlock_share(share);
+
+    mysql_mutex_lock(&LOCK_unused_shares);
+    if (share->tdc.prev)
+    {
+      *share->tdc.prev= share->tdc.next;
+      share->tdc.next->tdc.prev= share->tdc.prev;
+      /* Concurrent thread may start using share again, reset prev and next. */
+      share->tdc.prev= 0;
+      share->tdc.next= 0;
+    } 
+    mysql_mutex_unlock(&LOCK_unused_shares);
+
+    if (!tdc_delete_share_from_hash(share))
+      break;
+  }
+  DBUG_RETURN(0);
+}
+
+
+/**
+   Remove all or some (depending on parameter) instances of TABLE and
+   TABLE_SHARE from the table definition cache.
+
+   @param  thd          Thread context
+   @param  remove_type  Type of removal:
+                        TDC_RT_REMOVE_ALL     - remove all TABLE instances and
+                                                TABLE_SHARE instance. There
+                                                should be no used TABLE objects
+                                                and caller should have exclusive
+                                                metadata lock on the table.
+                        TDC_RT_REMOVE_NOT_OWN - remove all TABLE instances
+                                                except those that belong to
+                                                this thread. There should be
+                                                no TABLE objects used by other
+                                                threads and caller should have
+                                                exclusive metadata lock on the
+                                                table.
+                        TDC_RT_REMOVE_UNUSED  - remove all unused TABLE
+                                                instances (if there are no
+                                                used instances will also
+                                                remove TABLE_SHARE).
+                        TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE -
+                                                remove all TABLE instances
+                                                except those that belong to
+                                                this thread, but don't mark
+                                                TABLE_SHARE as old. There
+                                                should be no TABLE objects
+                                                used by other threads and
+                                                caller should have exclusive
+                                                metadata lock on the table.
+   @param  db           Name of database
+   @param  table_name   Name of table
+   @param  kill_delayed_threads     If TRUE, kill INSERT DELAYED threads
+
+   @note It assumes that table instances are already not used by any
+   (other) thread (this should be achieved by using meta-data locks).
+*/
+
+bool tdc_remove_table(THD *thd, enum_tdc_remove_table_type remove_type,
+                      const char *db, const char *table_name,
+                      bool kill_delayed_threads)
+{
+  TABLE *table;
+  TABLE_SHARE *share;
+  bool found= false;
+  DBUG_ENTER("tdc_remove_table");
+  DBUG_PRINT("enter",("name: %s  remove_type: %d", table_name, remove_type));
+
+  DBUG_ASSERT(remove_type == TDC_RT_REMOVE_UNUSED ||
+              thd->mdl_context.is_lock_owner(MDL_key::TABLE, db, table_name,
+                                             MDL_EXCLUSIVE));
+
+  if ((share= tdc_delete_share(db, table_name)))
+  {
+    I_P_List <TABLE, TABLE_share> purge_tables;
+    purge_tables.empty();
+
+    mysql_mutex_lock(&LOCK_open);
+    if (kill_delayed_threads)
+      kill_delayed_threads_for_table(share);
+
+    TABLE_SHARE::TABLE_list::Iterator it(share->tdc.free_tables);
+#ifndef DBUG_OFF
+    if (remove_type == TDC_RT_REMOVE_ALL)
+      DBUG_ASSERT(share->tdc.used_tables.is_empty());
+    else if (remove_type == TDC_RT_REMOVE_NOT_OWN)
+    {
+      TABLE_SHARE::TABLE_list::Iterator it2(share->tdc.used_tables);
+      while ((table= it2++))
+        DBUG_ASSERT(table->in_use == thd);
+    }
+#endif
+    /*
+      Set share's version to zero in order to ensure that it gets
+      automatically deleted once it is no longer referenced.
+
+      Note that code in TABLE_SHARE::wait_for_old_version() assumes that
+      incrementing of refresh_version is followed by purge of unused table
+      shares.
+    */
+    if (remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE)
+      share->version= 0;
+
+    while ((table= it++))
+    {
+      tc_remove_table(table);
+      purge_tables.push_front(table);
+    }
+    mysql_rwlock_rdlock(&LOCK_flush);
+    mysql_mutex_unlock(&LOCK_open);
+
+    while ((table= purge_tables.pop_front()))
+      intern_close_table(table);
+    mysql_rwlock_unlock(&LOCK_flush);
+
+    check_unused(thd);
+    tdc_release_share(share);
+
+    /* Wait for concurrent threads to free unused objects. */
+    mysql_rwlock_wrlock(&LOCK_flush);
+    mysql_rwlock_unlock(&LOCK_flush);
+
+    found= true;
+  }
+  DBUG_ASSERT(found || remove_type != TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE);
+  DBUG_RETURN(found);
+}
+
+
+/**
+  Check if table's share is being removed from the table definition
+  cache and, if yes, wait until the flush is complete.
+
+  @param thd             Thread context.
+  @param table_list      Table which share should be checked.
+  @param timeout         Timeout for waiting.
+  @param deadlock_weight Weight of this wait for deadlock detector.
+
+  @retval 0       Success. Share is up to date or has been flushed.
+  @retval 1       Error (OOM, was killed, the wait resulted
+                  in a deadlock or timeout). Reported.
+*/
+
+int tdc_wait_for_old_version(THD *thd, const char *db, const char *table_name,
+                             ulong wait_timeout, uint deadlock_weight)
+{
+  TABLE_SHARE *share;
+  int res= FALSE;
+
+  if ((share= tdc_lock_share(db, table_name)))
+  {
+    if (share->has_old_version())
+    {
+      struct timespec abstime;
+      set_timespec(abstime, wait_timeout);
+      res= share->wait_for_old_version(thd, &abstime, deadlock_weight);
+    }
+    else
+      tdc_unlock_share(share);
+  }
+  return res;
+}
+
+
+ulong tdc_refresh_version(void)
+{
+  my_atomic_rwlock_rdlock(&LOCK_tdc_atomics);
+  ulong v= my_atomic_load64(&tdc_version);
+  my_atomic_rwlock_wrunlock(&LOCK_tdc_atomics);
+  return v;
+}
+
+
+void tdc_increment_refresh_version(void)
+{
+  my_atomic_rwlock_wrlock(&LOCK_tdc_atomics);
+#ifndef DBUG_OFF
+  ulong v= my_atomic_add64(&tdc_version, 1);
+#else
+  my_atomic_add64(&tdc_version, 1);
+#endif
+  my_atomic_rwlock_wrunlock(&LOCK_tdc_atomics);
+  DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu", v));
+}
+
+
+/**
+  Initialize table definition cache iterator.
+*/
+
+void TDC_iterator::init(void)
+{
+  DBUG_ENTER("TDC_iterator::init");
+  idx= 0;
+  mysql_rwlock_rdlock(&LOCK_tdc);
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Deinitialize table definition cache iterator.
+*/
+
+void TDC_iterator::deinit(void)
+{
+  DBUG_ENTER("TDC_iterator::deinit");
+  mysql_rwlock_unlock(&LOCK_tdc);
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Get next TABLE_SHARE object from table definition cache.
+
+  Object is protected against removal from table definition cache.
+
+  @note Returned TABLE_SHARE is not guaranteed to be fully initialized:
+  tdc_acquire_share() added new share, but didn't open it yet. If caller
+  needs fully initializer share, it must lock table share mutex.
+*/
+
+TABLE_SHARE *TDC_iterator::next(void)
+{
+  TABLE_SHARE *share= 0;
+  DBUG_ENTER("TDC_iterator::next");
+  if (idx < tdc_hash.records)
+  {
+    share= (TABLE_SHARE*) my_hash_element(&tdc_hash, idx);
+    idx++;
+  }
+  DBUG_RETURN(share);
+}
+
+
+/*
+  Function to assign a new table map id to a table share.
+
+  PARAMETERS
+
+    share - Pointer to table share structure
+
+  DESCRIPTION
+
+    We are intentionally not checking that share->mutex is locked
+    since this function should only be called when opening a table
+    share and before it is entered into the table definition cache
+    (meaning that it cannot be fetched by another thread, even
+    accidentally).
+
+  PRE-CONDITION(S)
+
+    share is non-NULL
+    last_table_id_lock initialized (tdc_inited)
+
+  POST-CONDITION(S)
+
+    share->table_map_id is given a value that with a high certainty is
+    not used by any other table (the only case where a table id can be
+    reused is on wrap-around, which means more than 4 billion table
+    share opens have been executed while one table was open all the
+    time).
+
+    share->table_map_id is not ~0UL.
+*/
+
+void tdc_assign_new_table_id(TABLE_SHARE *share)
+{
+  ulong tid;
+  DBUG_ENTER("assign_new_table_id");
+  DBUG_ASSERT(share);
+  DBUG_ASSERT(tdc_inited);
+
+  /*
+    There is one reserved number that cannot be used.  Remember to
+    change this when 6-byte global table id's are introduced.
+  */
+  do
+  {
+    my_atomic_rwlock_wrlock(&LOCK_tdc_atomics);
+    tid= my_atomic_add64(&last_table_id, 1);
+    my_atomic_rwlock_wrunlock(&LOCK_tdc_atomics);
+  } while (unlikely(tid == ~0UL));
+
+  share->table_map_id= tid;
+  DBUG_PRINT("info", ("table_id= %lu", share->table_map_id));
+  DBUG_VOID_RETURN;
+}

=== added file 'sql/table_cache.h'
--- a/sql/table_cache.h	1970-01-01 00:00:00 +0000
+++ b/sql/table_cache.h	2013-08-14 08:48:50 +0000
@@ -0,0 +1,134 @@
+/* Copyright (c) 2000, 2012, Oracle and/or its affiliates.
+   Copyright (c) 2010, 2011 Monty Program Ab
+   Copyright (C) 2013 Sergey Vojtovich and MariaDB Foundation
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; version 2 of the License.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
+
+
+enum enum_tdc_remove_table_type
+{
+  TDC_RT_REMOVE_ALL,
+  TDC_RT_REMOVE_NOT_OWN,
+  TDC_RT_REMOVE_UNUSED,
+  TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE
+};
+
+extern ulong tdc_size;
+extern ulong tc_size;
+extern TABLE *unused_tables;    /* FIXME: make private */
+extern mysql_mutex_t LOCK_open; /* FIXME: make private */
+
+extern int tdc_init(void);
+extern void tdc_start_shutdown(void);
+extern void tdc_deinit(void);
+extern ulong tdc_records(void);
+extern void tdc_purge(bool all);
+extern void tdc_init_share(TABLE_SHARE *share);
+extern void tdc_deinit_share(TABLE_SHARE *share);
+extern TABLE_SHARE *tdc_lock_share(const char *db, const char *table_name);
+extern void tdc_unlock_share(TABLE_SHARE *share);
+extern TABLE_SHARE *tdc_acquire_share(THD *thd, const char *db,
+                                      const char *table_name,
+                                      const char *key, uint key_length,
+                                      uint flags, TABLE **out_table);
+extern void tdc_release_share(TABLE_SHARE *share);
+extern bool tdc_remove_table(THD *thd, enum_tdc_remove_table_type remove_type,
+                             const char *db, const char *table_name,
+                             bool kill_delayed_threads);
+extern int tdc_wait_for_old_version(THD *thd, const char *db,
+                                    const char *table_name,
+                                    ulong wait_timeout, uint deadlock_weight);
+extern ulong tdc_refresh_version(void);
+extern void tdc_increment_refresh_version(void);
+extern void tdc_assign_new_table_id(TABLE_SHARE *share);
+
+extern uint tc_records(void);
+extern void tc_purge(void);
+extern void tc_add_table(THD *thd, TABLE *table);
+extern bool tc_release_table(TABLE *table);
+
+/**
+  Create a table cache key for non-temporary table.
+
+  @param key         Buffer for key (must be at least NAME_LEN*2+2 bytes).
+  @param db          Database name.
+  @param table_name  Table name.
+
+  @return Length of key.
+*/
+
+inline uint tdc_create_key(char *key, const char *db, const char *table_name)
+{
+  /*
+    In theory caller should ensure that both db and table_name are
+    not longer than NAME_LEN bytes. In practice we play safe to avoid
+    buffer overruns.
+  */
+  return (uint) (strmake(strmake(key, db, NAME_LEN) + 1, table_name,
+                         NAME_LEN) - key + 1);
+}
+
+/**
+  Convenience helper: call tdc_acquire_share() without out_table.
+*/
+
+static inline TABLE_SHARE *tdc_acquire_share(THD *thd, const char *db,
+                                             const char *table_name,
+                                             const char *key,
+                                             uint key_length, uint flags)
+{
+  return tdc_acquire_share(thd, db, table_name, key, key_length, flags, 0);
+}
+
+
+/**
+  Convenience helper: call tdc_acquire_share() without precomputed cache key.
+*/
+
+static inline TABLE_SHARE *tdc_acquire_share(THD *thd, const char *db,
+                                             const char *table_name, uint flags)
+{
+  char key[MAX_DBKEY_LENGTH];
+  uint key_length;
+  key_length= tdc_create_key(key, db, table_name);
+  return tdc_acquire_share(thd, db, table_name, key, key_length, flags);
+}
+
+
+/**
+  Convenience helper: call tdc_acquire_share() reusing the MDL cache key.
+
+  @note lifetime of the returned TABLE_SHARE is limited by the
+        lifetime of the TABLE_LIST object!!!
+*/
+
+uint get_table_def_key(const TABLE_LIST *table_list, const char **key);
+
+static inline TABLE_SHARE *tdc_acquire_share_shortlived(THD *thd, TABLE_LIST *tl,
+                                                        uint flags)
+{
+  const char *key;
+  uint        key_length= get_table_def_key(tl, &key);
+  return tdc_acquire_share(thd, tl->db, tl->table_name, key, key_length, flags);
+}
+
+
+class TDC_iterator
+{
+  ulong idx;
+public:
+  void init(void);
+  void deinit(void);
+  TABLE_SHARE *next(void);
+};

=== modified file 'storage/connect/ha_connect.cc'
--- a/storage/connect/ha_connect.cc	2013-07-23 14:29:16 +0000
+++ b/storage/connect/ha_connect.cc	2013-08-14 08:48:50 +0000
@@ -3220,7 +3220,7 @@ int ha_connect::delete_or_rename_table(c
       *tabname == '#')
     goto fin;
 
-  key_length= create_table_def_key(key, db, tabname);
+  key_length= tdc_create_key(key, db, tabname);
 
   // share contains the option struct that we need
   if (!(share= alloc_table_share(db, tabname, key, key_length)))

=== modified file 'storage/innobase/handler/ha_innodb.cc'
--- a/storage/innobase/handler/ha_innodb.cc	2013-08-12 19:27:43 +0000
+++ b/storage/innobase/handler/ha_innodb.cc	2013-08-14 08:48:50 +0000
@@ -40,6 +40,7 @@ this program; if not, write to the Free
 #include <my_base.h>	// HA_OPTION_*
 #include <mysys_err.h>
 #include <innodb_priv.h>
+#include <table_cache.h>
 
 #ifdef _WIN32
 #include <io.h>
@@ -1705,16 +1706,16 @@ innobase_get_stmt(
 }
 
 /**********************************************************************//**
-Get the current setting of the table_def_size global parameter. We do
+Get the current setting of the tdc_size global parameter. We do
 a dirty read because for one there is no synchronization object and
 secondly there is little harm in doing so even if we get a torn read.
- at return	value of table_def_size */
+ at return	value of tdc_size */
 UNIV_INTERN
 ulint
 innobase_get_table_cache_size(void)
 /*===============================*/
 {
-	return(table_def_size);
+	return(tdc_size);
 }
 
 /**********************************************************************//**
@@ -3154,8 +3155,8 @@ innobase_init(
 
 	if (innobase_open_files < 10) {
 		innobase_open_files = 300;
-		if (srv_file_per_table && table_cache_size > 300) {
-			innobase_open_files = table_cache_size;
+		if (srv_file_per_table && tc_size > 300) {
+			innobase_open_files = tc_size;
 		}
 	}
 	srv_max_n_open_files = (ulint) innobase_open_files;



More information about the commits mailing list