Commit graph

256 commits

Author SHA1 Message Date
Monty
e9a2082634 Merge remote-tracking branch 'origin/10.2' into bb-10.2-ext
Conflicts:
	mysql-test/r/cte_nonrecursive.result
	mysql-test/suite/galera/r/galera_bf_abort.result
	mysql-test/suite/galera/r/galera_bf_abort_get_lock.result
	mysql-test/suite/galera/r/galera_bf_abort_sleep.result
	mysql-test/suite/galera/r/galera_enum.result
	mysql-test/suite/galera/r/galera_fk_conflict.result
	mysql-test/suite/galera/r/galera_insert_multi.result
	mysql-test/suite/galera/r/galera_many_indexes.result
	mysql-test/suite/galera/r/galera_mdl_race.result
	mysql-test/suite/galera/r/galera_nopk_bit.result
	mysql-test/suite/galera/r/galera_nopk_blob.result
	mysql-test/suite/galera/r/galera_nopk_large_varchar.result
	mysql-test/suite/galera/r/galera_nopk_unicode.result
	mysql-test/suite/galera/r/galera_pk_bigint_signed.result
	mysql-test/suite/galera/r/galera_pk_bigint_unsigned.result
	mysql-test/suite/galera/r/galera_serializable.result
	mysql-test/suite/galera/r/galera_toi_drop_database.result
	mysql-test/suite/galera/r/galera_toi_lock_exclusive.result
	mysql-test/suite/galera/r/galera_toi_truncate.result
	mysql-test/suite/galera/r/galera_unicode_pk.result
	mysql-test/suite/galera/r/galera_var_auto_inc_control_off.result
	mysql-test/suite/galera/r/galera_wsrep_log_conficts.result
	sql/field.cc
	sql/rpl_gtid.cc
	sql/share/errmsg-utf8.txt
	sql/sql_acl.cc
	sql/sql_parse.cc
	sql/sql_partition_admin.cc
	sql/sql_prepare.cc
	sql/sql_repl.cc
	sql/sql_table.cc
	sql/sql_yacc.yy
2018-01-05 16:52:40 +02:00
Monty
5e0b13d173 Fixed wrong arguments to printf and related functions
Other things, mainly to get
create_mysqld_error_find_printf_error tool to work:

- Added protection to not include mysqld_error.h twice
- Include "unireg.h" instead of "mysqld_error.h" in server
- Added protection if ER_XX messages are already defined
- Removed wrong calls to my_error(ER_OUTOFMEMORY) as
  my_malloc() and my_alloc will do this automatically
- Added missing %s to ER_DUP_QUERY_NAME
- Removed old and wrong calls to my_strerror() when using
  MY_ERROR_ON_RENAME (wrong merge)
- Fixed deadlock error message from Galera. Before the extra
  information given to ER_LOCK_DEADLOCK was missing because
  ER_LOCK_DEADLOCK doesn't provide any extra information.

I kept #ifdef mysqld_error_find_printf_error_used in sql_acl.h
to make it easy to do this kind of check again in the future
2018-01-04 16:24:09 +02:00
Monty
536215e32f Added DBUG_ASSERT_AS_PRINTF compile flag
If compiling a non DBUG binary with
-DDBUG_ASSERT_AS_PRINTF asserts will be
changed to printf + stack trace (of stack
trace are enabled).

- Changed #ifndef DBUG_OFF to
  #ifdef DBUG_ASSERT_EXISTS
  for those DBUG_OFF that was just used to enable
  assert
- Assert checking that could greatly impact
  performance where changed to DBUG_ASSERT_SLOW which
  is not affected by DBUG_ASSERT_AS_PRINTF
- Added one extra option to my_print_stacktrace() to
  get more silent in case of stack trace printing as
  part of assert.
2017-08-24 01:05:50 +02:00
Michael Widenius
4aaa38d26e Enusure that my_global.h is included first
- Added sql/mariadb.h file that should be included first by files in sql
  directory, if sql_plugin.h is not used (sql_plugin.h adds SHOW variables
  that must be done before my_global.h is included)
- Removed a lot of include my_global.h from include files
- Removed include's of some files that my_global.h automatically includes
- Removed duplicated include's of my_sys.h
- Replaced include my_config.h with my_global.h
2017-08-24 01:05:44 +02:00
Sergey Vojtovich
dd710e7552 MDEV-12882 - Assertion failed in MDL_context::upgrade_shared_lock
Relaxed assertion (in MySQL it was removed).
For "LOCK TABLES t1 WRITE CONCURRENT, t1 READ" upgrade lock to weakest
existing suitable lock, which is MDL_SHARED_NO_READ_WRITE.
2017-06-26 16:11:22 +04:00
Marko Mäkelä
3d615e4b1a Merge branch 'bb-10.2-ext' into 10.3
This excludes MDEV-12472 (InnoDB should accept XtraDB parameters,
warning that they are ignored). In other words, MariaDB 10.3 will not
recognize any XtraDB-specific parameters.
2017-06-02 09:36:04 +03:00
Monty
6a779a6d28 Make SEQUENCE working with replication
- Old sequence code forced row based replication for any statements that
  refered to a sequence table. What is new is that row based replication
  is now sequence aware:
   - NEXT VALUE is now generating a short row based event with only
     next_value and round being replicated.
   - Short row based events are now on the slave updated as trough
     SET_VALUE(sequence_name)
   - Full row based events are on the slave updated with a full insert,
     which is practically same as ALTER SEQUENCE.
- INSERT on a SEQUENCE table does now a EXCLUSIVE LOCK to ensure that
  it is logged in binary log before any following NEXT VALUE calls.
- Enable all sequence tests and fixed found bugs
- ALTER SEQUENCE doesn't anymore allow changes that makes the next_value
  outside of allowed range
- SEQUENCE changes are done with TL_WRITE_ALLOW_WRITE. Because of this
  one can generate a statement for MyISAM with both
  TL_WRITE_CONCURRENT_INSERT and TL_WRITE_ALLOW_WRITE. To fix a warning
  I had to add an extra test in thr_lock.c for this.
- Removed UPDATE of SEQUENCE (no need to support this as we
  have ALTER SEQUENCE, which takes the EXCLUSIVE lock properly.
- Removed DBUG_ASSERT() in MDL_context::upgrade_shared_lock. This was
  removed upstream in MySQL 5.6 in 72f823de453.
- Simplified test in decided_logging_format() by using sql_command_flags()
- Fix that we log DROP SEQUENCE correctly.
- Fixed that Aria works with SEQUENCE
2017-05-23 21:12:27 +03:00
Alexander Barkov
15d98ddc2a Merge remote-tracking branch 'origin/bb-10.2-ext' into 10.3 2017-04-03 17:35:55 +04:00
Sergei Golubchik
da4d71d10d Merge branch '10.1' into 10.2 2017-03-30 12:48:42 +02:00
Sergey Vojtovich
8026cd6202 MDEV-11379, MDEV-11388 - [WAIT n|NOWAIT]
Extended syntax so that it is now possible to set lock_wait_timeout for the
following statements:
SELECT ... FOR UPDATE [WAIT n|NOWAIT]
SELECT ... LOCK IN SHARED MODE [WAIT n|NOWAIT]
LOCK TABLE ... [WAIT n|NOWAIT]
CREATE ... INDEX ON tbl_name (index_col_name, ...) [WAIT n|NOWAIT] ...
ALTER TABLE tbl_name [WAIT n|NOWAIT] ...
OPTIMIZE TABLE tbl_name [WAIT n|NOWAIT]
DROP INDEX ... [WAIT n|NOWAIT]
TRUNCATE TABLE tbl_name [WAIT n|NOWAIT]
RENAME TABLE tbl_name [WAIT n|NOWAIT] ...
DROP TABLE tbl_name [WAIT n|NOWAIT] ...

Valid range of lock_wait_timeout and innodb_lock_wait_timeout was extended so
that 0 is acceptable value (means no wait).

This is amended AliSQL patch. We prefer Oracle syntax for [WAIT n|NOWAIT]
instead of original [WAIT [n]|NO_WAIT].
2017-03-22 19:08:24 +04:00
Nirbhay Choubey
6da2adfaa2 MDEV-12005: GET_LOCK: Fractional part of timeout is ignored
In order to include the fractional part, convert lock_wait_timeout
(in secs) to nanoseconds before calculating the absolute time for
timeout.
2017-02-07 13:54:46 -05:00
Sergey Vojtovich
8774a02364 MDEV-11227 - mysqlimport -l doesn't issue UNLOCK TABLES
Implementation of MDEV-7660 introduced unwanted incompatible change:
modifications under LOCK TABLES with autocommit enabled are rolled back on
disconnect. Previously everything was committed, because LOCK TABLES didn't
adjust autocommit setting.

This patch restores original behavior by reverting some changes done in
MDEV-7660:
- sql/sql_parse.cc: do not reset autocommit on LOCK TABLES
- sql/sql_base.cc: do not set autocommit on UNLOCK TABLES
- test cases: main.lock_tables_lost_commit, main.partition_explicit_prune,
  rpl.rpl_switch_stm_row_mixed, tokudb.nested_txn_implicit_commit,
  tokudb_bugs.db806

But it makes InnoDB tables under LOCK TABLES ... READ [LOCAL] not protected
against DML. To restore protection some changes from WL#6671 were merged,
specifically MDL_SHARED_READ_ONLY and test cases.

WL#6671 merge highlights:
- Not all tests merged.
- In MySQL LOCK TABLES ... READ acquires MDL_SHARED_READ_ONLY for all engines,
  in MariaDB MDL_SHARED_READ is always acquired first and then upgraded to
  MDL_SHARED_READ_ONLY for InnoDB only.
- The above allows us to omit MDL_SHARED_WRITE_LOW_PRIO implementation in
  MariaDB, which is rather useless with InnoDB. In MySQL it is needed to
  preserve locking behavior between low priority writes and LOCK TABLES ... READ
  for non-InnoDB engines (covered by sys_vars.sql_low_priority_updates_func).
- Omitted HA_NO_READ_LOCAL_LOCK, we rely on lock_count() instead.
- Omitted "piglets": in MariaDB stream of DML against InnoDB table may lead to
  concurrent LOCK TABLES ... READ starvation.
- HANDLER ... OPEN acquires MDL_SHARED_READ instead of MDL_SHARED in MariaDB.
- Omitted SNRW->X MDL lock upgrade for IMPORT/DISCARD TABLESPAECE under LOCK
  TABLES.
- Omitted strong locks for views, triggers and SP under LOCK TABLES.
- Omitted IX schema lock for LOCK TABLES READ.
- Omitted deadlock weight juggling for LOCK TABLES.

Full WL#6671 merge status:
- innodb.innodb-lock: fully merged
- main.alter_table: not merged due to different HANDLER solution
- main.debug_sync: fully merged
- main.handler_innodb: not merged due to different HANDLER solution
- main.handler_myisam: not merged due to different HANDLER solution
- main.innodb_mysql_lock: fully merged
- main.insert_notembedded: fully merged
- main.lock: not merged (due to no strong locks for views)
- main.lock_multi: not merged
- main.lock_sync: fully merged (partially in MDEV-7660)
- main.mdl_sync: not merged
- main.partition_debug_sync: not merged due to different HANDLER solution
- main.status: fully merged
- main.view: fully merged
- perfschema.mdl_func: not merged (no such test in MariaDB)
- perfschema.table_aggregate_global_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_global_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_global_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_global_4u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_hist_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_hist_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_hist_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_hist_4u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_thread_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_thread_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_thread_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_aggregate_thread_4u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_global_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_global_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_global_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_global_4u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_hist_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_hist_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_hist_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_hist_4u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_thread_2u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_thread_2u_3t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_thread_4u_2t: not merged (didn't fail in MariaDB)
- perfschema.table_lock_aggregate_thread_4u_3t: not merged (didn't fail in MariaDB)
- sys_vars.sql_low_priority_updates_func: not merged
- include/thr_rwlock.h: not merged, rw_pr_lock_assert_write_owner and
  rw_pr_lock_assert_not_write_owner are macros in MariaDB
- sql/handler.h: not merged (HA_NO_READ_LOCAL_LOCK)
- sql/mdl.cc: partially merged (MDL_SHARED_READ_ONLY only)
- sql/mdl.h: partially merged (MDL_SHARED_READ_ONLY only)
- sql/lock.cc: fully merged
- sql/sp_head.cc: not merged
- sql/sp_head.h: not merged
- sql/sql_base.cc: partially merged (MDL_SHARED_READ_ONLY only)
- sql/sql_base.h: not merged
- sql/sql_class.cc: fully merged
- sql/sql_class.h: fully merged
- sql/sql_handler.cc: merged partially (different solution in MariaDB)
- sql/sql_parse.cc: partially merged, mostly omitted low priority write part
- sql/sql_reload.cc: not merged comment change
- sql/sql_table.cc: not merged SNRW->X upgrade for IMPORT/DISCARD TABLESPACE
- sql/sql_view.cc: not merged
- sql/sql_yacc.yy: not merged (MDL_SHARED_WRITE_LOW_PRIO, MDL_SHARED_READ_ONLY)
- sql/table.cc: not merged (MDL_SHARED_WRITE_LOW_PRIO)
- sql/table.h: not merged (MDL_SHARED_WRITE_LOW_PRIO)
- sql/trigger.cc: not merged
- storage/innobase/handler/ha_innodb.cc: merged store_lock()/lock_count()
  changes (in MDEV-7660), didn't merge HA_NO_READ_LOCAL_LOCK
- storage/innobase/handler/ha_innodb.h: fully merged in MDEV-7660
- storage/myisammrg/ha_myisammrg.cc: not merged comment change
- storage/perfschema/table_helper.cc: not merged (no MDL support in MariaDB PFS)
- unittest/gunit/mdl-t.cc: not merged
- unittest/gunit/mdl_sync-t.cc: not merged

MariaDB specific changes:
- handler.heap: different HANDLER solution, MDEV-7660
- handler.innodb: different HANDLER solution, MDEV-7660
- handler.interface: different HANDLER solution, MDEV-7660
- handler.myisam: different HANDLER solution, MDEV-7660
- main.mdl_sync: MDEV-7660 specific changes
- main.partition_debug_sync: removed test due to different HANDLER solution,
  MDEV-7660
- main.truncate_coverage: removed test due to different HANDLER solution,
  MDEV-7660
- mysql-test/include/mtr_warnings.sql: additional cleanup, MDEV-7660
- mysql-test/lib/v1/mtr_report.pl: additional cleanup, MDEV-7660
- plugin/metadata_lock_info/metadata_lock_info.cc: not in MySQL
- sql/sql_handler.cc: MariaDB specific fix for mysql_ha_read(), MDEV-7660
2016-12-21 13:18:45 +04:00
Sergei Golubchik
06b7fce9f2 Merge branch '10.1' into 10.2 2016-09-09 08:33:08 +02:00
Sergei Golubchik
6b1863b830 Merge branch '10.0' into 10.1 2016-08-25 12:40:09 +02:00
Monty
b51109693e MDEV-10630 rpl.rpl_mdev6020 fails in buildbot with timeout
The issue was that when running with valgrind the wait for master_pos_Wait()
was not long enough.

This patch also fixes two other failures that could affect rpl_mdev6020:
- check_if_conflicting_replication_locks() didn't properly check domains
- 'did_mark_start_commit' was after signals to other threads was sent which could
  get the variable read too early.
2016-08-22 10:16:00 +03:00
Monty
98e36b2999 With parallel replication we have had a couple of bugs where DDL's
(like DROP TABLE) has been scheduled before conflicting DDL's (like INSERT)
are commited.

What makes these bugs hard to detect is that in most cases any wrong
schduling are caught by MDL locks. It's only when there are timing issues
that the bugs (usually deadlocks) are noticed.

This patch adds a DBUG_ASSERT() that detects, in parallel replication,
if a DDL is scheduled before any depending DML'S are commited.
It does this be checking if there are any conflicting replication locks
when the DDL is about to wait for getting it's MDL lock.

I also did some minor code cleanups in sql_base.cc to make this code
similar to other related code.
2016-08-12 20:02:23 +03:00
Nirbhay Choubey
355bf4fbb5 Cleanup around wsrep mdl exception. 2016-07-30 14:36:41 -04:00
Monty
4dc5075860 Fixed compiler warnings and test failures found by buildbot
Fixed ccfilter to detect errors where the column is included in the error message
2016-06-24 02:25:14 +03:00
Sergey Vojtovich
82a96926a7 MDEV-9728 - Hard crash in metadata_lock_info
metadata_lock_info plugin called MDL_context::find_ticket() to obtain lock
duration, which in turn iterates foreign thread private lists. These lists
can be updated by owner thread without protection.

Fixed by iterating threads (instead of MDL locks and tickets) and obtaining
data through APC.

Also fixed mdl_iterate_lock() to initialize iterator under prlock protection.
2016-06-21 17:04:57 +04:00
Nirbhay Choubey
cceec7858f Merge branch '10.0-galera' into bb-10.1-serg 2016-02-24 01:21:40 -05:00
sjaakola
32df0b1aac refs codership/mysql-wsrep#233
- avoiding the race condition, by not grabbing thd->LOCK_wsrep_thd for
  accessing thd->wsrep_exec_mode. The caller is same thread and exec mode
  can only be changed by self.
2016-02-23 00:22:04 -05:00
sjaakola
18f160d954 refs codership/mysql-wsrep#233
- added dbug sync points for further mtr test for this issue
2016-02-23 00:13:12 -05:00
Sergei Golubchik
2fc3dc393d Merge branch '10.1' into bb-10.1-serg 2015-11-20 09:31:13 +01:00
Monty
1e156e1436 Fixed compile warnings on Solaris 2015-11-20 10:00:06 +02:00
Sergei Golubchik
7f19330c59 Merge branch 'github/10.0-galera' into 10.1 2015-11-19 17:48:36 +01:00
Philip Stoev
43b2a451fe refs codership/mysql-wsrep#202 Added schema info into wsrep messages
Added schema info to wsrep messages above debug level.
2015-10-19 01:56:04 -07:00
sjaakola
2106fed865 Refs codership/mysql-wsrep#113
- changed BF thread's MDL wait to never timeout
- all explicit locks are now honored by BF threads
2015-09-09 21:37:17 -04:00
sjaakola
63c5bee535 Refs codership/mysql-wsrep#113 - Extended the protection of local FLUSH
sessions to cover all exclusive MDL locks
2015-09-09 21:31:16 -04:00
Nirbhay Choubey
dced5146bd Merge branch '10.0-galera' into 10.1 2015-07-14 16:05:29 -04:00
Monty
7332af49e4 - Renaming variables so that they don't shadow others (After this patch one can compile with -Wshadow and get much fewer warnings)
- Changed ER(ER_...) to ER_THD(thd, ER_...) when thd was known or if there was many calls to current_thd in the same function.
- Changed ER(ER_..) to ER_THD_OR_DEFAULT(current_thd, ER...) in some places where current_thd is not necessary defined.
- Removing calls to current_thd when we have access to thd

Part of this is optimization (not calling current_thd when not needed),
but part is bug fixing for error condition when current_thd is not defined
(For example on startup and end of mysqld)

Notable renames done as otherwise a lot of functions would have to be changed:
- In JOIN structure renamed:
   examined_rows -> join_examined_rows
   record_count -> join_record_count
- In Field, renamed new_field() to make_new_field()

Other things:
- Added DBUG_ASSERT(thd == tmp_thd) in Item_singlerow_subselect() just to be safe.
- Removed old 'tab' prefix in JOIN_TAB::save_explain_data() and use members directly
- Added 'thd' as argument to a few functions to avoid calling current_thd.
2015-07-06 20:24:14 +03:00
Nirbhay Choubey
70714d3597 Merge branch '5.5-galera' into 10.0-galera 2015-06-23 16:46:12 -04:00
Nirbhay Choubey
fc716dc5a5 MDEV-8260 : Issues related to concurrent CTAS
* Wait for aborted thd (victim) to release MDL locks
* Skip aborting an already aborted thd
* Defer setting OK status in case of CTAS
* Minor cosmetic changes
* Added a test case
2015-06-19 19:25:15 -04:00
Sergey Vojtovich
8f603bcbca MDEV-7952 - clock_gettime() takes 0.24% in OLTP RO
Initialize abs_timeout when it is about to be used. This saves one my_hrtime()
call on hot path (when we acquire MDL lock without waiting).

When filling I_S.PROCESSLIST use THD::start_utime/THD::utime_after_query instead
of THD::start_time. This allows us to save 2 clock_gettime() calls.

Overhead change:
__clock_gettime   0.13% -> 0.11% (122 -> 76 calls per OLTP RO transaction)
my_interval_timer 0.07% -> 0.06%
my_hrtime         0.04% -> 0.01%
2015-06-19 15:06:34 +04:00
Sergey Vojtovich
ff1e0821d1 MDEV-8073 - Build error in sql/mdl.cc on OS X 10.10
C++03 seem to require default constructor for const objects even though they're
fully initialized. There is defect report for this:
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#253

Apparently some compilers (e.g. gcc) addressed this defect report, while some
(e.g. clang) did not.

Added empty default constructor to MDL_scoped_lock and MDL_object_lock classes.

Also replaced lf_hash_search_using_hash_value() with lf_hash_search(). The
latter will call mdl_key->hash_value() anyway.
2015-04-30 12:36:39 +04:00
Sergey Vojtovich
5c6aa4dea0 MDEV-6089 - MySQL WL#7305 "Improve MDL scalability by using lock-free hash"
Replaced hash with lock-free hash.
2015-03-04 13:34:53 +04:00
Sergey Vojtovich
f5bd1d0126 MDEV-6089 - MySQL WL#7305 "Improve MDL scalability by using lock-free hash"
Simplified MDL_object_lock and MDL_scoped_lock dichotomy so that they can be
stored in LF_HASH. This was done by moving out their differences to a
MDL_lock_strategy structure which is referenced from the MDL_lock object by
pointer.
2015-03-04 13:34:53 +04:00
Sergey Vojtovich
f475a7f949 MDEV-6089 - MySQL WL#7305 "Improve MDL scalability by using lock-free hash"
Replaced m_ref_usage, m_ref_release, m_is_destroyed and m_version with single
m_state, which is updated atomically. Needed to get rid of MDL_map::m_mutex.
2015-03-04 13:34:52 +04:00
Sergey Vojtovich
ecd3ff9f24 MDEV-6089 - MySQL WL#7305 "Improve MDL scalability by using lock-free hash"
Removed MDL map partitions. Won't be needed when this MDEV is implemented.
2015-03-04 13:34:52 +04:00
Sergey Vojtovich
903160ef59 MDEV-6089 - MySQL WL#7305 "Improve MDL scalability by using lock-free hash"
Removed MDL objects cache. Won't be needed when this MDEV is implemented.
2015-03-04 13:34:52 +04:00
Sergei Golubchik
4b21cd21fe Merge branch '10.0' into merge-wip 2015-01-31 21:48:47 +01:00
Nirbhay Choubey
7cda4bee0e maria-10.0.16 merge
bzr merge -r4588 maria/10.0
2015-01-26 22:54:27 -05:00
Sergei Golubchik
73ebabd2ee MDEV-7299 Assertion `m_status == DA_ERROR || m_status == DA_OK' fails on concurrent execution of DDL, queries from I_S, and KILL QUERY
Fix MDL to report an error when a wait was killed, but preserve
the old documented behavior of GET_LOCK() where killing it is not an error.

Also remove race conditions in main.create_or_replace test
2015-01-19 14:19:14 +01:00
Sergei Golubchik
2ae7541bcf cleanup: s/const CHARSET_INFO/CHARSET_INFO/
as CHARSET_INFO is already const, using const on it
is redundant and results in compiler warnings (on Windows)
2014-12-04 10:41:51 +01:00
Nirbhay Choubey
3e792e6cbc MDEV-4018 : Feature Request: microseconds in GET_LOCK()
Updated MDL_context's lock methods to accept double precision
lock_wait_timeout.
2014-11-30 01:05:34 -05:00
Sergei Golubchik
7aabc2ded2 fixing embedded: WaaS. Wsrep as a Service. 2014-10-01 23:48:34 +02:00
Sergei Golubchik
3620910eea cleanup: galera merge, simple changes 2014-10-01 23:38:27 +02:00
Jan Lindström
df4dd593f2 MDEV-6247: Merge 10.0-galera to 10.1.
Merged lp:maria/maria-10.0-galera up to revision 3879.

Added a new functions to handler API to forcefully abort_transaction,
producing fake_trx_id, get_checkpoint and set_checkpoint for XA. These
were added for future possiblity to add more storage engines that
could use galera replication.
2014-08-26 15:43:46 +03:00
Nirbhay Choubey
086af8367e bzr merge -r4209 maria/10.0. 2014-05-21 11:09:55 -04:00
Sergey Vojtovich
b123249010 MDEV-5792 - Deadlock between SELECTs from METADATA_LOCK_INFO and another
I_S table

mdl_iterate() helper function (which is used by the plugin to iterate mdl
locks) acquired mutexes in reverse order.

Fixed by iterating MDL locks in two stages:
1. Iterate locks hash under the protection of hash mutex, store all
   lock pointers in a thread local array and increment reference counter
   for the lock.
2. Iterate local array without protection of hash mutex, handle destroyed
   locks.

It somewhat echoes hack in MDL_map_partition::move_from_hash_to_lock_mutex.
2014-04-23 11:34:06 +04:00
Nirbhay Choubey
4213263101 Merging mariadb-10.0.10.
* bzr merge -rtag:mariadb-10.0.10 maria/10.0.
2014-04-08 10:36:34 -04:00
Nirbhay Choubey
02ba2bfdb4 Merging revision from codership-mysql/5.5 (r3928..3968) and
codership-mysql/5.6 (r4021..4065).
- Also contains fixes for some build failures.
2014-03-27 16:26:00 -04:00
Nirbhay Choubey
90e4f7f9d3 * bzr merge -rtag:mariadb-10.0.9 maria/10.0
* Fix for post-merge build failures.
2014-03-26 14:27:24 -04:00
Nirbhay Choubey
b5871a51e9 * bzr merge -r4027..4061 codership/5.6
* Merged Innodb changes to xtradb
2014-03-26 11:12:38 -04:00
Nirbhay Choubey
3088d52c20 bzr merge -r3933..3945 codership/5.5 (Non-InnoDB changes only). 2014-03-25 14:42:15 -04:00
Sergey Vojtovich
e4fde57712 MDEV-5864 - Reduce usage of LOCK_open: TABLE_SHARE::tdc.free_tables
Let TABLE_SHARE::tdc.free_tables, TABLE_SHARE::tdc.all_tables,
TABLE_SHARE::tdc.flushed and corresponding invariants be protected by
per-share TABLE_SHARE::tdc.LOCK_table_share instead of global LOCK_open.
2014-03-20 11:11:13 +04:00
Sergey Vojtovich
b95c8ce530 MDEV-5675 - Performance: my_hash_sort_bin is called too often
Reduced number of my_hash_sort_bin() calls from 4 to 1 per query.
Reduced number of memory accesses done by my_hash_sort_bin().

Details:
- let MDL subsystem use pre-calculated hash value for hash
  inserts and deletes
- let table cache use pre-calculated MDL hash value
- MDL namespace is excluded from hash value calculation, so that
  hash value can be used by table cache as is
- hash value for MDL is calculated as resulting hash value + MDL
  namespace
- extended hash implementation to accept user defined hash function
2014-03-06 16:19:12 +04:00
Nirbhay Choubey
4cb029b38b * Merged the missing revision 3934 from
codership-mysql/5.5 (missed in the last merge).
* Merged changes from Innodb to xtradb.
* Updated WSREP_PATCH_REVNO
2014-02-05 00:28:11 -05:00
Jan Lindström
d43afb8828 Merge MariaDB-10.0.7 revision 3961. 2014-01-25 11:02:49 +02:00
Nirbhay Choubey
9d5c3731be Fixes for some compiler warnings. 2014-01-09 23:22:10 -05:00
Nirbhay Choubey
31eaa90a6e Merging revision 3839..3932 from codership-mysql/5.5. 2014-01-09 14:54:57 -05:00
Kentoku SHIBA
3771e14ea9 add metadata_lock_info 2013-12-11 00:31:04 +09:00
Seppo Jaakola
496e22cf3b merge with MariaDB 5.6 bzr merge lp:maria --rtag:mariadb-10.0.6
and a number of fixes to make this buildable. 
Run also few short multi-master high conflict rate tests, with no issues
2013-12-04 10:32:43 +02:00
Seppo Jaakola
2b4183f10b bzr merge -r3890..3891 lp:codership-mysql/5.5 2013-11-06 00:29:37 +02:00
Seppo Jaakola
61bda9a2f0 Merged revisions 3425..3430 from mariadb-galera-5.5 2013-10-07 09:43:19 +03:00
Seppo Jaakola
4e00dd6861 References: lp:1233353 - releasing explicit MDL locks for BF aborted transactions 2013-09-30 23:14:31 +03:00
Jan Lindström
ba3ff50ab2 Merge 10.0 to galera-10.0 2013-09-03 17:50:36 +03:00
Sergei Golubchik
b7b5f6f1ab 10.0-monty merge
includes:
* remove some remnants of "Bug#14521864: MYSQL 5.1 TO 5.5 BUGS PARTITIONING"
* introduce LOCK_share, now LOCK_ha_data is strictly for engines
* rea_create_table() always creates .par file (even in "frm-only" mode)
* fix a 5.6 bug, temp file leak on dummy ALTER TABLE
2013-07-21 16:39:19 +02:00
Seppo Jaakola
db0cfba638 Merged with lp:maria revision #3766 2013-07-13 13:30:03 +03:00
Seppo Jaakola
0a9216835f Initial merge result with mariaDB 10: lp:maria 2013-07-13 13:01:13 +03:00
Michael Widenius
99aae21ed2 mdl_sync now works.
mysql-test/r/mdl_sync.result:
  Full merge with 5.6
mysql-test/t/mdl_sync.test:
  Full merge with 5.6
sql/debug_sync.cc:
  Full merge with 5.6
sql/debug_sync.h:
  Full merge with 5.6
sql/mdl.cc:
  Full merge with 5.6
sql/sql_base.cc:
  Removed code not in 5.6 anymore
2013-07-02 20:43:35 +03:00
Michael Widenius
8075b05b7d More merge fixes:
- mdl.cc and mdl.h merged completely
- mysql_system_tables*.sql merged completely
- Fixed wrong merge of lock_tables
- Added some missing functions:
 - bool THD::notify_shared_lock()
 - Dynamic_array::pop, Dynamic_array::del
- Added MDL_context_owner to THD
- Added metadata_locks_hash_instances
2013-06-16 21:26:40 +03:00
Michael Widenius
5f1f2fc0e4 Applied all changes from Igor and Sanja 2013-06-15 18:32:08 +03:00
Michael Widenius
fab9a55d07 - Fixed compiler warning
- Don't abort InnoDB if one can't allocate resources for AIO
  (this patch was in 5.5 and 10.0-base but was missing in 10.0)


sql/mdl.cc:
  Fixed compiler warning
storage/innobase/os/os0file.cc:
  Don't abort InnoDB if one can't allocate resources for AIO
2013-06-05 13:51:28 +03:00
Sergei Golubchik
a9035be5b7 10.0-base merge 2013-04-15 15:09:22 +02:00
Alexey Botchkov
1a600125ff MDEV-3917 multiple use locks (GET_LOCK) in one connection.
The patch contributed by Konstantin Osipov applied.
    Native comments:
      Implement multiple user-level locks per connection.

      GET_LOCK() function in MySQL allows a connection  to hold at most
      one user level lock. Taking a new lock automatically releases the
      old lock, if any.

      The limit of one lock per session existed since  early versions
      of MySQL didn't have a deadlock detector for SQL locks.
      MDL patches in MySQL 5.5 added a deadlock detector,
      so starting from 5.5 it became possible to take multiple locks
      in any order -- a deadlock, should it occur, would be detected
      and an error returned to the client which closed the wait chain.

      This is exactly what is done in this patch: ULLs are moved
      to use MDL subsystem.
2013-04-12 18:06:51 +05:00
Seppo Jaakola
18c97eea5c References lp:1115708 - merged with lp:mariadb/5.5 revision 3657 2013-02-05 20:19:47 +02:00
Sergei Golubchik
ab83952f29 10.0-base merge 2013-01-31 09:48:19 +01:00
Sergei Golubchik
0af4b6c6ee 5.5 merge 2013-01-29 15:10:47 +01:00
Michael Widenius
a260b15554 MDEV-4011 Added per thread memory counting and usage
Base code and idea from a patch from by plinux at Taobao.

The idea is that we mark all memory that are thread specific with MY_THREAD_SPECIFIC.
Memory counting is done per thread in the my_malloc_size_cb_func callback function from my_malloc().
There are plenty of new asserts to ensure that for a debug server the counting is correct.

Information_schema.processlist gets two new columns: MEMORY_USED and EXAMINED_ROWS.
- The later is there mainly to show how query is progressing.

The following changes in interfaces was needed to get this to work:
- init_alloc_root() amd init_sql_alloc() has extra option so that one can mark memory with MY_THREAD_SPECIFIC
- One now have to use alloc_root_set_min_malloc() to set min memory to be allocated by alloc_root()
- my_init_dynamic_array()  has extra option so that one can mark memory with MY_THREAD_SPECIFIC
- my_net_init() has extra option so that one can mark memory with MY_THREAD_SPECIFIC
- Added flag for hash_init() so that one can mark hash table to be thread specific.
- Added flags to init_tree() so that one can mark tree to be thread specific.
- Removed with_delete option to init_tree(). Now one should instead use MY_TREE_WITH_DELETE_FLAG.
- Added flag to Warning_info::Warning_info() if the structure should be fully initialized.
- String elements can now be marked as thread specific.
- Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC.
- Changed type of myf from int to ulong, as this is always a set of bit flags.

Other things:
- Removed calls to net_end() and thd->cleanup() as these are now done in ~THD()
- We now also show EXAMINED_ROWS in SHOW PROCESSLIST
- Added new variable 'memory_used'
- Fixed bug where kill_threads_for_user() was using the wrong mem_root to allocate memory.
- Removed calls to the obsoleted function init_dynamic_array()
- Use set_current_thd() instead of my_pthread_setspecific_ptr(THR_THD,...)


client/completion_hash.cc:
  Updated call to init_alloc_root()
client/mysql.cc:
  Updated call to init_alloc_root()
client/mysqlbinlog.cc:
  init_dynamic_array() -> my_init_dynamic_array()
  Updated call to init_alloc_root()
client/mysqlcheck.c:
  Updated call to my_init_dynamic_array()
client/mysqldump.c:
  Updated call to init_alloc_root()
client/mysqltest.cc:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
  Fixed compiler warnings
extra/comp_err.c:
  Updated call to my_init_dynamic_array()
extra/resolve_stack_dump.c:
  Updated call to my_init_dynamic_array()
include/hash.h:
  Added HASH_THREAD_SPECIFIC
include/heap.h:
  Added flag is internal temporary table.
include/my_dir.h:
  Safety fix: Ensure that MY_DONT_SORT and MY_WANT_STAT don't interfer with other mysys flags
include/my_global.h:
  Changed type of myf from int to ulong, as this is always a set of bit flags.
include/my_sys.h:
  Added MY_THREAD_SPECIFIC and MY_THREAD_MOVE
  Added malloc_flags to DYNAMIC_ARRAY
  Added extra mysys flag argument to my_init_dynamic_array()
  Removed deprecated functions init_dynamic_array() and my_init_dynamic_array.._ci
  Updated paramaters for init_alloc_root()
include/my_tree.h:
  Added my_flags to allow one to use MY_THREAD_SPECIFIC with hash tables.
  Removed with_delete. One should now instead use MY_TREE_WITH_DELETE_FLAG
  Updated parameters to init_tree()
include/myisamchk.h:
  Added malloc_flags to allow one to use MY_THREAD_SPECIFIC for checks.
include/mysql.h:
  Added MYSQL_THREAD_SPECIFIC_MALLOC
  Used 'unused1' to mark memory as thread specific.
include/mysql.h.pp:
  Updated file
include/mysql_com.h:
  Used 'unused1' to mark memory as thread specific.
  Updated parameters for my_net_init()
libmysql/libmysql.c:
  Updated call to init_alloc_root() to mark memory thread specific.
libmysqld/emb_qcache.cc:
  Updated call to init_alloc_root()
libmysqld/lib_sql.cc:
  Updated call to init_alloc_root()
mysql-test/r/create.result:
  Updated results
mysql-test/r/user_var.result:
  Updated results
mysql-test/suite/funcs_1/datadict/processlist_priv.inc:
  Update to handle new format of SHOW PROCESSLIST
mysql-test/suite/funcs_1/datadict/processlist_val.inc:
  Update to handle new format of SHOW PROCESSLIST
mysql-test/suite/funcs_1/r/is_columns_is.result:
  Update to handle new format of SHOW PROCESSLIST
mysql-test/suite/funcs_1/r/processlist_priv_no_prot.result:
  Updated results
mysql-test/suite/funcs_1/r/processlist_val_no_prot.result:
  Updated results
mysql-test/t/show_explain.test:
  Fixed usage of debug variable so that one can run test with --debug
mysql-test/t/user_var.test:
  Added test of memory_usage variable.
mysys/array.c:
  Added extra my_flags option to init_dynamic_array() and init_dynamic_array2() so that one can mark memory with MY_THREAD_SPECIFIC
  All allocated memory is marked with the given my_flags.
  Removed obsolete function init_dynamic_array()
mysys/default.c:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
mysys/hash.c:
  Updated call to my_init_dynamic_array_ci().
  Allocated memory is marked with MY_THREAD_SPECIFIC if HASH_THREAD_SPECIFIC is used.
mysys/ma_dyncol.c:
  init_dynamic_array() -> my_init_dynamic_array()
  Added #if to get rid of compiler warnings
mysys/mf_tempdir.c:
  Updated call to my_init_dynamic_array()
mysys/my_alloc.c:
  Added extra parameter to init_alloc_root() so that one can mark memory with MY_THREAD_SPECIFIC
  Extend MEM_ROOT with a flag if memory is thread specific.
  This is stored in block_size, to keep the size of the MEM_ROOT object identical as before.
  Allocated memory is marked with MY_THREAD_SPECIFIC if used with init_alloc_root()
mysys/my_chmod.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_chsize.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_copy.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_create.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_delete.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_error.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_fopen.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_fstream.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_getwd.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_lib.c:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
  Updated DBUG_PRINT because of change of myf type
mysys/my_lock.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_malloc.c:
  Store at start of each allocated memory block the size of the block and if the block is thread specific.
  Call malloc_size_cb_func, if set, with the memory allocated/freed.
  Updated DBUG_PRINT because of change of myf type
mysys/my_open.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_pread.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_read.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_redel.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_rename.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_seek.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_sync.c:
  Updated DBUG_PRINT because of change of myf type
mysys/my_thr_init.c:
  Ensure that one can call my_thread_dbug_id() even if thread is not properly initialized.
mysys/my_write.c:
  Updated DBUG_PRINT because of change of myf type
mysys/mysys_priv.h:
  Updated parameters to sf_malloc and sf_realloc()
mysys/safemalloc.c:
  Added checking that for memory marked with MY_THREAD_SPECIFIC that it's the same thread that is allocation and freeing the memory.
  Added sf_malloc_dbug_id() to allow MariaDB to specify which THD is handling the memory.
  Added my_flags arguments to sf_malloc() and sf_realloc() to be able to mark memory with MY_THREAD_SPECIFIC.
  Added sf_report_leaked_memory() to get list of memory not freed by a thread.
mysys/tree.c:
  Added flags to init_tree() so that one can mark tree to be thread specific.
  Removed with_delete option to init_tree(). Now one should instead use MY_TREE_WITH_DELETE_FLAG.
  Updated call to init_alloc_root()
  All allocated memory is marked with the given malloc flags
mysys/waiting_threads.c:
  Updated call to my_init_dynamic_array()
sql-common/client.c:
  Updated call to init_alloc_root() and my_net_init() to mark memory thread specific.
  Updated call to my_init_dynamic_array().
  Added MYSQL_THREAD_SPECIFIC_MALLOC so that client can mark memory as MY_THREAD_SPECIFIC.
sql-common/client_plugin.c:
  Updated call to init_alloc_root()
sql/debug_sync.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/event_scheduler.cc:
  Removed calls to net_end() as this is now done in ~THD()
  Call set_current_thd() to ensure that memory is assigned to right thread.
sql/events.cc:
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/filesort.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/filesort_utils.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/ha_ndbcluster.cc:
  Updated call to init_alloc_root()
  Updated call to my_net_init()
  Removed calls to net_end() and thd->cleanup() as these are now done in ~THD()
sql/ha_ndbcluster_binlog.cc:
  Updated call to my_net_init()
  Updated call to init_sql_alloc()
  Removed calls to net_end() and thd->cleanup() as these are now done in ~THD()
sql/ha_partition.cc:
  Updated call to init_alloc_root()
sql/handler.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
  Added missing call to my_dir_end()
sql/item_func.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/item_subselect.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/item_sum.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/log.cc:
  More DBUG
  Updated call to init_alloc_root()
sql/mdl.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/mysqld.cc:
  Added total_memory_used
  Updated call to init_alloc_root()
  Move mysql_cond_broadcast() before my_thread_end()
  Added mariadb_dbug_id() to count memory per THD instead of per thread.
  Added my_malloc_size_cb_func() callback function for my_malloc() to count memory.
  Move initialization of mysqld_server_started and mysqld_server_initialized earlier.
  Updated call to my_init_dynamic_array().
  Updated call to my_net_init().
  Call my_pthread_setspecific_ptr(THR_THD,...) to ensure that memory is assigned to right thread.
  Added status variable 'memory_used'.
  Updated call to init_alloc_root()
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/mysqld.h:
  Added set_current_thd()
sql/net_serv.cc:
  Added new parameter to my_net_init() so that one can mark memory with MY_THREAD_SPECIFIC.
  Store in net->thread_specific_malloc if memory is thread specific.
  Mark memory to be thread specific if requested.
sql/opt_range.cc:
  Updated call to my_init_dynamic_array()
  Updated call to init_sql_alloc()
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/opt_subselect.cc:
  Updated call to init_sql_alloc() to mark memory thread specific.
sql/protocol.cc:
  Fixed compiler warning
sql/records.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/rpl_filter.cc:
  Updated call to my_init_dynamic_array()
sql/rpl_handler.cc:
  Updated call to my_init_dynamic_array2()
sql/rpl_handler.h:
  Updated call to init_sql_alloc()
sql/rpl_mi.cc:
  Updated call to my_init_dynamic_array()
sql/rpl_tblmap.cc:
  Updated call to init_alloc_root()
sql/rpl_utility.cc:
  Updated call to my_init_dynamic_array()
sql/slave.cc:
  Initialize things properly before calling functions that allocate memory.
  Removed calls to net_end() as this is now done in ~THD()
sql/sp_head.cc:
  Updated call to init_sql_alloc()
  Updated call to my_init_dynamic_array()
  Added parameter to warning_info() that it should be fully initialized.
sql/sp_pcontext.cc:
  Updated call to my_init_dynamic_array()
sql/sql_acl.cc:
  Updated call to init_sql_alloc()
  Updated call to my_init_dynamic_array()
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_admin.cc:
  Added parameter to warning_info() that it should be fully initialized.
sql/sql_analyse.h:
  Updated call to init_tree() to mark memory thread specific.
sql/sql_array.h:
  Updated call to my_init_dynamic_array() to mark memory thread specific.
sql/sql_audit.cc:
  Updated call to my_init_dynamic_array()
sql/sql_base.cc:
  Updated call to init_sql_alloc()
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_cache.cc:
  Updated comment
sql/sql_class.cc:
  Added parameter to warning_info() that not initialize it until THD is fully created.
  Updated call to init_sql_alloc()
  Mark THD::user_vars has to be thread specific.
  Updated call to my_init_dynamic_array()
  Ensure that memory allocated by THD is assigned to the THD.
  More DBUG
  Always acll net_end() in ~THD()
  Assert that all memory signed to this THD is really deleted at ~THD.
  Fixed set_status_var_init() to not reset memory_used.
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_class.h:
  Added MY_THREAD_SPECIFIC to allocated memory.
  Added malloc_size to THD to record allocated memory per THD.
sql/sql_delete.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/sql_error.cc:
  Added 'initialize' parameter to Warning_info() to say if should allocate memory for it's structures.
  This is used by THD::THD() to not allocate memory until THD is ready.
  Added Warning_info::free_memory()
sql/sql_error.h:
  Updated Warning_info() class.
sql/sql_handler.cc:
  Updated call to init_alloc_root() to mark memory thread specific.
sql/sql_insert.cc:
  More DBUG
sql/sql_join_cache.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/sql_lex.cc:
  Updated call to my_init_dynamic_array()
sql/sql_lex.h:
  Updated call to my_init_dynamic_array()
sql/sql_load.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/sql_parse.cc:
  Removed calls to net_end() and thd->cleanup() as these are now done in ~THD()
  Ensure that examined_row_count() is reset before query.
  Fixed bug where kill_threads_for_user() was using the wrong mem_root to allocate memory.
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
  Don't restore thd->status_var.memory_used when restoring thd->status_var
sql/sql_plugin.cc:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
  Don't allocate THD on the stack, as this causes problems with valgrind when doing thd memory counting.
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_prepare.cc:
  Added parameter to warning_info() that it should be fully initialized.
  Updated call to init_sql_alloc() to mark memory thread specific.
sql/sql_reload.cc:
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_select.cc:
  Updated call to my_init_dynamic_array() and init_sql_alloc() to mark memory thread specific.
  Added MY_THREAD_SPECIFIC to allocated memory.
  More DBUG
sql/sql_servers.cc:
  Updated call to init_sql_alloc() to mark memory some memory thread specific.
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_show.cc:
  Updated call to my_init_dynamic_array()
  Mark my_dir() memory thread specific.
  Use my_pthread_setspecific_ptr(THR_THD,...) to mark that allocated memory should be allocated to calling thread.
  More DBUG.
  Added malloc_size and examined_row_count to SHOW PROCESSLIST.
  Added MY_THREAD_SPECIFIC to allocated memory.
  Updated call to init_sql_alloc()
  Added parameter to warning_info() that it should be fully initialized.
sql/sql_statistics.cc:
  Fixed compiler warning
sql/sql_string.cc:
  String elements can now be marked as thread specific.
sql/sql_string.h:
  String elements can now be marked as thread specific.
sql/sql_table.cc:
  Updated call to init_sql_alloc() and my_malloc() to mark memory thread specific
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
  Fixed compiler warning
sql/sql_test.cc:
  Updated call to my_init_dynamic_array() to mark memory thread specific.
sql/sql_trigger.cc:
  Updated call to init_sql_alloc()
sql/sql_udf.cc:
  Updated call to init_sql_alloc()
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/sql_update.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
sql/table.cc:
  Updated call to init_sql_alloc().
  Mark memory used by temporary tables, that are not for slave threads, as MY_THREAD_SPECIFIC
  Updated call to init_sql_alloc()
sql/thr_malloc.cc:
  Added my_flags argument to init_sql_alloc() to be able to mark memory as MY_THREAD_SPECIFIC.
sql/thr_malloc.h:
  Updated prototype for init_sql_alloc()
sql/tztime.cc:
  Updated call to init_sql_alloc()
  Updated call to init_alloc_root() to mark memory thread specific.
  my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd()
sql/uniques.cc:
  Updated calls to init_tree(), my_init_dynamic_array() and my_malloc() to mark memory thread specific.
sql/unireg.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
storage/csv/ha_tina.cc:
  Updated call to init_alloc_root()
storage/federated/ha_federated.cc:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
  Ensure that memory allocated by fedarated is registered for the system, not for the thread.
storage/federatedx/federatedx_io_mysql.cc:
  Updated call to my_init_dynamic_array()
storage/federatedx/ha_federatedx.cc:
  Updated call to init_alloc_root()
  Updated call to my_init_dynamic_array()
storage/heap/ha_heap.cc:
  Added MY_THREAD_SPECIFIC to allocated memory.
storage/heap/heapdef.h:
  Added parameter to hp_get_new_block() to be able to do thread specific memory tagging.
storage/heap/hp_block.c:
  Added parameter to hp_get_new_block() to be able to do thread specific memory tagging.
storage/heap/hp_create.c:
  - Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC.
  - Use MY_TREE_WITH_DELETE instead of removed option 'with_delete'.
storage/heap/hp_open.c:
  Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC.
storage/heap/hp_write.c:
  Added new parameter to hp_get_new_block()
storage/maria/ma_bitmap.c:
  Updated call to my_init_dynamic_array()
storage/maria/ma_blockrec.c:
  Updated call to my_init_dynamic_array()
storage/maria/ma_check.c:
  Updated call to init_alloc_root()
storage/maria/ma_ft_boolean_search.c:
  Updated calls to init_tree() and init_alloc_root()
storage/maria/ma_ft_nlq_search.c:
  Updated call to init_tree()
storage/maria/ma_ft_parser.c:
  Updated call to init_tree()
  Updated call to init_alloc_root()
storage/maria/ma_loghandler.c:
  Updated call to my_init_dynamic_array()
storage/maria/ma_open.c:
  Updated call to my_init_dynamic_array()
storage/maria/ma_sort.c:
  Updated call to my_init_dynamic_array()
storage/maria/ma_write.c:
  Updated calls to my_init_dynamic_array() and init_tree()
storage/maria/maria_pack.c:
  Updated call to init_tree()
storage/maria/unittest/sequence_storage.c:
  Updated call to my_init_dynamic_array()
storage/myisam/ft_boolean_search.c:
  Updated call to init_tree()
  Updated call to init_alloc_root()
storage/myisam/ft_nlq_search.c:
  Updated call to init_tree()
storage/myisam/ft_parser.c:
  Updated call to init_tree()
  Updated call to init_alloc_root()
storage/myisam/ft_stopwords.c:
  Updated call to init_tree()
storage/myisam/mi_check.c:
  Updated call to init_alloc_root()
storage/myisam/mi_write.c:
  Updated call to my_init_dynamic_array()
  Updated call to init_tree()
storage/myisam/myisamlog.c:
  Updated call to init_tree()
storage/myisam/myisampack.c:
  Updated call to init_tree()
storage/myisam/sort.c:
  Updated call to my_init_dynamic_array()
storage/myisammrg/ha_myisammrg.cc:
  Updated call to init_sql_alloc()
storage/perfschema/pfs_check.cc:
  Rest current_thd
storage/perfschema/pfs_instr.cc:
  Removed DBUG_ENTER/DBUG_VOID_RETURN as at this point my_thread_var is not allocated anymore, which can cause problems.
support-files/compiler_warnings.supp:
  Disable compiler warning from offsetof macro.
2013-01-23 16:16:14 +01:00
Michael Widenius
6e9a48b67f Fixed some race conditons and bugs related to killed queries
KILL now breaks locks inside InnoDB
Fixed possible deadlock when running INNODB STATUS
Added ha_kill_query() and kill_query() to send kill signal to all storage engines
Added reset_killed() to ensure we don't reset killed state while awake() is getting called


include/mysql/plugin.h:
  Added thd_mark_as_hard_kill()
include/mysql/plugin_audit.h.pp:
  Added thd_mark_as_hard_kill()
include/mysql/plugin_auth.h.pp:
  Added thd_mark_as_hard_kill()
include/mysql/plugin_ftparser.h.pp:
  Added thd_mark_as_hard_kill()
sql/handler.cc:
  Added ha_kill_query() to send kill signal to all storage engines
sql/handler.h:
  Added ha_kill_query() and kill_query() to send kill signal to all storage engines
sql/log_event.cc:
  Use reset_killed()
sql/mdl.cc:
  use thd->killed instead of thd_killed() to abort on soft kill
sql/sp_rcontext.cc:
  Use reset_killed()
sql/sql_class.cc:
  Fixed possible deadlock in INNODB STATUS by not getting thd->LOCK_thd_data if it's locked.
  Use reset_killed()
  Tell storge engines that KILL has been sent
sql/sql_class.h:
  Added reset_killed() to ensure we don't reset killed state while awake() is getting called.
  Added mark_as_hard_kill()
sql/sql_insert.cc:
  Use reset_killed()
sql/sql_parse.cc:
  Simplify detection of killed queries.
  Use reset_killed()
sql/sql_select.cc:
  Use reset_killed()
sql/sql_union.cc:
  Use reset_killed()
storage/innobase/handler/ha_innodb.cc:
  Added innobase_kill_query()
  Fixed error reporting for interrupted queries.
storage/xtradb/handler/ha_innodb.cc:
  Added innobase_kill_query()
  Fixed error reporting for interrupted queries.
2013-01-11 00:22:14 +02:00
Michael Widenius
396f4d62c6 Fix for MDEV-4009: main.delayed sporadically fails with "query 'REPLACE DELAYED t1 VALUES (5)' failed: 1317: Query execution was interrupted"
- Fixed broadcast without a proper mutex
- Don't break existing locks if we are just testing if we can get the lock

mysql-test/r/create_delayed.result:
  Added test case for failures with INSERT DELAYED with CREATE and DROP TABLE
mysql-test/t/create_delayed.test:
  Added test case for failures with INSERT DELAYED with CREATE and DROP TABLE
sql/mdl.cc:
  Don't break existing locks for timeout=0 (ie, just check if there are conflicting locks).
  This fixed the bug that INSERT DELAYED didn't work properly with CREATE TABLE
sql/sql_base.cc:
  One neads to hold the mutex before doing a mysql_cond_broadcast()
  This fixed the bug that INSERT DELAYED didn't work properly with DROP TABLE
sql/sql_insert.cc:
  Protect setting of mysys_var->current_mutex.
2013-01-10 23:40:18 +02:00
Seppo Jaakola
fc6cd855e9 References: lp:1066784 - Merged revisions 3810-3827 from lp:codership-mysql 2012-11-28 17:38:32 +02:00
Sergei Golubchik
40e94a3734 merge with 5.5 2012-11-03 12:28:51 +01:00
Seppo Jaakola
9b47a442b5 References lp:1066784 - bzr merge lp:maria/5.5 (rev: 3562) 2012-10-24 23:13:43 +03:00
Seppo Jaakola
ef6f9a8250 References lp:1066784
merged with patch: bzr diff lp:codership-mysql/5.5 -r3795..3809
2012-10-23 22:38:11 +03:00
Sergei Golubchik
ee9afef271 mysql-5.5.28 2012-10-16 13:04:42 +02:00
Sergei Golubchik
474fe6d9d9 fixes for test failures
and small collateral changes

mysql-test/lib/My/Test.pm:
  somehow with "print" we get truncated writes sometimes
mysql-test/suite/perfschema/r/digest_table_full.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/dml_handler.result:
  host table is not ported over yet
mysql-test/suite/perfschema/r/information_schema.result:
  host table is not ported over yet
mysql-test/suite/perfschema/r/nesting.result:
  this differs, because we don't rewrite general log queries, and multi-statement
  packets are logged as a one entry. this result file is identical to what mysql-5.6.5
  produces with the --log-raw option.
mysql-test/suite/perfschema/r/relaylog.result:
  MariaDB modifies the binlog index file directly, while MySQL 5.6 has a feature "crash-safe binlog index" and modifies a special "crash-safe" shadow copy of the index file and then moves it over. That's why this test shows "NONE" index file writes in MySQL and "MANY" in MariaDB.
mysql-test/suite/perfschema/r/server_init.result:
  MariaDB initializes the "manager" resources from the "manager" thread, and starts this thread only when --flush-time is not 0. MySQL 5.6 initializes "manager" resources unconditionally on server startup.
mysql-test/suite/perfschema/r/stage_mdl_global.result:
  this differs, because MariaDB disables query cache when query_cache_size=0. MySQL does not
  do that, and this causes useless mutex locks and waits.
mysql-test/suite/perfschema/r/statement_digest.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/statement_digest_consumers.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/statement_digest_long_query.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/rpl/r/rpl_mixed_drop_create_temp_table.result:
  will be updated to match 5.6 when alfranio.correia@oracle.com-20110512172919-c1b5kmum4h52g0ni and anders.song@greatopensource.com-20110105052107-zoab0bsf5a6xxk2y are merged
mysql-test/suite/rpl/r/rpl_non_direct_mixed_mixing_engines.result:
  will be updated to match 5.6 when anders.song@greatopensource.com-20110105052107-zoab0bsf5a6xxk2y is merged
2012-09-27 20:09:46 +02:00
Praveenkumar Hulakund
d0766534bd Bug#13058122 - DML, LOCK/UNLOCK TABLES AND SELECT LEAD TO
FOREVER MDL LOCK

Analysis:
----------
While granting MDL lock for the lock requests in wait queue,
first the lock is granted to the high priority lock types
and then to the low priority lock types.

MDL Priority Matrix,
  +-------------+----+---+---+---+----+-----+
  | Locks       |    |   |   |   |    |     |
  | has Priority|    |   |   |   |    |     |
  | over --->   |  S | SR| SW| SU| SNW| SNRW|   
  +-------------+----+---+---+---+----+-----+
  | X           |  + | + | + | + | +  | +   |
  +-------------|----|---|---|---|----|-----|
  | SNRW        |  - | + | + | - | -  | -   |
  +-------------|----|---|---|---|----|-----|
  | SNW         |  - | - | + | - | -  | -   |
  +-------------+----+---+---+---+----+-----+

Here '+' means, Lock priority is higher.
     '-' means, Has same priority

In the scenario where,
   *. Lock wait queue has requests of type S/SR/SW/SU.
   *. And locks of high priority X/SNRW/SNW are requested 
      continuously.

In this case, while granting lock, always first high priority 
lock requests(X/SNRW/SNW) are considered. Low priority 
locks(S/SR/SW/SU) will not get chance and they will 
wait forever.

In the scenario for which this bug is reported, application
executed many LOCK TABLES ... WRITE statements concurrently.
These statements request SNRW lock. Also there were some
connections trying to execute DML statements requesting SR
lock. Since SNRW lock request has higher priority (and as
they were too many waiting SNRW requests) lock is always 
granted to it. So, lock request SR will wait forever, resulting
in DML starvation.

How is this handled in 5.1?
---------------------------
Even in 5.1 we have low priority lock starvation issue.
But, in 5.1 thread locking, system variable 
"max_write_lock_count" can be configured to grant
some pending read lock requests. After 
"max_write_lock_count" of write lock grants all the low
priority locks are granted.

Why this issue is seen in 5.5/trunk?
---------------------------------
In 5.5/trunk MDL locking, "max_write_lock_count" system 
variable exists but not used in MDL, only thread lock uses
it. So no effect of "max_write_lock_count" in MDL locking.
This means that starvation of metadata locks is possible 
even if max_write_lock_count is used.

Looks like, customer was using "max_write_lock_count" in
5.1 and when upgraded to 5.5, starvation is seen because
of not having effect of "max_write_lock_count" in MDL.

Fix:
----------
As a fix, support for max_write_lock_count is added to MDL.
To maintain write lock counter per MDL_lock object, new
member "m_hog_lock_count" is added in MDL_lock.

And following logic is added to increment the counter in 
function reschedule_waiters, 
(reschedule_waiters function is called while thread is
 releasing the lock)
    - After granting lock request from the wait queue.
    -  Check if there are any S/SR/SU/SW exists in the wait queue
      - If yes then increment the "m_hog_lock_count"

And following logic is added in the same function to
handle pending S/SU/SR/SW locks
    
    - Before granting locks 
    - Check if max_write_lock_count <= m_hog_lock_count
    - If Yes, then try to grant S/SR/SW/SU locks. 
      (Since all of these has same priority, all locks are
       granted together. But some lock grant may fail because
       of grant incompatibility)
    - Reset m_hog_lock_count if there no low priority lock
      requests in wait queue. 
    - return

Note:
--------------------------
In the lock priority matrix explained above,
though X has priority over the SNW and SNRW. X locks is
taken mostly for RENAME, TRUNCATE, CREATE ... operations.
So lock type X may not be requested in loop continuously 
in real world applications, as compared to other lock 
request types. So, lock request of type SNW and SNRW are 
not starved. So, we can grant all S/SR/SU/SW in one shot,
without considering SNW & SNRW lock request starvation.

ALTER table operations take SU lock first and then 
upgrade to SNW if required. All S, SR, SW, SU have same
lock priority. So while granting SU, request of types
SR, SW, S are also granted in one shot. So, lock request 
of type SU->SNW in loop will not make other low priority 
lock request to starve.

But, when there is request for lock of type SNRW, lock
requests of lower priority types are not granted. And if 
SNRW is requested in loop continuously then all 
S, SR, SW, SU are starved.

This patch addresses the latter scenario.
When we have S/SR/SW/SU in wait queue and if 
there are
    - Continuous SNRW lock requests
    - OR one or more X and Continuous SNRW lock requests.
    - OR one SNW and Continuous SNRW lock requests.
    - OR one SNW, one or more X and continuous SNRW lock 
      requests.
in wait queue then, S/SR/SW/SU lock request are starved.
2012-08-07 11:48:36 +05:30
Seppo Jaakola
2fc1ec4356 Initial push of codership-wsrep API implementation for MariaDB.
Merge of:
lp:maria/5.5, #3334: http://bazaar.launchpad.net/~maria-captains/maria/5.5/revision/3334
lp:codership-mysql/5.5, #3725: http://bazaar.launchpad.net/~codership/codership-mysql/wsrep-5.5/revision/3725
2012-04-13 01:33:24 +03:00
Sergei Golubchik
e7e2058550 MDEV-117 Assertion: prebuilt->sql_stat_start || trx->conc_state == 1 failed at row0sel.c:3933
DELETE IGNORE should not ignore deadlocks

sql/mdl.cc:
  more DBUG_ENTER/DBUG_RETURN
sql/sql_base.cc:
  more DBUG_ENTER/DBUG_RETURN
2012-03-01 16:24:59 +01:00
Sergei Golubchik
38e3ae155d mysql-5.5 merge 2012-01-16 20:16:35 +01:00
Dmitry Lenev
082e0b957d Fix for bug#12695572 - "IMPROVE MDL PERFORMANCE IN PRE-VISTA
BY CACHING OR REDUCING CREATEEVENT CALLS".
 
5.5 versions of MySQL server performed worse than 5.1 versions 
under single-connection workload in autocommit mode on Windows XP.
 
Part of this slowdown can be attributed to overhead associated
with constant creation/destruction of MDL_lock objects in the MDL
subsystem. The problem is that creation/destruction of these
objects causes creation and destruction of associated
synchronization primitives, which are expensive on Windows XP.
 
This patch tries to alleviate this problem by introducing a cache
of unused MDL_object_lock objects. Instead of destroying such
objects we put them into the cache and then reuse with a new
key when creation of a new object is requested.

To limit the size of this cache, a new --metadata-locks-cache-size
start-up parameter was introduced.

mysql-test/r/mysqld--help-notwin.result:
  Updated test after adding --metadata-locks-cache-size
  parameter.
mysql-test/r/mysqld--help-win.result:
  Updated test after adding --metadata-locks-cache-size
  parameter.
mysql-test/suite/sys_vars/r/metadata_locks_cache_size_basic.result:
  Added test coverage for newly introduced --metadata_locks_cache_size
  start-up parameter and corresponding global read-only variable.
mysql-test/suite/sys_vars/t/metadata_locks_cache_size_basic-master.opt:
  Added test coverage for newly introduced --metadata_locks_cache_size
  start-up parameter and corresponding global read-only variable.
mysql-test/suite/sys_vars/t/metadata_locks_cache_size_basic.test:
  Added test coverage for newly introduced --metadata_locks_cache_size
  start-up parameter and corresponding global read-only variable.
sql/mdl.cc:
  Introduced caching of unused MDL_object_lock objects, in order to
  avoid costs associated with constant creation and destruction of
  such objects in single-connection workloads run in autocommit mode.
  Such costs can be pretty high on systems where creation and 
  destruction of synchronization primitives require a system call 
  (e.g. Windows XP).
   
  To implement this cache,a list of unused MDL_object_lock instances 
  was added to MDL_map object. Instead of being destroyed 
  MDL_object_lock instances are put into this list and re-used later 
  when creation of a new instance is required. Also added 
  MDL_lock::m_version counter to allow threads having outstanding 
  references to an MDL_object_lock instance to notice that it has 
  been moved to the unused objects list.
   
  Added a global variable for a start-up parameter that limits
  the size of the unused objects list.
   
  Note that we don't cache MDL_scoped_lock objects since they
  are supposed to be created only during execution of DDL 
  statements and therefore should not affect performance much.
sql/mdl.h:
  Added a global variable for start-up parameter that limits the
  size of the unused MDL_object_lock objects list and constant
  for its default value.
sql/sql_plist.h:
  Added I_P_List<>::pop_front() function.
sql/sys_vars.cc:
  Introduced --metadata-locks-cache-size start-up parameter
  for specifying size of the cache of unused MDL_object_lock
  objects.
2011-11-15 22:00:14 +04:00
Sergei Golubchik
0e007344ea mysql-5.5.18 merge 2011-11-03 19:17:05 +01:00
Sergei Golubchik
42b8235788 cleanups 2011-10-19 22:50:45 +02:00
Kent Boortz
02e07e3b51 Updated/added copyright headers 2011-06-30 17:46:53 +02:00
Mikael Ronstrom
b14adc3921 More review fixes 2011-03-04 13:12:31 +01:00
Mikael Ronstrom
6e7752d557 merge 2011-01-04 18:46:01 +01:00
Dmitry Lenev
6bf6272fda Patch that refactors global read lock implementation and fixes
bug #57006 "Deadlock between HANDLER and FLUSH TABLES WITH READ
LOCK" and bug #54673 "It takes too long to get readlock for
'FLUSH TABLES WITH READ LOCK'".

The first bug manifested itself as a deadlock which occurred
when a connection, which had some table open through HANDLER
statement, tried to update some data through DML statement
while another connection tried to execute FLUSH TABLES WITH
READ LOCK concurrently.

What happened was that FTWRL in the second connection managed
to perform first step of GRL acquisition and thus blocked all
upcoming DML. After that it started to wait for table open
through HANDLER statement to be flushed. When the first connection
tried to execute DML it has started to wait for GRL/the second
connection creating deadlock.

The second bug manifested itself as starvation of FLUSH TABLES
WITH READ LOCK statements in cases when there was a constant
stream of concurrent DML statements (in two or more
connections).

This has happened because requests for protection against GRL
which were acquired by DML statements were ignoring presence of
pending GRL and thus the latter was starved.

This patch solves both these problems by re-implementing GRL
using metadata locks.

Similar to the old implementation acquisition of GRL in new
implementation is two-step. During the first step we block
all concurrent DML and DDL statements by acquiring global S
metadata lock (each DML and DDL statement acquires global IX
lock for its duration). During the second step we block commits
by acquiring global S lock in COMMIT namespace (commit code
acquires global IX lock in this namespace).

Note that unlike in old implementation acquisition of
protection against GRL in DML and DDL is semi-automatic.
We assume that any statement which should be blocked by GRL
will either open and acquires write-lock on tables or acquires
metadata locks on objects it is going to modify. For any such
statement global IX metadata lock is automatically acquired
for its duration.

The first problem is solved because waits for GRL become
visible to deadlock detector in metadata locking subsystem
and thus deadlocks like one in the first bug become impossible.

The second problem is solved because global S locks which
are used for GRL implementation are given preference over
IX locks which are acquired by concurrent DML (and we can
switch to fair scheduling in future if needed).

Important change:
FTWRL/GRL no longer blocks DML and DDL on temporary tables.
Before this patch behavior was not consistent in this respect:
in some cases DML/DDL statements on temporary tables were
blocked while in others they were not. Since the main use cases
for FTWRL are various forms of backups and temporary tables are
not preserved during backups we have opted for consistently
allowing DML/DDL on temporary tables during FTWRL/GRL.

Important change:
This patch changes thread state names which are used when
DML/DDL of FTWRL is waiting for global read lock. It is now
either "Waiting for global read lock" or "Waiting for commit
lock" depending on the stage on which FTWRL is.

Incompatible change:
To solve deadlock in events code which was exposed by this
patch we have to replace LOCK_event_metadata mutex with
metadata locks on events. As result we have to prohibit
DDL on events under LOCK TABLES.

This patch also adds extensive test coverage for interaction
of DML/DDL and FTWRL.

Performance of new and old global read lock implementations
in sysbench tests were compared. There were no significant
difference between new and old implementations.

mysql-test/include/check_ftwrl_compatible.inc:
  Added helper script which allows to check that a statement is
  compatible with FLUSH TABLES WITH READ LOCK.
mysql-test/include/check_ftwrl_incompatible.inc:
  Added helper script which allows to check that a statement is
  incompatible with FLUSH TABLES WITH READ LOCK.
mysql-test/include/handler.inc:
  Adjusted test case to the fact that now DROP TABLE closes
  open HANDLERs for the table to be dropped before checking
  if there active FTWRL in this connection.
mysql-test/include/wait_show_condition.inc:
  Fixed small error in the timeout message. The correct name
  of variable used as parameter for this script is "$condition"
  and not "$wait_condition".
mysql-test/r/delayed.result:
  Added test coverage for scenario which triggered assert in
  metadata locking subsystem.
mysql-test/r/events_2.result:
  Updated test results after prohibiting event DDL operations
  under LOCK TABLES.
mysql-test/r/flush.result:
  Added test coverage for bug #57006 "Deadlock between HANDLER
  and FLUSH TABLES WITH READ LOCK".
mysql-test/r/flush_read_lock.result:
  Added test coverage for various aspects of FLUSH TABLES WITH
  READ LOCK functionality.
mysql-test/r/flush_read_lock_kill.result:
  Adjusted test case after replacing custom global read lock
  implementation with one based on metadata locks. Use new
  debug_sync point. Do not disable concurrent inserts as now
  InnoDB we always use InnoDB table.
mysql-test/r/handler_innodb.result:
  Adjusted test case to the fact that now DROP TABLE closes
  open HANDLERs for the table to be dropped before checking
  if there active FTWRL in this connection.
mysql-test/r/handler_myisam.result:
  Adjusted test case to the fact that now DROP TABLE closes
  open HANDLERs for the table to be dropped before checking
  if there active FTWRL in this connection.
mysql-test/r/mdl_sync.result:
  Adjusted test case after replacing custom global read lock
  implementation with one based on metadata locks. Replaced
  usage of GRL-specific debug_sync's with appropriate sync
  points in MDL subsystem.
mysql-test/suite/perfschema/r/dml_setup_instruments.result:
  Updated test results after removing global
  COND_global_read_lock condition variable.
mysql-test/suite/perfschema/r/func_file_io.result:
  Ensure that this test doesn't affect subsequent tests.
  At the end of its execution enable back P_S instrumentation
  which this test disables at some point.
mysql-test/suite/perfschema/r/func_mutex.result:
  Ensure that this test doesn't affect subsequent tests.
  At the end of its execution enable back P_S instrumentation
  which this test disables at some point.
mysql-test/suite/perfschema/r/global_read_lock.result:
  Adjusted test case to take into account that new GRL
  implementation is based on MDL.
mysql-test/suite/perfschema/r/server_init.result:
  Adjusted test case after replacing custom global read
  lock implementation with one based on MDL and replacing
  LOCK_event_metadata mutex with metadata lock.
mysql-test/suite/perfschema/t/func_file_io.test:
  Ensure that this test doesn't affect subsequent tests.
  At the end of its execution enable back P_S instrumentation
  which this test disables at some point.
mysql-test/suite/perfschema/t/func_mutex.test:
  Ensure that this test doesn't affect subsequent tests.
  At the end of its execution enable back P_S instrumentation
  which this test disables at some point.
mysql-test/suite/perfschema/t/global_read_lock.test:
  Adjusted test case to take into account that new GRL
  implementation is based on MDL.
mysql-test/suite/perfschema/t/server_init.test:
  Adjusted test case after replacing custom global read
  lock implementation with one based on MDL and replacing
  LOCK_event_metadata mutex with metadata lock.
mysql-test/suite/rpl/r/rpl_tmp_table_and_DDL.result:
  Updated test results after prohibiting event DDL under
  LOCK TABLES.
mysql-test/t/delayed.test:
  Added test coverage for scenario which triggered assert in
  metadata locking subsystem.
mysql-test/t/events_2.test:
  Updated test case after prohibiting event DDL operations
  under LOCK TABLES.
mysql-test/t/flush.test:
  Added test coverage for bug #57006 "Deadlock between HANDLER
  and FLUSH TABLES WITH READ LOCK".
mysql-test/t/flush_block_commit.test:
  Adjusted test case after changing thread state name which
  is used when COMMIT waits for FLUSH TABLES WITH READ LOCK
  from "Waiting for release of readlock" to "Waiting for commit
  lock".
mysql-test/t/flush_block_commit_notembedded.test:
  Adjusted test case after changing thread state name which is
  used when DML waits for FLUSH TABLES WITH READ LOCK. Now we
  use "Waiting for global read lock" in this case.
mysql-test/t/flush_read_lock.test:
  Added test coverage for various aspects of FLUSH TABLES WITH
  READ LOCK functionality.
mysql-test/t/flush_read_lock_kill-master.opt:
  We no longer need to use make_global_read_lock_block_commit_loop
  debug tag in this test. Instead we rely on an appropriate
  debug_sync point in MDL code.
mysql-test/t/flush_read_lock_kill.test:
  Adjusted test case after replacing custom global read lock
  implementation with one based on metadata locks. Use new
  debug_sync point. Do not disable concurrent inserts as now
  InnoDB we always use InnoDB table.
mysql-test/t/lock_multi.test:
  Adjusted test case after changing thread state names which
  are used when DML or DDL waits for FLUSH TABLES WITH READ
  LOCK to "Waiting for global read lock".
mysql-test/t/mdl_sync.test:
  Adjusted test case after replacing custom global read lock
  implementation with one based on metadata locks. Replaced
  usage of GRL-specific debug_sync's with appropriate sync
  points in MDL subsystem. Updated thread state names which
  are used when DDL waits for FTWRL.
mysql-test/t/trigger_notembedded.test:
  Adjusted test case after changing thread state names which
  are used when DML or DDL waits for FLUSH TABLES WITH READ
  LOCK to "Waiting for global read lock".
sql/event_data_objects.cc:
  Removed Event_queue_element::status/last_executed_changed
  members and Event_queue_element::update_timing_fields()
  method. We no longer use this class for updating mysql.events
  once event is chosen for execution. Accesses to instances of
  this class in scheduler thread require protection by
  Event_queue::LOCK_event_queue mutex and we try to avoid
  updating table while holding this lock.
sql/event_data_objects.h:
  Removed Event_queue_element::status/last_executed_changed
  members and Event_queue_element::update_timing_fields()
  method. We no longer use this class for updating mysql.events
  once event is chosen for execution. Accesses to instances of
  this class in scheduler thread require protection by
  Event_queue::LOCK_event_queue mutex and we try to avoid
  updating table while holding this lock.
sql/event_db_repository.cc:
  - Changed Event_db_repository methods to not release all
    metadata locks once they are done updating mysql.events
    table. This allows to keep metadata lock protecting
    against GRL and lock protecting particular event around
    until corresponding DDL statement is written to the binary
    log.
  - Removed logic for conditional update of "status" and
    "last_executed" fields from update_timing_fields_for_event()
    method. In the only case when this method is called now
    "last_executed" is always modified and tracking change
    of "status" is too much hassle.
sql/event_db_repository.h:
  Removed logic for conditional update of "status" and
  "last_executed" fields from Event_db_repository::
  update_timing_fields_for_event() method.
  In the only case when this method is called now "last_executed"
  is always modified and tracking change of "status" field is
  too much hassle.
sql/event_queue.cc:
  Changed event scheduler code not to update mysql.events
  table while holding Event_queue::LOCK_event_queue mutex.
  Doing so led to a deadlock with a new GRL implementation.
  This deadlock didn't occur with old implementation due to
  fact that code acquiring protection against GRL ignored
  pending GRL requests (which lead to GRL starvation).
  One of goals of new implementation is to disallow GRL
  starvation and so we have to solve problem with this
  deadlock in a different way.
sql/events.cc:
  Changed methods of Events class to acquire protection
  against GRL while perfoming DDL statement and keep it
  until statement is written to the binary log.
  Unfortunately this step together with new GRL implementation
  exposed deadlock involving Events::LOCK_event_metadata
  and GRL. To solve it Events::LOCK_event_metadata mutex was
  replaced with a metadata lock on event. As a side-effect
  events DDL has to be prohibited under LOCK TABLES even in
  cases when mysql.events table was explicitly locked for
  write.
sql/events.h:
  Replaced Events::LOCK_event_metadata mutex with a metadata
  lock on event.
sql/ha_ndbcluster.cc:
  Updated code after replacing custom global read lock
  implementation with one based on MDL. Since MDL subsystem
  should now be able to detect deadlocks involving metadata
  locks and GRL there is no need for special handling of
  active GRL.
sql/handler.cc:
  Replaced custom implementation of global read lock with
  one based on metadata locks. Consequently when doing
  commit instead of calling method of Global_read_lock
  class to acquire protection against GRL we simply acquire
  IX in COMMIT namespace.
sql/lock.cc:
  Replaced custom implementation of global read lock with
  one based on metadata locks. This step allows to expose
  wait for GRL to deadlock detector of MDL subsystem and
  thus succesfully resolve deadlocks similar to one behind
  bug #57006 "Deadlock between HANDLER and FLUSH TABLES
  WITH READ LOCK". It also solves problem with GRL starvation
  described in bug #54673 "It takes too long to get readlock
  for 'FLUSH TABLES WITH READ LOCK'" since metadata locks used
  by GRL give preference to FTWRL statement instead of DML
  statements (if needed in future this can be changed to
  fair scheduling).
  
  Similar to old implementation of acquisition of GRL is
  two-step. During the first step we block all concurrent
  DML and DDL statements by acquiring global S metadata lock
  (each DML and DDL statement acquires global IX lock for
  its duration). During the second step we block commits by
  acquiring global S lock in COMMIT namespace (commit code
  acquires global IX lock in this namespace).
  
  Note that unlike in old implementation acquisition of
  protection against GRL in DML and DDL is semi-automatic.
  We assume that any statement which should be blocked by GRL
  will either open and acquires write-lock on tables or acquires
  metadata locks on objects it is going to modify. For any such
  statement global IX metadata lock is automatically acquired
  for its duration.
  
  To support this change:
  - Global_read_lock::lock/unlock_global_read_lock and
    make_global_read_lock_block_commit methods were changed
    accordingly.
  - Global_read_lock::wait_if_global_read_lock() and
    start_waiting_global_read_lock() methods were dropped.
    It is now responsibility of code acquiring metadata locks
    opening tables to acquire protection against GRL by
    explicitly taking global IX lock with statement duration.
  - Global variables, mutex and condition variable used by
    old implementation was removed.
  - lock_routine_name() was changed to use statement duration for
    its global IX lock. It was also renamed to lock_object_name()
    as it now also used to take metadata locks on events.
  - Global_read_lock::set_explicit_lock_duration() was added which
    allows not to release locks used for GRL when leaving prelocked
    mode.
sql/lock.h:
  - Renamed lock_routine_name() to lock_object_name() and changed
    its signature to allow its usage for events.
  - Removed broadcast_refresh() function. It is no longer needed
    with new GRL implementation.
sql/log_event.cc:
  Release metadata locks with statement duration at the end
  of processing legacy event for LOAD DATA. This ensures that
  replication thread processing such event properly releases
  its protection against global read lock.
sql/mdl.cc:
  Changed MDL subsystem to support new MDL-based implementation
  of global read lock.
  
  Added COMMIT and EVENTS namespaces for metadata locks. Changed
  thread state name for GLOBAL namespace to "Waiting for global
  read lock".
  
  Optimized MDL_map::find_or_insert() method to avoid taking
  m_mutex mutex when looking up MDL_lock objects for GLOBAL
  or COMMIT namespaces. We keep pre-created MDL_lock objects
  for these namespaces around and simply return pointers to
  these global objects when needed.
  
  Changed MDL_lock/MDL_scoped_lock to properly handle
  notification of insert delayed handler threads when FTWRL
  takes global S lock.
  
  Introduced concept of lock duration. In addition to locks with
  transaction duration which work in the way which is similar to
  how locks worked before (i.e. they are released at the end of
  transaction), locks with statement and explicit duration were
  introduced.
  Locks with statement duration are automatically released at the
  end of statement. Locks with explicit duration require explicit
  release and obsolete concept of transactional sentinel.
  
  * Changed MDL_request and MDL_ticket classes to support notion
    of duration.
  * Changed MDL_context to keep locks with different duration in
    different lists. Changed code handling ticket list to take
    this into account.
  * Changed methods responsible for releasing locks to take into
    account duration of tickets. Particularly public
    MDL_context::release_lock() method now only can release
    tickets with explicit duration (there is still internal
    method which allows to specify duration). To release locks
    with statement or transaction duration one have to use
    release_statement/transactional_locks() methods.
  * Concept of savepoint for MDL subsystem now has to take into
    account locks with statement duration. Consequently
    MDL_savepoint class was introduced and methods working with
    savepoints were updated accordingly.
  * Added methods which allow to set duration for one or all
    locks in the context.
sql/mdl.h:
  Changed MDL subsystem to support new MDL-based implementation
  of global read lock.
  
  Added COMMIT and EVENTS namespaces for metadata locks.
  
  Introduced concept of lock duration. In addition to locks with
  transaction duration which work in the way which is similar to
  how locks worked before (i.e. they are released at the end of
  transaction), locks with statement and explicit duration were
  introduced.
  Locks with statement duration are automatically released at the
  end of statement. Locks with explicit duration require explicit
  release and obsolete concept of transactional sentinel.
  
  * Changed MDL_request and MDL_ticket classes to support notion
    of duration.
  * Changed MDL_context to keep locks with different duration in
    different lists. Changed code handling ticket list to take
    this into account.
  * Changed methods responsible for releasing locks to take into
    account duration of tickets. Particularly public
    MDL_context::release_lock() method now only can release
    tickets with explicit duration (there is still internal
    method which allows to specify duration). To release locks
    with statement or transaction duration one have to use
    release_statement/transactional_locks() methods.
  * Concept of savepoint for MDL subsystem now has to take into
    account locks with statement duration. Consequently
    MDL_savepoint class was introduced and methods working with
    savepoints were updated accordingly.
  * Added methods which allow to set duration for one or all
    locks in the context.
sql/mysqld.cc:
  Removed global mutex and condition variables which were used
  by old implementation of GRL.
  Also we no longer need to initialize Events::LOCK_event_metadata
  mutex as it was replaced with metadata locks on events.
sql/mysqld.h:
  Removed global variable, mutex and condition variables which
  were used by old implementation of GRL.
sql/rpl_rli.cc:
  When slave thread closes tables which were open for handling
  of RBR events ensure that it releases global IX lock which
  was acquired as protection against GRL.
sql/sp.cc:
  Adjusted code to the new signature of lock_object/routine_name(),
  to the fact that one now needs specify duration of lock when
  initializing MDL_request and to the fact that savepoints for MDL
  subsystem are now represented by MDL_savepoint class.
sql/sp_head.cc:
  Ensure that statements in stored procedures release statement
  metadata locks and thus release their protectiong against GRL
  in proper moment in time.
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request.
sql/sql_admin.cc:
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request.
sql/sql_base.cc:
  - Implemented support for new approach to acquiring protection
    against global read lock. We no longer acquire such protection
    explicitly on the basis of statement flags. Instead we always
    rely on code which is responsible for acquiring metadata locks
    on object to be changed acquiring this protection. This is
    achieved by acquiring global IX metadata lock with statement
    duration. Code doing this also responsible for checking that
    current connection has no active GRL by calling an
    Global_read_lock::can_acquire_protection() method.
    Changed code in open_table() and lock_table_names()
    accordingly.
    Note that as result of this change DDL and DML on temporary
    tables is always compatible with GRL (before it was
    incompatible in some cases and compatible in other cases).
  - To speed-up code acquiring protection against GRL introduced
    m_has_protection_against_grl member in Open_table_context
    class. It indicates that protection was already acquired
    sometime during open_tables() execution and new attempts
    can be skipped.
  - Thanks to new GRL implementation calls to broadcast_refresh()
    became unnecessary and were removed.
  - Adjusted code to the fact that one now needs specify duration
    of lock when initializing MDL_request and to the fact that
    savepoints for MDL subsystem are now represented by
    MDL_savepoint class.
sql/sql_base.h:
  Adjusted code to the fact that savepoints for MDL subsystem are
  now represented by MDL_savepoint class.
  Also introduced Open_table_context::m_has_protection_against_grl
  member which allows to avoid acquiring protection against GRL
  while opening tables if such protection was already acquired.
sql/sql_class.cc:
  Changed THD::leave_locked_tables_mode() after transactional
  sentinel for metadata locks was obsoleted by introduction of
  locks with explicit duration.
sql/sql_class.h:
  - Adjusted code to the fact that savepoints for MDL subsystem
    are now represented by MDL_savepoint class.
  - Changed Global_read_lock class according to changes in
    global read lock implementation:
    * wait_if_global_read_lock and start_waiting_global_read_lock
      are now gone. Instead code needing protection against GRL
      has to acquire global IX metadata lock with statement
      duration itself. To help it new can_acquire_protection()
      was introduced. Also as result of the above change
      m_protection_count member is gone too.
    * Added m_mdl_blocks_commits_lock member to store metadata
      lock blocking commits.
    * Adjusted code to the fact that concept of transactional
      sentinel was obsoleted by concept of lock duration.
  - Removed CF_PROTECT_AGAINST_GRL flag as it is no longer
    necessary. New GRL implementation acquires protection
    against global read lock automagically when statement
    acquires metadata locks on tables or other objects it
    is going to change.
sql/sql_db.cc:
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request.
sql/sql_handler.cc:
  Removed call to broadcast_refresh() function. It is no longer
  needed with new GRL implementation.
  Adjusted code after introducing duration concept for metadata
  locks. Particularly to the fact transactional sentinel was
  replaced with explicit duration.
sql/sql_handler.h:
  Renamed mysql_ha_move_tickets_after_trans_sentinel() to
  mysql_ha_set_explicit_lock_duration() after transactional
  sentinel was obsoleted by locks with explicit duration.
sql/sql_insert.cc:
  Adjusted code handling delaying inserts after switching to
  new GRL implementation. Now connection thread initiating
  delayed insert has to acquire global IX lock in addition
  to metadata lock on table being inserted into. This IX lock
  protects against GRL and similarly to SW lock on table being
  inserted into has to be passed to handler thread in order to
  avoid deadlocks.
sql/sql_lex.cc:
  LEX::protect_against_global_read_lock member is no longer
  necessary since protection against GRL is automatically
  taken by code acquiring metadata locks/opening tables.
sql/sql_lex.h:
  LEX::protect_against_global_read_lock member is no longer
  necessary since protection against GRL is automatically
  taken by code acquiring metadata locks/opening tables.
sql/sql_parse.cc:
  - Implemented support for new approach to acquiring protection
    against global read lock. We no longer acquire such protection
    explicitly on the basis of statement flags. Instead we always
    rely on code which is responsible for acquiring metadata locks
    on object to be changed acquiring this protection. This is
    achieved by acquiring global IX metadata lock with statement
    duration. This lock is automatically released at the end of
    statement execution.
  - Changed implementation of CREATE/DROP PROCEDURE/FUNCTION not
    to release metadata locks and thus protection against of GRL
    in the middle of statement execution.
  - Adjusted code to the fact that one now needs specify duration
    of lock when initializing MDL_request and to the fact that
    savepoints for MDL subsystem are now represented by
    MDL_savepoint class.
sql/sql_prepare.cc:
  Adjusted code to the to the fact that savepoints for MDL
  subsystem are now represented by MDL_savepoint class.
sql/sql_rename.cc:
  With new GRL implementation there is no need to explicitly
  acquire protection against GRL before renaming tables.
  This happens automatically in code which acquires metadata
  locks on tables being renamed.
sql/sql_show.cc:
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request and to the fact that
  savepoints for MDL subsystem are now represented by
  MDL_savepoint class.
sql/sql_table.cc:
  - With new GRL implementation there is no need to explicitly
    acquire protection against GRL before dropping tables.
    This happens automatically in code which acquires metadata
    locks on tables being dropped.
  - Changed mysql_alter_table() not to release lock on new table
    name explicitly and to rely on automatic release of locks
    at the end of statement instead. This was necessary since
    now MDL_context::release_lock() is supported only for locks
    for explicit duration.
sql/sql_trigger.cc:
  With new GRL implementation there is no need to explicitly
  acquire protection against GRL before changing table triggers.
  This happens automatically in code which acquires metadata
  locks on tables which triggers are to be changed.
sql/sql_update.cc:
  Fix bug exposed by GRL testing. During prepare phase acquire
  only S metadata locks instead of SW locks to keep prepare of
  multi-UPDATE compatible with concurrent LOCK TABLES WRITE
  and global read lock.
sql/sql_view.cc:
  With new GRL implementation there is no need to explicitly
  acquire protection against GRL before creating view.
  This happens automatically in code which acquires metadata
  lock on view to be created.
sql/sql_yacc.yy:
  LEX::protect_against_global_read_lock member is no longer
  necessary since protection against GRL is automatically
  taken by code acquiring metadata locks/opening tables.
sql/table.cc:
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request.
sql/table.h:
  Adjusted code to the fact that one now needs specify duration
  of lock when initializing MDL_request.
sql/transaction.cc:
  Replaced custom implementation of global read lock with
  one based on metadata locks. Consequently when doing
  commit instead of calling method of Global_read_lock
  class to acquire protection against GRL we simply acquire
  IX in COMMIT namespace.
  Also adjusted code to the fact that MDL savepoint is now
  represented by MDL_savepoint class.
2010-11-11 20:11:05 +03:00
Mikael Ronstrom
4dff0296f4 Added more wait states for THD wait service 2010-10-27 20:29:09 +02:00
Dmitry Lenev
476939cb45 Reverted a temporary workaround for bug #56405 "Deadlock
in the MDL deadlock detector".

It is no longer needed as a better fix for this bug has
been pushed.
2010-09-30 17:29:12 +04:00
Dmitry Lenev
f052fa3aad A temporary workaround for bug #56405 "Deadlock in the
MDL deadlock detector".

Deadlock could have occurred when workload containing mix
of DML, DDL and FLUSH TABLES statements affecting same
set of tables was executed in heavily concurrent environment.

This deadlock occurred when several connections tried to
perform deadlock detection in metadata locking subsystem.
The first connection started traversing wait-for graph,
encountered sub-graph representing wait for flush, acquired
LOCK_open and dived into sub-graph inspection. When it has
encounterd sub-graph corresponding to wait for metadata lock
and blocked while trying to acquire rd-lock on
MDL_lock::m_rwlock (*) protecting this subgraph, since some
other thread had wr-lock on it. When this wr-lock was released
it could have happened (if there was other pending wr-lock
against this rwlock) that rd-lock from the first connection
was left unsatisfied but at the same time new rd-lock request
from the second connection sneaked in and was satisfied (for
this to be possible second rd- request should come exactly
after wr-lock is released but before pending wr-lock manages
to grab rwlock, which is possible both on Linux and in our
own rwlock implementation). If this second connection
continued traversing wait-for graph and encountered sub-graph
representing wait for flush it tried to acquire LOCK_open
and thus deadlock was created.

This patch tries to workaround this problem but not allowing
deadlock detector to lock LOCK_open mutex if some other thread
doing deadlock detection already owns it and current search
depth is greater than 0. Instead deadlock is reported.

Other possible solutions are either known to have negative
effects on performance or require much more time for proper
implementation and testing.

No test case is provided as this bug is very hard to repeat
in MTR environment but is repeatable with the help of RQG
tests.

sql/mdl.cc:
  Moved Deadlock_detection_visitor::m_current_search_depth to
  parent class to make it available in
  TABLE_SHARE::visit_subgraph().
  Added MDL_wait_for_graph_visitor::abort_traversal() method
  which allows to abort traversal of a wait-for graph and
  report a deadlock.
sql/mdl.h:
  Moved Deadlock_detection_visitor::m_current_search_depth to
  parent class to make it available in
  TABLE_SHARE::visit_subgraph().
  Added MDL_wait_for_graph_visitor::abort_traversal() method
  which allows to abort traversal of a wait-for graph and
  report a deadlock.
sql/sql_base.cc:
  Added dd_owns_lock_open counter and mutex protecting it to
  track number of connections which do deadlock detection and
  own or try to acquire LOCK_open.
sql/sql_base.h:
  Added dd_owns_lock_open counter and mutex protecting it to
  track number of connections which do deadlock detection and
  own or try to acquire LOCK_open.
sql/table.cc:
  Workaround bug #56405 but not allowing MDL deadlock detector
  to lock LOCK_open mutex if some other thread doing deadlock
  detection already owns it and current search depth is greater
  than 0. Instead report deadlock.
2010-09-06 21:29:02 +04:00
Konstantin Osipov
29c4873ad5 Commit on behalf of Dmitry Lenev.
Merge his patch for Bug#52044 into 5.5, and apply 
review comments.
2010-08-12 17:50:23 +04:00
Konstantin Osipov
523066987d A fix for Bug#41158 "DROP TABLE holds LOCK_open during unlink()".
Remove acquisition of LOCK_open around file system operations,
since such operations are now protected by metadata locks.
Rework table discovery algorithm to not require LOCK_open.

No new tests added since all MDL locking operations are covered
in lock.test and mdl_sync.test, and as long as these tests
pass despite the increased concurrency, consistency must be
unaffected.

mysql-test/t/disabled.def:
  Disable NDB tests due to Bug#55799.
sql/datadict.cc:
  No longer necessary to protect ha_create_table() with
  LOCK_open. Serial execution is now ensured by metadata
  locks.
sql/ha_ndbcluster.cc:
  Do not manipulate with LOCK_open in cluster code.
sql/ha_ndbcluster_binlog.cc:
  Do not manipulate with LOCK_open in cluster code.
sql/ha_ndbcluster_binlog.h:
  Update function signature.
sql/handler.cc:
  Implement ha_check_if_table_exists().
  @todo: some engines provide ha_table_exists_in_engine()
  handlerton call, for those we perhaps shouldn't
  call ha_discover(), to be more efficient.
  Since currently it's only NDB, postpone till
  integration with NDB.
sql/handler.h:
  Declare ha_check_if_table_exists() function.
sql/mdl.cc:
  Remove an obsolete comment.
sql/sql_base.cc:
  Update to a new signature of close_cached_tables():
  from now on we always call it without LOCK_open.
  Update comments.
  Remove get_table_share_with_create(), we should
  not attempt to create a table under LOCK_open.
  Introduce get_table_share_with_discover() instead,
  which would request a back off action if the table
  exists in engine.
  Remove acquisition of LOCK_open for 
  data dictionary operations, such as check_if_table_exists().
  Do not use get_table_share_with_create/discover for views,
  where it's not needed.
  Make tdc_remove_table() optionally acquire LOCK_open
  to simplify usage of this function.
  Use the right mutex in the partitioning code when
  manipulating with thd->open_tables.
sql/sql_base.h:
  Update signatures of changes functions.
sql/sql_insert.cc:
  Do not wrap quick_rm_table() with LOCK_open acquisition, 
  this is unnecessary.
sql/sql_parse.cc:
  Update to the new calling convention of tdc_remove_table().
  Update to the new signature of close_cached_tables().
  Update comments.
sql/sql_rename.cc:
  Update to the new calling convention of tdc_remove_table().
  Remove acquisition of LOCK_open around filesystem
  operations.
sql/sql_show.cc:
  Remove get_trigger_table_impl().
  Do not acquire LOCK_open for a dirty read of the trigger
  file.
sql/sql_table.cc:
  Do not acquire LOCK_open for filesystem operations.
sql/sql_trigger.cc:
  Do not require LOCK_open for trigger file I/O.
sql/sql_truncate.cc:
  Update to the new signature of tdc_remove_table().
sql/sql_view.cc:
  Do not require LOCK_open for view I/O.
  Use tdc_remove_table() to expel view share.
  Update comments.
sql/sys_vars.cc:
  Update to the new signature of close_cached_tables().
2010-08-09 22:33:47 +04:00
Dmitry Lenev
8d0dc9b58b Part of fix for bug#52044 "FLUSH TABLES WITH READ LOCK and
FLUSH TABLES <list> WITH READ LOCK are incompatible" to
be pushed as separate patch.

Replaced thread state name "Waiting for table", which was
used by threads waiting for a metadata lock or table flush, 
with a set of names which better reflect types of resources
being waited for.

Also replaced "Table lock" thread state name, which was used 
by threads waiting on thr_lock.c table level lock, with more
elaborate "Waiting for table level lock", to make it 
more consistent with other thread state names.

Updated test cases and their results according to these 
changes.

Fixed sys_vars.query_cache_wlock_invalidate_func test to not
to wait for timeout of wait_condition.inc script.

mysql-test/r/query_cache.result:
  Added test coverage for query_cache_wlock_invalidate
  behavior for implicitly locked tables.
mysql-test/suite/sys_vars/r/query_cache_wlock_invalidate_func.result:
  Fixed sys_vars.query_cache_wlock_invalidate_func test to not
  to wait for timeout of wait_condition.inc script. Reverted
  changes to test which introduced timeout and replaced waiting
  condition with a more appropriate one.
  Test coverage for query_cache_wlock_invalidate behavior for
  implicitly locked tables was added to query_cache.test.
mysql-test/suite/sys_vars/t/query_cache_wlock_invalidate_func.test:
  Fixed sys_vars.query_cache_wlock_invalidate_func test to not
  to wait for timeout of wait_condition.inc script. Reverted
  changes to test which introduced timeout and replaced waiting
  condition with a more appropriate one.
  Test coverage for query_cache_wlock_invalidate behavior for
  implicitly locked tables was added to query_cache.test.
mysql-test/t/query_cache.test:
  Added test coverage for query_cache_wlock_invalidate
  behavior for implicitly locked tables.
mysys/thr_lock.c:
  Replaced "Table lock" thread state name, which was used by 
  threads waiting on thr_lock.c table level lock, with more
  elaborate "Waiting for table level lock", to make it 
  consistent with thread state names which are used while
  waiting for metadata locks and table flush.
sql/mdl.cc:
  Replaced thread state name "Waiting for table", which was
  used by threads waiting for a metadata lock or table flush, 
  with a set of names which better reflect types of resources
  being waited for. 
  
  To implement this:
  - Adjusted MDL_wait::timed_wait() to take thread state name
    as parameter.
  - Introduced method of MDL_key class which allows to get
    thread state name to be used while waiting for resource
    corresponding to the key and changed code to use it.
    Added array translating namespaces to thread state names
    as part of this change.
sql/mdl.h:
  To implement this:
  - Adjusted MDL_wait::timed_wait() to take thread state name
    as parameter.
  - Introduced method of MDL_key class which allows to get
    thread state name to be used while waiting for resource
    corresponding to the key and changed code to use it.
    Added array translating namespaces to thread state names
    as part of this change.
sql/sql_base.cc:
  Replaced thread state name "Waiting for table", which was
  used by threads waiting for table flush, with a more elaborate
  "Waiting for table flush".
2010-08-06 15:29:37 +04:00
Dmitry Lenev
00496b7acd Fix for bug #52044 "FLUSH TABLES WITH READ LOCK and FLUSH
TABLES <list> WITH READ LOCK are incompatible".

The problem was that FLUSH TABLES <list> WITH READ LOCK
which was issued when other connection has acquired global
read lock using FLUSH TABLES WITH READ LOCK was blocked
and has to wait until global read lock is released.

This issue stemmed from the fact that FLUSH TABLES <list>
WITH READ LOCK implementation has acquired X metadata locks
on tables to be flushed. Since these locks required acquiring
of global IX lock this statement was incompatible with global
read lock.

This patch addresses problem by using SNW metadata type of
lock for tables to be flushed by FLUSH TABLES <list> WITH
READ LOCK. It is OK to acquire them without global IX lock
as long as we won't try to upgrade those locks. Since SNW
locks allow concurrent statements using same table FLUSH
TABLE <list> WITH READ LOCK now has to wait until old
versions of tables to be flushed go away after acquiring
metadata locks. Since such waiting can lead to deadlock
MDL deadlock detector was extended to take into account
waits for flush and resolve such deadlocks.

As a bonus code in open_tables() which was responsible for
waiting old versions of tables to go away was refactored.
Now when we encounter old version of table in open_table()
we don't back-off and wait for all old version to go away,
but instead wait for this particular table to be flushed.
Such approach supported by deadlock detection should reduce
number of scenarios in which FLUSH TABLES aborts concurrent
multi-statement transactions.

Note that active FLUSH TABLES <list> WITH READ LOCK still
blocks concurrent FLUSH TABLES WITH READ LOCK statement
as the former keeps tables open and thus prevents the
latter statement from doing flush.

mysql-test/include/handler.inc:
  Adjusted test case after changing status which is set
  when FLUSH TABLES waits for tables to be flushed from
  "Flushing tables" to "Waiting for table".
mysql-test/r/flush.result:
  Added test which checks that "flush tables <list> with
  read lock" is compatible with active "flush tables with
  read lock" but not vice-versa. This test also covers
  bug #52044 "FLUSH TABLES WITH READ LOCK and FLUSH TABLES
  <list> WITH READ LOCK are incompatible".
mysql-test/r/mdl_sync.result:
  Added scenarios in which wait for table to be flushed
  causes deadlocks to the coverage of MDL deadlock detector.
mysql-test/suite/perfschema/r/dml_setup_instruments.result:
  Adjusted test results after removal of COND_refresh
  condition variable.
mysql-test/suite/perfschema/r/server_init.result:
  Adjusted test and its results after removal of COND_refresh
  condition variable.
mysql-test/suite/perfschema/t/server_init.test:
  Adjusted test and its results after removal of COND_refresh
  condition variable.
mysql-test/t/flush.test:
  Added test which checks that "flush tables <list> with
  read lock" is compatible with active "flush tables with
  read lock" but not vice-versa. This test also covers
  bug #52044 "FLUSH TABLES WITH READ LOCK and FLUSH TABLES
  <list> WITH READ LOCK are incompatible".
mysql-test/t/kill.test:
  Adjusted test case after changing status which is set
  when FLUSH TABLES waits for tables to be flushed from
  "Flushing tables" to "Waiting for table".
mysql-test/t/lock_multi.test:
  Adjusted test case after changing status which is set
  when FLUSH TABLES waits for tables to be flushed from
  "Flushing tables" to "Waiting for table".
mysql-test/t/mdl_sync.test:
  Added scenarios in which wait for table to be flushed
  causes deadlocks to the coverage of MDL deadlock detector.
sql/ha_ndbcluster.cc:
  Adjusted code after adding one more parameter for
  close_cached_tables() call - timeout for waiting for
  table to be flushed.
sql/ha_ndbcluster_binlog.cc:
  Adjusted code after adding one more parameter for
  close_cached_tables() call - timeout for waiting for
  table to be flushed.
sql/lock.cc:
  Removed COND_refresh condition variable. See comment
  for sql_base.cc for details.
sql/mdl.cc:
  Now MDL deadlock detector takes into account information
  about waits for table flushes when searching for deadlock.
  To implement this change:
  - Declaration of enum_deadlock_weight and
    Deadlock_detection_visitor were moved to mdl.h header
    to make them available to the code in table.cc which
    implements deadlock detector traversal through edges
    of waiters graph representing waiting for flush.
  - Since now MDL_context may wait not only for metadata
    lock but also for table to be flushed an abstract
    Wait_for_edge class was introduced. Its descendants
    MDL_ticket and Flush_ticket incapsulate specifics
    of inspecting waiters graph when following through
    edge representing wait of particular type.
  
  We no longer require global IX metadata lock when acquiring
  SNW or SNRW locks. Such locks are needed only when metadata
  locks of these types are upgraded to X locks. This allows
  to use SNW locks in FLUSH TABLES <list> WITH READ LOCK
  implementation and keep the latter compatible with global
  read lock.
sql/mdl.h:
  Now MDL deadlock detector takes into account information
  about waits for table flushes when searching for deadlock.
  To implement this change:
  - Declaration of enum_deadlock_weight and
    Deadlock_detection_visitor were moved to mdl.h header
    to make them available to the code in table.cc which
    implements deadlock detector traversal through edges
    of waiters graph representing waiting for flush.
  - Since now MDL_context may wait not only for metadata
    lock but also for table to be flushed an abstract
    Wait_for_edge class was introduced. Its descendants
    MDL_ticket and Flush_ticket incapsulate specifics
    of inspecting waiters graph when following through
    edge representing wait of particular type.
  - Deadlock_detection_visitor now has m_table_shares_visited
    member which allows to support recursive locking for
    LOCK_open. This is required when deadlock detector
    inspects waiters graph which contains several edges
    representing waits for flushes or needs to come through
    the such edge more than once.
sql/mysqld.cc:
  Removed COND_refresh condition variable. See comment
  for sql_base.cc for details.
sql/mysqld.h:
  Removed COND_refresh condition variable. See comment
  for sql_base.cc for details.
sql/sql_base.cc:
  Changed approach to how threads are waiting for table
  to be flushed. Now thread that wants to wait for old
  table to go away subscribes for notification by adding
  Flush_ticket to table's share and waits using
  MDL_context::m_wait object. Once table gets flushed
  (i.e. all tables are closed and table share is ready
  to be destroyed) all such waiters are notified
  individually.
  Thanks to this change MDL deadlock detector can take
  such waits into account.
  
  To implement this/as result of this change:
  - tdc_wait_for_old_versions() was replaced with
    tdc_wait_for_old_version() which waits for individual
    old share to go away and which is called by open_table()
    after finding out that share is outdated. We don't
    need to perform back-off before such waiting thanks
    to the fact that deadlock detector now sees such waits.
  - As result Open_table_ctx::m_mdl_requests became
    unnecessary and was removed. We no longer allocate
    copies of MDL_request objects on MEM_ROOT when
    MYSQL_OPEN_FORCE_SHARED/SHARED_HIGH_PRIO flags are
    in effect.
  - close_cached_tables() and tdc_wait_for_old_version()
    share code which implements waiting for share to be
    flushed - the both use TABLE_SHARE::wait_until_flush()
    method. Thanks to this close_cached_tables() supports
    timeouts and has extra parameter for this.
  - Open_table_context::OT_MDL_CONFLICT enum element was
    renamed to OT_CONFLICT as it is now also used in cases
    when back-off is required to resolve deadlock caused
    by waiting for flush and not metadata lock.
  - In cases when we discover that current connection tries
    to open tables from different generation we now simply
    back-off and restart process of opening tables. To
    support this Open_table_context::OT_REOPEN_TABLES enum
    element was added.
  - COND_refresh condition variable became unnecessary and
    was removed.
  - mysql_notify_thread_having_shared_lock() no longer wakes
    up connections waiting for flush as all such connections
    can be waken up by deadlock detector if necessary.
sql/sql_base.h:
  - close_cached_tables() now has one more parameter -
    timeout for waiting for table to be flushed.
  - Open_table_context::OT_MDL_CONFLICT enum element was
    renamed to OT_CONFLICT as it is now also used in cases
    when back-off is required to resolve deadlock caused
    by waiting for flush and not metadata lock.
    Added new OT_REOPEN_TABLES enum element to be used in
    cases when we need to restart open tables process even
    in the middle of transaction.
  - Open_table_ctx::m_mdl_requests became unnecessary and
    was removed.
sql/sql_class.h:
  Added assert ensuring that we won't use LOCK_open mutex
  with THD::enter_cond(). Otherwise deadlocks can arise in
  MDL deadlock detector.
sql/sql_parse.cc:
  Changed FLUSH TABLES <list> WITH READ LOCK to take SNW
  metadata locks instead of X locks on tables to be flushed.
  Since we no longer require global IX lock to be taken
  when SNW locks are taken this makes this statement
  compatible with FLUSH TABLES WITH READ LOCK statement.
  Since SNW locks allow other connections to have table
  opened FLUSH TABLES <list> WITH READ LOCK now has to
  wait during open_tables() for old version to go away.
  Such waits can lead to deadlocks which will be detected
  by MDL deadlock detector which now takes waits for table
  to be flushed into account.
  
  Also adjusted code after adding one more parameter for
  close_cached_tables() call - timeout for waiting for
  table to be flushed.
sql/sql_yacc.yy:
  FLUSH TABLES <list> WITH READ LOCK now needs only SNW
  metadata locks on tables.
sql/sys_vars.cc:
  Adjusted code after adding one more parameter for
  close_cached_tables() call - timeout for waiting for
  table to be flushed.
sql/table.cc:
  Implemented new approach to how threads are waiting for
  table to be flushed. Now thread that wants to wait for
  old table to go away subscribes for notification by
  adding Flush_ticket to table's share and waits using
  MDL_context::m_wait object. Once table gets flushed
  (i.e. all tables are closed and table share is ready
  to be destroyed) all such waiters are notified
  individually. This change allows to make such waits
  visible inside of MDL deadlock detector.
  To do it:
  
  - Added list of waiters/Flush_tickets to TABLE_SHARE
    class.
  - Changed free_table_share() to postpone freeing of
    share memory until last waiter goes away and to
    wake up subscribed waiters.
  - Added TABLE_SHARE::wait_until_flushed() method which
    implements subscription to the list of waiters for
    table to be flushed and waiting for this event.
  
  Implemented interface which allows to expose waits for
  flushes to MDL deadlock detector:
  
  - Introduced Flush_ticket class a descendant of
    Wait_for_edge class.
  - Added TABLE_SHARE::find_deadlock() method which allows
    deadlock detector to find out what contexts are still
    using old version of table in question (i.e. to find
    out what contexts are waited for by owner of
    Flush_ticket).
sql/table.h:
  In order to support new strategy of waiting for table flush
  (see comment for table.cc for details) added list of
  waiters/Flush_tickets to TABLE_SHARE class.
  
  Implemented interface which allows to expose waits for
  flushes to MDL deadlock detector:
  - Introduced Flush_ticket class a descendant of
    Wait_for_edge class.
  - Added TABLE_SHARE::find_deadlock() method which allows
    deadlock detector to find out what contexts are still
    using old version of table in question (i.e. to find
    out what contexts are waited for by owner of
    Flush_ticket).
2010-07-27 17:34:58 +04:00
Jon Olav Hauglid
ec002090b9 Bug #55223 assert in Protocol::end_statement during CREATE DATABASE
The problem was that a statement could cause an assert if it was aborted by
KILL QUERY while it waited on a metadata lock. This assert checks that a
statement either sends OK or an error to the client. If the bug was triggered
on release builds, it caused OK to be sent to the client instead of
ER_QUERY_INTERRUPTED.

The root cause of the problem was that there are two separate ways to tell if a
statement is killed: thd->killed and mysys_var->abort. KILL QUERY causes both
to be set, thd->killed before mysys_var->abort. Also, both values are reset
at the end of statement execution. This means that it is possible for
KILL QUERY to first set thd->killed, then have the killed statement reset
both thd->killed and mysys_var->abort and finally have KILL QUERY set
mysys_var->abort. This means that the connection with the killed statement
will start executing the next statement with the two values out of sync - i.e.
thd->killed not set but mysys_var->abort set.

Since mysys_var->abort is used to check if a wait for a metadata lock should
be aborted, the next statement would immediately abort any such waiting.
When waiting is aborted, no OK message is sent and thd->killed is checked to
see if ER_QUERY_INTERRUPTED should be sent to the client. But since
the->killed had been reset, neither OK nor an error message was sent to the
client. This then triggered the assert.

This patch fixes the problem by changing the metadata lock waiting code to
check thd->killed.

No test case added as reproducing the assert is dependent on very exact timing
of two (or more) threads. The patch has been checked using RQG and the grammar
posted on the bug report.
2010-07-22 10:00:32 +02:00
Dmitry Lenev
a6a8e10c79 A pre-requisite for patch fixing bug #52044 "FLUSH TABLES
WITH READ LOCK and FLUSH TABLES <list> WITH READ LOCK are
incompatible", which adds information about waits caused by 
FLUSH TABLES statement to deadlock detector in MDL subsystem.

Remove API supporting caching of pointers to TABLE_SHARE 
object in MDL subsystem and all code related to it. 

The problem was that locking requirements of code 
implementing this API conflicted with locking requirements 
of code which adds information about waits caused by flushes 
to deadlock detector in MDL subsystem (the former needed to
lock LOCK_open or its future equivalent while having 
write-lock on MDL_lock's rwlock, and the latter needs to be 
able to read-lock MDL_lock rwlock while owning LOCK_open or 
its future equivalent).

Since caching of pointers to TABLE_SHARE objects in MDL 
subsystem didn't bring expected performance benefits we 
decided to remove caching API rather than try to come up 
with some complex solution for this problem.
2010-07-13 22:01:54 +04:00
Jon Olav Hauglid
f45523188e merge from mysql-trunk-bugfixing 2010-07-13 10:39:24 +02:00
Davi Arnaut
f56dd32bf7 Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled
Essentially, the problem is that safemalloc is excruciatingly
slow as it checks all allocated blocks for overrun at each
memory management primitive, yielding a almost exponential
slowdown for the memory management functions (malloc, realloc,
free). The overrun check basically consists of verifying some
bytes of a block for certain magic keys, which catches some
simple forms of overrun. Another minor problem is violation
of aliasing rules and that its own internal list of blocks
is prone to corruption.

Another issue with safemalloc is rather the maintenance cost
as the tool has a significant impact on the server code.
Given the magnitude of memory debuggers available nowadays,
especially those that are provided with the platform malloc
implementation, maintenance of a in-house and largely obsolete
memory debugger becomes a burden that is not worth the effort
due to its slowness and lack of support for detecting more
common forms of heap corruption.

Since there are third-party tools that can provide the same
functionality at a lower or comparable performance cost, the
solution is to simply remove safemalloc. Third-party tools
can provide the same functionality at a lower or comparable
performance cost. 

The removal of safemalloc also allows a simplification of the
malloc wrappers, removing quite a bit of kludge: redefinition
of my_malloc, my_free and the removal of the unused second
argument of my_free. Since free() always check whether the
supplied pointer is null, redudant checks are also removed.

Also, this patch adds unit testing for my_malloc and moves
my_realloc implementation into the same file as the other
memory allocation primitives.

client/mysqldump.c:
  Pass my_free directly as its signature is compatible with the
  callback type -- which wasn't the case for free_table_ent.
2010-07-08 18:20:08 -03:00
Jon Olav Hauglid
9ff272fbbd A 5.5 version of the fix for Bug #54360 "Deadlock DROP/ALTER/CREATE
DATABASE with open HANDLER"

Remove LOCK_create_db, database name locks, and use metadata locks instead.
This exposes CREATE/DROP/ALTER DATABASE statements to the graph-based
deadlock detector in MDL, and paves the way for a safe, deadlock-free
implementation of RENAME DATABASE.

Database DDL statements will now take exclusive metadata locks on
the database name, while table/view/routine DDL statements take
intention exclusive locks on the database name. This prevents race
conditions between database DDL and table/view/routine DDL.
(e.g. DROP DATABASE with concurrent CREATE/ALTER/DROP TABLE)

By adding database name locks, this patch implements
WL#4450 "DDL locking: CREATE/DROP DATABASE must use database locks" and
WL#4985 "DDL locking: namespace/hierarchical locks".

The patch also changes code to use init_one_table() where appropriate.
The new lock_table_names() function requires TABLE_LIST::db_length to
be set correctly, and this is taken care of by init_one_table().

This patch also adds a simple template to help work with 
the mysys HASH data structure.

Most of the patch was written by Konstantin Osipov.
2010-07-01 15:53:46 +02:00
Konstantin Osipov
429454f76e A new implementation for the TABLE_SHARE cache in MDL
subsystem. Fix a number of caveates that the previous
implementation suffered from, including unprotected
access to shared data and lax resource accounting
(share->ref_count) that could lead to deadlocks.

The new implementation still suffers from a number
of potential deadlocks in some edge cases, and this is 
still not enabled by default. Especially since performance
testing has shown that it gives only marginable (not even 
exceeding measuring accuracy) improvements.

@todo: 
- Remove calls to close_cached_tables() with REFRESH_FAST,
and have_lock, because they break the MDL cache. 
- rework FLUSH TABLES <list> to not use close_cached_tables()
- make sure that whenever we set TABLE_SHARE::version to
0 we free MDL cache references to it.


sql/mdl.cc:
  We may cache references to TABLE_SHARE objects in 
  MDL_lock objects for tables. Create a separate
  MDL_lock class to represent a table.
sql/mdl.h:
  Adjust the MDL caching API to avoid races.
sql/sql_base.cc:
  Move all caching functionality close together.
  Implement a solution for deadlocks caused by 
  close_cached_tables() when MDL cache is enabled (incomplete).
sql/sql_yacc.yy:
  Adjust FLUSH rule to do the necessary initialization of
  TABLE_LIST elements used in for FLUSH TABLES <list>, and thus
  work OK with flush_mdl_cache() function.
2010-06-18 20:14:10 +04:00
Dmitry Lenev
9dbd9ce185 Patch that changes approach to how we acquire metadata
locks for DML statements and changes the way MDL locks
are acquired/granted in contended case.

Instead of backing-off when a lock conflict is encountered
and waiting for it to go away before restarting open_tables()
process we now wait for lock to be released without releasing
any previously acquired locks. If conflicting lock goes away
we resume opening tables. If waiting leads to a deadlock we
try to resolve it by backing-off and restarting open_tables()
immediately.

As result both waiting for possibility to acquire and
acquiring of a metadata lock now always happen within the
same MDL API call. This has allowed to make release of a lock
and granting it to the most appropriate pending request an
atomic operation.
Thanks to this it became possible to wake up during release
of lock only those waiters which requests can be satisfied
at the moment as well as wake up only one waiter in case
when granting its request would prevent all other requests
from being satisfied. This solves thundering herd problem
which occured in cases when we were releasing some lock and
woke up many waiters for SNRW or X locks (this was the issue
in bug#52289 "performance regression for MyISAM in sysbench
OLTP_RW test".
This also allowed to implement more fair (FIFO) scheduling
among waiters with the same priority.
It also opens the door for introducing new types of requests
for metadata locks such as low-prio SNRW lock which is
necessary in order to support LOCK TABLES LOW_PRIORITY WRITE.

Notice that after this sometimes can report ER_LOCK_DEADLOCK
error in cases in which it has not happened before.
Particularly we will always report this error if waiting for
conflicting lock has happened in the middle of transaction
and resulted in a deadlock. Before this patch the error was
not reported if deadlock could have been resolved by backing
off all metadata locks acquired by the current statement.

mysql-test/r/mdl_sync.result:
  Added test coverage for some aspects of deadlock handling in
  metadata locking subsystem.
  Adjusted test case after removing back-off in general case
  when conflicting metadata lock is encountered during
  open_tables() (now this happens only if waiting for
  conflicting lock to go away leads to a deadlock).
mysql-test/r/sp_sync.result:
  Adjusted test case after removing back-off in general case
  when conflicting metadata lock is encountered during
  open_tables() (now this happens only if waiting for
  conflicting lock to go away leads to a deadlock).
mysql-test/suite/perfschema/r/dml_setup_instruments.result:
  Adjusted test results after renaming MDL_context::
  m_waiting_for_lock rwlock to m_LOCK_waiting_for.
mysql-test/suite/rpl/r/rpl_sp.result:
  Adjusted test case after implementing new approach to
  acquiring metadata locks in open_tables(). We no longer
  release all MDL locks acquired by statement before waiting
  for conflicting lock to go away. As result DROP FUNCTION
  statement has to wait for DML statement which managed to
  acquire metadata lock on function being dropped and now
  waits for other conflicting metadata lock to go away.
mysql-test/suite/rpl/t/rpl_sp.test:
  Adjusted test case after implementing new approach to
  acquiring metadata locks in open_tables(). We no longer
  release all MDL locks acquired by statement before waiting
  for conflicting lock to go away. As result DROP FUNCTION
  statement has to wait for DML statement which managed to
  acquire metadata lock on function being dropped and now
  waits for other conflicting metadata lock to go away.
mysql-test/t/mdl_sync.test:
  Added test coverage for some aspects of deadlock handling in
  metadata locking subsystem.
  Adjusted test case after removing back-off in general case
  when conflicting metadata lock is encountered during
  open_tables() (now this happens only if waiting for
  conflicting lock to go away leads to a deadlock).
mysql-test/t/sp_sync.test:
  Adjusted test case after removing back-off in general case
  when conflicting metadata lock is encountered during
  open_tables() (now this happens only if waiting for
  conflicting lock to go away leads to a deadlock).
sql/mdl.cc:
  Changed MDL subsystem to support new approach to acquring
  metadata locks in open tables and more fair and efficient
  scheduling of metadata locks. To implement this:
  - Made releasing of the lock and granting it to the most
    appropriate pending request atomic operation. As result it
    became possible to wake up only those waiters requests from
    which can be satisfied at the moment as well as wake-up
    only one waiter in case when granting its request would
    prevent all other requests from being satisfied.
    This solved thundering herd problem which occured in cases
    when we were releasing some lock and woke up many waiters
    for SNRW or X locks (this was the issue in Bug #52289
    "performance regression for MyISAM in sysbench OLTP_RW
    test".
    To emphasize above changes wake_up_waiters() was renamed
    to MDL_context::reschedule_waiters().
  - Changed code to add tickets for new requests to the back of
    waiters queue and to select tickets to be satisfied from
    the head of the queue if possible (this makes scheduling of
    requests with the same priority fair). To be able to do
    this efficiently we now use for waiting and granted queues
    version of I_P_List class which provides fast push_back()
    method.
  - Members and methods of MDL_context related to sending
    and waiting for signal were moved to separate MDL_wait
    class.
  - Since in order to avoid race conditions we must grant the
    lock only to the context which was not chosen as a victim
    of deadlock, killed or aborted due to timeout
    MDL_wait::set_status() (former awake()) was changed not to
    send signal if signal slot is already occupied and to
    indicate this fact through its return value. As another
    consequence MDL_wait::timed_wait() method was changed to
    handle timeout (optionally) and abort due to kill as
    signals which make signal slot occupied.
  - Renamed MDL_context::acquire_lock_impl() to acquire_lock().
    Changed it to be able correctly process requests for shared
    locks when there are open HANDLERs, made this method more
    optimized for acquisition of shared locks. As part of this
    change moved code common between try_acquire_lock() and
    acquire_lock() to new try_acquire_lock_impl() method.
    Also adjusted acquire_lock()'s code to take into account
    the fact that in cases when lock is granted as result of
    MDL_context::reschedule_waiters() call (i.e. when it is
    granted after waiting for lock conflict to go away)
    updating MDL_lock state is responsibility of the thread
    calling reschedule_waiters().
  - Changed MDL_context::find_deadlock() to send VICTIM
    signal even if victim is the context which has initiated
    deadlock detection. This is required in order to avoid
    races in cases when the same context simultaneously is
    chosen as a victim and its request for lock is satisfied.
    As result return value of this method became unnecessary
    and it was changed to return void.
    Adjusted MDL_lock::find_deadlock() method to take into
    account that now there can be a discrepancy between
    MDL_context::m_waiting_for value being set and real state
    of the ticket this member points to.
  - Renamed MDL_context::m_waiting_for_lock to m_LOCK_waiting_for
    and MDL_context::stop_waiting() to done_waiting_for().
  - Finally, removed MDL_context::wait_for_lock() method.
sql/mdl.h:
  Changed MDL subsystem to support new approach to acquring
  metadata locks in open tables and more fair and efficient
  scheduling of metadata locks. To implement this:
  - Members and methods of MDL_context related to sending
    and waiting for signal were moved to separate MDL_wait
    class.
  - Since now in order to avoid race conditions we must grant
    the lock only to the context which was not chosen as a
    victim of deadlock, killed or aborted due to timeout
    MDL_wait::set_status (former awake()) was changed not to
    send signal if signal slot is already occupied and to
    indicate this fact through its return value.
    Also NORMAL_WAKE_UP signal became GRANTED, and timeouts
    and aborts due to kill became full blown signals rather
    than simple return values.
  - MDL_wait::timed_wait() now takes extra parameter that
    indicates whether signal should be set if timeout is
    reached.
  - Enabled fast push_back() operation in MDL_context::m_tickets
    list to make move_ticket_after_trans_sentinel() method more
    efficient.
  - Removed MDL_context::wait_for_lock() method.
  - Renamed MDL_context::m_waiting_for_lock to m_LOCK_waiting_for
    and MDL_context::stop_waiting() to done_waiting_for().
  - MDL_context::acquire_lock_impl() became acquire_lock().
  - Introduced MDL_context::try_acquire_lock_impl() as a
    place for code shared by try_acquire_lock and
    acquire_lock().
  - Due to fact that now VICTIM signal is sent even if victim
    is the context which has initiated deadlock detection
    find_deadlock() no longer needs a return value.
sql/sql_base.cc:
  Implemented new approach to acquiring metadata locks in
  open_tables(). We no longer perform back-off when conflicting
  metadata lock is encountered. Instead we wait for this lock
  to go away while holding all locks which were acquired so
  far. Back-off is only used in situation when further waiting
  will cause a deadlock which could be avoided by performing
  back-off and restarting open_tables() process. Absence of
  waiting between back-off and restart of acquiring metadata
  locks can't lead to livelocks as MDL subsystem was changed
  to make release of lock and granting it to waiting lock
  an atomic action, so back-off will automatically give way
  to other participants of deadlock loop.
  Accordingly:
  - open_table_get_mdl_lock() and open_and_process_routine()
    were changed to wait for conflicting metadata lock to
    go away without back-off. Only if such wait leads to a
    deadlock back-off is requested. As part of this change
    new error handler class was introduced which converts,
    if possible, ER_LOCK_DEADLOCK error to a request for
    back-off and re-start of open_tables() process.
  - Open_table_context::recover_from_failed_open() was changed
    not to wait in case of metadata lock conflict. Instead we
    immediately proceed to re-acquiring locks.
  - Open_table_context::request_backoff_action() now always
    emits error if back-off is requested in the middle of
    transaction as we can't be sure that releasing lock
    which were acquired only by current statement will
    resolve a deadlock. Before this patch such situations were
    successfully detected thanks to the fact that we called
    MDL_context::wait_for_lock() method in
    recover_from_failed_open().
  - In order to avoid deadlocks open_tables() code was adjusted
    to flush open HANDLERs for which there are pending requests
    for X locks before restarting the process of acquiring
    metadata locks.
  - Changed close_tables_for_reopen() not to reset MDL_request
    for tables belonging to the tail of prelocking list. It is
    no longer necessary as these MDL_request objects won't be
    used for any waiting.
  - Adjusted comment in tdc_wait_for_old_version() to avoid
    mentioning removed MDL_context::wait_for_lock() method.
sql/sql_base.h:
  As we no longer wait for conflicting metadata lock away in
  Open_table_context::recover_from_failed_open() method,
  Open_table_context::OT_WAIT_MDL_LOCK action was renamed to
  OT_MDL_CONFLICT.
  Also Open_table_context::m_failed_mdl_request became
  unnecessary and was removed.
sql/sql_plist.h:
  Extended I_P_List template to support efficient push_back()
  operation if it is parameterized with an appropriate policy
  class.
sql/sql_show.cc:
  Adjusted code after removal of MDL_context::wait_for_lock()
  method. Now if one needs to acquire metadata lock with waiting
  one has to use a variant of MDL_context::acquire_lock() method.
2010-06-07 11:06:55 +04:00
Konstantin Osipov
cbf4019a1b A follow up for the previous patch, titled:
A code review comment for Bug#52289.
Encapsulate the deadlock detection functionality into
a visitor class...

Remove a race introduced by omission: 
initialize iterators under a read lock on the object.

sql/mdl.cc:
  Initialize iterators under a read lock on the object.
2010-06-03 18:32:56 +04:00
Konstantin Osipov
e7854c86a7 A code review comment for Bug#52289.
Encapsulate the deadlock detection functionality into 
a visitor class, and separate it from the wait-for graph
traversal code.

Use "Internal iterator" and "Visitor" patterns to 
achieve the desired separation of responsibilities.

Add comments.

sql/mdl.cc:
  Encapsulate deadlock detection into a class.
sql/mdl.h:
  Adjust for a rename of a class.
2010-06-03 18:08:22 +04:00
Konstantin Osipov
8867c0a52c Add comments to a few MDL deadlock-search related variables
and methods.

sql/mdl.cc:
  Add comments.
sql/mdl.h:
  Add a comment.
2010-06-02 12:06:07 +04:00
Dmitry Lenev
ae1ae4bd63 Fix for bug #51263 "Deadlock between transactional
SELECT and ALTER TABLE ...  REBUILD PARTITION".

ALTER TABLE on InnoDB table (including partitioned tables)
acquired exclusive locks on rows of table being altered.
In cases when there was concurrent transaction which did
locking reads from this table this sometimes led to a
deadlock which was not detected by MDL subsystem nor by
InnoDB engine (and was reported only after exceeding
innodb_lock_wait_timeout).

This problem stemmed from the fact that ALTER TABLE acquired
TL_WRITE_ALLOW_READ lock on table being altered. This lock
was interpreted as a write lock and thus for table being
altered handler::external_lock() method was called with
F_WRLCK as an argument. As result InnoDB engine treated
ALTER TABLE as an operation which is going to change data
and acquired LOCK_X locks on rows being read from old
version of table.

In case when there was a transaction which already acquired
SR metadata lock on table and some LOCK_S locks on its rows
(e.g. by using it in subquery of DML statement) concurrent
ALTER TABLE was blocked at the moment when it tried to
acquire LOCK_X lock before reading one of these rows.
The transaction's attempt to acquire SW metadata lock on
table being altered led to deadlock, since it had to wait
for ALTER TABLE to release SNW lock. This deadlock was not
detected and got resolved only after timeout expiring
because waiting were happening in two different subsystems.

Similar deadlocks could have occured in other situations.
This patch tries to solve the problem by changing ALTER TABLE
implementation to use TL_READ_NO_INSERT lock instead of
TL_WRITE_ALLOW_READ. After this step handler::external_lock()
is called with F_RDLCK as an argument and InnoDB engine
correctly interprets ALTER TABLE as operation which only
reads data from original version of table. Thanks to this
ALTER TABLE acquires only LOCK_S locks on rows it reads.
This, in its turn, causes inter-subsystem deadlocks to go
away, as all potential lock conflicts and thus deadlocks will
be limited to metadata locking subsystem:

- When ALTER TABLE reads rows from table being altered it
  can't encounter any locks which conflict with LOCK_S row
  locks. There should be no concurrent transactions holding
  LOCK_X row locks. Such a transaction should have been
  acquired SW metadata lock on table first which would have
  conflicted with ALTER's SNW lock.
- Vice versa, when DML which runs concurrently with ALTER
  TABLE tries to lock row it should be requesting only LOCK_S
  lock which is compatible with locks acquired by ALTER,
  as otherwise such DML must own an SW metadata lock on table
  which would be incompatible with ALTER's SNW lock.

mysql-test/r/innodb_mysql_lock2.result:
  Added test for bug #51263 "Deadlock between transactional
  SELECT and ALTER TABLE ... REBUILD PARTITION".
mysql-test/suite/rpl_ndb/r/rpl_ndb_binlog_format_errors.result:
  Since CREATE TRIGGER no longer acquires write lock on table
  it is no longer interpreted as an operation which modifies
  table data and therefore no longer fails if invoked for
  SBR-only engine in ROW mode.
mysql-test/suite/rpl_ndb/t/rpl_ndb_binlog_format_errors.test:
  Since CREATE TRIGGER no longer acquires write lock on table
  it is no longer interpreted as an operation which modifies
  table data and therefore no longer fails if invoked for
  SBR-only engine in ROW mode.
mysql-test/t/innodb_mysql_lock2.test:
  Added test for bug #51263 "Deadlock between transactional
  SELECT and ALTER TABLE ... REBUILD PARTITION".
sql/ha_partition.cc:
  When ALTER TABLE creates a new partition to be filled from
  other partition lock it in F_WRLCK mode instead of using
  mode which was used for locking the whole table (it is
  F_RDLCK now).
sql/lock.cc:
  Replaced conditions which used TL_WRITE_ALLOW_READ
  lock type with equivalent conditions using
  TL_WRITE_ALLOW_WRITE. This should allow to get rid
  of TL_WRITE_ALLOW_READ lock type eventually.
sql/mdl.cc:
  Updated outdated comment to reflect current situation.
sql/sql_base.cc:
  Replaced conditions which used TL_WRITE_ALLOW_READ
  lock type with equivalent conditions using
  TL_WRITE_ALLOW_WRITE. This should allow to get rid
  of TL_WRITE_ALLOW_READ lock type eventually.
sql/sql_table.cc:
  mysql_admin_table():
    Use TL_WRITE_ALLOW_WRITE lock type instead of
    TL_WRITE_ALLOW_READ to determine that we need to acquire
    upgradable metadata lock. This should allow to completely
    get rid of TL_WRITE_ALLOW_READ in long term.
  mysql_recreate_table():
    ALTER TABLE now requires TL_READ_NO_INSERT thr_lock.c lock
    instead of TL_WRITE_ALLOW_READ.
sql/sql_trigger.cc:
  Changed CREATE/DROP TRIGGER implementation to use
  TL_READ_NO_INSERT lock instead of TL_WRITE_ALLOW_READ lock.
  The latter is no longer necessary since:
  a) We now can rely on metadata locks to achieve proper
     isolation between two DDL statements or DDL and DML
     statements.
  b) This statement does not change any data in table so there
     is no need to inform storage engine about it.
sql/sql_yacc.yy:
  Changed implementation of ALTER TABLE (and CREATE/DROP INDEX
  as a consequence) to use TL_READ_NO_INSERT lock instead of
  TL_WRITE_ALLOW_READ lock. This is possible since:
  a) We now can rely on metadata locks to achieve proper
     isolation between two DDL statements or DDL and DML
     statements.
  b) This statement only reads data in table being open.
     We write data only to the new version of table and
     then replace with it old version of table under
     X metadata lock.
  
  Thanks to this change InnoDB will no longer acquire LOCK_X
  locks on rows being read by ALTER TABLE (instead LOCK_S
  locks will be acquired) and thus cause of bug #51263
  "Deadlock between transactional SELECT and ALTER TABLE ...
  REBUILD PARTITION" is removed.
  
  Did the similar change for CREATE TRIGGER (see comments
  for sql_trigger.cc for details).
2010-05-26 16:18:08 +04:00
Marc Alff
a7c9bf2ccf Bug#51295 Build warnings in mdl.cc
Before this fix, the performance schema instrumentation
in mdl.h / mdl.cc was incomplete, causing:
- build warnings,
- no data collection for the performance schema

This fix:
- added instrumentation helpers for the new preferred
  reader read write lock, mysql_prlock_*
- implemented completely the performance schema
  instrumentation of mdl.h / mdl.cc
2010-03-07 10:50:47 -07:00
Dmitry Lenev
6b5c4a9ef6 Fix for bug #51105 "MDL deadlock in rqg_mdl_stability test
on Windows".

On platforms where read-write lock implementation does not
prefer readers by default (Windows, Solaris) server might
have deadlocked while detecting MDL deadlock.

MDL deadlock detector relies on the fact that read-write
locks which are used in its implementation prefer readers
(see new comment for MDL_lock::m_rwlock for details).
So far MDL code assumed that default implementation of
read/write locks for the system has this property.
Indeed, this turned out ot be wrong, for example, for
Windows or Solaris. Thus MDL deadlock detector might have
deadlocked on these systems.

This fix simply adds portable implementation of read/write
lock which prefer readers and changes MDL code to use this
new type of synchronization primitive.

No test case is added as existing rqg_mdl_stability test can
serve as one.

config.h.cmake:
  Check for presence of pthread_rwlockattr_setkind_np to be
  able to determine if system natively supports read-write
  locks for which we can specify if readers or writers should
  be preferred.
configure.cmake:
  Check for presence of pthread_rwlockattr_setkind_np to be
  able to determine if system natively supports read-write
  locks for which we can specify if readers or writers should
  be preferred.
configure.in:
  Check for presence of pthread_rwlockattr_setkind_np to be
  able to determine if system natively supports read-write
  locks for which we can specify if readers or writers should
  be preferred.
include/my_pthread.h:
  Added support for portable read-write locks which prefer
  readers.
  To do so extended existing my_rw_lock_t implementation to
  support selection of whom to prefer depending on a flag.
mysys/thr_rwlock.c:
  Extended existing my_rw_lock_t implementation to support
  selection of whom to prefer depending on a flag.
  Added rw_pr_init() function implementing initialization of
  read-write locks preferring readers.
sql/mdl.cc:
  Use portable read-write locks which prefer readers instead of
  relying on that system implementation of read-write locks has
  this property (this was true for Linux/NPTL but was false,
  for example, for Windows and Solaris).
  Added comment explaining why preferring readers is important
  for MDL deadlock detector (thanks to Serg for example!).
sql/mdl.h:
  Use portable read-write locks which prefer readers instead of
  relying on that system implementation of read-write locks has
  this property (this was true for Linux/NPTL but was false,
  for example, for Windows and Solaris).
2010-02-28 07:35:09 +03:00
Dmitry Lenev
03672b9696 Fix for bug #51093 "Crash (possibly stack overflow) in
MDL_lock::find_deadlock".

On some platforms deadlock detector in metadata locking 
subsystem under certain conditions might have exhausted
stack space causing server crashes.

Particularly this caused failures of rqg_mdl_stability
test on Solaris in PushBuild.

During search for deadlock MDL deadlock detector could 
sometimes encounter loop in the waiters graph in which 
MDL_context which has started search for a deadlock 
does not participate. In such case our algorithm will 
continue looping assuming that either this deadlock will 
be resolved by MDL_context which has created it (i.e.
by one of loop participants) or maximum search depth
will be reached. 
Since max search depth was set to 1000 in the latter case 
on platforms where each iteration of deadlock search 
algorithm needs more than DEFAULT_STACK_SIZE/1000 bytes 
of stack (around 192 bytes for 32-bit and around 256 bytes 
for 64-bit platforms) we might have exhausted stack space.

This patch solves this problem by reducing maximum search
depth for MDL deadlock detector to 32. This should be safe
at the moment as it is unlikely that each iteration of the 
current deadlock detector algorithm will consume more than 
1K of stack (thus total amount of stack required can't be
more than 32K) and we require at least 80K of stack in order
to open any table. Also this value should be (hopefully) big
enough to not cause too much false deadlock errors (there
is an anecdotal evidence that real-life deadlocks are
typically shorter than that).

Additional reasearch should be conducted in future in order
to determine the more optimal value of maximum search depth.

This patch does not include test case as existing
rqg_mdl_stability test can serve as one.
2010-02-15 15:37:48 +03:00
Dmitry Lenev
eb0f09712e Fix for bug #51134 "Crash in MDL_lock::destroy on a concurrent
DDL workload".

When a RENAME TABLE or LOCK TABLE ... WRITE statement which
mentioned the same table several times were aborted during 
the process of acquring metadata locks (due to deadlock 
which was discovered or because of KILL statement) server 
might have crashed.

When attempt to acquire all locks requested had failed we
went through the list of requests and released locks which
we have managed to acquire by that moment one by one. Since 
in the scenario described above list of requests contained 
duplicates this led to releasing the same ticket twice and 
a crash as result.

This patch solves the problem by employing different approach
to releasing locks in case of failure to acquire all locks
requested. 
Now we take a MDL savepoint before starting acquiring locks 
and simply rollback to it if things go bad.

mysql-test/r/lock_multi.result:
  Updated test results (see lock_multi.test).
mysql-test/t/lock_multi.test:
  Added test case for bug #51134 "Crash in MDL_lock::destroy
  on a concurrent DDL workload".
sql/mdl.cc:
  MDL_context::acquire_locks():
    When attempt to acquire all locks requested has failed do
    not go through the list of requests and release locks which
    we have managed to acquire one by one. 
    Since list of requests can contain duplicates such approach
    may lead to releasing the same ticket twice and a crash as
    result.
    Instead use the following approach - take a MDL savepoint
    before starting acquiring locks and simply rollback to it
    if things go bad.
2010-02-15 13:23:34 +03:00
Jon Olav Hauglid
3d6a89e792 Bug #45225 Locking: hang if drop table with no timeout
This patch introduces timeouts for metadata locks. 

The timeout is specified in seconds using the new dynamic system 
variable  "lock_wait_timeout" which has both GLOBAL and SESSION
scopes. Allowed values range from 1 to 31536000 seconds (= 1 year). 
The default value is 1 year.

The new server parameter "lock-wait-timeout" can be used to set
the default value parameter upon server startup.

"lock_wait_timeout" applies to all statements that use metadata locks.
These include DML and DDL operations on tables, views, stored procedures
and stored functions. They also include LOCK TABLES, FLUSH TABLES WITH
READ LOCK and HANDLER statements.

The patch also changes thr_lock.c code (table data locks used by MyISAM
and other simplistic engines) to use the same system variable.
InnoDB row locks are unaffected.

One exception to the handling of the "lock_wait_timeout" variable
is delayed inserts. All delayed inserts are executed with a timeout
of 1 year regardless of the setting for the global variable. As the
connection issuing the delayed insert gets no notification of 
delayed insert timeouts, we want to avoid unnecessary timeouts.

It's important to note that the timeout value is used for each lock
acquired and that one statement can take more than one lock.
A statement can therefore block for longer than the lock_wait_timeout 
value before reporting a timeout error. When lock timeout occurs, 
ER_LOCK_WAIT_TIMEOUT is reported.

Test case added to lock_multi.test.


include/my_pthread.h:
  Added macros for comparing two timespec structs.
include/thr_lock.h:
  Introduced timeouts for thr_lock.c locks.
mysql-test/r/mysqld--help-notwin.result:
  Updated result file with the new server variable.
mysql-test/r/mysqld--help-win.result:
  Updated result file with the new server variable.
mysql-test/suite/sys_vars/r/lock_wait_timeout_basic.result:
  Added basic test for the new server variable.
mysql-test/suite/sys_vars/t/lock_wait_timeout_basic.test:
  Added basic test for the new server variable.
mysys/thr_lock.c:
  Introduced timeouts for thr_lock.c locks.
sql/mdl.cc:
  Introduced timeouts for metadata locks.
sql/mdl.h:
  Introduced timeouts for metadata locks.
sql/sql_base.cc:
  Introduced timeouts in tdc_wait_for_old_versions().
sql/sql_class.h:
  Added new server variable lock_wait_timeout.
sql/sys_vars.cc:
  Added new server variable lock_wait_timeout.
2010-02-11 11:23:39 +01:00
Dmitry Lenev
96344befd3 Fix for bug #50998 "Deadlock in MDL code during test
rqg_mdl_stability".

When start of statement's waiting on a metadata lock 
created more than one loop in waiters graph server might 
have entered deadlock condition.

The problem was that in the case described above MDL deadlock 
detector had to perform several searches for deadlock but
forgot to reset Deadlock_detection_context before performing 
new search. 
Failure to do so has broken assumption in code resposible for 
choosing victim that if Deadlock_detection_context::victim
is set we also have read lock on m_waiting_for_lock for this
context. As result this lock could have been unlocked more
times than it was acquired which corrupted rwlock's state
which led to server deadlock.

This fix ensures that such reset is done before each attempt
to find a deadlock.

mysql-test/r/mdl_sync.result:
  Added test for bug #50998 "Deadlock in MDL code during test
  rqg_mdl_stability" as well as coverage for the case when
  addition of statement waiting for metadata lock adds several
  loops in the waiters graph and therefore several searches
  for deadlock should be performed by MDL deadlock detector.
mysql-test/t/mdl_sync.test:
  Added test for bug #50998 "Deadlock in MDL code during test
  rqg_mdl_stability" as well as coverage for the case when
  addition of statement waiting for metadata lock adds several
  loops in the waiters graph and therefore several searches
  for deadlock should be performed by MDL deadlock detector.
sql/mdl.cc:
  Ensure that in cases when MDL deadlock detector had to
  perform several searches for deadlock because several loops
  in waiters graph are possible we reset
  Deadlock_detection_context before performing each search.
  Failure to do so has broken assumption in code resposible
  for choosing victim that if Deadlock_detection_context::victim
  is set we also have read lock on m_waiting_for_lock for this
  context. As result this lock could have been unlocked more
  times than it was acquired which corrupted rwlock's state
  (no one was able to acquire write lock on it anymore).
2010-02-10 18:46:03 +03:00
Jon Olav Hauglid
95c2386148 Bug #50912 Assertion `ticket->m_type >= mdl_request->type'
failed on HANDLER + I_S

This assert was triggered when an I_S query tried to acquire a
metadata lock on a table which was already locked by a HANDLER
statement in the same connection.

First the HANDLER took a MDL_SHARED lock. Afterwards, the I_S query
requested a MDL_SHARED_HIGH_PRIO lock. The existing MDL_SHARED ticket
is found in find_ticket() since it satisfies 
ticket->has_stronger_or_equal_type(mdl_request->type) as MDL_SHARED
and MDL_SHARED_HIGH_PRIO have equal strengths, just different priority.

However, two asserts later check lock type strengths using relational
operators (>= and <=) rather than MDL_ticket::has_stronger_or_equal_type().
These asserts are triggered since MDL_SHARED >= MDL_SHARED_HIGH_PRIORITY
is false (mapped to 1 and 2 respectively).

This patch updates the asserts to use MDL_ticket::has_stronger_or_equal_type()
rather than relational operators to check lock type strength.

Test case added to include/handler.inc.
2010-02-06 10:44:03 +01:00
Konstantin Osipov
a6f804228d A post-merge fix for next-mr -> next-4284 merge:
Make all mutexes and conditions of type mysql_mutex_t, mysql_cond_t,
since it's now the expectation of THD::awake().
2010-02-05 01:37:44 +03:00
Dmitry Lenev
f1f0228f84 Improve concurrency in metadata locking subsystem by
moving calculation of hash value when looking up
MDL_lock objects in MDL_map out of critical section.
2010-02-04 09:25:32 +03:00
Dmitry Lenev
f677e97746 A follow-up for the patch which implemented new
type-of-operation-aware metadata locks and added a
wait-for graph based deadlock detector to the MDL
subsystem (this patch fixed bug #46272 "MySQL 5.4.4,
new MDL: unnecessary deadlock" and bug #37346
"innodb does not detect deadlock between update and
alter table").

Removed unused and redundant method.
2010-02-03 22:55:46 +03:00
Konstantin Osipov
665100b69d Merge next-mr -> next-4284. 2010-02-02 02:22:16 +03:00
Dmitry Lenev
e89c08b670 Fix for sporadical crashes of lock_multi_bug38499.test
caused by patch which implemented new type-of-operation-aware
metadata locks and added a wait-for graph based deadlock
detector to the MDL subsystem (this patch fixed bug #46272
"MySQL 5.4.4, new MDL: unnecessary deadlock" and bug #37346
"innodb does not detect deadlock between update and alter
table").

Crashes were caused by a race in MDL_context::try_acquire_lock().
This method added MDL_ticket to the list of granted tickets and
released lock protecting list before setting MDL_ticket::m_lock.
Thus some other thread was able to see ticket without properly
set m_lock member for some short period of time. If this thread
called method involving this member during this period crash
happened.

This fix ensures that MDL_ticket::m_lock is set in all cases
when ticket is added to granted/pending lists in MDL_lock.

sql/mdl.cc:
  We must set MDL_ticket::m_lock member before adding ticket
  to the list of granted tickets, since such tickets can be
  accessed by other threads which might call methods using
  this member.
  Added assert which ensures that all MDL_tickets which are
  added to the granted/pending lists have properly set
  MDL_ticket::m_lock member.
sql/mdl.h:
  Adjusted comment describing MDL_ticket::m_lock member to
  reflect current reality.
  Added accessor method for this member.
2010-02-01 17:38:50 +03:00
Konstantin Osipov
83d5384931 Fix a Windows compilation warning (req_count is later used
in a pointer arithmetics expression).
2010-02-01 17:12:56 +03:00
Dmitry Lenev
eba5d30e67 Implement new type-of-operation-aware metadata locks.
Add a wait-for graph based deadlock detector to the
MDL subsystem.

Fixes bug #46272 "MySQL 5.4.4, new MDL: unnecessary deadlock" and
bug #37346 "innodb does not detect deadlock between update and
alter table".

The first bug manifested itself as an unwarranted abort of a
transaction with ER_LOCK_DEADLOCK error by a concurrent ALTER
statement, when this transaction tried to repeat use of a
table, which it has already used in a similar fashion before
ALTER started.

The second bug showed up as a deadlock between table-level
locks and InnoDB row locks, which was "detected" only after
innodb_lock_wait_timeout timeout.

A transaction would start using the table and modify a few
rows.
Then ALTER TABLE would come in, and start copying rows
into a temporary table. Eventually it would stumble on
the modified records and get blocked on a row lock.
The first transaction would try to do more updates, and get
blocked on thr_lock.c lock.
This situation of circular wait would only get resolved
by a timeout.

Both these bugs stemmed from inadequate solutions to the
problem of deadlocks occurring between different
locking subsystems.

In the first case we tried to avoid deadlocks between metadata
locking and table-level locking subsystems, when upgrading shared
metadata lock to exclusive one.
Transactions holding the shared lock on the table and waiting for
some table-level lock used to be aborted too aggressively.

We also allowed ALTER TABLE to start in presence of transactions
that modify the subject table. ALTER TABLE acquires
TL_WRITE_ALLOW_READ lock at start, and that block all writes
against the table (naturally, we don't want any writes to be lost
when switching the old and the new table). TL_WRITE_ALLOW_READ
lock, in turn, would block the started transaction on thr_lock.c
lock, should they do more updates. This, again, lead to the need
to abort such transactions.

The second bug occurred simply because we didn't have any
mechanism to detect deadlocks between the table-level locks
in thr_lock.c and row-level locks in InnoDB, other than
innodb_lock_wait_timeout.

This patch solves both these problems by moving lock conflicts
which are causing these deadlocks into the metadata locking
subsystem, thus making it possible to avoid or detect such
deadlocks inside MDL.

To do this we introduce new type-of-operation-aware metadata
locks, which allow MDL subsystem to know not only the fact that
transaction has used or is going to use some object but also what
kind of operation it has carried out or going to carry out on the
object.

This, along with the addition of a special kind of upgradable
metadata lock, allows ALTER TABLE to wait until all
transactions which has updated the table to go away.
This solves the second issue.
Another special type of upgradable metadata lock is acquired
by LOCK TABLE WRITE. This second lock type allows to solve the
first issue, since abortion of table-level locks in event of
DDL under LOCK TABLES becomes also unnecessary.

Below follows the list of incompatible changes introduced by
this patch:

- From now on, ALTER TABLE and CREATE/DROP TRIGGER SQL (i.e. those
  statements that acquire TL_WRITE_ALLOW_READ lock)
  wait for all transactions which has *updated* the table to
  complete.

- From now on, LOCK TABLES ... WRITE, REPAIR/OPTIMIZE TABLE
  (i.e. all statements which acquire TL_WRITE table-level lock) wait
  for all transaction which *updated or read* from the table
  to complete.
  As a consequence, innodb_table_locks=0 option no longer applies
  to LOCK TABLES ... WRITE.

- DROP DATABASE, DROP TABLE, RENAME TABLE no longer abort
  statements or transactions which use tables being dropped or
  renamed, and instead wait for these transactions to complete.

- Since LOCK TABLES WRITE now takes a special metadata lock,
  not compatible with with reads or writes against the subject table
  and transaction-wide, thr_lock.c deadlock avoidance algorithm
  that used to ensure absence of deadlocks between LOCK TABLES
  WRITE and other statements is no longer sufficient, even for
  MyISAM. The wait-for graph based deadlock detector of MDL
  subsystem may sometimes be necessary and is involved. This may
  lead to ER_LOCK_DEADLOCK error produced for multi-statement
  transactions even if these only use MyISAM:

  session 1:         session 2:
  begin;

  update t1 ...      lock table t2 write, t1 write;
                     -- gets a lock on t2, blocks on t1

  update t2 ...
  (ER_LOCK_DEADLOCK)

- Finally,  support of LOW_PRIORITY option for LOCK TABLES ... WRITE
  was abandoned.
  LOCK TABLE ... LOW_PRIORITY WRITE from now on has the same
  priority as the usual LOCK TABLE ... WRITE.
  SELECT HIGH PRIORITY no longer trumps LOCK TABLE ... WRITE  in
  the wait queue.

- We do not take upgradable metadata locks on implicitly
  locked tables. So if one has, say, a view v1 that uses
  table t1, and issues:
  LOCK TABLE v1 WRITE;
  FLUSH TABLE t1; -- (or just 'FLUSH TABLES'),
  an error is produced.
  In order to be able to perform DDL on a table under LOCK TABLES,
  the table must be locked explicitly in the LOCK TABLES list.

mysql-test/include/handler.inc:
  Adjusted test case to trigger an execution path on which bug 41110
  "crash with handler command when used concurrently with alter
  table" and bug 41112 "crash in mysql_ha_close_table/get_lock_data
  with alter table" were originally discovered. Left old test case
  which no longer triggers this execution path for the sake of
  coverage.
  Added test coverage for HANDLER SQL statements and type-aware
  metadata locks.
  Added a test for the global shared lock and HANDLER SQL.
  Updated tests to take into account that the old simple deadlock
  detection heuristics was replaced with a graph-based deadlock
  detector.
mysql-test/r/debug_sync.result:
  Updated results (see debug_sync.test).
mysql-test/r/handler_innodb.result:
  Updated results (see handler.inc test).
mysql-test/r/handler_myisam.result:
  Updated results (see handler.inc test).
mysql-test/r/innodb-lock.result:
  Updated results (see innodb-lock.test).
mysql-test/r/innodb_mysql_lock.result:
  Updated results (see innodb_mysql_lock.test).
mysql-test/r/lock.result:
  Updated results (see lock.test).
mysql-test/r/lock_multi.result:
  Updated results (see lock_multi.test).
mysql-test/r/lock_sync.result:
  Updated results (see lock_sync.test).
mysql-test/r/mdl_sync.result:
  Updated results (see mdl_sync.test).
mysql-test/r/sp-threads.result:
  SHOW PROCESSLIST output has changed due to the fact that waiting
  for LOCK TABLES WRITE now happens within metadata locking
  subsystem.
mysql-test/r/truncate_coverage.result:
  Updated results (see truncate_coverage.test).
mysql-test/suite/funcs_1/datadict/processlist_val.inc:
  SELECT FROM I_S.PROCESSLIST output has changed due to fact that
  waiting for LOCK TABLES WRITE now happens within metadata locking
  subsystem.
mysql-test/suite/funcs_1/r/processlist_val_no_prot.result:
  SELECT FROM I_S.PROCESSLIST output has changed due to fact that
  waiting for LOCK TABLES WRITE now happens within metadata locking
  subsystem.
mysql-test/suite/rpl/t/rpl_sp.test:
  Updated to a new SHOW PROCESSLIST state name.
mysql-test/t/debug_sync.test:
  Use LOCK TABLES READ instead of LOCK TABLES WRITE as the latter
  no longer allows to trigger execution path involving waiting on
  thr_lock.c lock and therefore reaching debug sync-point covered
  by this test.
mysql-test/t/innodb-lock.test:
  Adjusted test case to the fact that innodb_table_locks=0 option is
  no longer supported, since LOCK TABLES WRITE handles all its
  conflicts within MDL subsystem.
mysql-test/t/innodb_mysql_lock.test:
  Added test for bug #37346 "innodb does not detect deadlock between
  update and alter table".
mysql-test/t/lock.test:
  Added test coverage which checks the fact that we no longer support
  DDL under LOCK TABLES on tables which were locked implicitly.
  Adjusted existing test cases accordingly.
mysql-test/t/lock_multi.test:
  Added test for bug #46272 "MySQL 5.4.4, new MDL: unnecessary
  deadlock".  Adjusted other test cases to take into account the
  fact that waiting for LOCK TABLES ... WRITE now happens within MDL
  subsystem.
mysql-test/t/lock_sync.test:
  Since LOCK TABLES ... WRITE now takes SNRW metadata lock for
  tables locked explicitly we have to implicitly lock InnoDB tables
  (through view) to trigger the table-level lock conflict between
  TL_WRITE and TL_WRITE_ALLOW_WRITE.
mysql-test/t/mdl_sync.test:
  Added basic test coverage for type-of-operation-aware metadata
  locks. Also covered with tests some use cases involving HANDLER
  statements in which a deadlock could arise.
  Adjusted existing tests to take type-of-operation-aware MDL into
  account.
mysql-test/t/multi_update.test:
  Update to a new SHOW PROCESSLIST state name.
mysql-test/t/truncate_coverage.test:
  Adjusted test case after making LOCK TABLES WRITE to wait until
  transactions that use the table to be locked are completed.
  Updated to the changed name of DEBUG_SYNC point.
sql/handler.cc:
  Global read lock functionality has been
  moved into a class.
sql/lock.cc:
  Global read lock functionality has been
  moved into a class.
  Updated code to use the new MDL API.
sql/mdl.cc:
  Introduced new type-of-operation aware metadata locks.
  To do this:
  - Changed MDL_lock to use one list for waiting requests and one
    list for granted requests. For each list, added a bitmap
    that holds information what lock types a list contains.
    Added a helper class MDL_lock::List to manipulate with granted
    and waited lists while keeping the bitmaps in sync
    with list contents.
  - Changed lock-compatibility functions to use bitmaps that
    define compatibility.
  - Introduced a graph based deadlock detector inspired by
    waiting_threads.c from Maria implementation.
  - Now that we have a deadlock detector, and no longer have
    a global lock to protect individual lock objects, but rather
    use an rw lock per object, removed redundant code for upgrade,
    and the global read lock. Changed the MDL API to
    no longer require the caller to acquire the global
    intention exclusive lock by means of a separate method.
    Removed a few more methods that became redundant.
  - Removed deadlock detection heuristic, it has been made
    obsolete by the deadlock detector.
  - With operation-type-aware metadata locks, MDL subsystem has
    become aware of potential conflicts between DDL and open
    transactions. This made it possible to remove calls to
    mysql_abort_transactions_with_shared_lock() from acquisition
    paths for exclusive lock and lock upgrade. Now we can simply
    wait for these transactions to complete without fear of
    deadlock. Function mysql_lock_abort() has also become
    unnecessary for all conflicting cases except when a DDL
    conflicts with a connection that has an open HANDLER.
sql/mdl.h:
  Introduced new type-of-operation aware metadata locks.
  Introduced a graph based deadlock detector and supporting
  methods.
  Added comments.
  God rid of redundant API calls.
  Renamed m_lt_or_ha_sentinel to m_trans_sentinel,
  since now it guards the global read lock as well as
  LOCK TABLES and HANDLER locks.
sql/mysql_priv.h:
  Moved the global read lock functionality into a
  class.
  Added MYSQL_OPEN_FORCE_SHARED_MDL flag which forces
  open_tables() to take MDL_SHARED on tables instead of
  metadata locks specified in the parser. We use this to
  allow PREPARE run concurrently in presence of
  LOCK TABLES ... WRITE.
  Added signature for find_table_for_mdl_ugprade().
sql/set_var.cc:
  Global read lock functionality has been
  moved into a class.
sql/sp_head.cc:
  When creating TABLE_LIST elements for prelocking or
  system tables set the type of request for metadata
  lock according to the operation that will be performed
  on the table.
sql/sql_base.cc:
  - Updated code to use the new MDL API.
  - In order to avoid locks starvation we take upgradable
    locks all at once. As result implicitly locked tables no
    longer get an upgradable lock. Consequently DDL and FLUSH
    TABLES for such tables is prohibited.
    find_write_locked_table() was replaced by
    find_table_for_mdl_upgrade() function.
    open_table() was adjusted to return TABLE instance with
    upgradable ticket when necessary.
  - We no longer wait for all locks on OT_WAIT back off
    action -- only on the lock that caused the wait
    conflict. Moreover, now we distinguish cases when we
    have to wait due to conflict in MDL and old version
    of table in TDC.
  - Upate mysql_notify_threads_having_share_locks()
    to only abort thr_lock.c waits of threads that
    have open HANDLERs, since lock conflicts with only
    these threads now can lead to deadlocks not detectable
    by the MDL deadlock detector.
  - Remove mysql_abort_transactions_with_shared_locks()
    which is no longer needed.
sql/sql_class.cc:
  Global read lock functionality has been moved into a class.
  Re-arranged code in THD::cleanup() to simplify assert.
sql/sql_class.h:
  Introduced class to incapsulate global read lock
  functionality.
  Now sentinel in MDL subsystem guards the global read lock
  as well as LOCK TABLES and HANDLER locks. Adjusted code
  accordingly.
sql/sql_db.cc:
  Global read lock functionality has been moved into a class.
sql/sql_delete.cc:
  We no longer acquire upgradable metadata locks on tables
  which are locked by LOCK TABLES implicitly. As result
  TRUNCATE TABLE is no longer allowed for such tables.
  Updated code to use the new MDL API.
sql/sql_handler.cc:
  Inform MDL_context about presence of open HANDLERs.
  Since HANLDERs break MDL protocol by acquiring table-level
  lock while holding only S metadata lock on a table MDL
  subsystem should take special care about such contexts (Now
  this is the only case when mysql_lock_abort() is used).
sql/sql_parse.cc:
  Global read lock functionality has been moved into a class.
  Do not take upgradable metadata locks when opening tables
  for CREATE TABLE SELECT as it is not necessary and limits
  concurrency.
  When initializing TABLE_LIST objects before adding them
  to the table list set the type of request for metadata lock
  according to the operation that will be performed on the
  table.
  We no longer acquire upgradable metadata locks on tables
  which are locked by LOCK TABLES implicitly. As result FLUSH
  TABLES is no longer allowed for such tables.
sql/sql_prepare.cc:
  Use MYSQL_OPEN_FORCE_SHARED_MDL flag when opening
  tables during PREPARE. This allows PREPARE to run
  concurrently in presence of LOCK TABLES ... WRITE.
sql/sql_rename.cc:
  Global read lock functionality has been moved into a class.
sql/sql_show.cc:
  Updated code to use the new MDL API.
sql/sql_table.cc:
  Global read lock functionality has been moved into a class.
  We no longer acquire upgradable metadata locks on tables
  which are locked by LOCK TABLES implicitly. As result DROP
  TABLE is no longer allowed for such tables.
  Updated code to use the new MDL API.
sql/sql_trigger.cc:
  Global read lock functionality has been moved into a class.
  We no longer acquire upgradable metadata locks on tables
  which are locked by LOCK TABLES implicitly. As result
  CREATE/DROP TRIGGER is no longer allowed for such tables.
  Updated code to use the new MDL API.
sql/sql_view.cc:
  Global read lock functionality has been moved into a class.
  Fixed results of wrong merge that led to misuse of GLR API.
  CREATE VIEW statement is not a commit statement.
sql/table.cc:
  When resetting TABLE_LIST objects for PS or SP re-execution
  set the type of request for metadata lock according to the
  operation that will be performed on the table. Do the same
  in auxiliary function initializing metadata lock requests
  in a table list.
sql/table.h:
  When initializing TABLE_LIST objects set the type of request
  for metadata lock according to the operation that will be
  performed on the table.
sql/transaction.cc:
  Global read lock functionality has been moved into a class.
2010-02-01 14:43:06 +03:00
Dmitry Lenev
6ddd01c27a Patch that changes metadata locking subsystem to use mutex per lock and
condition variable per context instead of one mutex and one conditional
variable for the whole subsystem.

This should increase concurrency in this subsystem.

It also opens the way for further changes which are necessary to solve
such bugs as bug #46272 "MySQL 5.4.4, new MDL: unnecessary deadlock"
and bug #37346 "innodb does not detect deadlock between update and alter
table".

Two other notable changes done by this patch:

- MDL subsystem no longer implicitly acquires global intention exclusive
  metadata lock when per-object metadata lock is acquired. Now this has
  to be done by explicit calls outside of MDL subsystem.
- Instead of using separate MDL_context for opening system tables/tables
  for purposes of I_S we now create MDL savepoint in the main context
  before opening tables and rollback to this savepoint after closing
  them. This means that it is now possible to get ER_LOCK_DEADLOCK error
  even not inside a transaction. This might happen in unlikely case when
  one runs DDL on one of system tables while also running DDL on some
  other tables. Cases when this ER_LOCK_DEADLOCK error is not justified
  will be addressed by advanced deadlock detector for MDL subsystem which
  we plan to implement.

mysql-test/include/handler.inc:
  Adjusted handler_myisam.test and handler_innodb.test to the fact that
  exclusive metadata locks on tables are now acquired according to
  alphabetical order of fully qualified table names instead of order
  in which tables are mentioned in statement.
mysql-test/r/handler_innodb.result:
  Adjusted handler_myisam.test and handler_innodb.test to the fact that
  exclusive metadata locks on tables are now acquired according to
  alphabetical order of fully qualified table names instead of order
  in which tables are mentioned in statement.
mysql-test/r/handler_myisam.result:
  Adjusted handler_myisam.test and handler_innodb.test to the fact that
  exclusive metadata locks on tables are now acquired according to
  alphabetical order of fully qualified table names instead of order
  in which tables are mentioned in statement.
mysql-test/r/mdl_sync.result:
  Adjusted mdl_sync.test to the fact that exclusive metadata locks on
  tables are now acquired according to alphabetical order of fully
  qualified table names instead of order in which tables are mentioned
  in statement.
mysql-test/t/mdl_sync.test:
  Adjusted mdl_sync.test to the fact that exclusive metadata locks on
  tables are now acquired according to alphabetical order of fully
  qualified table names instead of order in which tables are mentioned
  in statement.
sql/events.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/ha_ndbcluster.cc:
  Since manipulations with open table state no longer install proxy
  MDL_context it does not make sense to perform them in order to
  satisfy assert in mysql_rm_tables_part2(). Removed them per agreement
  with Cluster team. This has not broken test suite since scenario in
  which deadlock can occur and assertion fails is not covered by tests.
sql/lock.cc:
  MDL subsystem no longer implicitly acquires global intention exclusive
  metadata lock when per-object exclusive metadata lock is acquired.
  Now this has to be done by explicit calls outside of MDL subsystem.
sql/log.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/mdl.cc:
  Changed metadata locking subsystem to use mutex per lock and condition
  variable per context instead of one mutex and one conditional variable
  for the whole subsystem.
  Changed approach to handling of global metadata locks. Instead of
  implicitly acquiring intention exclusive locks when user requests
  per-object upgradeable or exclusive locks now we require them to be
  acquired explicitly in the same way as ordinary metadata locks.
  In fact global lock are now ordinary metadata locks in new GLOBAL
  namespace.
  
  To implement these changes:
  - Removed LOCK_mdl mutex and COND_mdl condition variable.
  - Introduced MDL_lock::m_mutex mutexes which protect individual lock
    objects.
  - Replaced mdl_locks hash with MDL_map class, which has hash for
    MDL_lock objects as a member and separate mutex which protects this
    hash. Methods of this class allow to find(), find_or_create() or
    remove() MDL_lock objects in concurrency-friendly fashion (i.e.
    for most common operation, find_or_create(), we don't acquire
    MDL_lock::m_mutex while holding MDL_map::m_mutex. Thanks to MikaelR
    for this idea and benchmarks!). Added three auxiliary members to
    MDL_lock class (m_is_destroyed, m_ref_usage, m_ref_release) to
    support this concurrency-friendly behavior.
  - Introduced MDL_context::m_ctx_wakeup_cond condition variable to be
    used for waiting until this context's pending request can be
    satisfied or its thread has to perform actions to resolve potential
    deadlock. Context which want to wait add ticket corresponding to the
    request to an appropriate queue of waiters in MDL_lock object so
    they can be noticed when other contexts change state of lock and be
    awaken by them by signalling on MDL_context::m_ctx_wakeup_cond.
    As consequence MDL_ticket objects has to be used for any waiting
    in metadata locking subsystem including one which happens in
    MDL_context::wait_for_locks() method.
    Another consequence is that MDL_context is no longer copyable and
    can't be saved/restored when working with system tables.
  - Made MDL_lock an abstract class, which delegates specifying exact
    compatibility matrix to its descendants. Added MDL_global_lock child
    class for global lock (The old is_lock_type_compatible() method
    became can_grant_lock() method of this class). Added MDL_object_lock
    class to represent per-object lock (The old MDL_lock::can_grant_lock()
    became its method). Choice between two classes happens based on MDL
    namespace in MDL_lock::create() method.
  - Got rid of MDL_lock::type member as its meaning became ambigous for
    global locks.
  - To simplify waking up of contexts waiting for lock split waiting queue
    in MDL_lock class in two queues. One for pending requests for exclusive
    (including intention exclusive) locks and another for requests for
    shared locks.
  - Added virtual wake_up_waiters() method to MDL_lock, MDL_global_lock and
    MDL_object_lock classes which allows to wake up waiting contexts after
    state of lock changes. Replaced old duplicated code with calls to this
    method.
  - Adjusted MDL_context::try_acquire_shared_lock()/exclusive_lock()/
    global_shared_lock(), MDL_ticket::upgrade_shared_lock_to_exclusive_lock()
    and MDL_context::release_ticket() methods to use MDL_map and
    MDL_lock::m_mutex instead of single LOCK_mdl mutex and wake up
    waiters according to the approach described above. The latter method
    also was renamed to MDL_context::release_lock().
  - Changed MDL_context::try_acquire_shared_lock()/exclusive_lock() and
    release_lock() not to handle global locks. They are now supposed to
    be taken explicitly like ordinary metadata locks.
  - Added helper MDL_context::try_acquire_global_intention_exclusive_lock()
    and acquire_global_intention_exclusive_lock() methods.
  - Moved common code from MDL_context::acquire_global_shared_lock() and
    acquire_global_intention_exclusive_lock() to new method -
    MDL_context::acquire_lock_impl().
  - Moved common code from MDL_context::try_acquire_shared_lock(),
    try_acquire_global_intention_exclusive_lock()/exclusive_lock()
    to MDL_context::try_acquire_lock_impl().
  - Since acquiring of several exclusive locks can no longer happen under
    single LOCK_mdl mutex the approach to it had to be changed. Now we do
    it in one by one fashion. This is done in alphabetical order to avoid
    deadlocks. Changed MDL_context::acquire_exclusive_locks() accordingly
    (as part of this change moved code responsible for acquiring single
    exclusive lock to new MDL_context::acquire_exclusive_lock_impl()
    method).
  - Since we no longer have single LOCK_mdl mutex which protects all
    MDL_context::m_is_waiting_in_mdl members using these members to
    determine if we have really awaken context holding conflicting
    shared lock became inconvinient. Got rid of this member and changed
    notify_shared_lock() helper function and process of acquiring
    of/upgrading to exclusive lock not to rely on such information.
    Now in MDL_context::acquire_exclusive_lock_impl() and
    MDL_ticket::upgrade_shared_lock_to_exclusive_lock() we simply
    re-try to wake up threads holding conflicting shared locks after
    small time out.
  - Adjusted MDL_context::can_wait_lead_to_deadlock() and
    MDL_ticket::has_pending_conflicting_lock() to use per-lock
    mutexes instead of LOCK_mdl. To do this introduced
    MDL_lock::has_pending_exclusive_lock() method.
sql/mdl.h:
  Changed metadata locking subsystem to use mutex per lock and condition
  variable per context instead of one mutex and one conditional variable
  for the whole subsystem. In order to implement this change:
  
  - Added MDL_key::cmp() method to be able to sort MDL_key objects
    alphabetically. Changed length fields in MDL_key class to uint16
    as 16-bit is enough for length of any key.
  - Changed MDL_ticket::get_ctx() to return pointer to non-const
    object in order to be able to use MDL_context::awake() method
    for such contexts.
  - Got rid of unlocked versions of can_wait_lead_to_deadlock()/
    has_pending_conflicting_lock() methods in MDL_context and
    MDL_ticket. We no longer has single mutex which protects all
    locks. Thus one always has to use versions of these methods
    which acquire per-lock mutexes.
  - MDL_request_list type of list now counts its elements.
  - Added MDL_context::m_ctx_wakeup_cond condition variable to be used
    for waiting until this context's pending request can be satisfied
    or its thread has to perform actions to resolve potential deadlock.
    Added awake() method to wake up context from such wait.
    Addition of condition variable made MDL_context uncopyable.
    As result we no longer can save/restore MDL_context when working
    with system tables. Instead we create MDL savepoint before opening
    those tables and rollback to it once they are closed.
  - MDL_context::release_ticket() became release_lock() method.
  - Added auxiliary MDL_context::acquire_exclusive_lock_impl() method
    which does all necessary work to acquire exclusive lock on one object
    but should not be used directly as it does not enforce any asserts
    ensuring that no deadlocks are possible.
  - Since we no longer need to know if thread trying to acquire exclusive
    lock managed to wake up any threads having conflicting shared locks
    (as, anyway, we will try to wake up such threads again shortly)
  - MDL_context::m_is_waiting_in_mdl member became unnecessary and
    notify_shared_lock() no longer needs to be friend of MDL_context.
  
  Changed approach to handling of global metadata locks. Instead of
  implicitly acquiring intention exclusive locks when user requests
  per-object upgradeable or exclusive locks now we require them to be
  acquired explicitly in the same way as ordinary metadata locks.
  
  - Added new GLOBAL namespace for such locks.
  - Added new type of lock to be requested MDL_INTENTION_EXCLISIVE.
  - Added MDL_context::try_acquire_global_intention_exclusive_lock()
    and acquire_global_intention_exclusive_lock() methods.
  - Moved common code from MDL_context::acquire_global_shared_lock()
    and acquire_global_intention_exclusive_lock() to new method -
    MDL_context::acquire_lock_impl().
  - Moved common code from MDL_context::try_acquire_shared_lock(),
    try_acquire_global_intention_exclusive_lock()/exclusive_lock()
    to MDL_context::try_acquire_lock_impl().
  - Added helper MDL_context::is_global_lock_owner() method to be
    able easily to find what kind of global lock this context holds.
  - MDL_context::m_has_global_shared_lock became unnecessary as
    global read lock is now represented by ordinary ticket.
  - Removed assert in MDL_context::set_lt_or_ha_sentinel() which became
    false for cases when we execute LOCK TABLES under global read lock
    mode.
sql/mysql_priv.h:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result calls
  opening/closing system tables were changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/sp.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/sp.h:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/sql_base.cc:
  close_thread_tables():
    Since we no longer use separate MDL_context for opening system
    tables we need to avoid releasing all transaction locks when
    closing system table. Releasing metadata lock on system table
    is now responsibility of THD::restore_backup_open_tables_state().
  open_table_get_mdl_lock(),
  Open_table_context::recover_from_failed_open():
    MDL subsystem no longer implicitly acquires global intention exclusive
    metadata lock when per-object upgradable or exclusive metadata lock is
    acquired. So this have to be done explicitly from these calls.
    Changed Open_table_context class to store MDL_request object for
    global intention exclusive lock acquired when opening tables.
  open_table():
    Do not release metadata lock if we have failed to open table as
    this lock might have been acquired by one of previous statements
    in transaction, and therefore should not be released.
  open_system_tables_for_read()/close_system_tables()/
  open_performance_schema_table():
    Instead of using separate MDL_context for opening system tables we now
    create MDL savepoint in the main context before opening such tables
    and rollback to this savepoint after closing them. To support this
    change methods of THD responsible for saving/restoring open table
    state were changed to use Open_tables_backup class which in addition
    to Open_table_state has a member for this savepoint. As result code
    opening/closing system tables was changed to use Open_tables_backup
    instead of Open_table_state class as well.
  close_performance_schema_table():
    Got rid of duplicated code.
sql/sql_class.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. Also releasing
  metadata lock on system table is now responsibility of
  THD::restore_backup_open_tables_state().
  Adjusted assert in THD::cleanup() to take into account fact that now
  we also use MDL sentinel for global read lock.
sql/sql_class.h:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. As result:
  - 'mdl_context' member was moved out of Open_tables_state to THD class.
    enter_locked_tables_mode()/leave_locked_tables_mode() had to follow.
  - Methods of THD responsible for saving/restoring open table state were
    changed to use Open_tables_backup class which in addition to
    Open_table_state has a member for this savepoint.
  Changed Open_table_context class to store MDL_request object for
  global intention exclusive lock acquired when opening tables.
sql/sql_delete.cc:
  MDL subsystem no longer implicitly acquires global intention exclusive
  metadata lock when per-object exclusive metadata lock is acquired.
  Now this has to be done by explicit calls outside of MDL subsystem.
sql/sql_help.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
sql/sql_parse.cc:
  Adjusted assert reload_acl_and_cache() to the fact that global read
  lock now takes full-blown metadata lock.
sql/sql_plist.h:
  Added support for element counting to I_P_List list template.
  One can use policy classes to specify if such counting is needed
  or not needed for particular list.
sql/sql_show.cc:
  Instead of using separate MDL_context for opening tables for I_S
  purposes we now create MDL savepoint in the main context before
  opening tables and rollback to this savepoint after closing them.
  To support this and similar change for system tables methods of
  THD responsible for saving/restoring open table state were changed
  to use Open_tables_backup class which in addition to Open_table_state
  has a member for this savepoint. As result code opening/closing tables
  for I_S purposes was changed to use Open_tables_backup instead of
  Open_table_state class as well.
sql/sql_table.cc:
  mysql_rm_tables_part2():
    Since now global intention exclusive metadata lock is ordinary
    metadata lock we no longer can rely that by releasing MDL locks
    on all tables we will release all locks acquired by this routine.
    So in non-LOCK-TABLES mode we have to release all locks acquired
    explicitly.
  prepare_for_repair(), mysql_alter_table():
    MDL subsystem no longer implicitly acquires global intention
    exclusive metadata lock when per-object exclusive metadata lock
    is acquired. Now this has to be done by explicit calls outside of
    MDL subsystem.
sql/tztime.cc:
  Instead of using separate MDL_context for opening system tables we now
  create MDL savepoint in the main context before opening such tables
  and rollback to this savepoint after closing them. To support this
  change methods of THD responsible for saving/restoring open table
  state were changed to use Open_tables_backup class which in addition
  to Open_table_state has a member for this savepoint. As result code
  opening/closing system tables was changed to use Open_tables_backup
  instead of Open_table_state class as well.
  Also changed code not to use special mechanism for open system tables
  when it is not really necessary.
2010-01-21 23:43:03 +03:00
Dmitry Lenev
0228c98936 Implementation of simple deadlock detection for metadata locks.
This change is supposed to reduce number of ER_LOCK_DEADLOCK
errors which occur when multi-statement transaction encounters
conflicting metadata lock in cases when waiting is possible.

The idea is not to fail ER_LOCK_DEADLOCK error immediately when
we encounter conflicting metadata lock. Instead we release all
metadata locks acquired by current statement and start to wait
until conflicting lock go away. To avoid deadlocks we use simple
empiric which aborts waiting with ER_LOCK_DEADLOCK error if it
turns out that somebody is waiting for metadata locks owned by
this transaction.

This patch also fixes bug #46273 "MySQL 5.4.4 new MDL: Bug#989
is not fully fixed in case of ALTER".

The bug was that concurrent execution of UPDATE or MULTI-UPDATE
statement as a part of multi-statement transaction that already
has used table being updated and ALTER TABLE statement might have
resulted of loss of isolation between this transaction and ALTER
TABLE statement, which manifested itself as changes performed by
ALTER TABLE becoming visible in transaction and wrong binary log
order as a consequence.

This problem occurred when UPDATE or MULTI-UPDATE's wait in
mysql_lock_tables() call was aborted due to metadata lock
upgrade performed by concurrent ALTER TABLE. After such abort all
metadata locks held by transaction were released but transaction
silently continued to be executed as if nothing has happened.

We solve this problem by changing our code not to release all
locks in such case. Instead we release only locks which were
acquired by current statement and then try to reacquire them
by restarting open/lock tables process. We piggyback on simple
deadlock detector implementation since this change has to be
done anyway for it.

mysql-test/include/handler.inc:
  After introduction of basic deadlock detector for metadata locks
  it became necessary to change parts of test for HANDLER statements
  which covered some of scenarios in which ER_LOCK_DEADLOCK error
  was detected in absence of real deadlock (with new deadlock detector
  this no longer happens).
  Also adjusted test to the fact that HANDLER READ for the table no
  longer will be blocked by ALTER TABLE for the same table which awaits
  for metadata lock upgrade (this is due to removal of mysql_lock_abort()
  from wait_while_table_is_used()).
mysql-test/r/handler_innodb.result:
  After introduction of basic deadlock detector for metadata locks
  it became necessary to change parts of test for HANDLER statements
  which covered some of scenarios in which ER_LOCK_DEADLOCK error
  was detected in absence of real deadlock (with new deadlock detector
  this no longer happens).
  Also adjusted test to the fact that HANDLER READ for the table no
  longer will be blocked by ALTER TABLE for the same table which awaits
  for metadata lock upgrade (this is due to removal of mysql_lock_abort()
  from wait_while_table_is_used()).
mysql-test/r/handler_myisam.result:
  After introduction of basic deadlock detector for metadata locks
  it became necessary to change parts of test for HANDLER statements
  which covered some of scenarios in which ER_LOCK_DEADLOCK error
  was detected in absence of real deadlock (with new deadlock detector
  this no longer happens).
  Also adjusted test to the fact that HANDLER READ for the table no
  longer will be blocked by ALTER TABLE for the same table which awaits
  for metadata lock upgrade (this is due to removal of mysql_lock_abort()
  from wait_while_table_is_used()).
mysql-test/r/mdl_sync.result:
  Added test coverage for basic deadlock detection in metadata
  locking subsystem and for bug #46273 "MySQL 5.4.4 new MDL:
  Bug#989 is not fully fixed in case of ALTER".
mysql-test/r/sp-lock.result:
  Adjusted test coverage for metadata locking for stored routines
  since after introduction of basic deadlock detector for metadata
  locks number of scenarios in which ER_LOCK_DEADLOCK error in
  absence of deadlock has decreased.
mysql-test/t/mdl_sync.test:
  Added test coverage for basic deadlock detection in metadata
  locking subsystem and for bug #46273 "MySQL 5.4.4 new MDL:
  Bug#989 is not fully fixed in case of ALTER".
mysql-test/t/sp-lock.test:
  Adjusted test coverage for metadata locking for stored routines
  since after introduction of basic deadlock detector for metadata
  locks number of scenarios in which ER_LOCK_DEADLOCK error in
  absence of deadlock has decreased.
sql/log_event_old.cc:
  close_tables_for_reopen() now takes one more argument which
  specifies at which point it should stop releasing metadata
  locks acquired by this connection.
sql/mdl.cc:
  Changed metadata locking subsystem to support basic deadlock detection
  with a help of the following simple empiric -- we assume that there is
  a deadlock if there is a connection which has to wait for a metadata
  lock which is currently acquired by some connection which is itself
  waiting to be able to acquire some shared metadata lock.
  
  To implement this change:
  - Added MDL_context::can_wait_lead_to_deadlock()/_impl() methods
    which allow to find out if there is someone waiting for metadata
    lock which is held by the connection and therefore deadlocks are
    possible if this connection is going to wait for some metadata lock.
    To do this added version of MDL_ticket::has_pending_conflicting_lock()
    method which assumes that its caller already owns LOCK_mdl mutex.
  - Changed MDL_context::wait_for_locks() to use one of the above methods
    to check if somebody is waiting for metadata lock owned by this
    context (and therefore deadlock is possible) and emit ER_LOCK_DEADLOCK
    error in this case. Also now we mark context of connections waiting
    inside of this method by setting MDL_context::m_is_waiting_in_mdl
    member. Thanks to this such connection could be waken up if some
    other connection starts waiting for one of its metadata locks and
    so a deadlock can occur.
  - Adjusted notify_shared_lock() to wake up connections which wait inside
    MDL_context::wait_for_locks() while holding shared metadata lock.
  - Changed MDL_ticket::upgrade_shared_lock_to_exclusive() to add
    temporary ticket for exclusive lock to MDL_lock::waiting queue, so
    request for metadata lock upgrade can be properly detected by our
    empiric.
    Also now this method invokes a callback which forces transactions
    holding shared metadata lock on the table to call MDL_context::
    can_wait_lead_to_deadlock() method even if they don't need any new
    metadata locks. Thanks to this such transactions can detect deadlocks/
    livelocks between MDL and table-level locks.
  
  Also reduced timeouts between calls to notify_shared_lock()
  in MDL_ticket::upgrade_shared_lock_to_exclusive() and
  MDL_context::acquire_exclusive_locks(). This was necessary
  to get rid of call to mysql_lock_abort() in wait_while_table_is_used().
  (Now we instead rely on notify_shared_lock() timely calling
  mysql_lock_abort_for_thread() for the table on which lock
  is being upgraded/acquired).
sql/mdl.h:
  - Added a version of MDL_ticket::has_pending_conflicting_lock() method
    to be used in situations when caller already has acquired LOCK_mdl
    mutex.
  - Added MDL_context::can_wait_lead_to_deadlock()/_impl() methods
    which allow to find out if there is someone waiting for metadata lock
    which is held by this connection and thus deadlocks are possible if
    this connections will start waiting for some metadata lock.
  - Added MDL_context::m_is_waiting_in_mdl member to mark connections
    waiting in MDL_context::wait_for_locks() method of metadata locking
    subsystem. Added getter method for this private member to make it
    accessible in notify_shared_lock() auxiliary so we can wake-up such
    connections if they hold shared metadata locks.
  - Finally, added mysql_abort_transactions_with_shared_lock() callback
    to be able force transactions which don't need any new metadata
    locks still call MDL_context::can_wait_lead_to_deadlock() and detect
    some of deadlocks between metadata locks and table-level locks.
sql/mysql_priv.h:
  close_tables_for_reopen() now takes one more argument which
  specifies at which point it should stop releasing metadata
  locks acquired by this connection.
sql/sql_base.cc:
  Changed approach to metadata locking for multi-statement transactions.
  We no longer fail ER_LOCK_DEADLOCK error immediately when we encounter
  conflicting metadata lock. Instead we release all metadata locks
  acquired by current statement and start to wait until conflicting
  locks to go away by calling MDL_context::wait_for_locks() method.
  To avoid deadlocks the latter implements simple empiric which aborts
  waiting with ER_LOCK_DEADLOCK error if it turns out that somebody
  is waiting for metadata locks owned by this transaction.
  
  To implement the change described above:
  - Introduced Open_table_context::m_start_of_statement_svp member to
    store state of metadata locks at the start of the statement.
  - Changed Open_table_context::request_backoff_action() not to
    fail with ER_LOCK_DEADLOCK immediately if back-off is requested
    due to conflicting metadata lock.
  - Added new argument for close_tables_for_reopen() procedure which
    allows to specify subset of metadata locks to be released.
  - Changed open_tables() not to release all metadata locks acquired
    by current transaction when metadata lock conflict is discovered.
    Instead we release only locks acquired by current statement.
  - Changed open_ltable() and open_and_lock_tables_derived() not to emit
    ER_LOCK_DEADLOCK error when mysql_lock_tables() is aborted in
    multi-statement transaction when somebody tries to acquire exclusive
    metadata lock on the table. Instead we release metadata locks acquired
    by current statement and try to wait until they can be re-acquired.
  - Adjusted tdc_wait_for_old_versions() to check if there is someone
    waiting for one of metadata locks held by this connection and run
    deadlock detection in order to avoid deadlocks in some
    situations.
  - Added mysql_abort_transactions_with_shared_lock() callback which
    allows to force transactions holding shared metadata lock on the
    table to call MDL_context::can_wait_lead_to_deadlock() even if they
    don't need any new metadata locks so they can detect potential
    deadlocks between metadata locking subsystem and table-level locks.
  - Adjusted wait_while_table_is_used() not to set TABLE::version to
    0 as it is now done only when necessary by the above-mentioned
    callback. Also removed unnecessary call to mysql_lock_abort().
    Instead we rely on code performing metadata lock upgrade aborting
    waits on the table-level lock for this table by calling
    mysql_lock_abort_for_thread() (invoked by
    mysql_notify_thread_having_shared_lock()). In future this should
    allow to reduce number of scenarios in which we produce
    ER_LOCK_DEADLOCK error even though no real deadlock exists.
sql/sql_class.h:
  Introduced Open_table_context::m_start_of_statement_svp member to
  store state of metadata locks at the start of the statement.
  Replaced Open_table_context::m_can_deadlock member with m_has_locks
  member to reflect the fact that we no longer unconditionally emit
  ER_LOCK_DEADLOCK error for transaction having some metadata locks
  when conflicting metadata lock is discovered.
sql/sql_insert.cc:
  close_tables_for_reopen() now takes one more argument which
  specifies at which point it should stop releasing metadata
  locks acquired by this connection.
sql/sql_plist.h:
  Made I_P_List_iterator<T, B> usable with const lists.
sql/sql_show.cc:
  close_tables_for_reopen() now takes one more argument which
  specifies at which point it should stop releasing metadata
  locks acquired by this connection.
sql/sql_update.cc:
  Changed UPDATE and MULTI-UPDATE code not to release all metadata
  locks when calls to mysql_lock_tables() are aborted. Instead we
  release only locks which are acquired by this statement and then
  try to reacquire them by calling open_tables(). This solves
  bug #46273 "MySQL 5.4.4 new MDL: Bug#989 is not fully fixed in
  case of ALTER".
2009-12-30 20:53:30 +03:00
Konstantin Osipov
dfdbc84585 A prerequisite patch for the fix for Bug#46224
"HANDLER statements within a transaction might lead to deadlocks".
Introduce a notion of a sentinel to MDL_context. A sentinel
is a ticket that separates all tickets in the context into two
groups: before and after it. Currently we can have (and need) only
one designated sentinel -- it separates all locks taken by LOCK
TABLE or HANDLER statement, which must survive COMMIT and ROLLBACK
and all other locks, which must be released at COMMIT or ROLLBACK.
The tricky part is maintaining the sentinel up to date when
someone release its corresponding ticket. This can happen, e.g.
if someone issues DROP TABLE under LOCK TABLES (generally,
see all calls to release_all_locks_for_name()).
MDL_context::release_ticket() is modified to take care of it.

******
A fix and a test case for Bug#46224 "HANDLER statements within a
transaction might lead to deadlocks".

An attempt to mix HANDLER SQL statements, which are transaction-
agnostic, an open multi-statement transaction,
and DDL against the involved tables (in a concurrent connection) 
could lead to a deadlock. The deadlock would occur when
HANDLER OPEN or HANDLER READ would have to wait on a conflicting
metadata lock. If the connection that issued HANDLER statement
also had other metadata locks (say, acquired in scope of a 
transaction), a classical deadlock situation of mutual wait
could occur.

Incompatible change: entering LOCK TABLES mode automatically
closes all open HANDLERs in the current connection.

Incompatible change: previously an attempt to wait on a lock
in a connection that has an open HANDLER statement could wait
indefinitely/deadlock. After this patch, an error ER_LOCK_DEADLOCK
is produced.

The idea of the fix is to merge thd->handler_mdl_context
with the main mdl_context of the connection, used for transactional
locks. This makes deadlock detection possible, since all waits
with locks are "visible" and available to analysis in a single
MDL context of the connection.

Since HANDLER locks and transactional locks have a different life
cycle -- HANDLERs are explicitly open and closed, and so
are HANDLER locks, explicitly acquired and released, whereas
transactional locks "accumulate" till the end of a transaction
and are released only with COMMIT, ROLLBACK and ROLLBACK TO SAVEPOINT,
a concept of "sentinel" was introduced to MDL_context.
All locks, HANDLER and others, reside in the same linked list.
However, a selected element of the list separates locks with
different life cycle. HANDLER locks always reside at the
end of the list, after the sentinel. Transactional locks are
prepended to the beginning of the list, before the sentinel.
Thus, ROLLBACK, COMMIT or ROLLBACK TO SAVEPOINT, only
release those locks that reside before the sentinel. HANDLER locks
must be released explicitly as part of HANDLER CLOSE statement,
or an implicit close. 
The same approach with sentinel
is also employed for LOCK TABLES locks. Since HANDLER and LOCK TABLES
statement has never worked together, the implementation is
made simple and only maintains one sentinel, which is used either
for HANDLER locks, or for LOCK TABLES locks.


mysql-test/include/handler.inc:
  Add test coverage for Bug#46224 "HANDLER statements within a
  transaction might lead to deadlocks".
  Extended HANDLER coverage to cover a mix of HANDLER, transactions
  and DDL statements.
mysql-test/r/handler_innodb.result:
  Update results (Bug#46224).
mysql-test/r/handler_myisam.result:
  Update results (Bug#46224).
sql/lock.cc:
  Remove thd->some_tables_deleted, it's never used.
sql/log_event.cc:
  No need to check for thd->locked_tables_mode, 
  it's done inside release_transactional_locks().
sql/mdl.cc:
  Implement the concept of HANDLER and LOCK TABLES "sentinel".
  Implement a method to clone an acquired ticket.
  Do not return tickets beyond the sentinel when acquiring
  locks, create a copy.
  Remove methods to merge and backup MDL_context, they are now
  not used (Hurra!). This opens a path to a proper constructor
  and destructor of class MDL_context (to be done in a separate
  patch).
  Modify find_ticket() to provide information about where
  the ticket position is with regard to the sentinel.
sql/mdl.h:
  Add declarations necessary for the implementation of the concept
  of "sentinel", a dedicated ticket separating transactional and
  non-transactional locks.
sql/mysql_priv.h:
  Add mark_tmp_table_for_reuse() declaration, 
  a function to "close" a single session (temporary) table.
sql/sql_base.cc:
  Remove thd->some_tables_deleted.
  Modify deadlock-prevention asserts and deadlock detection
  heuristics to take into account that from now on HANDLER locks
  reside in the same locking context.
  Add broadcast_refresh() to mysql_notify_thread_having_shared_lock():
  this is necessary for the case when a thread having a shared lock
  is asleep in tdc_wait_for_old_versions(). This situation is only
  possible with HANDLER t1 OPEN; FLUSH TABLE (since all over code paths
  that lead to tdc_wait_for_old_versions() always have an
  empty MDL_context). Previously the server would simply deadlock
  in this situation.
sql/sql_class.cc:
  Remove now unused member "THD::some_tables_deleted". 
  Move mysql_ha_cleanup() a few lines above in THD::cleanup() 
  to make sure that all handlers are closed when it's time to 
  destroy the MDL_context of this connection.
  Remove handler_mdl_context and handler_tables.
sql/sql_class.h:
  Remove THD::handler_tables, THD::handler_mdl_context,
  THD::some_tables_deleted.
sql/sql_handler.cc:
  Remove thd->handler_tables.
  Remove thd->handler_mdl_context.
  Rewrite mysql_ha_open() to have no special provision for MERGE
  tables, now that we don't have to manipulate with thd->handler_tables
  it's easy to do.
  Remove dead code.
  Fix a bug in mysql_ha_flush() when we would always flush
  a temporary HANDLER when mysql_ha_flush() is called (actually
  mysql_ha_flush() never needs to flush temporary tables).
sql/sql_insert.cc:
  Update a comment, no more thd->some_tables_deleted.
sql/sql_parse.cc:
  Implement an incompatible change: entering LOCK TABLES closes
  active HANDLERs, if any.
  Now that we have a sentinel, we don't need to check
  for thd->locked_tables_mode when releasing metadata locks in
  COMMIT/ROLLBACK.
sql/sql_plist.h:
  Add new (now necessary) methods to the list class.
sql/sql_prepare.cc:
  Make sure we don't release HANDLER locks when rollback to a
  savepoint, set to not keep locks taken at PREPARE.
sql/sql_servers.cc:
  Update to a new signature of MDL_context::release_all_locks().
sql/sql_table.cc:
  Remove thd->some_tables_deleted.
sql/transaction.cc:
  Add comments. 
  Make sure rollback to (MDL) savepoint works under LOCK TABLES and
  with HANDLER tables.
2009-12-22 19:09:15 +03:00
Jon Olav Hauglid
6d4e09d68e Bug #48541 Deadlock between LOCK_open and LOCK_mdl
The reason for the deadlock was an improper exit from
MDL_context::wait_for_locks() which caused mysys_var->current_mutex to remain
LOCK_mdl even though LOCK_mdl was no longer held by that connection. 

This could for example lead to a deadlock in the following way:
1) INSERT DELAYED tries to open a table but fails, and trying to recover it
calls wait_for_locks().
2) Due to a pending exclusive request, wait_for_locks() fails and exits without
resetting mysys_var->current_mutex for the delayed insert handler thread. So it
continues to point to LOCK_mdl.
3) The handler thread manages to open a table.
4) A different connection takes LOCK_open and tries to take LOCK_mdl.
5) FLUSH TABLES from a third connection notices that the handler thread has a
table open, and tries to kill it. This involves locking mysys_var->current_mutex
while having LOCK_open locked. Since current_mutex mistakenly points to LOCK_mdl,
we have a deadlock.

This patch makes sure MDL_EXIT_COND() is called before exiting wait_for_locks().
This clears mysys->current_mutex which resolves the issue. 

An assert is added to recover_from_failed_open_table_attempt() after
wait_for_locks() is called, to check that current_mutex is indeed reset.
With this assert in place, existing tests in (e.g.) mdl_sync.test will fail
without this patch.
2009-12-16 12:32:11 +01:00
Jon Olav Hauglid
5e1dfa4c06 Backport of revno: 2617.71.1
Bug#42546 Backup: RESTORE fails, thinking it finds an existing table

The problem occured when a MDL locking conflict happened for a non-existent 
table between a CREATE and a INSERT statement. The code for CREATE 
interpreted this lock conflict to mean that the table existed, 
which meant that the statement failed when it should not have.
The problem could occur for CREATE TABLE, CREATE TABLE LIKE and
ALTER TABLE RENAME.

This patch fixes the problem for CREATE TABLE and CREATE TABLE LIKE.
It is based on code backported from the mysql-6.1-fk tree written
by Dmitry Lenev. CREATE now uses normal open_and_lock_tables() code 
to acquire exclusive locks. This means that for the test case in the bug 
description, CREATE will wait until INSERT completes so that it can 
get the exclusive lock. This resolves the reported bug.

The patch also prohibits CREATE TABLE and CREATE TABLE LIKE under 
LOCK TABLES. Note that this is an incompatible change and must 
be reflected in the documentation. Affected test cases have been
updated.

mdl_sync.test contains tests for CREATE TABLE and CREATE TABLE LIKE.

Fixing the issue for ALTER TABLE RENAME is beyond the scope of this
patch. ALTER TABLE cannot be prohibited from working under LOCK TABLES
as this could seriously impact customers and a proper fix would require
a significant rewrite.
2009-12-10 11:53:20 +01:00
Konstantin Osipov
f26f632b44 Backport of:
------------------------------------------------------------
revno: 2617.68.25
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-next-bg-pre2-2
timestamp: Wed 2009-09-16 18:26:50 +0400
message:
  Follow-up for one of pre-requisite patches for fixing bug #30977
  "Concurrent statement using stored function and DROP FUNCTION
  breaks SBR".

  Made enum_mdl_namespace enum part of MDL_key class and removed MDL_
  prefix from the names of enum members. In order to do the latter
  changed name of PROCEDURE symbol to PROCEDURE_SYM (otherwise macro
  which was automatically generated for this symbol conflicted with
  MDL_key::PROCEDURE enum member).
2009-12-10 11:21:38 +03:00
Konstantin Osipov
634a810942 Backport of:
------------------------------------------------------------
revno: 2617.68.24
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-next-bg-pre2-2
timestamp: Wed 2009-09-16 17:25:29 +0400
message:
  Pre-requisite patch for fixing bug #30977 "Concurrent statement
  using stored function and DROP FUNCTION breaks SBR".

  Added MDL_request for stored routine as member to Sroutine_hash_entry
  in order to be able perform metadata locking for stored routines in
  future (Sroutine_hash_entry is an equivalent of TABLE_LIST class for
  stored routines).
(WL#4284, follow up fixes).

sql/mdl.cc:
  Introduced version of MDL_request::init() method which initializes
  lock request using pre-built MDL key.
  MDL_key::table_name/table_name_length() getters were
  renamed to reflect the fact that MDL_key objects are
  now created not only for tables.
sql/mdl.h:
  Extended enum_mdl_namespace enum with values which correspond
  to namespaces for stored functions and triggers.
  Renamed MDL_key::table_name/table_name_length() getters
  to MDL_key::name() and name_length() correspondingly to
  reflect the fact that MDL_key objects are now created
  not only for tables.
  Added MDL_key::mdl_namespace() getter.
  Also added version of MDL_request::init() method which
  initializes lock request using pre-built MDL key.
sql/sp.cc:
  Added MDL_request for stored routine as member to Sroutine_hash_entry.
  Changed code to use MDL_key from this request as a key for LEX::sroutines
  set. Removed separate "key" member from Sroutine_hash_entry as it became
  unnecessary.
sql/sp.h:
  Added MDL_request for stored routine as member to Sroutine_hash_entry
  in order to be able perform metadata locking for stored routines in
  future (Sroutine_hash_entry is an equivalent of TABLE_LIST class for
  stored routines).
  Removed Sroutine_hash_entry::key member as now we can use MDL_key from
  this request as a key for LEX::sroutines set.
sql/sp_head.cc:
  Removed sp_name::m_sroutines_key member and set_routine_type() method.
  Since key for routine in LEX::sroutines set has no longer sp_name::m_qname
  as suffix we won't save anything by creating it at sp_name construction
  time.
  Adjusted sp_name constructor used for creating temporary objects for
  lookups in SP-cache to accept MDL_key as parameter and to avoid any
  memory allocation.
  Finally, removed sp_head::m_soutines_key member for reasons similar
  to why sp_name::m_sroutines_key was removed
sql/sp_head.h:
  Removed sp_name::m_sroutines_key member and set_routine_type() method.
  Since key for routine in LEX::sroutines set has no longer sp_name::m_qname
  as suffix we won't save anything by creating it at sp_name construction
  time.
  Adjusted sp_name constructor used for creating temporary objects for
  lookups in SP-cache to accept MDL_key as parameter and to avoid any
  memory allocation.
  Finally, removed sp_head::m_soutines_key member for reasons similar
  to why sp_name::m_sroutines_key was removed.
sql/sql_base.cc:
  Adjusted code to the fact that we now use MDL_key from
  Sroutine_hash_entry::mdl_request as a key for LEX::sroutines set.
  MDL_key::table_name/table_name_length() getters were
  renamed to reflect the fact that MDL_key objects are
  now created not only for tables.
sql/sql_trigger.cc:
  sp_add_used_routine() now takes MDL_key as parameter as now we use
  instance of this class as a key for LEX::sroutines set.
2009-12-09 19:11:26 +03:00
Jon Olav Hauglid
fcae99271a Backport of revno: 2617.68.39
Bug #47249 assert in MDL_global_lock::is_lock_type_compatible

This assert could be triggered if LOCK TABLES were used to lock
both a table and a view that used the same table. The table would have
to be first WRITE locked and then READ locked. So "LOCK TABLES v1
WRITE, t1 READ" would eventually trigger the assert, "LOCK TABLES
v1 READ, t1 WRITE" would not. The reason is that the ordering of locks
in the interal representation made a difference when executing 
FLUSH TABLE on the table.

During FLUSH TABLE, a lock was upgraded to exclusive. If this lock
was of type MDL_SHARED and not MDL_SHARED_UPGRADABLE, an internal
counter in the MDL subsystem would get out of sync. This would happen
if the *last* mention of the table in LOCK TABLES was a READ lock.

The counter in question is the number exclusive locks (active or intention). 
This is used to make sure a global metadata lock is only taken when the 
counter is zero (= no conflicts). The counter is increased when a
MDL_EXCLUSIVE or MDL_SHARED_UPGRADABLE lock is taken, but not when 
upgrade_shared_lock_to_exclusive() is used to upgrade directly
from MDL_SHARED to MDL_EXCLUSIVE. 

This patch fixes the problem by searching for a TABLE instance locked
with MDL_SHARED_UPGRADABLE or MDL_EXCLUSIVE before calling
upgrade_shared_lock_to_exclusive(). The patch also adds an assert checking
that only MDL_SHARED_UPGRADABLE locks are upgraded to exclusive.

Test case added to lock_multi.test.
2009-12-09 10:44:01 +01:00
Jon Olav Hauglid
546e16ebd8 Backport of revno: 2617.69.40
A pre-requisite patch for Bug#30977 "Concurrent statement using 
stored function and DROP FUNCTION breaks SBR".

This patch changes the MDL API by introducing a namespace for
lock keys: MDL_TABLE for tables and views and MDL_PROCEDURE
for stored procedures and functions. The latter is needed for
the fix for Bug#30977.
2009-12-09 09:51:20 +01:00
Konstantin Osipov
ce5c87a3d3 Backport of:
----------------------------------------------------------
revno: 2617.69.20
committer: Konstantin Osipov <kostja@sun.com>
branch nick: 5.4-4284-1-assert
timestamp: Thu 2009-08-13 18:29:55 +0400
message:
  WL#4284 "Transactional DDL locking"
  A review fix.
  Since WL#4284 implementation separated MDL_request and MDL_ticket,
  MDL_request becamse a utility object necessary only to get a ticket.
  Store it by-value in TABLE_LIST with the intent to merge
  MDL_request::key with table_list->table_name and table_list->db
  in future.
  Change the MDL subsystem to not require MDL_requests to
  stay around till close_thread_tables().
  Remove the list of requests from the MDL context.
  Requests for shared metadata locks acquired in open_tables()
  are only used as a list in recover_from_failed_open_table_attempt(),
  which calls mdl_context.wait_for_locks() for this list.
  To keep such list for recover_from_failed_open_table_attempt(),
  introduce a context class (Open_table_context), that collects
  all requests.
  A lot of minor cleanups and simplications that became possible
  with this change.


sql/event_db_repository.cc:
  Remove alloc_mdl_requests(). Now MDL_request instance is a member
  of TABLE_LIST, and init_one_table() initializes it.
sql/ha_ndbcluster_binlog.cc:
  Remove now unnecessary declaration and initialization
  of binlog_mdl_request.
sql/lock.cc:
  No need to allocate MDL requests in lock_table_names() now.
sql/log.cc:
  Use init_one_table() method, remove alloc_mdl_requests(),
  which is now unnecessary.
sql/log_event.cc:
  No need to allocate mdl_request separately now.
  Use init_one_table() method.
sql/log_event_old.cc:
  Update to the new signature of close_tables_for_reopen().
sql/mdl.cc:
  Update try_acquire_exclusive_lock() to be more easy to use.
  Function lock_table_name_if_not_cached() has been removed.
  Make acquire_shared_lock() signature consistent with
  try_acquire_exclusive_lock() signature.
  Remove methods that are no longer used.
  Update comments.
sql/mdl.h:
  Implement an assignment operator that doesn't
  copy MDL_key (MDL_key::operator= is private and
  should remain private).
  This is a hack to work-around assignment of TABLE_LIST
  by value in several places. Such assignments violate
  encapsulation, since only perform a shallow copy.
  In most cases these assignments are a hack on their own.
sql/mysql_priv.h:
  Update signatures of close_thread_tables() and close_tables_for_reopen().
sql/sp.cc:
  Allocate TABLE_LIST in thd->mem_root.
  Use init_one_table().
sql/sp_head.cc:
  Use init_one_table().
  Remove thd->locked_tables_root, it's no longer needed.
sql/sql_acl.cc:
  Use init_mdl_requests() and init_one_table().
sql/sql_base.cc:
  Update to new signatures of try_acquire_shared_lock() and
  try_acquire_exclusive_lock().
  Remove lock_table_name_if_not_cached().
  Fix a bug in open_ltable() that would not return ER_LOCK_DEADLOCK
  in case of a failed lock_tables() and a multi-statement
  transaction.
  Fix a bug in open_and_lock_tables_derived() that would
  not return ER_LOCK_DEADLOCK in case of a multi-statement
  transaction and a failure of lock_tables().
  Move assignment of enum_open_table_action to a method of Open_table_context, a new class that maintains information
  for backoff actions.
  Minor rearrangements of the code.
  Remove alloc_mdl_requests() in functions that work with system
  tables: instead the patch ensures that callers always initialize
  TABLE_LIST argument.
sql/sql_class.cc:
  THD::locked_tables_root is no more.
sql/sql_class.h:
  THD::locked_tables_root is no more.
  Add a declaration for Open_table_context class.
sql/sql_delete.cc:
  Update to use the simplified MDL API.
sql/sql_handler.cc:
  TABLE_LIST::mdl_request is stored by-value now.
  Ensure that mdl_request.ticket is NULL for every request
  that is passed into MDL, to satisfy MDL asserts.
  @ sql/sql_help.cc
  Function open_system_tables_for_read() no longer initializes
  mdl_requests.
  Move TABLE_LIST::mdl_request initialization closer to
  TABLE_LIST initialization.
sql/sql_help.cc:
  Function open_system_tables_for_read() no longer initializes
  mdl_requests.
  Move TABLE_LIST::mdl_request initialization closer to
  TABLE_LIST initialization.
sql/sql_insert.cc:
  Remove assignment by-value of TABLE_LIST in
  TABLEOP_HOOKS. We can't carry over a granted
  MDL ticket from one table list to another.
sql/sql_parse.cc:
  Change alloc_mdl_requests() -> init_mdl_requests().
  @todo We can remove init_mdl_requests() altogether
  in some places: all places that call add_table_to_list()
  already have mdl requests initialized.
sql/sql_plugin.cc:
  Use init_one_table().
  THD::locked_tables_root is no more.
sql/sql_servers.cc:
  Use init_one_table().
sql/sql_show.cc:
  Update acquire_high_priority_shared_lock() to use
  TABLE_LIST::mdl_request rather than allocate an own.
  Fix get_trigger_table_impl() to use init_one_table(),
  check for out of memory, follow the coding style.
sql/sql_table.cc:
  Update to work with TABLE_LIST::mdl_request by-value.
  Remove lock_table_name_if_not_cached().
  The code that used to delegate to it is quite simple and
  concise without it now.
sql/sql_udf.cc:
  Use init_one_table().
sql/sql_update.cc:
  Update to use the new signature of close_tables_for_reopen().
sql/table.cc:
  Move re-setting of mdl_requests for prepared statements
  and stored procedures from close_thread_tables() to
  reinit_stmt_before_use().
  Change alloc_mdl_requests() to init_mdl_requests().
  init_mdl_requests() is a hack that can't be deleted
  until we don't have a list-aware TABLE_LIST constructor.
  Hopefully its use will be minimal
sql/table.h:
  Change alloc_mdl_requests() to init_mdl_requests()
  TABLE_LIST::mdl_request is stored by value.
sql/tztime.cc:
  We no longer initialize mdl requests in open_system_tables_for*()
  functions. Move this initialization closer to initialization
  of the rest of TABLE_LIST members.
storage/myisammrg/ha_myisammrg.cc:
  Simplify mdl_request initialization.
2009-12-08 12:57:07 +03:00
Konstantin Osipov
a14bbee5ab Backport of revno ## 2617.31.1, 2617.31.3, 2617.31.4, 2617.31.5,
2617.31.12, 2617.31.15, 2617.31.15, 2617.31.16, 2617.43.1
- initial changeset that introduced the fix for 
Bug#989 and follow up fixes for all test suite failures
introduced in the initial changeset. 
------------------------------------------------------------
revno: 2617.31.1
committer: Davi Arnaut <Davi.Arnaut@Sun.COM>
branch nick: 4284-6.0
timestamp: Fri 2009-03-06 19:17:00 -0300
message:
Bug#989: If DROP TABLE while there's an active transaction, wrong binlog order
WL#4284: Transactional DDL locking

Currently the MySQL server does not keep metadata locks on
schema objects for the duration of a transaction, thus failing
to guarantee the integrity of the schema objects being used
during the transaction and to protect then from concurrent
DDL operations. This also poses a problem for replication as
a DDL operation might be replicated even thought there are
active transactions using the object being modified.

The solution is to defer the release of metadata locks until
a active transaction is either committed or rolled back. This
prevents other statements from modifying the table for the
entire duration of the transaction. This provides commitment
ordering for guaranteeing serializability across multiple
transactions.

- Incompatible change:

If MySQL's metadata locking system encounters a lock conflict,
the usual schema is to use the try and back-off technique to
avoid deadlocks -- this schema consists in releasing all locks
and trying to acquire them all in one go.

But in a transactional context this algorithm can't be utilized
as its not possible to release locks acquired during the course
of the transaction without breaking the transaction commitments.
To avoid deadlocks in this case, the ER_LOCK_DEADLOCK will be
returned if a lock conflict is encountered during a transaction.

Let's consider an example:

A transaction has two statements that modify table t1, then table
t2, and then commits. The first statement of the transaction will
acquire a shared metadata lock on table t1, and it will be kept
utill COMMIT to ensure serializability.

At the moment when the second statement attempts to acquire a
shared metadata lock on t2, a concurrent ALTER or DROP statement
might have locked t2 exclusively. The prescription of the current
locking protocol is that the acquirer of the shared lock backs off
-- gives up all his current locks and retries. This implies that
the entire multi-statement transaction has to be rolled back.

- Incompatible change:

FLUSH commands such as FLUSH PRIVILEGES and FLUSH TABLES WITH READ
LOCK won't cause locked tables to be implicitly unlocked anymore.


mysql-test/extra/binlog_tests/drop_table.test:
  Add test case for Bug#989.
mysql-test/extra/binlog_tests/mix_innodb_myisam_binlog.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction.
mysql-test/include/mix1.inc:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction.
mysql-test/include/mix2.inc:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction.
mysql-test/r/flush_block_commit.result:
  Update test case result (WL#4284).
mysql-test/r/flush_block_commit_notembedded.result:
  Update test case result (WL#4284).
mysql-test/r/innodb.result:
  Update test case result (WL#4284).
mysql-test/r/innodb_mysql.result:
  Update test case result (WL#4284).
mysql-test/r/lock.result:
  Add test case result for an effect of WL#4284/Bug#989
  (all locks should be released when a connection terminates).
mysql-test/r/mix2_myisam.result:
  Update test case result (effects of WL#4284/Bug#989).
mysql-test/r/not_embedded_server.result:
  Update test case result (effects of WL#4284/Bug#989).
  Add a test case for interaction of WL#4284 and FLUSH PRIVILEGES.
mysql-test/r/partition_innodb_semi_consistent.result:
  Update test case result (effects of WL#4284/Bug#989).
mysql-test/r/partition_sync.result:
  Temporarily disable the test case for Bug#43867,
  which will be fixed by a subsequent backport.
mysql-test/r/ps.result:
  Add a test case for effect of PREPARE on transactional
  locks: we take a savepoint at beginning of PREAPRE
  and release it at the end. Thus PREPARE does not 
  accumulate metadata locks (Bug#989/WL#4284).
mysql-test/r/read_only_innodb.result:
  Update test case result (effects of WL#4284/Bug#989).
mysql-test/suite/binlog/r/binlog_row_drop_tbl.result:
  Add a test case result (WL#4284/Bug#989).
mysql-test/suite/binlog/r/binlog_row_mix_innodb_myisam.result:
  Update test case result (effects of WL#4284/Bug#989).
mysql-test/suite/binlog/r/binlog_stm_drop_tbl.result:
  Add a test case result (WL#4284/Bug#989).
mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result:
  Update test case result (effects of WL#4284/Bug#989).
mysql-test/suite/binlog/r/binlog_unsafe.result:
  A side effect of Bug#989 -- slightly different table map ids.
mysql-test/suite/binlog/t/binlog_row_drop_tbl.test:
  Add a test case for WL#4284/Bug#989.
mysql-test/suite/binlog/t/binlog_stm_drop_tbl.test:
  Add a test case for WL#4284/Bug#989.
mysql-test/suite/binlog/t/binlog_stm_row.test:
  Update to the new state name. This
  is actually a follow up to another patch for WL#4284, 
  that changes Locked thread state to Table lock.
mysql-test/suite/ndb/r/ndb_index_ordered.result:
  Remove result for disabled part of the test case.
mysql-test/suite/ndb/t/disabled.def:
  Temporarily disable a test case (Bug#45621).
mysql-test/suite/ndb/t/ndb_index_ordered.test:
  Disable a part of a test case (needs update to
  reflect semantics of Bug#989).
mysql-test/suite/rpl/t/disabled.def:
  Disable tests made meaningless by transactional metadata
  locking.
mysql-test/suite/sys_vars/r/autocommit_func.result:
  Add a commit (Bug#989).
mysql-test/suite/sys_vars/t/autocommit_func.test:
  Add a commit (Bug#989).
mysql-test/t/flush_block_commit.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction.
mysql-test/t/flush_block_commit_notembedded.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction.
  Add a test case for transaction-scope locks and the global
  read lock (Bug#989/WL#4284).
mysql-test/t/innodb.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction
  (effects of Bug#989/WL#4284).
mysql-test/t/lock.test:
  Add a test case for Bug#989/WL#4284.
mysql-test/t/not_embedded_server.test:
  Add a test case for Bug#989/WL#4284.
mysql-test/t/partition_innodb_semi_consistent.test:
  Replace TRUNCATE with DELETE, to not issue
  an implicit commit of a transaction, and not depend
  on metadata locks.
mysql-test/t/partition_sync.test:
  Temporarily disable the test case for Bug#43867,
  which needs a fix to be backported from 6.0.
mysql-test/t/ps.test:
  Add a test case for semantics of PREPARE and transaction-scope
  locks: metadata locks on tables used in PREPARE are enclosed into a
  temporary savepoint, taken at the beginning of PREPARE,
  and released at the end. Thus PREPARE does not effect
  what locks a transaction owns.
mysql-test/t/read_only_innodb.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction 
  (Bug#989/WL#4284).
  
  Wait for the read_only statement to actually flush tables before
  sending other concurrent statements that depend on its state.
mysql-test/t/xa.test:
  Fix test case to reflect the fact that transactions now hold
  metadata locks for the duration of a transaction 
  (Bug#989/WL#4284).
sql/ha_ndbcluster_binlog.cc:
  Backport bits of changes of ha_ndbcluster_binlog.cc
  from 6.0, to fix the failing binlog test suite with
  WL#4284. WL#4284 implementation does not work
  with 5.1 implementation of ndbcluster binlog index.
sql/log_event.cc:
  Release metadata locks after issuing a commit.
sql/mdl.cc:
  Style changes (WL#4284).
sql/mysql_priv.h:
  Rename parameter to match the name used in the definition (WL#4284).
sql/rpl_injector.cc:
  Release metadata locks on commit (WL#4284).
sql/rpl_rli.cc:
  Remove assert made meaningless, metadata locks are released
  at the end of the transaction.
sql/set_var.cc:
  Close tables and release locks if autocommit mode is set.
sql/slave.cc:
  Release metadata locks after a rollback.
sql/sql_acl.cc:
  Don't implicitly unlock locked tables. Issue a implicit commit
  at the end and unlock tables.
sql/sql_base.cc:
  Defer the release of metadata locks when closing tables
  if not required to.
  Issue a deadlock error if the locking protocol requires
  that a transaction re-acquire its locks.
  
  Release metadata locks when closing tables for reopen.
sql/sql_class.cc:
  Release metadata locks if the thread is killed.
sql/sql_parse.cc:
  Release metadata locks after implicitly committing a active
  transaction, or after explicit commits or rollbacks.
sql/sql_plugin.cc:
  
  Allocate MDL request on the stack as the use of the table
  is contained within the function. It will be removed from
  the context once close_thread_tables is called at the end
  of the function.
sql/sql_prepare.cc:
  The problem is that the prepare phase of the CREATE TABLE
  statement takes a exclusive metadata lock lock and this can
  cause a self-deadlock the thread already holds a shared lock
  on the table being that should be created.
  
  The solution is to make the prepare phase take a shared
  metadata lock when preparing a CREATE TABLE statement. The
  execution of the statement will still acquire a exclusive
  lock, but won't cause any problem as it issues a implicit
  commit.
  
  After some discussions with stakeholders it has been decided that
  metadata locks acquired during a PREPARE statement must be released
  once the statement is prepared even if it is prepared within a multi
  statement transaction.
sql/sql_servers.cc:
  Don't implicitly unlock locked tables. Issue a implicit commit
  at the end and unlock tables.
sql/sql_table.cc:
  Close table and release metadata locks after a admin operation.
sql/table.h:
  The problem is that the prepare phase of the CREATE TABLE
  statement takes a exclusive metadata lock lock and this can
  cause a self-deadlock the thread already holds a shared lock
  on the table being that should be created.
  
  The solution is to make the prepare phase take a shared
  metadata lock when preparing a CREATE TABLE statement. The
  execution of the statement will still acquire a exclusive
  lock, but won't cause any problem as it issues a implicit
  commit.
sql/transaction.cc:
  Release metadata locks after the implicitly committed due
  to a new transaction being started. Also, release metadata
  locks acquired after a savepoint if the transaction is rolled
  back to the save point.
  
  The problem is that in some cases transaction-long metadata locks
  could be released before the transaction was committed. This could
  happen when a active transaction was ended by a "START TRANSACTION"
  or "BEGIN" statement, in which case the metadata locks would be
  released before the actual commit of the active transaction.
  
  The solution is to defer the release of metadata locks to after the
  transaction has been implicitly committed. No test case is provided
  as the effort to provide one is too disproportional to the size of
  the fix.
2009-12-05 02:02:48 +03:00
Konstantin Osipov
f5f708d4e1 Backport of (WL#4284):
------------------------------------------------------------
revno: 2617.23.23
committer: Davi Arnaut <Davi.Arnaut@Sun.COM>
branch nick: mysql-6.0-runtime
timestamp: Thu 2009-03-05 18:39:58 -0300
message:
Fix for broken build: SHARED is defined by Solaris headers.


sql/mdl.cc:
  Add MDL_LOCK prefix to the lock types of MDL_LOCK.
2009-12-04 02:55:26 +03:00
Konstantin Osipov
a9013f8fba Backport of:
----------------------------------------------------------
revno: 2617.23.20
committer: Konstantin Osipov <kostja@sun.com>
branch nick: mysql-6.0-runtime
timestamp: Wed 2009-03-04 16:31:31 +0300
message:
  WL#4284 "Transactional DDL locking"
  Review comments: "Objectify" the MDL API.
  MDL_request and MDL_context still need manual construction and
  destruction, since they are used in environment that is averse
  to constructors/destructors.


sql/mdl.cc:
  Improve comments.
  Add asserts to backup()/restore_from_backup()/merge() methods.
  Fix an order bug in the error path of mdl_acquire_exclusive_locks():
  we used to first free a ticket object, and only then exclude
  it from the list of tickets.
2009-12-04 02:52:05 +03:00
Konstantin Osipov
97abce0e7c Backport of:
----------------------------------------------------------
revno: 2617.23.19
committer: Konstantin Osipov <kostja@sun.com>
branch nick: mysql-6.0-runtime
timestamp: Tue 2009-03-03 01:20:44 +0300
message:
  Metadata locking: realign comments. No semantical changes,
  only enforce a bit of the coding style.
This is a review fix for WL#4284 "Transactional DDL locking".

sql/mdl.cc:
  Realign doxygen comments.
sql/mdl.h:
  Realign doxygen comments.
2009-12-04 02:34:19 +03:00
Konstantin Osipov
f477e66ec5 Backport of:
------------------------------------------------------------
revno: 2617.23.18
committer: Davi Arnaut <Davi.Arnaut@Sun.COM>
branch nick: 4284-6.0
timestamp: Mon 2009-03-02 18:18:26 -0300
message:
Bug#989: If DROP TABLE while there's an active transaction, wrong binlog order
WL#4284: Transactional DDL locking

This is a prerequisite patch:

These changes are intended to split lock requests from granted
locks and to allow the memory and lifetime of granted locks to
be managed within the MDL subsystem. Furthermore, tickets can
now be shared and therefore are used to satisfy multiple lock
requests, but only shared locks can be recursive.

The problem is that the MDL subsystem morphs lock requests into
granted locks locks but does not manage the memory and lifetime
of lock requests, and hence, does not manage the memory of
granted locks either. This can be problematic because it puts the
burden of tracking references on the users of the subsystem and
it can't be easily done in transactional contexts where the locks
have to be kept around for the duration of a transaction.

Another issue is that recursive locks (when the context trying to
acquire a lock already holds a lock on the same object) requires
that each time the lock is granted, a unique lock request/granted
lock structure structure must be kept around until the lock is
released. This can lead to memory leaks in transactional contexts
as locks taken during the transaction should only be released at
the end of the transaction. This also leads to unnecessary wake
ups (broadcasts) in the MDL subsystem if the context still holds
a equivalent of the lock being released.

These issues are exacerbated due to the fact that WL#4284 low-level
design says that the implementation should "2) Store metadata locks
in transaction memory root, rather than statement memory root" but
this is not possible because a memory root, as implemented in mysys,
requires all objects allocated from it to be freed all at once.

This patch combines review input and significant code contributions
from Konstantin Osipov (kostja) and Dmitri Lenev (dlenev).


mysql-test/r/mdl_sync.result:
  Add test case result.
mysql-test/t/mdl_sync.test:
  Add test case for shared lock upgrade case.
sql/event_db_repository.cc:
  Rename mdl_alloc_lock to mdl_request_alloc.
sql/ha_ndbcluster_binlog.cc:
  Use new function names to initialize MDL lock requests.
sql/lock.cc:
  Rename MDL functions.
sql/log_event.cc:
  The MDL request now holds the table and database name data (MDL_KEY).
sql/mdl.cc:
  Move the MDL key to the MDL_LOCK structure in order to make the
  object suitable for allocation from a fixed-size allocator. This
  allows the simplification of the lists in the MDL_LOCK object,
  which now are just two, one for granted tickets and other for
  waiting (upgraders) tickets.
  
  Recursive requests for a shared lock on the same object can now
  be granted using the same lock ticket. This schema is only used
  for shared locks because that the only case that matters. This
  is used to avoid waste of resources in case a context (connection)
  already holds a shared lock on a object.
sql/mdl.h:
  Introduce a metadata lock object key which is used  to uniquely
  identify lock objects.
  
  Separate the structure used to represent pending lock requests
  from the structure used to represent granted metadata locks.
  
  Rename functions used to manipulate locks requests in order to
  have a more consistent function naming schema.
sql/sp_head.cc:
  Rename mdl_alloc_lock to mdl_request_alloc.
sql/sql_acl.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/sql_base.cc:
  Various changes to accommodate that lock requests are separated
  from lock tickets (granted locks).
sql/sql_class.h:
  Last acquired lock before the savepoint was set.
sql/sql_delete.cc:
  Various changes to accommodate that lock requests are separated
  from lock tickets (granted locks).
sql/sql_handler.cc:
  Various changes to accommodate that lock requests are separated
  from lock tickets (granted locks).
sql/sql_insert.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/sql_parse.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/sql_plist.h:
  Typedef for iterator type.
sql/sql_plugin.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/sql_servers.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/sql_show.cc:
  Various changes to accommodate that lock requests are separated
  from lock tickets (granted locks).
sql/sql_table.cc:
  Various changes to accommodate that lock requests are separated
  from lock tickets (granted locks).
sql/sql_trigger.cc:
  Save reference to the lock ticket so it can be downgraded later.
sql/sql_udf.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
sql/table.cc:
  Rename mdl_alloc_lock to mdl_request_alloc.
sql/table.h:
  Separate MDL lock requests from lock tickets (granted locks).
storage/myisammrg/ha_myisammrg.cc:
  Rename alloc_mdl_locks to alloc_mdl_requests.
2009-12-04 02:29:40 +03:00
Konstantin Osipov
cae6e72a40 Backport of:
----------------------------------------------------------
revno: 2617.22.7
committer: Konstantin Osipov <kostja@sun.com>
branch nick: mysql-6.0-runtime
timestamp: Tue 2009-01-27 16:41:58 +0300
message:
  WL#4284 "Transactional DDL locking" review.
  Improve a comment.


sql/mdl.cc:
  Improve a comment.
2009-12-04 01:48:14 +03:00
Konstantin Osipov
eef538ab96 Backport of (WL#3726)
------------------------------------------------------------ 
revno: 2630.13.4
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-6.0-runtime
timestamp: Mon 2008-07-07 19:51:20 +0400
message:
  Fixed outdated comment describing mdl_init_lock() function.
2009-12-03 14:32:29 +03:00
Konstantin Osipov
124cda8a0a Backport of:
------------------------------------------------------------
revno: 2630.4.33
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-6.0-3726-w2
timestamp: Fri 2008-06-20 17:11:20 +0400
message:
  WL#3726 "DDL locking for all metadata objects".

  After-review fixes in progress.

  Minimized dependency of mdl.cc on other modules (particularly
  made it independant of mysql_priv.h) in order to be able
  write unit tests for metadata locking subsystem.


sql/ha_ndbcluster_binlog.cc:
  Use newly introduced MAX_MDLKEY_LENGTH constant for allocating
  buffer for object key for metadata locking subsystem.
sql/log_event.cc:
  Use newly introduced MAX_MDLKEY_LENGTH constant for allocating
  buffer for object key for metadata locking subsystem.
sql/mdl.cc:
  Removed dependency on THD class (and thus on mysql_priv.h)
  by using direct access to members of st_my_thread_var instead
  of accessing THD::killed/enter_cond()/exit_cond().
sql/mdl.h:
  Added MAX_MDLKEY_LENGTH constant to be used for allocating
  buffers for key for metadata locking subsystem.
  Added declarations of server kernel functions used by metadata
  locking subsystem to mdl.h in order to decrease dependency of
  mdl.cc on other files.
sql/mysql_priv.h:
  Moved declaration of notify_thread_having_shared_lock() to the
  mdl.h (also renamed it to make clear in metadata locking code
  that it is a callback to SQL-layer).
sql/sql_base.cc:
  Renamed notify_thread_having_shared_lock() to make it clear
  in metadata locking subsystem code that it is a callback
  to SQL layer.
sql/sql_handler.cc:
  Use newly introduced MAX_MDLKEY_LENGTH constant for allocating
  buffer for object key for metadata locking subsystem.
sql/sql_show.cc:
  Use newly introduced MAX_MDLKEY_LENGTH constant for allocating
  buffer for object key for metadata locking subsystem.
2009-12-02 19:31:57 +03:00
Konstantin Osipov
e3b3907c4f Backport of:
------------------------------------------------------------
revno: 2630.4.32
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-6.0-3726-w2
timestamp: Thu 2008-06-19 16:39:58 +0400
message:
  WL#3726 "DDL locking for all metadata objects".

  After-review fixes in progress.

  Ensure that metadata locking subsystem properly handles
  out-of-memory conditions. Clarified MDL interface by
  separating release of locks and removal of lock requests
  from the context.

sql/lock.cc:
  mdl_release_lock(), mdl_acquire_exclusive_locks() and 
  mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
sql/mdl.cc:
  Ensured that metadata locking subsystem properly handles
  out-of-memory conditions.
  Introduced new MDL_INITIALIZED state for metadata lock
  request which is used in all cases when lock is not acquired 
  and we have not associated request with object respesenting 
  lock.
  
  MDL_PENDING is now only used for requests for exclusive locks
  which are added to the MDL_LOCK::waiting_exclusive queue.
  mdl_release_lock(), mdl_acquire_exclusive_locks() and 
  mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  newly introduced mdl_remove_lock() to do this.
  Also renamed mdl_release_all_locks_for_name() to 
  emphasize that it also actually removes lock requests
  from the context.
  
  Finally mdl_try_acquire_exclusive_lock() is now returs
  information about encountered lock conflict in separate
  out parameter since its return value is used for distinguishing
  between error (e.g. due to OOM) and success.
sql/mdl.h:
  Introduced new MDL_INITIALIZED state for metadata lock
  request which is used in all cases when lock is not acquired 
  and we have not associated request with object respesenting 
  lock.
  
  MDL_PENDING is now only used for requests for exclusive locks
  which are added to the MDL_LOCK::waiting_exclusive queue.
  mdl_release_lock(), mdl_acquire_exclusive_locks() and 
  mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  newly introduced mdl_remove_lock() to do this.
  Also renamed mdl_release_all_locks_for_name() to 
  emphasize that it also actually removes lock requests
  from the context.
  
  Finally mdl_try_acquire_exclusive_lock() is now returs
  information about encountered lock conflict in separate
  out parameter since its return value is used for distinguishing
  between error (e.g. due to OOM) and success.
sql/sql_base.cc:
  mdl_release_lock(), mdl_acquire_exclusive_locks() and mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
  Also adjusted open_table() to ensure that it 
  releases/removes metadata locks in case of error 
  after adding/acquiring them (unless keeping these
  lock requests is required for recovering action).
sql/sql_delete.cc:
  mdl_release_lock(), mdl_acquire_exclusive_locks() and mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
sql/sql_handler.cc:
  mdl_release_lock(), mdl_acquire_exclusive_locks() and mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
sql/sql_show.cc:
  mdl_release_lock(), mdl_acquire_exclusive_locks() and mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
sql/sql_table.cc:
  Renamed mdl_release_all_locks_for_name() to emphasize
  that it also actually removes lock requests from the context.
  mdl_release_lock(), mdl_acquire_exclusive_locks() and mdl_try_acquire_exclusive_lock() are no longer responsible
  for removal of metadata lock requests from the context.
  One should explicitly call mdl_remove_all_locks() and
  mdl_remove_lock() to do this.
  Finally mdl_try_acquire_exclusive_lock() is now returs
  information about encountered lock conflict in separate
  out parameter since its return value is used for distinguishing
  between error (e.g. due to OOM) and success.
2009-12-02 19:15:40 +03:00
Konstantin Osipov
f7ba9dafd5 Backport of:
------------------------------------------------------------
revno: 2630.9.2
committer: Dmitry Lenev <dlenev@mysql.com>
branch nick: mysql-6.0-3726-w3
timestamp: Tue 2008-06-10 18:01:56 +0400
message:
  WL#3726 "DDL locking for all metadata objects".

  After review fixes in progress.


sql/mdl.cc:
  Changed mdl_acquire_shared_lock() signature to accept MDL_CONTEXT
  as one of arguments as described in specification.
sql/mdl.h:
  Changed mdl_acquire_shared_lock() signature to accept MDL_CONTEXT
   as one of arguments as described in specification.
sql/sql_base.cc:
  Changed mdl_acquire_shared_lock() signature to accept MDL_CONTEXT
  as one of arguments as described in specification.
  Renamed handle_failed_open_table_attempt() to
  recover_from_failed_open_table_attempt() as suggested by review.
  Added comment clarifying why we need to check TABLE::db_stat
  while looking at TABLE instances open by other threads.
sql/sql_show.cc:
  Changed mdl_acquire_shared_lock() signature to accept MDL_CONTEXT
  as one of arguments as described in specification.
2009-12-01 18:20:43 +03:00