Debian Codegraph @

storage/innobase/lock/lock0lock.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1996, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file lock/lock0lock.cc
29 The transaction lock system
30
31 Created 5/7/1996 Heikki Tuuri
32 *******************************************************/
33
34 #define LOCK_MODULE_IMPLEMENTATION
35
36 #include <mysql/service_thd_engine_lock.h>
37 #include <sys/types.h>
38
39 #include <algorithm>
40 #include <set>
41 #include <unordered_map>
42 #include <vector>
43
44 #include "btr0btr.h"
45 #include "current_thd.h"
46 #include "debug_sync.h" /* CONDITIONAL_SYNC_POINT */
47 #include "dict0boot.h"
48 #include "dict0mem.h"
49 #include "ha_prototypes.h"
50 #include "lock0lock.h"
51 #include "lock0priv.h"
52 #include "os0thread.h"
53 #include "pars0pars.h"
54 #include "row0mysql.h"
55 #include "row0sel.h"
56 #include "srv0mon.h"
57 #include "trx0purge.h"
58 #include "trx0sys.h"
59 #include "usr0sess.h"
60 #include "ut0bitset.h"
61 #include "ut0new.h"
62 #include "ut0vec.h"
63
64 #include "my_dbug.h"
65 #include "my_psi_config.h"
66 #include "mysql/plugin.h"
67 #include "mysql/psi/psi_thread.h"
68
69 /* Flag to enable/disable deadlock detector. */
70 bool innobase_deadlock_detect = true;
71
72 /** Total number of cached record locks */
73 static const ulint REC_LOCK_CACHE = 8;
74
75 /** Maximum record lock size in bytes */
76 static const ulint REC_LOCK_SIZE = sizeof(ib_lock_t) + 256;
77
78 /** Total number of cached table locks */
79 static const ulint TABLE_LOCK_CACHE = 8;
80
81 /** Size in bytes, of the table lock instance */
82 static const ulint TABLE_LOCK_SIZE = sizeof(ib_lock_t);
83
84 template <typename T>
85 using Locks = std::vector<T, mem_heap_allocator<T>>;
86
87 /** Used by lock_get_mode_str to build a lock mode description */
88 static const std::map<uint, const char *> lock_constant_names{
89 {LOCK_GAP, "GAP"},
90 {LOCK_REC_NOT_GAP, "REC_NOT_GAP"},
91 {LOCK_INSERT_INTENTION, "INSERT_INTENTION"},
92 {LOCK_PREDICATE, "PREDICATE"},
93 {LOCK_PRDT_PAGE, "PRDT_PAGE"},
94 };
95 /** Used by lock_get_mode_str to cache results. Strings pointed by these
96 pointers might be in use by performance schema and thus can not be freed
97 until the very end.
98 Protected by exclusive global lock_cached_lock_mode_names_mutex.
99 */
100 static std::unordered_map<uint, const char *> lock_cached_lock_mode_names;
101
102 /** Mutex protecting access to lock_cached_lock_mode_names */
103 static std::mutex lock_cached_lock_mode_names_mutex;
104
105 /** A static class for reporting notifications about deadlocks */
106 class Deadlock_notifier {
107 public:
108 Deadlock_notifier() = delete;
109
110 /** Handles writing the information about found deadlock to the log files
111 and caches it for future lock_latest_err_file() calls (for example used by
112 SHOW ENGINE INNODB STATUS)
113 @param[in] trxs_on_cycle trxs causing deadlock, i-th waits for i+1-th
114 @param[in] victim_trx the trx from trx_on_cycle which will be rolled back
115 */
116 static void notify(const ut::vector<const trx_t *> &trxs_on_cycle,
117 const trx_t *victim_trx);
118
119 private:
120 #ifdef UNIV_DEBUG
121 /** Determines if a situation in which the lock takes part in a deadlock
122 cycle is expected (as in: handled correctly) or not (say because it is on a DD
123 table, for which there is no reason to expect a deadlock and we don't handle
124 deadlocks correctly). The purpose of the function is to use it in an assertion
125 failing as soon as the deadlock is identified, to give developer a chance to
126 investigate the root cause of the situation (without such assertion, the code
127 might continue to run and either fail at later stage when the data useful for
128 debugging is no longer on stack, or not fail at all, which is risky).
129 @param[in] lock lock found in a deadlock cycle
130 @return true if we expect that this lock can take part in a deadlock cycle */
131 static bool is_allowed_to_be_on_cycle(const lock_t *lock);
132 #endif /* UNIV_DEBUG */
133
134 /** Print transaction data to the deadlock file and possibly to stderr.
135 @param trx transaction
136 @param max_query_len max query length to print */
137 static void print(const trx_t *trx, ulint max_query_len);
138
139 /** rewind(3) the file used for storing the latest detected deadlock
140 and print a heading message to stderr if printing of all deadlocks to
141 stderr is enabled. */
142 static void start_print();
143
144 /** Print lock data to the deadlock file and possibly to stderr.
145 @param lock record or table type lock */
146 static void print(const lock_t *lock);
147
148 /** Print a message to the deadlock file and possibly to stderr.
149 @param msg message to print */
150 static void print(const char *msg);
151
152 /** Prints a numbered section title to the deadlock file and possibly to
153 stderr. Numbers do not have to be unique, as they are used to identify
154 transactions on the cycle, and there are multiple sections per transaction.
155 @param[in] pos_on_cycle The zero-based position of trx on deadlock cycle
156 @param[in] title The title of the section */
157 static void print_title(size_t pos_on_cycle, const char *title);
158 };
159
160 #ifdef UNIV_DEBUG
161 namespace locksys {
162
163 bool owns_exclusive_global_latch() {
164 return lock_sys->latches.owns_exclusive_global_latch();
165 }
166
167 bool owns_shared_global_latch() {
168 return lock_sys->latches.owns_shared_global_latch();
169 }
170
171 bool owns_page_shard(const page_id_t &page_id) {
172 return lock_sys->latches.owns_page_shard(page_id);
173 }
174
175 bool owns_table_shard(const dict_table_t &table) {
176 return lock_sys->latches.owns_table_shard(table);
177 }
178
179 bool owns_lock_shard(const lock_t *lock) {
180 if (lock->is_record_lock()) {
181 return lock_sys->latches.owns_page_shard(lock->rec_lock.page_id);
182 } else {
183 return lock_sys->latches.owns_table_shard(*lock->tab_lock.table);
184 }
185 }
186 } // namespace locksys
187
188 /** Validates the record lock queues on a page.
189 @param[in] block A (possibly freed) block for which we want to validate all
190 lock queues. If any of the queues is non-empty we
191 additionally assert that the block was not freed.
192 */
193 static void lock_rec_validate_page(const buf_block_t *block);
194 #endif /* UNIV_DEBUG */
195
196 /* The lock system */
197 lock_sys_t *lock_sys = nullptr;
198
199 /** We store info on the latest deadlock error to this buffer. InnoDB
200 Monitor will then fetch it and print */
201 static bool lock_deadlock_found = false;
202
203 /** Only created if !srv_read_only_mode. I/O operations on this file require
204 exclusive lock_sys latch */
205 static FILE *lock_latest_err_file;
206
207 void lock_report_trx_id_insanity(trx_id_t trx_id, const rec_t *rec,
208 const dict_index_t *index,
209 const ulint *offsets, trx_id_t next_trx_id) {
210 ib::error(ER_IB_MSG_634) << "Transaction id " << trx_id
211 << " associated with record"
212 << rec_offsets_print(rec, offsets) << " in index "
213 << index->name << " of table " << index->table->name
214 << " is greater or equal than the global counter "
215 << next_trx_id << "! The table is corrupted.";
216 }
217
218 bool lock_check_trx_id_sanity(trx_id_t trx_id, const rec_t *rec,
219 const dict_index_t *index, const ulint *offsets) {
220 ut_ad(rec_offs_validate(rec, index, offsets));
221
222 trx_id_t next_trx_id = trx_sys_get_next_trx_id_or_no();
223 bool is_ok = trx_id < next_trx_id;
224
225 if (!is_ok) {
226 lock_report_trx_id_insanity(trx_id, rec, index, offsets, next_trx_id);
227 }
228
229 return (is_ok);
230 }
231
232 /** Checks that a record is seen in a consistent read.
233 @return true if sees, or false if an earlier version of the record
234 should be retrieved */
235 bool lock_clust_rec_cons_read_sees(
236 const rec_t *rec, /*!< in: user record which should be read or
237 passed over by a read cursor */
238 dict_index_t *index, /*!< in: clustered index */
239 const ulint *offsets, /*!< in: rec_get_offsets(rec, index) */
240 ReadView *view) /*!< in: consistent read view */
241 {
242 ut_ad(index->is_clustered());
243 ut_ad(page_rec_is_user_rec(rec));
244 ut_ad(rec_offs_validate(rec, index, offsets));
245
246 /* Temp-tables are not shared across connections and multiple
247 transactions from different connections cannot simultaneously
248 operate on same temp-table and so read of temp-table is
249 always consistent read. */
250 if (srv_read_only_mode || index->table->is_temporary()) {
251 ut_ad(view == nullptr || index->table->is_temporary());
252 return (true);
253 }
254
255 /* NOTE that we call this function while holding the search
256 system latch. */
257
258 trx_id_t trx_id = row_get_rec_trx_id(rec, index, offsets);
259
260 return (view->changes_visible(trx_id, index->table->name));
261 }
262
263 /** Checks that a non-clustered index record is seen in a consistent read.
264
265 NOTE that a non-clustered index page contains so little information on
266 its modifications that also in the case false, the present version of
267 rec may be the right, but we must check this from the clustered index
268 record.
269
270 @return true if certainly sees, or false if an earlier version of the
271 clustered index record might be needed */
272 bool lock_sec_rec_cons_read_sees(
273 const rec_t *rec, /*!< in: user record which
274 should be read or passed over
275 by a read cursor */
276 const dict_index_t *index, /*!< in: index */
277 const ReadView *view) /*!< in: consistent read view */
278 {
279 ut_ad(page_rec_is_user_rec(rec));
280
281 /* NOTE that we might call this function while holding the search
282 system latch. */
283
284 if (recv_recovery_is_on()) {
285 return (false);
286
287 } else if (index->table->is_temporary()) {
288 /* Temp-tables are not shared across connections and multiple
289 transactions from different connections cannot simultaneously
290 operate on same temp-table and so read of temp-table is
291 always consistent read. */
292
293 return (true);
294 }
295
296 trx_id_t max_trx_id = page_get_max_trx_id(page_align(rec));
297
298 ut_ad(max_trx_id > 0);
299
300 return (view->sees(max_trx_id));
301 }
302
303 /** Creates the lock system at database start. */
304 void lock_sys_create(
305 ulint n_cells) /*!< in: number of slots in lock hash table */
306 {
307 ulint lock_sys_sz;
308
309 lock_sys_sz = sizeof(*lock_sys) + srv_max_n_threads * sizeof(srv_slot_t);
310
311 lock_sys = static_cast<lock_sys_t *>(
312 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, lock_sys_sz));
313
314 new (lock_sys) lock_sys_t{n_cells};
315
316 void *ptr = &lock_sys[1];
317
318 lock_sys->waiting_threads = static_cast<srv_slot_t *>(ptr);
319
320 lock_sys->last_slot = lock_sys->waiting_threads;
321
322 mutex_create(LATCH_ID_LOCK_SYS_WAIT, &lock_sys->wait_mutex);
323
324 lock_sys->timeout_event = os_event_create();
325
326 if (!srv_read_only_mode) {
327 lock_latest_err_file = os_file_create_tmpfile();
328 ut_a(lock_latest_err_file);
329 }
330 }
331
332 /** Calculates the hash value of a lock: used in migrating the hash table.
333 @param[in] lock record lock object
334 @return hashed value */
335 static uint64_t lock_rec_lock_hash_value(const lock_t *lock) {
336 return lock_rec_hash_value(lock->rec_lock.page_id);
337 }
338
339 /** Resize the lock hash tables.
340 @param[in] n_cells number of slots in lock hash table */
341 void lock_sys_resize(ulint n_cells) {
342 /* We will rearrange locks between cells and change the parameters of hash
343 function used in sharding of latches, so we have to prevent everyone from
344 accessing lock sys queues, or even computing shard id. */
345 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
346
347 /* This invalidates All_lock_iterators */
348 lock_sys->n_resizes++;
349
350 lock_sys->rec_hash.resize(n_cells);
351
352 DBUG_EXECUTE_IF("syncpoint_after_lock_sys_resize_rec_hash", {
353 /* A workaround for buf_resize_thread() not using create_thd().
354 TBD: if buf_resize_thread() were to use create_thd() then should it be
355 instrumented (together or instead of os_thread_create instrumentation)? */
356 ut_ad(current_thd == nullptr);
357 THD *thd = create_internal_thd();
358 ut_ad(current_thd == thd);
359 CONDITIONAL_SYNC_POINT("after_lock_sys_resize_rec_hash");
360 destroy_internal_thd(thd);
361 ut_ad(current_thd == nullptr);
362 });
363
364 lock_sys->prdt_hash.resize(n_cells);
365
366 lock_sys->prdt_page_hash.resize(n_cells);
367 }
368 void Locks_hashtable::resize(size_t n_cells) {
369 auto new_ht = ut::new_<hash_table_t>(n_cells);
370 HASH_MIGRATE(ht.get(), new_ht, lock_t, hash, lock_rec_lock_hash_value);
371 ht.reset(new_ht);
372 cells_in_use = Cells_in_use{ht->get_n_cells(),
373 ut::make_psi_memory_key(mem_key_lock_sys)};
374 for (size_t i = 0; i < ht->get_n_cells(); ++i) {
375 if (hash_get_first(ht.get(), i) != nullptr) {
376 cells_in_use.set(i);
377 }
378 }
379 }
380 size_t Locks_hashtable::get_cell_id(uint64_t hash_value) {
381 return hash_calc_cell_id(hash_value, ht.get());
382 }
383 bool Locks_hashtable::append(hash_cell_t *cell, lock_t *lock) {
384 lock_t *last = (lock_t *)cell->node;
385 lock->hash = nullptr;
386 if (last == nullptr) {
387 cell->node = lock;
388 return true;
389 }
390 while (last->hash != nullptr) {
391 last = last->hash;
392 }
393 last->hash = lock;
394 return false;
395 }
396 bool Locks_hashtable::prepend(hash_cell_t *cell, lock_t *lock) {
397 lock->hash = (lock_t *)cell->node;
398 cell->node = lock;
399 return lock->hash == nullptr;
400 }
401 bool Locks_hashtable::erase(hash_cell_t *cell, lock_t *lock) {
402 lock_t *last = (lock_t *)cell->node;
403 if (last == lock) {
404 cell->node = lock->hash;
405 HASH_INVALIDATE(lock, hash);
406 return cell->node == nullptr;
407 }
408 while (last->hash != lock) {
409 last = last->hash;
410 }
411 last->hash = lock->hash;
412 HASH_INVALIDATE(lock, hash);
413 return false;
414 }
415 void Locks_hashtable::append(lock_t *lock, uint64_t hash_value) {
416 ut_ad(hash_value == lock_rec_lock_hash_value(lock));
417 const auto cell_id = get_cell_id(hash_value);
418 auto *cell = hash_get_nth_cell(ht.get(), cell_id);
419 if (append(cell, lock)) {
420 cells_in_use.set(cell_id);
421 }
422 }
423 void Locks_hashtable::prepend(lock_t *lock, uint64_t hash_value) {
424 ut_ad(hash_value == lock_rec_lock_hash_value(lock));
425 const auto cell_id = get_cell_id(hash_value);
426 auto *cell = hash_get_nth_cell(ht.get(), cell_id);
427 if (prepend(cell, lock)) {
428 cells_in_use.set(cell_id);
429 }
430 }
431 void Locks_hashtable::erase(lock_t *lock, uint64_t hash_value) {
432 ut_ad(hash_value == lock_rec_lock_hash_value(lock));
433 const auto cell_id = get_cell_id(hash_value);
434 auto *cell = hash_get_nth_cell(ht.get(), cell_id);
435 if (erase(cell, lock)) {
436 cells_in_use.reset(cell_id);
437 }
438 }
439 void Locks_hashtable::move_to_front(lock_t *lock, uint64_t hash_value) {
440 ut_ad(hash_value == lock_rec_lock_hash_value(lock));
441 const auto cell_id = get_cell_id(hash_value);
442 auto *cell = hash_get_nth_cell(ht.get(), cell_id);
443 erase(cell, lock);
444 prepend(cell, lock);
445 }
446
447 /** Closes the lock system at database shutdown. */
448 void lock_sys_close(void) {
449 if (lock_latest_err_file != nullptr) {
450 fclose(lock_latest_err_file);
451 lock_latest_err_file = nullptr;
452 }
453
454 os_event_destroy(lock_sys->timeout_event);
455
456 mutex_destroy(&lock_sys->wait_mutex);
457
458 srv_slot_t *slot = lock_sys->waiting_threads;
459
460 for (uint32_t i = 0; i < srv_max_n_threads; i++, ++slot) {
461 if (slot->event != nullptr) {
462 os_event_destroy(slot->event);
463 }
464 }
465 for (auto &cached_lock_mode_name : lock_cached_lock_mode_names) {
466 ut::free(const_cast<char *>(cached_lock_mode_name.second));
467 }
468 lock_cached_lock_mode_names.clear();
469
470 lock_sys->~lock_sys_t();
471
472 ut::free(lock_sys);
473
474 lock_sys = nullptr;
475 }
476
477 bool lock_is_waiting(const lock_t &lock) {
478 ut_ad(locksys::owns_lock_shard(&lock));
479 return lock.is_waiting();
480 }
481
482 /** Sets the wait flag of a lock and the back pointer in trx to lock.
483 @param[in] lock The lock on which a transaction is waiting */
484 static inline void lock_set_lock_and_trx_wait(lock_t *lock) {
485 auto trx = lock->trx;
486 ut_ad(trx_mutex_own(trx));
487 ut_a(trx->lock.wait_lock == nullptr);
488 ut_ad(locksys::owns_lock_shard(lock));
489
490 trx->lock.wait_lock = lock;
491 trx->lock.wait_lock_type = lock_get_type_low(lock);
492 lock->type_mode |= LOCK_WAIT;
493 }
494
495 /** Gets the gap flag of a record lock.
496 @return LOCK_GAP or 0 */
497 static inline ulint lock_rec_get_gap(const lock_t *lock) /*!< in: record lock */
498 {
499 ut_ad(lock_get_type_low(lock) == LOCK_REC);
500
501 return (lock->type_mode & LOCK_GAP);
502 }
503
504 /** Gets the LOCK_REC_NOT_GAP flag of a record lock.
505 @return LOCK_REC_NOT_GAP or 0 */
506 static inline ulint lock_rec_get_rec_not_gap(
507 const lock_t *lock) /*!< in: record lock */
508 {
509 ut_ad(lock_get_type_low(lock) == LOCK_REC);
510
511 return (lock->type_mode & LOCK_REC_NOT_GAP);
512 }
513
514 /** Gets the waiting insert flag of a record lock.
515 @return LOCK_INSERT_INTENTION or 0 */
516 static inline ulint lock_rec_get_insert_intention(
517 const lock_t *lock) /*!< in: record lock */
518 {
519 ut_ad(lock_get_type_low(lock) == LOCK_REC);
520
521 return (lock->type_mode & LOCK_INSERT_INTENTION);
522 }
523 namespace locksys {
524
525 enum class Conflict {
526 HAS_TO_WAIT,
527 NO_CONFLICT,
528 CAN_BYPASS,
529 };
530
531 /** Checks if a new request for a record lock has to wait for existing request.
532 @param[in] trx The trx requesting the new lock
533 @param[in] type_mode precise mode of the new lock to set: LOCK_S or
534 LOCK_X, possibly ORed to LOCK_GAP or
535 LOCK_REC_NOT_GAP, LOCK_INSERT_INTENTION
536 @param[in] lock2 another record lock;
537 NOTE that it is assumed that this has a lock
538 bit set on the same record as in the new lock
539 we are setting
540 @param[in] lock_is_on_supremum true if we are setting the lock on the
541 'supremum' record of an index page: we know
542 then that the lock request is really for a
543 'gap' type lock
544 @param[in] trx_locks_cache An object which can be passed to consecutive
545 calls to this function for the same trx and
546 heap_no (which is implicitly the bit common to
547 all lock2 objects passed) which can be used by
548 this function to cache some partial results.
549 @retval NO_CONFLICT the trx does not have to wait for lock2
550 @retval CAN_BYPASS the trx does not have to wait for lock2, as it can bypass it
551 @retval HAS_TO_WAIT the trx has to wait for lock2
552 */
553 static inline Conflict rec_lock_check_conflict(const trx_t *trx,
554 ulint type_mode,
555 const lock_t *lock2,
556 bool lock_is_on_supremum,
557 Trx_locks_cache &trx_locks_cache)
558
559 {
560 ut_ad(trx && lock2);
561 ut_ad(lock_get_type_low(lock2) == LOCK_REC);
562
563 if (trx == lock2->trx ||
564 lock_mode_compatible(static_cast<lock_mode>(LOCK_MODE_MASK & type_mode),
565 lock_get_mode(lock2))) {
566 return Conflict::NO_CONFLICT;
567 }
568
569 const bool is_hp = trx_is_high_priority(trx);
570 /* If our trx is High Priority and the existing lock is WAITING and not
571 high priority, then we can ignore it. */
572 if (is_hp && lock2->is_waiting() && !trx_is_high_priority(lock2->trx)) {
573 return Conflict::NO_CONFLICT;
574 }
575
576 /* We have somewhat complex rules when gap type record locks
577 cause waits */
578
579 if ((lock_is_on_supremum || (type_mode & LOCK_GAP)) &&
580 !(type_mode & LOCK_INSERT_INTENTION)) {
581 /* Gap type locks without LOCK_INSERT_INTENTION flag
582 do not need to wait for anything. This is because
583 different users can have conflicting lock types
584 on gaps. */
585
586 return Conflict::NO_CONFLICT;
587 }
588
589 if (!(type_mode & LOCK_INSERT_INTENTION) && lock_rec_get_gap(lock2)) {
590 /* Record lock (LOCK_ORDINARY or LOCK_REC_NOT_GAP
591 does not need to wait for a gap type lock */
592
593 return Conflict::NO_CONFLICT;
594 }
595
596 if ((type_mode & LOCK_GAP) && lock_rec_get_rec_not_gap(lock2)) {
597 /* Lock on gap does not need to wait for
598 a LOCK_REC_NOT_GAP type lock */
599
600 return Conflict::NO_CONFLICT;
601 }
602
603 if (lock_rec_get_insert_intention(lock2)) {
604 /* No lock request needs to wait for an insert
605 intention lock to be removed. This is ok since our
606 rules allow conflicting locks on gaps. This eliminates
607 a spurious deadlock caused by a next-key lock waiting
608 for an insert intention lock; when the insert
609 intention lock was granted, the insert deadlocked on
610 the waiting next-key lock.
611
612 Also, insert intention locks do not disturb each
613 other. */
614
615 return Conflict::NO_CONFLICT;
616 }
617
618 /* This is very important that LOCK_INSERT_INTENTION should not overtake a
619 WAITING Gap or Next-Key lock on the same heap_no, because the following
620 insertion of the record would split the gap duplicating the waiting lock,
621 violating the rule that a transaction can have at most one waiting lock. */
622 if (!(type_mode & LOCK_INSERT_INTENTION) && lock2->is_waiting() &&
623 lock2->mode() == LOCK_X && (type_mode & LOCK_MODE_MASK) == LOCK_X) {
624 // We would've already returned false if it was a gap lock.
625 ut_ad(!(type_mode & LOCK_GAP));
626 // Similarly, since locks on supremum are either LOCK_INSERT_INTENTION or
627 // gap locks, we would've already returned false if it's about supremum.
628 ut_ad(!lock_is_on_supremum);
629 // If lock2 was a gap lock (in particular: insert intention), it could
630 // only block LOCK_INSERT_INTENTION, which we've ruled out.
631 ut_ad(!lock_rec_get_gap(lock2));
632 // So, both locks are REC_NOT_GAP or Next-Key locks
633 ut_ad(lock2->is_record_not_gap() || lock2->is_next_key_lock());
634 ut_ad((type_mode & LOCK_REC_NOT_GAP) ||
635 lock_mode_is_next_key_lock(type_mode));
636 /* In this case, we should ignore lock2, if trx already has a GRANTED lock
637 blocking lock2 from being granted. */
638 if (trx_locks_cache.has_granted_blocker(trx, lock2)) {
639 return Conflict::CAN_BYPASS;
640 }
641 }
642
643 return Conflict::HAS_TO_WAIT;
644 }
645
646 /** Checks if a record lock request lock1 has to wait for request lock2.
647 @param[in] lock1 waiting record lock
648 @param[in] lock2 another record lock;
649 NOTE that it is assumed that this has a lock bit set
650 on the same record as in lock1
651 @param[in] lock1_cache Cached info gathered during calls with lock1
652 @return true if lock1 has to wait for lock2 to be removed */
653 static inline bool rec_lock_has_to_wait(const lock_t *lock1,
654 const lock_t *lock2,
655 Trx_locks_cache &lock1_cache) {
656 ut_ad(lock1->is_waiting());
657 ut_ad(lock_rec_get_nth_bit(lock2, lock_rec_find_set_bit(lock1)));
658 return rec_lock_check_conflict(lock1->trx, lock1->type_mode, lock2,
659 lock1->includes_supremum(),
660 lock1_cache) == Conflict::HAS_TO_WAIT;
661 }
662
663 bool has_to_wait(const lock_t *lock1, const lock_t *lock2,
664 Trx_locks_cache &lock1_cache) {
665 if (lock_get_type_low(lock1) == LOCK_REC) {
666 ut_ad(lock_get_type_low(lock2) == LOCK_REC);
667
668 if (lock1->type_mode & (LOCK_PREDICATE | LOCK_PRDT_PAGE)) {
669 return lock_prdt_has_to_wait(lock1->trx, lock1->type_mode,
670 lock_get_prdt_from_lock(lock1), lock2);
671 }
672 return rec_lock_has_to_wait(lock1, lock2, lock1_cache);
673 }
674 // Rules for LOCK_TABLE are much simpler:
675 return (lock1->trx != lock2->trx &&
676 !lock_mode_compatible(lock_get_mode(lock1), lock_get_mode(lock2)));
677 }
678 } // namespace locksys
679
680 bool lock_has_to_wait(const lock_t *lock1, const lock_t *lock2) {
681 /* We assume that the caller doesn't expect lock2 to be waiting, or record
682 lock or to execute multiple calls for the same lock1, or doesn't care about
683 performance too much, thus we create a single-use cache */
684 locksys::Trx_locks_cache trx_locks_cache{};
685 return locksys::has_to_wait(lock1, lock2, trx_locks_cache);
686 }
687
688 /*============== RECORD LOCK BASIC FUNCTIONS ============================*/
689
690 ulint lock_rec_find_set_bit(const lock_t *lock) {
691 const auto bs = lock->bitset();
692 const size_t i = bs.find_set(0);
693 return i == bs.NOT_FOUND ? ULINT_UNDEFINED : i;
694 }
695
696 /** Looks for the next set bit in the record lock bitmap.
697 @param[in] lock record lock with at least one bit set
698 @param[in] heap_no current set bit
699 @return The next bit index == heap number following heap_no, or ULINT_UNDEFINED
700 if none found */
701 ulint lock_rec_find_next_set_bit(const lock_t *lock, ulint heap_no) {
702 ut_ad(heap_no != ULINT_UNDEFINED);
703 const auto bs = lock->bitset();
704 const size_t i = bs.find_set(heap_no + 1);
705 return i == bs.NOT_FOUND ? ULINT_UNDEFINED : i;
706 }
707
708 /** Reset the nth bit of a record lock.
709 @param[in,out] lock record lock
710 @param[in] i index of the bit that will be reset
711 @return previous value of the bit */
712 static inline byte lock_rec_reset_nth_bit(lock_t *lock, ulint i) {
713 auto bitset = lock->bitset();
714 const byte bit = bitset.test(i);
715 if (bit != 0) {
716 bitset.reset(i);
717 ut_ad(lock->trx->lock.n_rec_locks.load() > 0);
718 lock->trx->lock.n_rec_locks.fetch_sub(1, std::memory_order_relaxed);
719 }
720
721 return (bit);
722 }
723
724 bool lock_rec_clear_request_no_wakeup(lock_t *lock, uint16_t heap_no) {
725 if (lock_rec_reset_nth_bit(lock, heap_no)) {
726 if (lock->is_waiting()) {
727 lock_reset_lock_and_trx_wait(lock);
728 }
729 return true;
730 }
731 return false;
732 }
733
734 static bool lock_rec_has_any(Locks_hashtable &hash, page_id_t page_id) {
735 return hash.find_on_page(page_id, [](auto) { return true; });
736 }
737 static bool lock_rec_has_any(Locks_hashtable &hash, page_id_t page_id,
738 uint16_t heap_no) {
739 return hash.find_on_record(RecID{page_id, heap_no},
740 [](auto) { return true; });
741 }
742
743 bool lock_rec_expl_exist_on_page(const page_id_t &page_id) {
744 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, page_id};
745 /* Only used in ibuf pages, so rec_hash is good enough */
746 return lock_rec_has_any(lock_sys->rec_hash, page_id);
747 }
748
749 /** Resets the record lock bitmap to zero. NOTE: does not touch the wait_lock
750 pointer in the transaction! This function is used in lock object creation
751 and resetting. */
752 static void lock_rec_bitmap_reset(lock_t *lock) /*!< in: record lock */
753 {
754 lock->bitset().reset();
755 }
756
757 /** Copies a record lock to heap.
758 @return copy of lock */
759 static lock_t *lock_rec_copy(const lock_t *lock, /*!< in: record lock */
760 mem_heap_t *heap) /*!< in: memory heap */
761 {
762 ulint size;
763
764 ut_ad(lock_get_type_low(lock) == LOCK_REC);
765
766 size = sizeof(lock_t) + lock_rec_get_n_bits(lock) / 8;
767
768 return (static_cast<lock_t *>(mem_heap_dup(heap, lock, size)));
769 }
770
771 /*============= FUNCTIONS FOR ANALYZING RECORD LOCK QUEUE ================*/
772
773 /** Checks if a transaction has a GRANTED explicit lock on rec stronger or equal
774 to precise_mode.
775 @param[in] precise_mode LOCK_S or LOCK_X possibly ORed to LOCK_GAP or
776 LOCK_REC_NOT_GAP, for a supremum record we regard
777 this always a gap type request
778 @param[in] page_id id of the page containing the record
779 @param[in] heap_no heap number of the record
780 @param[in] trx transaction
781 @return lock or NULL */
782 static inline const lock_t *lock_rec_has_expl(ulint precise_mode,
783 const page_id_t page_id,
784 uint32_t heap_no,
785 const trx_t *trx) {
786 ut_ad(locksys::owns_page_shard(page_id));
787 ut_ad((precise_mode & LOCK_MODE_MASK) == LOCK_S ||
788 (precise_mode & LOCK_MODE_MASK) == LOCK_X);
789 ut_ad(
790 !(precise_mode & ~(ulint)(LOCK_MODE_MASK | LOCK_GAP | LOCK_REC_NOT_GAP)));
791 ut_ad(!(precise_mode & LOCK_INSERT_INTENTION));
792 ut_ad(!(precise_mode & LOCK_PREDICATE));
793 ut_ad(!(precise_mode & LOCK_PRDT_PAGE));
794 const RecID rec_id{page_id, heap_no};
795 const bool is_on_supremum = rec_id.is_supremum();
796 const bool is_rec_not_gap = 0 != (precise_mode & LOCK_REC_NOT_GAP);
797 const bool is_gap = 0 != (precise_mode & LOCK_GAP);
798 const auto mode = static_cast<lock_mode>(precise_mode & LOCK_MODE_MASK);
799 const auto p_implies_q = [](bool p, bool q) { return q || !p; };
800 /* Stop iterating on first matching record or first WAITING lock */
801 const auto first =
802 lock_sys->rec_hash.find_on_record(rec_id, [&](const lock_t *lock) {
803 return (lock->is_waiting() ||
804 (lock->trx == trx && !lock->is_insert_intention() &&
805 lock_mode_stronger_or_eq(lock_get_mode(lock), mode) &&
806 (is_on_supremum ||
807 (p_implies_q(lock->is_record_not_gap(), is_rec_not_gap) &&
808 p_implies_q(lock->is_gap(), is_gap)))));
809 });
810 /* There are no GRANTED locks after the first WAITING lock in the queue. */
811 return first == nullptr || first->is_waiting() ? nullptr : first;
812 }
813 static inline const lock_t *lock_rec_has_expl(ulint precise_mode,
814 const buf_block_t *block,
815 ulint heap_no, const trx_t *trx) {
816 return lock_rec_has_expl(precise_mode, block->get_page_id(), heap_no, trx);
817 }
818 namespace locksys {
819 bool Trx_locks_cache::has_granted_blocker(const trx_t *trx,
820 const lock_t *waiting_lock) {
821 ut_ad(waiting_lock->is_waiting());
822 ut_ad(waiting_lock->trx != trx);
823 /* We only support case where waiting_lock is on a record or record and gap,
824 and has mode X. This allows for very simple implementation and state. */
825 ut_ad(waiting_lock->is_record_lock());
826 ut_ad(waiting_lock->is_next_key_lock() || waiting_lock->is_record_not_gap());
827 ut_ad(waiting_lock->mode() == LOCK_X);
828 if (!m_computed) {
829 const auto page_id = waiting_lock->rec_lock.page_id;
830 const auto heap_no = lock_rec_find_set_bit(waiting_lock);
831 /* A lock is blocking an X or X|REC_NOT_GAP lock, if and only if it is
832 stronger or equal to LOCK_S|LOCK_REC_NOT_GAP */
833 m_has_s_lock_on_record =
834 lock_rec_has_expl(LOCK_S | LOCK_REC_NOT_GAP, page_id, heap_no, trx);
835 m_computed = true;
836 #ifdef UNIV_DEBUG
837 m_cached_trx = trx;
838 m_cached_page_id = page_id;
839 m_cached_heap_no = heap_no;
840 #endif /* UNIV_DEBUG*/
841 }
842 ut_ad(m_cached_trx == trx);
843 ut_ad(m_cached_page_id == waiting_lock->rec_lock.page_id);
844 ut_ad(lock_rec_get_nth_bit(waiting_lock, m_cached_heap_no));
845 return m_has_s_lock_on_record;
846 }
847 } // namespace locksys
848 #ifdef UNIV_DEBUG
849 /** Checks if some other transaction has a lock request in the queue.
850 @return lock or NULL */
851 static const lock_t *lock_rec_other_has_expl_req(
852 lock_mode mode, /*!< in: LOCK_S or LOCK_X */
853 const buf_block_t *block, /*!< in: buffer block containing
854 the record */
855 bool wait, /*!< in: whether also waiting locks
856 are taken into account */
857 ulint heap_no, /*!< in: heap number of the record */
858 const trx_t *trx) /*!< in: transaction, or NULL if
859 requests by all transactions
860 are taken into account */
861 {
862 ut_ad(locksys::owns_page_shard(block->get_page_id()));
863 ut_ad(mode == LOCK_X || mode == LOCK_S);
864
865 /* Only GAP lock can be on SUPREMUM, and we are not looking
866 for GAP lock */
867
868 RecID rec_id{block, heap_no};
869
870 if (rec_id.is_supremum()) {
871 return (nullptr);
872 }
873
874 return lock_sys->rec_hash.find_on_record(rec_id, [=](const lock_t *lock) {
875 /* Ignore transactions that are being rolled back. */
876 return (lock->trx != trx && !lock->is_gap() &&
877 (wait || !lock->is_waiting()) &&
878 lock_mode_stronger_or_eq(lock->mode(), mode));
879 });
880 }
881 #endif /* UNIV_DEBUG */
882
883 namespace locksys {
884 struct Conflicting {
885 /** a conflicting lock or null if no conflicting lock found */
886 const lock_t *wait_for;
887 /** true iff the trx has bypassed one of waiting locks */
888 bool bypassed;
889 };
890 } /*namespace locksys*/
891 /** Checks if some other transaction has a conflicting explicit lock request
892 in the queue, so that we have to wait.
893 @param[in] mode LOCK_S or LOCK_X, possibly ORed to
894 LOCK_GAP or LOC_REC_NOT_GAP, LOCK_INSERT_INTENTION
895 @param[in] block buffer block containing the record
896 @param[in] heap_no heap number of the record
897 @param[in] trx our transaction
898 @return a pair, where:
899 the first element is a conflicting lock or null if no conflicting lock found,
900 the second element indicates if the trx has bypassed one of waiting locks.
901 */
902 static locksys::Conflicting lock_rec_other_has_conflicting(
903 ulint mode, const buf_block_t *block, ulint heap_no, const trx_t *trx) {
904 ut_ad(locksys::owns_page_shard(block->get_page_id()));
905 ut_ad(!(mode & ~(ulint)(LOCK_MODE_MASK | LOCK_GAP | LOCK_REC_NOT_GAP |
906 LOCK_INSERT_INTENTION)));
907 ut_ad(!(mode & LOCK_PREDICATE));
908 ut_ad(!(mode & LOCK_PRDT_PAGE));
909 bool bypassed{false};
910
911 RecID rec_id{block, heap_no};
912 const bool is_supremum = rec_id.is_supremum();
913 locksys::Trx_locks_cache trx_locks_cache{};
914 const lock_t *wait_for =
915 lock_sys->rec_hash.find_on_record(rec_id, [&](const lock_t *lock) {
916 const auto conflict = locksys::rec_lock_check_conflict(
917 trx, mode, lock, is_supremum, trx_locks_cache);
918 if (conflict == locksys::Conflict::CAN_BYPASS) {
919 bypassed = true;
920 }
921 return conflict == locksys::Conflict::HAS_TO_WAIT;
922 });
923 return {wait_for, bypassed};
924 }
925
926 /** Checks if the (-infinity,max_old_active_id] range contains an id of
927 a currently active transaction which has modified a record.
928 The premise is that the caller has seen a record modified by a trx with
929 trx->id <= max_old_active_id, and wants to know if it might be still active.
930 It may err on the safe side.
931
932 @remarks
933 The difficulties to keep in mind here:
934 - the caller doesn't hold trx_sys mutex, nor can prevent any transaction
935 from committing or starting before the start and after the end of execution
936 of this function. Thus the result of this function has to be interpreted
937 as if it could have a "one sided error", even if the return value is exact
938 during the execution
939 - the transactions are assigned ids from increasing sequence, but they are
940 added to various structures like lists and shards out of order. This means
941 that the answer this function gives only makes sense in the context that
942 the caller already saw an effect of the trx modifying some row, which
943 means it had to be already added to these structures. In other words,
944 calling this function twice for the same number can give false then true.
945 Still the false from the first call is "correct" for the purpose of the
946 caller (as it must mean that the trx which modified the record had to be
947 removed from the structures already, hence is not active anymore).
948 Also the true from the second call is "correct" in that indeed some smaller
949 transaction id had to be added to the structures meanwhile, even if it's
950 not the one which modified the record in question - error on the safe side.
951
952 @param[in] max_old_active_id The end of the range inclusive. For example
953 found in the PAGE_MAX_TRX_ID field of a
954 header of a secondary index page.
955 @retval false the caller may assume that if before the call it saw a
956 record modified by trx_id, and trx_id < max_old_active_id,
957 then it is no longer active
958 @retval true the caller should double check in a synchronized way if
959 the seen trx_id is still active or not
960 */
961 static bool can_older_trx_be_still_active(trx_id_t max_old_active_id) {
962 if (mutex_enter_nowait(&trx_sys->mutex) != 0) {
963 ut_ad(!trx_sys_mutex_own());
964 /* The mutex is currently locked by somebody else. Instead of wasting time
965 on spinning and waiting to acquire it, we loop over the shards and check if
966 any of them contains a value in the range (-infinity,max_old_active_id].
967 NOTE: Do not be tempted to "cache" the minimum, until you also enforce that
968 transactions are inserted to shards in a monotone order!
969 Current implementation heavily depends on the property that even if we put
970 a trx with smaller id to any structure later, it could not have modified a
971 row the caller saw earlier. */
972 static_assert(TRX_SHARDS_N < 1000, "The loop should be short");
973 for (auto &shard : trx_sys->shards) {
974 if (shard.active_rw_trxs.peek().min_id() <= max_old_active_id) {
975 return true;
976 }
977 }
978 return false;
979 }
980 ut_ad(trx_sys_mutex_own());
981 const trx_t *trx = UT_LIST_GET_LAST(trx_sys->rw_trx_list);
982 if (trx == nullptr) {
983 trx_sys_mutex_exit();
984 return false;
985 }
986 assert_trx_in_rw_list(trx);
987 const trx_id_t min_active_now_id = trx->id;
988 trx_sys_mutex_exit();
989 return min_active_now_id <= max_old_active_id;
990 }
991
992 /** Checks if some transaction has an implicit x-lock on a record in a secondary
993 index.
994 @param[in] rec user record
995 @param[in] index secondary index
996 @param[in] offsets rec_get_offsets(rec, index)
997 @return transaction id of the transaction which has the x-lock, or 0;
998 NOTE that this function can return false positives but never false
999 negatives. The caller must confirm all positive results by checking if the trx
1000 is still active. */
1001 static trx_t *lock_sec_rec_some_has_impl(const rec_t *rec, dict_index_t *index,
1002 const ulint *offsets) {
1003 trx_t *trx;
1004 trx_id_t max_trx_id;
1005 const page_t *page = page_align(rec);
1006
1007 ut_ad(!locksys::owns_exclusive_global_latch());
1008 ut_ad(!trx_sys_mutex_own());
1009 ut_ad(!index->is_clustered());
1010 ut_ad(page_rec_is_user_rec(rec));
1011 ut_ad(rec_offs_validate(rec, index, offsets));
1012
1013 max_trx_id = page_get_max_trx_id(page);
1014
1015 /* Some transaction may have an implicit x-lock on the record only
1016 if the max trx id for the page >= min trx id for the trx list, or
1017 database recovery is running. We do not write the changes of a page
1018 max trx id to the log, and therefore during recovery, this value
1019 for a page may be incorrect. */
1020
1021 if (!recv_recovery_is_on() && !can_older_trx_be_still_active(max_trx_id)) {
1022 trx = nullptr;
1023
1024 } else if (!lock_check_trx_id_sanity(max_trx_id, rec, index, offsets)) {
1025 /* The page is corrupt: try to avoid a crash by returning 0 */
1026 trx = nullptr;
1027
1028 /* In this case it is possible that some transaction has an implicit
1029 x-lock. We have to look in the clustered index. */
1030
1031 } else {
1032 trx = row_vers_impl_x_locked(rec, index, offsets);
1033 }
1034
1035 return (trx);
1036 }
1037
1038 #ifdef UNIV_DEBUG
1039 /** Checks if some transaction, other than given trx_id, has an explicit
1040 lock on the given rec, in the given precise_mode.
1041 @param[in] precise_mode LOCK_S or LOCK_X possibly ORed to LOCK_GAP or
1042 LOCK_REC_NOT_GAP.
1043 @param[in] trx the trx holding implicit lock on rec
1044 @param[in] rec user record
1045 @param[in] block buffer block containing the record
1046 @return true iff there's a transaction, whose id is not equal to trx_id,
1047 that has an explicit lock on the given rec, in the given
1048 precise_mode. */
1049 static bool lock_rec_other_trx_holds_expl(ulint precise_mode, const trx_t *trx,
1050 const rec_t *rec,
1051 const buf_block_t *block) {
1052 bool holds = false;
1053
1054 /* We will inspect locks from various shards when inspecting transactions. */
1055 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
1056 /* If trx_rw_is_active returns non-null impl_trx it only means that impl_trx
1057 was active at some moment during the call, but might already be in
1058 TRX_STATE_COMMITTED_IN_MEMORY when we execute the body of the if.
1059 However, we hold exclusive latch on whole lock_sys, which prevents anyone
1060 from creating any new explicit locks.
1061 So, all explicit locks we will see must have been created at the time when
1062 the transaction was not committed yet. */
1063 if (trx_t *impl_trx = trx_rw_is_active(trx->id, false)) {
1064 ulint heap_no = page_rec_get_heap_no(rec);
1065 mutex_enter(&trx_sys->mutex);
1066
1067 for (auto t : trx_sys->rw_trx_list) {
1068 const lock_t *expl_lock =
1069 lock_rec_has_expl(precise_mode, block, heap_no, t);
1070
1071 if (expl_lock && expl_lock->trx != impl_trx) {
1072 /* An explicit lock is held by trx other than
1073 the trx holding the implicit lock. */
1074 holds = true;
1075 break;
1076 }
1077 }
1078
1079 mutex_exit(&trx_sys->mutex);
1080 }
1081
1082 return (holds);
1083 }
1084 #endif /* UNIV_DEBUG */
1085
1086 ulint lock_number_of_rows_locked(const trx_lock_t *trx_lock) {
1087 /* We need exclusive lock_sys access, because trx_lock->n_rec_locks is
1088 modified while holding sharded lock only, so we need to disable all writers
1089 for this number to be meaningful */
1090 ut_ad(locksys::owns_exclusive_global_latch());
1091
1092 return (trx_lock->n_rec_locks);
1093 }
1094
1095 ulint lock_number_of_tables_locked(const trx_t *trx) {
1096 ut_ad(trx_mutex_own(trx));
1097 ulint count = 0;
1098 for (const lock_t *lock = UT_LIST_GET_FIRST(trx->lock.trx_locks);
1099 lock != nullptr && lock_get_type(lock) == LOCK_TABLE;
1100 lock = UT_LIST_GET_NEXT(trx_locks, lock)) {
1101 count++;
1102 }
1103
1104 return count;
1105 }
1106
1107 lock_t *lock_alloc_from_heap(mem_heap_t *heap, size_t bitmap_bytes) {
1108 const size_t n_bytes = sizeof(lock_t) + bitmap_bytes;
1109 static_assert(alignof(lock_t) <= UNIV_MEM_ALIGNMENT,
1110 "heap allocator must ensure lock_t is properly aligned");
1111 auto ptr = mem_heap_alloc(heap, n_bytes);
1112 ut_a(ut::is_aligned_as<lock_t>(ptr));
1113 return reinterpret_cast<lock_t *>(ptr);
1114 }
1115
1116 /*============== RECORD LOCK CREATION AND QUEUE MANAGEMENT =============*/
1117
1118 /**
1119 Do some checks and prepare for creating a new record lock */
1120 void RecLock::prepare() const {
1121 ut_ad(locksys::owns_page_shard(m_rec_id.get_page_id()));
1122 ut_ad(m_trx == thr_get_trx(m_thr));
1123
1124 /* Test if there already is some other reason to suspend thread:
1125 we do not enqueue a lock request if the query thread should be
1126 stopped anyway */
1127
1128 if (que_thr_stop(m_thr)) {
1129 ut_error;
1130 }
1131
1132 switch (trx_get_dict_operation(m_trx)) {
1133 case TRX_DICT_OP_NONE:
1134 break;
1135 case TRX_DICT_OP_TABLE:
1136 case TRX_DICT_OP_INDEX:
1137 ib::error(ER_IB_MSG_635)
1138 << "A record lock wait happens in a dictionary"
1139 " operation. index "
1140 << m_index->name << " of table " << m_index->table->name << ". "
1141 << BUG_REPORT_MSG;
1142 ut_d(ut_error);
1143 }
1144
1145 ut_ad(m_index->table->n_ref_count > 0 || !m_index->table->can_be_evicted);
1146 }
1147
1148 /**
1149 Create the lock instance
1150 @param[in, out] trx The transaction requesting the lock
1151 @param[in, out] index Index on which record lock is required
1152 @param[in] mode The lock mode desired
1153 @param[in] rec_id The record id
1154 @param[in] size Size of the lock + bitmap requested
1155 @return a record lock instance */
1156 lock_t *RecLock::lock_alloc(trx_t *trx, dict_index_t *index, ulint mode,
1157 const RecID &rec_id, ulint size) {
1158 ut_ad(locksys::owns_page_shard(rec_id.get_page_id()));
1159 /* We are about to modify structures in trx->lock which needs trx->mutex */
1160 ut_ad(trx_mutex_own(trx));
1161
1162 lock_t *lock;
1163
1164 if (trx->lock.rec_cached >= trx->lock.rec_pool.size() ||
1165 sizeof(*lock) + size > REC_LOCK_SIZE) {
1166 lock = lock_alloc_from_heap(trx->lock.lock_heap, size);
1167 } else {
1168 lock = trx->lock.rec_pool[trx->lock.rec_cached];
1169 ++trx->lock.rec_cached;
1170 }
1171
1172 lock->trx = trx;
1173
1174 lock->index = index;
1175
1176 /* Note the creation timestamp */
1177 ut_d(lock->m_seq = lock_sys->m_seq.fetch_add(1));
1178
1179 /* Setup the lock attributes */
1180
1181 lock->type_mode = LOCK_REC | (mode & ~LOCK_TYPE_MASK);
1182
1183 lock_rec_t &rec_lock = lock->rec_lock;
1184
1185 /* Predicate lock always on INFIMUM (0) */
1186
1187 ut_ad(size < UINT32_MAX / 8);
1188 rec_lock.n_bits = is_predicate_lock(mode) ? 8 : 8 * size;
1189 lock_rec_bitmap_reset(lock);
1190
1191 rec_lock.page_id = rec_id.get_page_id();
1192
1193 /* Set the bit corresponding to rec */
1194
1195 lock_rec_set_nth_bit(lock, rec_id.m_heap_no);
1196
1197 MONITOR_INC(MONITOR_NUM_RECLOCK);
1198
1199 MONITOR_INC(MONITOR_RECLOCK_CREATED);
1200
1201 return (lock);
1202 }
1203
1204 /** Insert lock record to the tail of the queue where the WAITING locks reside.
1205 @param[in,out] lock_hash Hash table containing the locks
1206 @param[in,out] lock Record lock instance to insert
1207 @param[in] rec_id Record being locked */
1208 static void lock_rec_insert_to_waiting(Locks_hashtable &lock_hash, lock_t *lock,
1209 const RecID &rec_id) {
1210 ut_ad(lock->is_waiting());
1211 ut_ad(rec_id.matches(lock));
1212 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1213 ut_ad(locksys::owns_page_shard(rec_id.get_page_id()));
1214 lock_hash.append(lock, rec_id.hash_value());
1215 }
1216
1217 /** Insert lock record to the head of the queue where the GRANTED locks reside.
1218 @param[in,out] lock_hash Hash table containing the locks
1219 @param[in,out] lock Record lock instance to insert
1220 @param[in] rec_id Record being locked */
1221 static void lock_rec_insert_to_granted(Locks_hashtable &lock_hash, lock_t *lock,
1222 const RecID &rec_id) {
1223 ut_ad(rec_id.matches(lock));
1224 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1225 ut_ad(locksys::owns_page_shard(rec_id.get_page_id()));
1226 ut_ad(!lock->is_waiting());
1227 lock_hash.prepend(lock, rec_id.hash_value());
1228 }
1229 namespace locksys {
1230 /**
1231 Adds the lock to the list of trx's locks.
1232 Requires lock->trx to be already set.
1233 Bumps the trx_lock_version.
1234 @param[in,out] lock The lock that we want to add to lock->trx->lock.trx_locks
1235 */
1236 static void add_to_trx_locks(lock_t *lock) {
1237 ut_ad(lock->trx != nullptr);
1238 ut_ad(trx_mutex_own(lock->trx));
1239 if (lock_get_type_low(lock) == LOCK_REC) {
1240 UT_LIST_ADD_LAST(lock->trx->lock.trx_locks, lock);
1241 } else {
1242 UT_LIST_ADD_FIRST(lock->trx->lock.trx_locks, lock);
1243 }
1244 lock->trx->lock.trx_locks_version++;
1245 }
1246
1247 /**
1248 Removes the lock from the list of trx's locks.
1249 Bumps the trx_lock_version.
1250 @param[in,out] lock The lock that we want to remove from
1251 lock->trx->lock.trx_locks
1252 */
1253 static void remove_from_trx_locks(lock_t *lock) {
1254 ut_ad(lock->trx != nullptr);
1255 ut_ad(trx_mutex_own(lock->trx));
1256 UT_LIST_REMOVE(lock->trx->lock.trx_locks, lock);
1257 lock->trx->lock.trx_locks_version++;
1258 }
1259 } // namespace locksys
1260
1261 void RecLock::lock_add(lock_t *lock) {
1262 ut_ad((lock->type_mode | LOCK_REC) == (m_mode | LOCK_REC));
1263 ut_ad(m_rec_id.matches(lock));
1264 ut_ad(locksys::owns_page_shard(m_rec_id.get_page_id()));
1265 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1266 ut_ad(trx_mutex_own(lock->trx));
1267
1268 bool wait = m_mode & LOCK_WAIT;
1269
1270 auto &lock_hash = lock_hash_get(m_mode);
1271
1272 lock->index->table->n_rec_locks.fetch_add(1, std::memory_order_relaxed);
1273
1274 if (!wait) {
1275 lock_rec_insert_to_granted(lock_hash, lock, m_rec_id);
1276 } else {
1277 lock_rec_insert_to_waiting(lock_hash, lock, m_rec_id);
1278 }
1279
1280 #ifdef HAVE_PSI_THREAD_INTERFACE
1281 #ifdef HAVE_PSI_DATA_LOCK_INTERFACE
1282 /* The performance schema THREAD_ID and EVENT_ID are used only
1283 when DATA_LOCKS are exposed. */
1284 PSI_THREAD_CALL(get_current_thread_event_id)
1285 (&lock->m_psi_internal_thread_id, &lock->m_psi_event_id);
1286 #endif /* HAVE_PSI_DATA_LOCK_INTERFACE */
1287 #endif /* HAVE_PSI_THREAD_INTERFACE */
1288
1289 locksys::add_to_trx_locks(lock);
1290
1291 if (wait) {
1292 lock_set_lock_and_trx_wait(lock);
1293 }
1294 }
1295
1296 /**
1297 Create a lock for a transaction and initialise it.
1298 @param[in, out] trx Transaction requesting the new lock
1299 @param[in] prdt Predicate lock (optional)
1300 @return new lock instance */
1301 lock_t *RecLock::create(trx_t *trx, const lock_prdt_t *prdt) {
1302 ut_ad(locksys::owns_page_shard(m_rec_id.get_page_id()));
1303
1304 /* Ensure that another transaction doesn't access the trx
1305 lock state and lock data structures while we are adding the
1306 lock and changing the transaction state to LOCK_WAIT.
1307 In particular it protects the lock_alloc which uses trx's private pool of
1308 lock structures.
1309 It might be the case that we already hold trx->mutex because we got here from:
1310 - lock_rec_convert_impl_to_expl_for_trx
1311 - add_to_waitq
1312 */
1313 ut_ad(trx_mutex_own(trx));
1314
1315 /* Create the explicit lock instance and initialise it. */
1316
1317 lock_t *lock = lock_alloc(trx, m_index, m_mode, m_rec_id, m_size);
1318
1319 #ifdef UNIV_DEBUG
1320 /* GAP lock shouldn't be taken on DD tables with some exceptions */
1321 if (m_index->table->is_dd_table &&
1322 strstr(m_index->table->name.m_name,
1323 "mysql/st_spatial_reference_systems") == nullptr &&
1324 strstr(m_index->table->name.m_name, "mysql/innodb_table_stats") ==
1325 nullptr &&
1326 strstr(m_index->table->name.m_name, "mysql/innodb_index_stats") ==
1327 nullptr &&
1328 strstr(m_index->table->name.m_name, "mysql/table_stats") == nullptr &&
1329 strstr(m_index->table->name.m_name, "mysql/index_stats") == nullptr) {
1330 ut_ad(lock_rec_get_rec_not_gap(lock));
1331 }
1332 #endif /* UNIV_DEBUG */
1333
1334 if (prdt != nullptr && (m_mode & LOCK_PREDICATE)) {
1335 lock_prdt_set_prdt(lock, prdt);
1336 }
1337
1338 lock_add(lock);
1339
1340 return (lock);
1341 }
1342
1343 /**
1344 Collect the transactions that will need to be rolled back asynchronously
1345 @param[in, out] hit_list The list of transactions to be rolled back, to which
1346 the trx should be appended.
1347 @param[in] hp_trx_id The id of the blocked High Priority Transaction
1348 @param[in, out] trx The blocking transaction to be rolled back */
1349 static void lock_mark_trx_for_rollback(hit_list_t &hit_list, trx_id_t hp_trx_id,
1350 trx_t *trx) {
1351 trx->abort = true;
1352
1353 ut_ad(!trx->read_only);
1354 ut_ad(trx_mutex_own(trx));
1355 ut_ad(!(trx->in_innodb & TRX_FORCE_ROLLBACK));
1356 ut_ad(!(trx->in_innodb & TRX_FORCE_ROLLBACK_DISABLE));
1357
1358 trx->in_innodb |= TRX_FORCE_ROLLBACK;
1359
1360 std::thread::id thread_id = std::this_thread::get_id();
1361
1362 std::thread::id zero{};
1363 ut_a(trx->killed_by.compare_exchange_strong(zero, thread_id));
1364
1365 hit_list.push_back(hit_list_t::value_type(trx));
1366
1367 #ifdef UNIV_DEBUG
1368 THD *thd = trx->mysql_thd;
1369
1370 if (thd != nullptr) {
1371 char buffer[1024];
1372 ib::info(ER_IB_MSG_636, ulonglong{hp_trx_id}, to_string(thread_id).c_str(),
1373 ulonglong{trx->id},
1374 thd_security_context(thd, buffer, sizeof(buffer), 512));
1375 }
1376 #endif /* UNIV_DEBUG */
1377 }
1378 /**
1379 Checks if the waits-for edge between waiting_lock and blocking_lock may
1380 survive PREPARE of the blocking_lock->trx. For transactions in low
1381 isolation levels we release some of the locks during PREPARE.
1382 @param[in] waiting_lock A lock waiting in queue, blocked by blocking_lock
1383 @param[in] blocking_lock A lock which is a reason the waiting_lock has to
1384 wait
1385 @return if the waiting_lock->trx MAY have to wait for blocking_lock->trx
1386 even if blocking_lock->trx PREPAREs. The nondeterminism comes from
1387 situations like when X lock conflicts with S lock on a delete-marked
1388 record - purgining it might convert both to non-conflicitng gap locks
1389 @retval true the waiting_lock->trx MAY have to wait for blocking_lock->trx
1390 even if blocking_lock->trx PREPAREs.
1391 @retval false the waiting_lock->trx CERTAINLY will not have to wait for
1392 blocking_lock->trx for this particular reason.
1393 */
1394 static bool lock_edge_may_survive_prepare(const lock_t *waiting_lock,
1395 const lock_t *blocking_lock) {
1396 /* Keep in sync with lock_relase_read_lock(blocking_lock, only_gap)
1397 for the only_gap value currently used in the call from trx_prepare().
1398 Currently some transactions release locks on gaps and a lock on a gap blocks
1399 only Insert Intention, and II is only blocked by locks on a gap.
1400 A "lock on a gap" can be either a LOCK_GAP, or a part of LOCK_ORDINARY. */
1401 if (blocking_lock->trx->releases_gap_locks_at_prepare() &&
1402 waiting_lock->is_insert_intention()) {
1403 ut_ad(blocking_lock->is_record_lock());
1404 ut_ad(waiting_lock->is_record_lock());
1405
1406 return false;
1407 }
1408 return true;
1409 }
1410 static void lock_report_wait_for_edge_to_server(const lock_t *waiting_lock,
1411 const lock_t *blocking_lock) {
1412 thd_report_lock_wait(
1413 waiting_lock->trx->mysql_thd, blocking_lock->trx->mysql_thd,
1414 lock_edge_may_survive_prepare(waiting_lock, blocking_lock));
1415 }
1416 /** Creates a new edge in wait-for graph, from waiter to blocker
1417 @param[in] waiting_lock A lock waiting in queue, blocked by blocking_lock
1418 @param[in] blocking_lock A lock which is a reason the waiting_lock has to
1419 wait */
1420 static void lock_create_wait_for_edge(const lock_t *waiting_lock,
1421 const lock_t *blocking_lock) {
1422 trx_t *waiter = waiting_lock->trx;
1423 trx_t *blocker = blocking_lock->trx;
1424 ut_ad(trx_mutex_own(waiter));
1425 ut_ad(waiter->lock.wait_lock != nullptr);
1426 ut_ad(locksys::owns_lock_shard(waiter->lock.wait_lock));
1427 ut_ad(waiter->lock.blocking_trx.load() == nullptr);
1428 /* We don't call lock_wait_request_check_for_cycles() here as it
1429 would be slightly premature: the trx is not yet inserted into a slot of
1430 lock_sys->waiting_threads at this point, and thus it would be invisible to
1431 the thread which analyzes these slots. What we do instead is to let the
1432 lock_wait_table_reserve_slot() function be responsible for calling
1433 lock_wait_request_check_for_cycles() once it insert the trx to a
1434 slot.*/
1435 waiter->lock.blocking_trx.store(blocker);
1436 lock_report_wait_for_edge_to_server(waiting_lock, blocking_lock);
1437 }
1438
1439 /**
1440 Setup the requesting transaction state for lock grant
1441 @param[in,out] lock Lock for which to change state */
1442 void RecLock::set_wait_state(lock_t *lock) {
1443 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1444 ut_ad(m_trx == lock->trx);
1445 ut_ad(trx_mutex_own(m_trx));
1446 ut_ad(lock_get_wait(lock));
1447
1448 m_trx->lock.wait_started =
1449 std::chrono::system_clock::from_time_t(time(nullptr));
1450
1451 m_trx->lock.que_state = TRX_QUE_LOCK_WAIT;
1452
1453 m_trx->lock.was_chosen_as_deadlock_victim = false;
1454
1455 bool stopped = que_thr_stop(m_thr);
1456 ut_a(stopped);
1457 }
1458
1459 dberr_t RecLock::add_to_waitq(const lock_t *wait_for, const lock_prdt_t *prdt) {
1460 ut_ad(locksys::owns_page_shard(m_rec_id.get_page_id()));
1461 ut_ad(m_trx == thr_get_trx(m_thr));
1462
1463 /* It is not that the body of this function requires trx->mutex, but some of
1464 the functions it calls require it and it so happens that we always posses it
1465 so it makes reasoning about code easier if we simply assert this fact. */
1466 ut_ad(trx_mutex_own(m_trx));
1467
1468 DEBUG_SYNC_C("rec_lock_add_to_waitq");
1469
1470 if (m_trx->in_innodb & TRX_FORCE_ROLLBACK) {
1471 return (DB_DEADLOCK);
1472 }
1473
1474 m_mode |= LOCK_WAIT;
1475
1476 /* Do the preliminary checks, and set query thread state */
1477
1478 prepare();
1479
1480 /* Don't queue the lock to hash table, if high priority transaction. */
1481 lock_t *lock = create(m_trx, prdt);
1482
1483 lock_create_wait_for_edge(lock, wait_for);
1484
1485 ut_ad(lock_get_wait(lock));
1486
1487 set_wait_state(lock);
1488
1489 MONITOR_INC(MONITOR_LOCKREC_WAIT);
1490
1491 return (DB_LOCK_WAIT);
1492 }
1493
1494 /** Moves a granted lock to the front of the queue for a given record by
1495 removing it adding it to the front. As a single lock can correspond to multiple
1496 rows (and thus: queues) this function moves it to the front of whole hash cell.
1497 @param [in] lock a granted lock to be moved
1498 @param [in] rec_id record id which specifies particular queue and hash
1499 cell */
1500 static void lock_rec_move_granted_to_front(lock_t *lock, const RecID &rec_id) {
1501 ut_ad(!lock->is_waiting());
1502 ut_ad(rec_id.matches(lock));
1503 ut_ad(locksys::owns_page_shard(rec_id.get_page_id()));
1504 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1505 lock->hash_table().move_to_front(lock, rec_id.hash_value());
1506 }
1507
1508 /** Adds a record lock request in the record queue. The request is normally
1509 added as the last in the queue, but if the request to be added is not a waiting
1510 request, we can reuse a suitable record lock object already existing on the
1511 same page, just setting the appropriate bit in its bitmap. This is a low-level
1512 function which does NOT check for deadlocks or lock compatibility!
1513 @param[in] type_mode lock mode, wait, gap etc. flags; type is
1514 ignored and replaced by LOCK_REC
1515 @param[in] block buffer block containing the record
1516 @param[in] heap_no heap number of the record
1517 @param[in] index index of record
1518 @param[in,out] trx transaction
1519 @param[in] we_own_trx_mutex true iff the caller own trx->mutex (optional).
1520 Defaults to false. */
1521 static void lock_rec_add_to_queue(ulint type_mode, const buf_block_t *block,
1522 const ulint heap_no, dict_index_t *index,
1523 trx_t *trx,
1524 const bool we_own_trx_mutex = false) {
1525 #ifdef UNIV_DEBUG
1526 ut_ad(locksys::owns_page_shard(block->get_page_id()));
1527 ut_ad(we_own_trx_mutex == trx_mutex_own(trx));
1528
1529 ut_ad(index->is_clustered() ||
1530 dict_index_get_online_status(index) != ONLINE_INDEX_CREATION);
1531 switch (type_mode & LOCK_MODE_MASK) {
1532 case LOCK_X:
1533 case LOCK_S:
1534 break;
1535 default:
1536 ut_error;
1537 }
1538
1539 if (!(type_mode & (LOCK_WAIT | LOCK_GAP))) {
1540 lock_mode mode = (type_mode & LOCK_MODE_MASK) == LOCK_S ? LOCK_X : LOCK_S;
1541 const lock_t *other_lock =
1542 lock_rec_other_has_expl_req(mode, block, false, heap_no, trx);
1543 ut_a(!other_lock);
1544 }
1545 #endif /* UNIV_DEBUG */
1546
1547 type_mode |= LOCK_REC;
1548
1549 /* If rec is the supremum record, then we can reset the gap bit, as
1550 all locks on the supremum are automatically of the gap type, and we
1551 try to avoid unnecessary memory consumption of a new record lock
1552 struct for a gap type lock */
1553
1554 if (heap_no == PAGE_HEAP_NO_SUPREMUM) {
1555 ut_ad(!(type_mode & LOCK_REC_NOT_GAP));
1556
1557 /* There should never be LOCK_REC_NOT_GAP on a supremum
1558 record, but let us play safe */
1559
1560 type_mode &= ~(LOCK_GAP | LOCK_REC_NOT_GAP);
1561 }
1562
1563 if (!(type_mode & LOCK_WAIT)) {
1564 {
1565 /* Look for a similar record lock on the same page:
1566 if one is found we can just set the bit */
1567 bool found_waiter_before_lock = false;
1568 lock_t *lock =
1569 lock_hash_get(type_mode).find_on_block(block, [&](lock_t *lock) {
1570 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
1571
1572 if (lock->trx == trx && lock->type_mode == type_mode &&
1573 heap_no < lock_rec_get_n_bits(lock)) {
1574 return true;
1575 }
1576 if (lock->is_waiting()) {
1577 found_waiter_before_lock = true;
1578 }
1579 return false;
1580 });
1581
1582 if (lock != nullptr) {
1583 /* Some B-tree reorganization functions, when moving locks from one
1584 place to another, can leave a lock_t struct with an empty bitmap. They
1585 also clear a LOCK_WAIT flag. This means it's possible that `lock` was
1586 a waiting lock in the past, and if we want to reuse it, we have to move
1587 it to the front of the queue where granted locks reside.
1588 We only NEED to do that if there are any waiting locks in front of it.
1589 We CAN move the lock to front ONLY IF it wasn't part of any queue.
1590 In other words, moving to front is not safe if it has non-empty bitmap.
1591 Moving a lock to the front of its queue can create endless loop in the
1592 caller if it is iterating over the queue.
1593 Fortunately, the only situation in which a GRANTED lock can be after a
1594 WAITING lock in the hash cell is if it was WAITING in the past and the
1595 only bit for the heap_no was cleared, so it no longer belongs to any
1596 queue.*/
1597 ut_ad(!found_waiter_before_lock ||
1598 (ULINT_UNDEFINED == lock_rec_find_set_bit(lock)));
1599
1600 if (!lock_rec_get_nth_bit(lock, heap_no)) {
1601 lock_rec_set_nth_bit(lock, heap_no);
1602 if (found_waiter_before_lock) {
1603 lock_rec_move_granted_to_front(lock, RecID{lock, heap_no});
1604 }
1605 }
1606
1607 return;
1608 }
1609 }
1610 }
1611
1612 RecLock rec_lock(index, block, heap_no, type_mode);
1613
1614 if (!we_own_trx_mutex) {
1615 trx_mutex_enter(trx);
1616 }
1617 rec_lock.create(trx);
1618 if (!we_own_trx_mutex) {
1619 trx_mutex_exit(trx);
1620 }
1621 }
1622
1623 /** This is a fast routine for locking a record in the most common cases:
1624 there are no explicit locks on the page, or there is just one lock, owned
1625 by this transaction, and of the right type_mode. This is a low-level function
1626 which does NOT look at implicit locks! Checks lock compatibility within
1627 explicit locks. This function sets a normal next-key lock, or in the case of
1628 a page supremum record, a gap type lock.
1629 @return whether the locking succeeded LOCK_REC_SUCCESS,
1630 LOCK_REC_SUCCESS_CREATED, LOCK_REC_FAIL */
1631 static inline lock_rec_req_status lock_rec_lock_fast(
1632 bool impl, /*!< in: if true, no lock is set
1633 if no wait is necessary: we
1634 assume that the caller will
1635 set an implicit lock */
1636 ulint mode, /*!< in: lock mode: LOCK_X or
1637 LOCK_S possibly ORed to either
1638 LOCK_GAP or LOCK_REC_NOT_GAP */
1639 const buf_block_t *block, /*!< in: buffer block containing
1640 the record */
1641 ulint heap_no, /*!< in: heap number of record */
1642 dict_index_t *index, /*!< in: index of record */
1643 que_thr_t *thr) /*!< in: query thread */
1644 {
1645 ut_ad(locksys::owns_page_shard(block->get_page_id()));
1646 ut_ad(!srv_read_only_mode);
1647 ut_ad((LOCK_MODE_MASK & mode) != LOCK_S ||
1648 lock_table_has(thr_get_trx(thr), index->table, LOCK_IS));
1649 ut_ad((LOCK_MODE_MASK & mode) != LOCK_X ||
1650 lock_table_has(thr_get_trx(thr), index->table, LOCK_IX) ||
1651 srv_read_only_mode);
1652 ut_ad((LOCK_MODE_MASK & mode) == LOCK_S || (LOCK_MODE_MASK & mode) == LOCK_X);
1653 ut_ad(mode - (LOCK_MODE_MASK & mode) == LOCK_GAP ||
1654 mode - (LOCK_MODE_MASK & mode) == 0 ||
1655 mode - (LOCK_MODE_MASK & mode) == LOCK_REC_NOT_GAP);
1656 ut_ad(index->is_clustered() || !dict_index_is_online_ddl(index));
1657 ut_ad(!(mode & LOCK_PREDICATE));
1658 ut_ad(!(mode & LOCK_PRDT_PAGE));
1659 DBUG_EXECUTE_IF("innodb_report_deadlock", return (LOCK_REC_FAIL););
1660 lock_t *lock = nullptr;
1661 lock_t *other_lock =
1662 lock_sys->rec_hash.find_on_block(block, [&](lock_t *seen) {
1663 if (lock != nullptr) {
1664 return true;
1665 }
1666 lock = seen;
1667 return false;
1668 });
1669
1670 trx_t *trx = thr_get_trx(thr);
1671 ut_ad(!trx_mutex_own(trx));
1672
1673 lock_rec_req_status status = LOCK_REC_SUCCESS;
1674
1675 if (lock == nullptr) {
1676 if (!impl) {
1677 RecLock rec_lock(index, block, heap_no, mode);
1678
1679 trx_mutex_enter(trx);
1680 rec_lock.create(trx);
1681 trx_mutex_exit(trx);
1682
1683 status = LOCK_REC_SUCCESS_CREATED;
1684 }
1685 } else {
1686 trx_mutex_enter(trx);
1687
1688 if (other_lock != nullptr || lock->trx != trx ||
1689 lock->type_mode != (mode | LOCK_REC) ||
1690 lock_rec_get_n_bits(lock) <= heap_no) {
1691 status = LOCK_REC_FAIL;
1692 } else if (!impl) {
1693 /* If the nth bit of the record lock is already set
1694 then we do not set a new lock bit, otherwise we do
1695 set */
1696 if (!lock_rec_get_nth_bit(lock, heap_no)) {
1697 lock_rec_set_nth_bit(lock, heap_no);
1698 status = LOCK_REC_SUCCESS_CREATED;
1699 }
1700 }
1701
1702 trx_mutex_exit(trx);
1703 }
1704 ut_ad(status == LOCK_REC_SUCCESS || status == LOCK_REC_SUCCESS_CREATED ||
1705 status == LOCK_REC_FAIL);
1706 return (status);
1707 }
1708
1709 /** A helper function for lock_rec_lock_slow(), which grants a Next Key Lock
1710 (either LOCK_X or LOCK_S as specified by `mode`) on <`block`,`heap_no`> in the
1711 `index` to the `trx`, assuming that it already has a granted `held_lock`, which
1712 is at least as strong as mode|LOCK_REC_NOT_GAP. It does so by either reusing the
1713 lock if it already covers the gap, or by ensuring a separate GAP Lock, which in
1714 combination with Record Lock satisfies the request.
1715 @param[in] held_lock a lock granted to `trx` which is at least as strong
1716 as mode|LOCK_REC_NOT_GAP
1717 @param[in] mode requested lock mode: LOCK_X or LOCK_S
1718 @param[in] block buffer block containing the record to be locked
1719 @param[in] heap_no heap number of the record to be locked
1720 @param[in] index index of record to be locked
1721 @param[in] trx the transaction requesting the Next Key Lock */
1722 static void lock_reuse_for_next_key_lock(const lock_t *held_lock, ulint mode,
1723 const buf_block_t *block,
1724 ulint heap_no, dict_index_t *index,
1725 trx_t *trx) {
1726 ut_ad(mode == LOCK_S || mode == LOCK_X);
1727 ut_ad(lock_mode_is_next_key_lock(mode));
1728
1729 if (!held_lock->is_record_not_gap()) {
1730 ut_ad(held_lock->is_next_key_lock());
1731 return;
1732 }
1733
1734 /* We have a Record Lock granted, so we only need a GAP Lock. We assume
1735 that GAP Locks do not conflict with anything. Therefore a GAP Lock
1736 could be granted to us right now if we've requested: */
1737 mode |= LOCK_GAP;
1738 ut_ad(nullptr ==
1739 lock_rec_other_has_conflicting(mode, block, heap_no, trx).wait_for);
1740
1741 /* It might be the case we already have one, so we first check that. */
1742 if (lock_rec_has_expl(mode, block, heap_no, trx) == nullptr) {
1743 lock_rec_add_to_queue(LOCK_REC | mode, block, heap_no, index, trx);
1744 }
1745 }
1746 /** This is the general, and slower, routine for locking a record. This is a
1747 low-level function which does NOT look at implicit locks! Checks lock
1748 compatibility within explicit locks. This function sets a normal next-key
1749 lock, or in the case of a page supremum record, a gap type lock.
1750 @param[in] impl if true, no lock might be set if no wait is
1751 necessary: we assume that the caller will
1752 set an implicit lock
1753 @param[in] sel_mode select mode: SELECT_ORDINARY,
1754 SELECT_SKIP_LOCKED, or SELECT_NO_WAIT
1755 @param[in] mode lock mode: LOCK_X or LOCK_S possibly ORed to
1756 either LOCK_GAP or LOCK_REC_NOT_GAP
1757 @param[in] block buffer block containing the record
1758 @param[in] heap_no heap number of record
1759 @param[in] index index of record
1760 @param[in,out] thr query thread
1761 @return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, DB_LOCK_WAIT, DB_DEADLOCK,
1762 DB_SKIP_LOCKED, or DB_LOCK_NOWAIT */
1763 static dberr_t lock_rec_lock_slow(bool impl, select_mode sel_mode, ulint mode,
1764 const buf_block_t *block, ulint heap_no,
1765 dict_index_t *index, que_thr_t *thr) {
1766 ut_ad(locksys::owns_page_shard(block->get_page_id()));
1767 ut_ad(!srv_read_only_mode);
1768 ut_ad((LOCK_MODE_MASK & mode) != LOCK_S ||
1769 lock_table_has(thr_get_trx(thr), index->table, LOCK_IS));
1770 ut_ad((LOCK_MODE_MASK & mode) != LOCK_X ||
1771 lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
1772 ut_ad((LOCK_MODE_MASK & mode) == LOCK_S || (LOCK_MODE_MASK & mode) == LOCK_X);
1773 ut_ad(mode - (LOCK_MODE_MASK & mode) == LOCK_GAP ||
1774 mode - (LOCK_MODE_MASK & mode) == LOCK_ORDINARY ||
1775 mode - (LOCK_MODE_MASK & mode) == LOCK_REC_NOT_GAP);
1776 ut_ad(index->is_clustered() || !dict_index_is_online_ddl(index));
1777
1778 DBUG_EXECUTE_IF("innodb_report_deadlock", return (DB_DEADLOCK););
1779
1780 trx_t *trx = thr_get_trx(thr);
1781
1782 ut_ad(sel_mode == SELECT_ORDINARY ||
1783 (sel_mode != SELECT_ORDINARY && !trx_is_high_priority(trx)));
1784
1785 /* A very common type of lock in InnoDB is "Next Key Lock", which is almost
1786 equivalent to two locks: Record Lock and GAP Lock separately.
1787 Thus, in case we need to wait, we check if we already own a Record Lock,
1788 and if we do, we only need the GAP Lock.
1789 We don't do the opposite thing (of checking for GAP Lock, and only requesting
1790 Record Lock), because if Next Key Lock has to wait, then it is because of a
1791 conflict with someone who locked the record, as locks on gaps are compatible
1792 with each other, so even if we have a GAP Lock, narrowing the requested mode
1793 to Record Lock will not make the conflict go away.
1794
1795 In current implementation locks on supremum are treated like GAP Locks,
1796 in particular they never have to wait for anything (unless they are Insert
1797 Intention locks, but we've ruled that out with asserts before getting here),
1798 so there is no gain in using the above "lock splitting" heuristic for locks on
1799 supremum, and reasoning becomes a bit simpler without this special case. */
1800
1801 auto checked_mode =
1802 (heap_no != PAGE_HEAP_NO_SUPREMUM && lock_mode_is_next_key_lock(mode))
1803 ? mode | LOCK_REC_NOT_GAP
1804 : mode;
1805
1806 const auto *held_lock = lock_rec_has_expl(checked_mode, block, heap_no, trx);
1807
1808 if (held_lock != nullptr) {
1809 if (checked_mode == mode) {
1810 /* The trx already has a strong enough lock on rec: do nothing */
1811 return (DB_SUCCESS);
1812 }
1813
1814 /* As check_mode != mode, the mode is Next Key Lock, which can not be
1815 emulated by implicit lock (which are LOCK_REC_NOT_GAP only). */
1816 ut_ad(!impl);
1817
1818 lock_reuse_for_next_key_lock(held_lock, mode, block, heap_no, index, trx);
1819 return (DB_SUCCESS);
1820 }
1821 const auto conflicting =
1822 lock_rec_other_has_conflicting(mode, block, heap_no, trx);
1823
1824 if (conflicting.wait_for != nullptr) {
1825 switch (sel_mode) {
1826 case SELECT_SKIP_LOCKED:
1827 return (DB_SKIP_LOCKED);
1828 case SELECT_NOWAIT:
1829 return (DB_LOCK_NOWAIT);
1830 case SELECT_ORDINARY:
1831 /* If another transaction has a non-gap conflicting request in the
1832 queue, as this transaction does not have a lock strong enough already
1833 granted on the record, we may have to wait. */
1834
1835 RecLock rec_lock(thr, index, block, heap_no, mode);
1836
1837 trx_mutex_enter(trx);
1838
1839 dberr_t err = rec_lock.add_to_waitq(conflicting.wait_for);
1840
1841 trx_mutex_exit(trx);
1842
1843 ut_ad(err == DB_SUCCESS_LOCKED_REC || err == DB_LOCK_WAIT ||
1844 err == DB_DEADLOCK);
1845 return (err);
1846 }
1847 }
1848 /* In case we've used a heuristic to bypass a conflicting waiter, we prefer to
1849 create an explicit lock so it is easier to track the wait-for relation.*/
1850 if (!impl || conflicting.bypassed) {
1851 /* Set the requested lock on the record. */
1852
1853 lock_rec_add_to_queue(LOCK_REC | mode, block, heap_no, index, trx);
1854
1855 return (DB_SUCCESS_LOCKED_REC);
1856 }
1857 return (DB_SUCCESS);
1858 }
1859
1860 /** Tries to lock the specified record in the mode requested. If not immediately
1861 possible, enqueues a waiting lock request. This is a low-level function
1862 which does NOT look at implicit locks! Checks lock compatibility within
1863 explicit locks. This function sets a normal next-key lock, or in the case
1864 of a page supremum record, a gap type lock.
1865 @param[in] impl if true, no lock is set if no wait is
1866 necessary: we assume that the caller will
1867 set an implicit lock
1868 @param[in] sel_mode select mode: SELECT_ORDINARY,
1869 SELECT_SKIP_LOCKED, or SELECT_NO_WAIT
1870 @param[in] mode lock mode: LOCK_X or LOCK_S possibly ORed to
1871 either LOCK_GAP or LOCK_REC_NOT_GAP
1872 @param[in] block buffer block containing the record
1873 @param[in] heap_no heap number of record
1874 @param[in] index index of record
1875 @param[in,out] thr query thread
1876 @return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, DB_LOCK_WAIT, DB_DEADLOCK,
1877 DB_SKIP_LOCKED, or DB_LOCK_NOWAIT */
1878 static dberr_t lock_rec_lock(bool impl, select_mode sel_mode, ulint mode,
1879 const buf_block_t *block, ulint heap_no,
1880 dict_index_t *index, que_thr_t *thr) {
1881 ut_ad(locksys::owns_page_shard(block->get_page_id()));
1882 ut_ad(!srv_read_only_mode);
1883 ut_ad((LOCK_MODE_MASK & mode) != LOCK_S ||
1884 lock_table_has(thr_get_trx(thr), index->table, LOCK_IS));
1885 ut_ad((LOCK_MODE_MASK & mode) != LOCK_X ||
1886 lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
1887 ut_ad((LOCK_MODE_MASK & mode) == LOCK_S || (LOCK_MODE_MASK & mode) == LOCK_X);
1888 ut_ad(mode - (LOCK_MODE_MASK & mode) == LOCK_GAP ||
1889 mode - (LOCK_MODE_MASK & mode) == LOCK_REC_NOT_GAP ||
1890 mode - (LOCK_MODE_MASK & mode) == 0);
1891 ut_ad(index->is_clustered() || !dict_index_is_online_ddl(index));
1892 /* Implicit locks are equivalent to LOCK_X|LOCK_REC_NOT_GAP, so we can omit
1893 creation of explicit lock only if the requested mode was LOCK_REC_NOT_GAP */
1894 ut_ad(!impl || ((mode & LOCK_REC_NOT_GAP) == LOCK_REC_NOT_GAP));
1895 /* We try a simplified and faster subroutine for the most
1896 common cases */
1897 switch (lock_rec_lock_fast(impl, mode, block, heap_no, index, thr)) {
1898 case LOCK_REC_SUCCESS:
1899 return (DB_SUCCESS);
1900 case LOCK_REC_SUCCESS_CREATED:
1901 return (DB_SUCCESS_LOCKED_REC);
1902 case LOCK_REC_FAIL:
1903 return (
1904 lock_rec_lock_slow(impl, sel_mode, mode, block, heap_no, index, thr));
1905 default:
1906 ut_error;
1907 }
1908 }
1909
1910 /** Checks if a waiting record lock request still has to wait in a queue.
1911 @param[in] wait_lock Waiting record lock
1912 @param[in] blocking_trx If not nullptr, it restricts the search to only the
1913 locks held by the blocking_trx, which is useful in
1914 case when there might be multiple reasons for waiting
1915 in queue, but we need to report the specific one.
1916 Useful when reporting a deadlock cycle. (optional)
1917 @return The conflicting lock which is the reason wait_lock has to wait
1918 or nullptr if it can be granted now */
1919 static const lock_t *lock_rec_has_to_wait_in_queue(
1920 const lock_t *wait_lock, const trx_t *blocking_trx = nullptr) {
1921 ut_ad(lock_get_type_low(wait_lock) == LOCK_REC);
1922 const auto page_id = wait_lock->rec_lock.page_id;
1923 ut_ad(locksys::owns_page_shard(page_id));
1924 ut_ad(lock_get_wait(wait_lock));
1925
1926 const auto heap_no = (uint16_t)lock_rec_find_set_bit(wait_lock);
1927
1928 locksys::Trx_locks_cache wait_lock_cache{};
1929 lock_t *stopped_at = wait_lock->hash_table().find_on_record(
1930 RecID{page_id, heap_no}, [&](lock_t *lock) {
1931 return lock == wait_lock ||
1932 ((blocking_trx == nullptr || blocking_trx == lock->trx) &&
1933 locksys::rec_lock_has_to_wait(wait_lock, lock,
1934 wait_lock_cache));
1935 });
1936 return stopped_at == wait_lock ? nullptr : stopped_at;
1937 }
1938
1939 /** Grants a lock to a waiting lock request and releases the waiting
1940 transaction. The caller must hold lock_sys latch for the shard containing the
1941 lock, but not the lock->trx->mutex.
1942 @param[in,out] lock waiting lock request
1943 */
1944 static void lock_grant(lock_t *lock) {
1945 ut_ad(locksys::owns_lock_shard(lock));
1946 ut_ad(!trx_mutex_own(lock->trx));
1947
1948 trx_mutex_enter(lock->trx);
1949
1950 if (lock_get_mode(lock) == LOCK_AUTO_INC) {
1951 dict_table_t *table = lock->tab_lock.table;
1952
1953 if (table->autoinc_trx == lock->trx) {
1954 ib::error(ER_IB_MSG_637) << "Transaction already had an"
1955 << " AUTO-INC lock!";
1956 } else {
1957 ut_ad(table->autoinc_trx == nullptr);
1958 table->autoinc_trx = lock->trx;
1959
1960 ib_vector_push(lock->trx->lock.autoinc_locks, &lock);
1961 }
1962 }
1963
1964 DBUG_PRINT("ib_lock", ("wait for trx " TRX_ID_FMT " ends",
1965 trx_get_id_for_print(lock->trx)));
1966
1967 lock_reset_wait_and_release_thread_if_suspended(lock);
1968 ut_ad(trx_mutex_own(lock->trx));
1969
1970 trx_mutex_exit(lock->trx);
1971 }
1972
1973 void lock_make_trx_hit_list(trx_t *hp_trx, hit_list_t &hit_list) {
1974 trx_mutex_enter(hp_trx);
1975 const trx_id_t hp_trx_id = hp_trx->id;
1976 ut_ad(trx_can_be_handled_by_current_thread(hp_trx));
1977 ut_ad(trx_is_high_priority(hp_trx));
1978 /* To avoid slow procedure below, we first
1979 check if this transaction is waiting for a lock at all. It's unsafe to read
1980 hp->lock.wait_lock without latching whole lock_sys as it might temporarily
1981 change to NULL during a concurrent B-tree reorganization, even though the
1982 trx actually is still waiting. Thus we use hp_trx->lock.blocking_trx instead.
1983 */
1984 const bool is_waiting = (hp_trx->lock.blocking_trx.load() != nullptr);
1985 trx_mutex_exit(hp_trx);
1986 if (!is_waiting) {
1987 return;
1988 }
1989 /* We don't expect hp_trx to commit (change version) as we are the thread
1990 running the hp_trx */
1991 locksys::run_if_waiting({hp_trx}, [&]() {
1992 const lock_t *lock = hp_trx->lock.wait_lock;
1993 // TBD: could this technique be used for table locks as well?
1994 if (!lock->is_record_lock()) {
1995 return;
1996 }
1997 trx_mutex_exit(hp_trx);
1998 lock->hash_table().find_on_record(
1999 RecID{lock, lock_rec_find_set_bit(lock)}, [&](lock_t *next) {
2000 trx_t *trx = next->trx;
2001 /* Check only for conflicting, granted locks on the current
2002 row. Currently, we don't rollback read only transactions,
2003 transactions owned by background threads. */
2004 if (trx == hp_trx || next->is_waiting() || trx->read_only ||
2005 trx->mysql_thd == nullptr || !lock_has_to_wait(lock, next)) {
2006 return false;
2007 }
2008
2009 trx_mutex_enter(trx);
2010
2011 /* Skip high priority transactions, if already marked for
2012 abort by some other transaction or if ASYNC rollback is
2013 disabled. A transaction must complete kill/abort of a
2014 victim transaction once marked and added to hit list. */
2015 if (!trx_is_high_priority(trx) &&
2016 (trx->in_innodb & TRX_FORCE_ROLLBACK) == 0 &&
2017 (trx->in_innodb & TRX_FORCE_ROLLBACK_DISABLE) == 0 &&
2018 !trx->abort) {
2019 /* Mark for ASYNC Rollback and add to hit list. */
2020 lock_mark_trx_for_rollback(hit_list, hp_trx_id, trx);
2021 }
2022
2023 trx_mutex_exit(trx);
2024 return false;
2025 });
2026 // the run_if_waiting expects the hp_trx to be held after callback
2027 trx_mutex_enter(hp_trx);
2028 });
2029 }
2030
2031 /** Cancels a waiting record lock request and releases the waiting transaction
2032 that requested it. NOTE: does NOT check if waiting lock requests behind this
2033 one can now be granted! */
2034 static void lock_rec_cancel(
2035 lock_t *lock) /*!< in: waiting record lock request */
2036 {
2037 ut_ad(lock_get_type_low(lock) == LOCK_REC);
2038 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
2039
2040 /* Reset the bit (there can be only one set bit) in the lock bitmap */
2041 lock_rec_reset_nth_bit(lock, lock_rec_find_set_bit(lock));
2042
2043 trx_mutex_enter(lock->trx);
2044
2045 lock_reset_wait_and_release_thread_if_suspended(lock);
2046
2047 trx_mutex_exit(lock->trx);
2048 }
2049
2050 /** Given a waiting_lock, and blocking_lock which is the reason it has to wait,
2051 makes sure that the (only) edge in the wait-for graph outgoing from the
2052 waiting_lock->trx points to blocking_lock->trx
2053 @param[in] waiting_lock A lock waiting in queue, blocked by blocking_lock
2054 @param[in] blocking_lock A lock which is a reason the waiting_lock has to
2055 wait */
2056 static void lock_update_wait_for_edge(const lock_t *waiting_lock,
2057 const lock_t *blocking_lock) {
2058 ut_ad(locksys::owns_lock_shard(waiting_lock));
2059 ut_ad(locksys::owns_lock_shard(blocking_lock));
2060 ut_ad(waiting_lock->is_waiting());
2061 ut_ad(lock_has_to_wait(waiting_lock, blocking_lock));
2062 /* Still needs to wait, but perhaps the reason has changed */
2063 if (waiting_lock->trx->lock.blocking_trx.load() != blocking_lock->trx) {
2064 waiting_lock->trx->lock.blocking_trx.store(blocking_lock->trx);
2065 /* We call lock_wait_request_check_for_cycles() because the outgoing edge of
2066 wait_lock->trx has changed it's endpoint and we need to analyze the
2067 wait-for-graph again. */
2068 lock_wait_request_check_for_cycles();
2069 lock_report_wait_for_edge_to_server(waiting_lock, blocking_lock);
2070 }
2071 }
2072
2073 /** Checks if a waiting record lock request still has to wait for granted locks.
2074 @param[in] wait_lock Waiting record lock
2075 @param[in] granted Granted record locks
2076 @param[in] new_granted_index Start of new granted locks
2077 @return The conflicting lock which is the reason wait_lock has to wait
2078 or nullptr if it can be granted now */
2079 template <typename Container>
2080 static const lock_t *lock_rec_has_to_wait_for_granted(
2081 const typename Container::value_type &wait_lock, const Container &granted,
2082 const size_t new_granted_index)
2083
2084 {
2085 ut_ad(locksys::owns_page_shard(wait_lock->rec_lock.page_id));
2086 ut_ad(wait_lock->is_record_lock());
2087
2088 ut_ad(new_granted_index <= granted.size());
2089
2090 /* We iterate over granted locks in reverse order.
2091 Conceptually this corresponds to chronological order.
2092 This way, we pick as blocking_trx the oldest reason for waiting we haven't
2093 yet analyzed in deadlock checker. Our hope is that eventually (perhaps after
2094 several such updates) we will set blocking_trx to the real cause of the
2095 deadlock, which is the next node on the deadlock cycle. */
2096 for (size_t i = new_granted_index; i--;) {
2097 const auto granted_lock = granted[i];
2098 if (lock_has_to_wait(wait_lock, granted_lock)) {
2099 return (granted_lock);
2100 }
2101 }
2102
2103 for (size_t i = new_granted_index; i < granted.size(); ++i) {
2104 const auto granted_lock = granted[i];
2105 ut_ad(granted_lock->trx->error_state != DB_DEADLOCK);
2106 ut_ad(!granted_lock->trx->lock.was_chosen_as_deadlock_victim);
2107
2108 if (lock_has_to_wait(wait_lock, granted_lock)) {
2109 return (granted_lock);
2110 }
2111 }
2112
2113 return (nullptr);
2114 }
2115
2116 /** Grant a lock to waiting transactions. This function scans the queue of locks
2117 in which in_lock resides (or resided) paying attention only to locks on
2118 heap_no-th bit. For each waiting lock which was blocked by in_lock->trx it
2119 checks if it can be granted now. It iterates on waiting locks in order favoring
2120 high-priority transactions and then transactions of high
2121 trx->lock.schedule_weight.
2122 @param[in] in_lock Lock which was released, or
2123 partially released by modifying its type/mode
2124 (see lock_trx_release_read_locks) or
2125 resetting heap_no-th bit in the bitmap
2126 (see lock_rec_release)
2127 @param[in] heap_no Heap number within the page on which the
2128 lock was (or still is) held */
2129 static void lock_rec_grant_by_heap_no(lock_t *in_lock, ulint heap_no) {
2130 ut_ad(in_lock->is_record_lock());
2131 ut_ad(locksys::owns_page_shard(in_lock->rec_lock.page_id));
2132
2133 using LockDescriptorEx = std::pair<trx_schedule_weight_t, lock_t *>;
2134 /* Preallocate for 4 lists with 32 locks. */
2135 Scoped_heap heap((sizeof(lock_t *) * 3 + sizeof(LockDescriptorEx)) * 32,
2136 UT_LOCATION_HERE);
2137
2138 RecID rec_id{in_lock, heap_no};
2139 Locks<lock_t *> low_priority_light{heap.get()};
2140 Locks<lock_t *> waiting{heap.get()};
2141 Locks<lock_t *> granted{heap.get()};
2142 Locks<LockDescriptorEx> low_priority_heavier{heap.get()};
2143
2144 const auto in_trx = in_lock->trx;
2145 #ifdef UNIV_DEBUG
2146 bool seen_waiting_lock = false;
2147 #endif
2148 in_lock->hash_table().find_on_record(rec_id, [&](lock_t *lock) {
2149 /* Split the relevant locks in the queue into:
2150 - granted = granted locks
2151 - waiting = waiting locks of high priority transactions
2152 - low_priority_heavier = waiting locks of low priority, but heavy weight
2153 - low_priority_light = waiting locks of low priority and light weight
2154 */
2155 if (!lock->is_waiting()) {
2156 /* Granted locks should be before waiting locks. */
2157 ut_ad(!seen_waiting_lock);
2158 granted.push_back(lock);
2159 return false;
2160 }
2161 ut_d(seen_waiting_lock = true);
2162 const auto trx = lock->trx;
2163 if (trx->error_state == DB_DEADLOCK ||
2164 trx->lock.was_chosen_as_deadlock_victim) {
2165 return false;
2166 }
2167 /* We read blocking_trx while holding this lock_sys queue latched, and
2168 each write to blocking_trx is done while holding the latch. So, even
2169 though we use memory_order_relaxed we will see modifications performed
2170 before we acquired the latch. */
2171 const auto blocking_trx =
2172 trx->lock.blocking_trx.load(std::memory_order_relaxed);
2173 /* No one should be WAITING without good reason! */
2174 ut_ad(blocking_trx);
2175 /* We will only consider granting the `lock`, if we are the reason it
2176 was waiting. */
2177 if (blocking_trx != in_trx) {
2178 return false;
2179 }
2180 if (trx_is_high_priority(trx)) {
2181 waiting.push_back(lock);
2182 return false;
2183 }
2184 /* The values of schedule_weight are read with memory_order_relaxed as
2185 we do not care neither about having the most recent value, nor about any
2186 relative order between this load and other operations.
2187 As std::sort requires the order to be consistent during execution we
2188 have to take a snapshot of all schedule_weight atomics, so they don't
2189 change during call to stable_sort in a way which causes the algorithm to
2190 crash. */
2191 const auto schedule_weight =
2192 trx->lock.schedule_weight.load(std::memory_order_relaxed);
2193 if (schedule_weight <= 1) {
2194 low_priority_light.push_back(lock);
2195 return false;
2196 }
2197 low_priority_heavier.push_back(LockDescriptorEx{schedule_weight, lock});
2198
2199 return false;
2200 });
2201
2202 if (waiting.empty() && low_priority_light.empty() &&
2203 low_priority_heavier.empty()) {
2204 /* Nothing to grant. */
2205 return;
2206 }
2207 /* We want high schedule weight to be in front, and break ties by position */
2208 std::stable_sort(low_priority_heavier.begin(), low_priority_heavier.end(),
2209 [](const LockDescriptorEx &a, const LockDescriptorEx &b) {
2210 return (a.first > b.first);
2211 });
2212 for (const auto &descriptor : low_priority_heavier) {
2213 waiting.push_back(descriptor.second);
2214 }
2215 waiting.insert(waiting.end(), low_priority_light.begin(),
2216 low_priority_light.end());
2217
2218 /* New granted locks will be added from this index. */
2219 const auto new_granted_index = granted.size();
2220
2221 granted.reserve(granted.size() + waiting.size());
2222
2223 for (lock_t *wait_lock : waiting) {
2224 /* Check if the transactions in the waiting queue have
2225 to wait for locks granted above. If they don't have to
2226 wait then grant them the locks and add them to the granted
2227 queue. */
2228
2229 /* We don't expect to be a waiting trx, and we can't grant to ourselves as
2230 that would require entering trx->mutex while holding in_trx->mutex. */
2231 ut_ad(wait_lock->trx != in_trx);
2232
2233 const lock_t *blocking_lock =
2234 lock_rec_has_to_wait_for_granted(wait_lock, granted, new_granted_index);
2235 if (blocking_lock == nullptr) {
2236 lock_grant(wait_lock);
2237
2238 lock_rec_move_granted_to_front(wait_lock, rec_id);
2239
2240 granted.push_back(wait_lock);
2241 } else {
2242 lock_update_wait_for_edge(wait_lock, blocking_lock);
2243 }
2244 }
2245 }
2246
2247 /* Forward declaration to minimize the diff */
2248 static const lock_t *lock_has_to_wait_in_queue(const lock_t *wait_lock,
2249 const trx_t *blocking_trx);
2250
2251 /** Given a lock, which was found in waiting queue, checks if it still has to
2252 wait in queue, and either grants it, or makes sure that the reason it has to
2253 wait is reflected in the wait-for graph.
2254 @param[in] lock A lock in WAITING state, which perhaps can be granted now */
2255 static void lock_grant_or_update_wait_for_edge(lock_t *lock) {
2256 ut_ad(lock->is_waiting());
2257 const lock_t *blocking_lock = lock_has_to_wait_in_queue(lock, nullptr);
2258 if (blocking_lock == nullptr) {
2259 /* Grant the lock */
2260 lock_grant(lock);
2261 } else {
2262 ut_ad(lock->trx != blocking_lock->trx);
2263 lock_update_wait_for_edge(lock, blocking_lock);
2264 }
2265 }
2266
2267 /** Given a lock, and a transaction which is releasing another lock from the
2268 same queue, makes sure that if the lock was waiting for this transaction, then
2269 it will either be granted, or another reason for waiting is reflected in the
2270 wait-for graph. */
2271 static void lock_grant_or_update_wait_for_edge_if_waiting(
2272 lock_t *lock, const trx_t *releasing_trx) {
2273 if (lock->is_waiting() && lock->trx->lock.blocking_trx == releasing_trx) {
2274 ut_ad(lock->trx != releasing_trx);
2275 lock_grant_or_update_wait_for_edge(lock);
2276 }
2277 }
2278
2279 /** Grant lock to waiting requests that no longer conflicts.
2280 The in_lock might be modified before call to this function by clearing some flag
2281 (see for example lock_trx_release_read_locks). It also might already be removed
2282 from the hash cell (a.k.a. waiting queue) or still reside in it. However the
2283 content of bitmap should not be changed prior to calling this function, as the
2284 bitmap will be inspected to see which heap_no at all were blocked by this
2285 in_lock, and only locks waiting for those heap_no's will be checked.
2286 @param[in,out] in_lock record lock object: grant all non-conflicting
2287 locks waiting behind this lock object */
2288 static void lock_rec_grant(lock_t *in_lock) {
2289 const auto page_id = in_lock->rec_lock.page_id;
2290
2291 /* In some scenarios, in particular in replication appliers, it is often the
2292 case, that there are no WAITING locks, and in such situation iterating over
2293 all bits, and calling lock_rec_grant_by_heap_no() slows down the execution
2294 noticeably. (I guess that checking bits is not the costly part, but rather the
2295 allocation of vectors inside lock_rec_grant_by_heap_no). Therefore we first
2296 check if there is any lock which is waiting at all.
2297 Note: This condition could be further narrowed to check if the `lock` is
2298 waiting for the `in_lock` and/or `lock->trx` is blocked by the `in_lock->trx`,
2299 and we could optimize lock_rec_grant_by_heap_no() to allocate vectors only if
2300 there are at least two waiters to arbitrate among, but in practice the current
2301 simple heuristic is good enough. */
2302
2303 if (in_lock->hash_table().find_on_page(
2304 page_id, [](lock_t *lock) { return lock->is_waiting(); })) {
2305 mon_type_t grant_attempts = 0;
2306 for (ulint heap_no = 0; heap_no < lock_rec_get_n_bits(in_lock); ++heap_no) {
2307 if (lock_rec_get_nth_bit(in_lock, heap_no)) {
2308 lock_rec_grant_by_heap_no(in_lock, heap_no);
2309 ++grant_attempts;
2310 }
2311 }
2312 MONITOR_INC_VALUE(MONITOR_RECLOCK_GRANT_ATTEMPTS, grant_attempts);
2313 }
2314 MONITOR_INC(MONITOR_RECLOCK_RELEASE_ATTEMPTS);
2315 }
2316
2317 /** Removes a record lock request, waiting or granted, from the queue and
2318 grants locks to other transactions in the queue if they now are entitled
2319 to a lock. NOTE: all record locks contained in in_lock are removed.
2320 @param[in,out] in_lock record lock object: all record locks which
2321 are contained in this lock object are removed;
2322 transactions waiting behind will get their
2323 lock requests granted, if they are now
2324 qualified to it */
2325 static void lock_rec_dequeue_from_page(lock_t *in_lock) {
2326 lock_rec_discard(in_lock);
2327 lock_rec_grant(in_lock);
2328 }
2329
2330 /** Removes a record lock request, waiting or granted, from the queue.
2331 @param[in] in_lock record lock object: all record locks
2332 which are contained in this lock object
2333 are removed */
2334 void lock_rec_discard(lock_t *in_lock) {
2335 ut_ad(lock_get_type_low(in_lock) == LOCK_REC);
2336 ut_ad(locksys::owns_page_shard(in_lock->rec_lock.page_id));
2337
2338 ut_ad(in_lock->index->table->n_rec_locks.load() > 0);
2339 in_lock->index->table->n_rec_locks.fetch_sub(1, std::memory_order_relaxed);
2340
2341 /* We want the state of lock queue and trx_locks list to be synchronized
2342 atomically from the point of view of people using trx->mutex, so we perform
2343 HASH_DELETE and UT_LIST_REMOVE while holding trx->mutex. */
2344
2345 ut_ad(trx_mutex_own(in_lock->trx));
2346
2347 locksys::remove_from_trx_locks(in_lock);
2348
2349 in_lock->hash_table().erase(in_lock, lock_rec_lock_hash_value(in_lock));
2350
2351 MONITOR_INC(MONITOR_RECLOCK_REMOVED);
2352 MONITOR_DEC(MONITOR_NUM_RECLOCK);
2353 }
2354
2355 static const lock_t *lock_find_record_lock_by_guid(Locks_hashtable &lock_hash,
2356 page_id_t page_id,
2357 const lock_guid_t &guid) {
2358 ut_ad(locksys::owns_page_shard(page_id));
2359 return lock_hash.find_on_page(
2360 page_id, [&](lock_t *lock) { return lock_guid_t(*lock) == guid; });
2361 }
2362
2363 const lock_t *lock_find_record_lock_by_guid(page_id_t page_id,
2364 const lock_guid_t &guid) {
2365 ut_ad(locksys::owns_page_shard(page_id));
2366 for (Locks_hashtable *lock_hash :
2367 {&lock_sys->rec_hash, &lock_sys->prdt_hash, &lock_sys->prdt_page_hash}) {
2368 const lock_t *lock =
2369 lock_find_record_lock_by_guid(*lock_hash, page_id, guid);
2370 if (lock != nullptr) {
2371 return lock;
2372 }
2373 }
2374 return nullptr;
2375 }
2376
2377 /** Removes record lock objects set on an index page which is discarded. This
2378 function does not move locks, or check for waiting locks, therefore the
2379 lock bitmaps must already be reset when this function is called. */
2380 static void lock_rec_free_all_from_discard_page_low(
2381 page_id_t page_id, Locks_hashtable &lock_hash) {
2382 lock_hash.find_on_page(page_id, [](lock_t *lock) {
2383 ut_ad(lock_rec_find_set_bit(lock) == ULINT_UNDEFINED);
2384 ut_ad(!lock_get_wait(lock));
2385
2386 trx_t *trx = lock->trx;
2387 trx_mutex_enter(trx);
2388 lock_rec_discard(lock);
2389 trx_mutex_exit(trx);
2390 return false;
2391 });
2392 }
2393
2394 /** Removes record lock objects set on an index page which is discarded. This
2395 function does not move locks, or check for waiting locks, therefore the
2396 lock bitmaps must already be reset when this function is called. */
2397 void lock_rec_free_all_from_discard_page(
2398 const buf_block_t *block) /*!< in: page to be discarded */
2399 {
2400 const auto page_id = block->get_page_id();
2401 ut_ad(locksys::owns_page_shard(page_id));
2402
2403 lock_rec_free_all_from_discard_page_low(page_id, lock_sys->rec_hash);
2404 lock_rec_free_all_from_discard_page_low(page_id, lock_sys->prdt_hash);
2405 lock_rec_free_all_from_discard_page_low(page_id, lock_sys->prdt_page_hash);
2406 }
2407
2408 /*============= RECORD LOCK MOVING AND INHERITING ===================*/
2409
2410 /** Resets the lock bits for a single record. Releases transactions waiting for
2411 lock requests here. */
2412 static void lock_rec_reset_and_release_wait_low(
2413 Locks_hashtable &hash, /*!< in: hash table */
2414 const buf_block_t *block, /*!< in: buffer block containing
2415 the record */
2416 ulint heap_no) /*!< in: heap number of record */
2417 {
2418 ut_ad(locksys::owns_page_shard(block->get_page_id()));
2419 hash.find_on_record(RecID{block, heap_no}, [&](lock_t *lock) {
2420 if (lock_get_wait(lock)) {
2421 lock_rec_cancel(lock);
2422 } else {
2423 lock_rec_reset_nth_bit(lock, heap_no);
2424 }
2425 return false;
2426 });
2427 }
2428
2429 /** Resets the lock bits for a single record. Releases transactions waiting for
2430 lock requests here. */
2431 static void lock_rec_reset_and_release_wait(
2432 const buf_block_t *block, /*!< in: buffer block containing
2433 the record */
2434 ulint heap_no) /*!< in: heap number of record */
2435 {
2436 lock_rec_reset_and_release_wait_low(lock_sys->rec_hash, block, heap_no);
2437
2438 lock_rec_reset_and_release_wait_low(lock_sys->prdt_hash, block,
2439 PAGE_HEAP_NO_INFIMUM);
2440 lock_rec_reset_and_release_wait_low(lock_sys->prdt_page_hash, block,
2441 PAGE_HEAP_NO_INFIMUM);
2442 }
2443
2444 void lock_on_statement_end(trx_t *trx) { trx->lock.inherit_all.store(false); }
2445
2446 /* Used to store information that `thr` requested a lock asking for protection
2447 at least till the end of the current statement which requires it to be inherited
2448 as gap locks even in READ COMMITTED isolation level.
2449 @param[in] thr the requesting thread */
2450 static inline void lock_protect_locks_till_statement_end(que_thr_t *thr) {
2451 thr_get_trx(thr)->lock.inherit_all.store(true);
2452 }
2453
2454 /** Makes a record to inherit the locks (except LOCK_INSERT_INTENTION type)
2455 of another record as gap type locks, but does not reset the lock bits of
2456 the other record. Also waiting lock requests on rec are inherited as
2457 GRANTED gap locks. */
2458 static void lock_rec_inherit_to_gap(
2459 const buf_block_t *heir_block, /*!< in: block containing the
2460 record which inherits */
2461 const buf_block_t *block, /*!< in: block containing the
2462 record from which inherited;
2463 does NOT reset the locks on
2464 this record */
2465 ulint heir_heap_no, /*!< in: heap_no of the
2466 inheriting record */
2467 ulint heap_no) /*!< in: heap_no of the
2468 donating record */
2469 {
2470 ut_ad(locksys::owns_page_shard(heir_block->get_page_id()));
2471 ut_ad(locksys::owns_page_shard(block->get_page_id()));
2472
2473 /* If session is using READ COMMITTED or READ UNCOMMITTED isolation
2474 level, we do not want locks set by an UPDATE or a DELETE to be
2475 inherited as gap type locks. But we DO want S-locks/X-locks(taken for
2476 replace) set by a consistency constraint to be inherited also then. */
2477
2478 /* We also dont inherit these locks as gap type locks for DD tables
2479 because the serialization is guaranteed by MDL on DD tables. */
2480
2481 /* Constraint checks place LOCK_S or (in case of INSERT ... ON DUPLICATE
2482 UPDATE... or REPLACE INTO..) LOCK_X on records.
2483 If such a record is delete-marked, it may then become purged, and
2484 lock_rec_inheirt_to_gap will be called to decide the fate of each lock on it:
2485 either it will be inherited as gap lock, or discarded.
2486 In READ COMMITTED and less restricitve isolation levels we generally avoid gap
2487 locks, but we make an exception for precisely this situation: we want to
2488 inherit locks created for constraint checks.
2489 More precisely we need to keep inheriting them only for the duration of the
2490 query which has requested them, as such inserts have two phases : first they
2491 check for constraints, then they do actual row insert, and they trust that
2492 the locks set in the first phase will survive till the second phase.
2493 It is not easy to tell if a particular lock was created for constraint check
2494 or not, because we do not store this bit of information on it.
2495 What we do, is we use a heuristic: whenever a trx requests a lock with
2496 lock_duration_t::AT_LEAST_STATEMENT we set trx->lock.inherit_all, meaning that
2497 locks of this trx need to be inherited.
2498 And we clear trx->lock.inherit_all on statement end. */
2499 lock_sys->rec_hash.find_on_record(RecID{block, heap_no}, [&](lock_t *lock) {
2500 if (!lock->trx->skip_lock_inheritance &&
2501 !lock_rec_get_insert_intention(lock) &&
2502 !lock->index->table->skip_gap_locks() &&
2503 (!lock->trx->skip_gap_locks() || lock->trx->lock.inherit_all.load())) {
2504 lock_rec_add_to_queue(LOCK_REC | LOCK_GAP | lock_get_mode(lock),
2505 heir_block, heir_heap_no, lock->index, lock->trx);
2506 }
2507 return false;
2508 });
2509 }
2510
2511 /** Makes a record to inherit the gap locks (except LOCK_INSERT_INTENTION type)
2512 of another record as gap type locks, but does not reset the lock bits of the
2513 other record. Also waiting lock requests are inherited as GRANTED gap locks. */
2514 static void lock_rec_inherit_to_gap_if_gap_lock(
2515 const buf_block_t *block, /*!< in: buffer block */
2516 uint16_t heir_heap_no, /*!< in: heap_no of
2517 record which inherits */
2518 uint16_t heap_no) /*!< in: heap_no of record
2519 from which inherited;
2520 does NOT reset the locks
2521 on this record */
2522 {
2523 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
2524 lock_sys->rec_hash.find_on_record(RecID{block, heap_no}, [&](lock_t *lock) {
2525 if (!lock->trx->skip_lock_inheritance &&
2526 !lock_rec_get_insert_intention(lock) &&
2527 (heap_no == PAGE_HEAP_NO_SUPREMUM || !lock_rec_get_rec_not_gap(lock))) {
2528 lock_rec_add_to_queue(LOCK_REC | LOCK_GAP | lock_get_mode(lock), block,
2529 heir_heap_no, lock->index, lock->trx);
2530 }
2531 return false;
2532 });
2533 }
2534 /** Moves the locks of a record to another record and resets the lock bits of
2535 the donating record. */
2536 static void lock_rec_move(
2537 const buf_block_t *receiver, /*!< in: buffer block containing
2538 the receiving record */
2539 const buf_block_t *donator, /*!< in: buffer block containing
2540 the donating record */
2541 ulint receiver_heap_no, /*!< in: heap_no of the record
2542 which gets the locks; there
2543 must be no lock requests
2544 on it! */
2545 ulint donator_heap_no) /*!< in: heap_no of the record
2546 which gives the locks */
2547 {
2548 ut_ad(locksys::owns_page_shard(receiver->get_page_id()));
2549 ut_ad(locksys::owns_page_shard(donator->get_page_id()));
2550 auto &lock_hash = lock_sys->rec_hash;
2551
2552 ut_ad(
2553 !lock_rec_has_any(lock_hash, receiver->get_page_id(), receiver_heap_no));
2554 lock_hash.find_on_record(RecID{donator, donator_heap_no}, [&](lock_t *lock) {
2555 const ulint type_mode = lock->type_mode;
2556
2557 lock_rec_clear_request_no_wakeup(lock, donator_heap_no);
2558
2559 /* Note that we FIRST reset the bit, and then set the lock:
2560 the function works also if donator == receiver */
2561
2562 lock_rec_add_to_queue(type_mode, receiver, receiver_heap_no, lock->index,
2563 lock->trx);
2564 return false;
2565 });
2566
2567 ut_ad(!lock_rec_has_any(lock_hash, donator->get_page_id(), donator_heap_no));
2568 }
2569
2570 /** Move all the granted locks to the front of the given lock list.
2571 All the waiting locks will be at the end of the list.
2572 @param[in,out] lock_list the given lock list. */
2573 static void lock_move_granted_locks_to_front(trx_lock_list_t &lock_list) {
2574 bool seen_waiting_lock = false;
2575 /* Note: We need iterator to removable container, as the ut_list_move_to_front
2576 effectively removes the current element as part of its operation. */
2577 for (auto lock : lock_list.removable()) {
2578 if (!seen_waiting_lock) {
2579 if (lock->is_waiting()) {
2580 seen_waiting_lock = true;
2581 }
2582 continue;
2583 }
2584
2585 ut_ad(seen_waiting_lock);
2586
2587 if (!lock->is_waiting()) {
2588 ut_list_move_to_front(lock_list, lock);
2589 }
2590 }
2591 }
2592
2593 /** Updates the lock table when we have reorganized a page. NOTE: we copy
2594 also the locks set on the infimum of the page; the infimum may carry
2595 locks if an update of a record is occurring on the page, and its locks
2596 were temporarily stored on the infimum. */
2597 void lock_move_reorganize_page(
2598 const buf_block_t *block, /*!< in: old index page, now
2599 reorganized */
2600 const buf_block_t *oblock) /*!< in: copy of the old, not
2601 reorganized page */
2602 {
2603 trx_lock_list_t old_locks;
2604 mem_heap_t *heap = nullptr;
2605 {
2606 /* We only process locks on block, not oblock */
2607 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
2608
2609 /* Note: all predicate locks are on INFIMUM, and that doesn't change */
2610 /* Copy first all the locks on the page to heap and reset the
2611 bitmaps in the original locks; chain the copies of the locks
2612 using the trx_locks field in them. */
2613 lock_sys->rec_hash.find_on_block(block, [&](lock_t *lock) {
2614 if (heap == nullptr) {
2615 heap = mem_heap_create(256, UT_LOCATION_HERE);
2616 }
2617 /* Make a copy of the lock */
2618 lock_t *old_lock = lock_rec_copy(lock, heap);
2619
2620 UT_LIST_ADD_LAST(old_locks, old_lock);
2621
2622 /* Reset bitmap of lock */
2623 lock_rec_bitmap_reset(lock);
2624
2625 if (lock_get_wait(lock)) {
2626 lock_reset_lock_and_trx_wait(lock);
2627 }
2628 return false;
2629 });
2630 /* If no lock was found, no allocation happened, and we take quick exit */
2631 if (heap == nullptr) {
2632 return;
2633 }
2634
2635 auto comp = page_is_comp(block->frame);
2636 ut_ad(comp == page_is_comp(oblock->frame));
2637
2638 lock_move_granted_locks_to_front(old_locks);
2639
2640 DBUG_EXECUTE_IF("do_lock_reverse_page_reorganize",
2641 UT_LIST_REVERSE(old_locks););
2642
2643 for (auto lock : old_locks) {
2644 /* NOTE: we copy also the locks set on the infimum and
2645 supremum of the page; the infimum may carry locks if an
2646 update of a record is occurring on the page, and its locks
2647 were temporarily stored on the infimum */
2648 const rec_t *rec1 = page_get_infimum_rec(buf_block_get_frame(block));
2649 const rec_t *rec2 = page_get_infimum_rec(buf_block_get_frame(oblock));
2650
2651 /* Set locks according to old locks */
2652 for (;;) {
2653 ulint old_heap_no;
2654 ulint new_heap_no;
2655
2656 if (comp) {
2657 old_heap_no = rec_get_heap_no_new(rec2);
2658 new_heap_no = rec_get_heap_no_new(rec1);
2659
2660 rec1 = page_rec_get_next_low(rec1, true);
2661 rec2 = page_rec_get_next_low(rec2, true);
2662 } else {
2663 old_heap_no = rec_get_heap_no_old(rec2);
2664 new_heap_no = rec_get_heap_no_old(rec1);
2665 ut_ad(!memcmp(rec1, rec2, rec_get_data_size_old(rec2)));
2666
2667 rec1 = page_rec_get_next_low(rec1, false);
2668 rec2 = page_rec_get_next_low(rec2, false);
2669 }
2670
2671 /* Clear the bit in old_lock. */
2672 if (old_heap_no < lock->rec_lock.n_bits &&
2673 lock_rec_reset_nth_bit(lock, old_heap_no)) {
2674 /* NOTE that the old lock bitmap could be too
2675 small for the new heap number! */
2676
2677 lock_rec_add_to_queue(lock->type_mode, block, new_heap_no,
2678 lock->index, lock->trx);
2679 }
2680
2681 if (new_heap_no == PAGE_HEAP_NO_SUPREMUM) {
2682 ut_ad(old_heap_no == PAGE_HEAP_NO_SUPREMUM);
2683 break;
2684 }
2685 }
2686
2687 ut_ad(lock_rec_find_set_bit(lock) == ULINT_UNDEFINED);
2688 }
2689 } /* Shard_latch_guard */
2690
2691 mem_heap_free(heap);
2692
2693 #ifdef UNIV_DEBUG_LOCK_VALIDATE
2694 ut_d(lock_rec_validate_page(block));
2695 #endif /* UNIV_DEBUG_LOCK_VALIDATE */
2696 }
2697
2698 /** Moves the explicit locks on user records to another page if a record
2699 list end is moved to another page.
2700 @param[in] new_block Index page to move to
2701 @param[in] block Index page
2702 @param[in,out] rec Record on page: this is the first record moved */
2703 void lock_move_rec_list_end(const buf_block_t *new_block,
2704 const buf_block_t *block, const rec_t *rec) {
2705 const auto comp = page_rec_is_comp(rec);
2706
2707 ut_ad(buf_block_get_frame(block) == page_align(rec));
2708 ut_ad(comp == page_is_comp(buf_block_get_frame(new_block)));
2709
2710 {
2711 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *block, *new_block};
2712 lock_sys->rec_hash.find_on_block(block, [&](lock_t *lock) {
2713 const rec_t *rec1 = rec;
2714 const rec_t *rec2;
2715 const ulint type_mode = lock->type_mode;
2716
2717 if (comp) {
2718 if (page_offset(rec1) == PAGE_NEW_INFIMUM) {
2719 rec1 = page_rec_get_next_low(rec1, true);
2720 }
2721
2722 rec2 = page_rec_get_next_low(
2723 buf_block_get_frame(new_block) + PAGE_NEW_INFIMUM, true);
2724 } else {
2725 if (page_offset(rec1) == PAGE_OLD_INFIMUM) {
2726 rec1 = page_rec_get_next_low(rec1, false);
2727 }
2728
2729 rec2 = page_rec_get_next_low(
2730 buf_block_get_frame(new_block) + PAGE_OLD_INFIMUM, false);
2731 }
2732
2733 /* Copy lock requests on user records to new page and
2734 reset the lock bits on the old */
2735
2736 for (;;) {
2737 ulint rec1_heap_no;
2738 ulint rec2_heap_no;
2739
2740 if (comp) {
2741 rec1_heap_no = rec_get_heap_no_new(rec1);
2742
2743 if (rec1_heap_no == PAGE_HEAP_NO_SUPREMUM) {
2744 break;
2745 }
2746
2747 rec2_heap_no = rec_get_heap_no_new(rec2);
2748 rec1 = page_rec_get_next_low(rec1, true);
2749 rec2 = page_rec_get_next_low(rec2, true);
2750 } else {
2751 rec1_heap_no = rec_get_heap_no_old(rec1);
2752
2753 if (rec1_heap_no == PAGE_HEAP_NO_SUPREMUM) {
2754 break;
2755 }
2756
2757 rec2_heap_no = rec_get_heap_no_old(rec2);
2758
2759 ut_ad(!memcmp(rec1, rec2, rec_get_data_size_old(rec2)));
2760
2761 rec1 = page_rec_get_next_low(rec1, false);
2762 rec2 = page_rec_get_next_low(rec2, false);
2763 }
2764
2765 if (rec1_heap_no < lock->rec_lock.n_bits &&
2766 lock_rec_clear_request_no_wakeup(lock, rec1_heap_no)) {
2767 lock_rec_add_to_queue(type_mode, new_block, rec2_heap_no, lock->index,
2768 lock->trx);
2769 }
2770 }
2771 return false;
2772 });
2773 } /* Shard_latches_guard */
2774
2775 #ifdef UNIV_DEBUG_LOCK_VALIDATE
2776 ut_d(lock_rec_validate_page(block));
2777 ut_d(lock_rec_validate_page(new_block));
2778 #endif /* UNIV_DEBUG_LOCK_VALIDATE */
2779 }
2780
2781 /** Moves the explicit locks on user records to another page if a record
2782 list start is moved to another page.
2783 @param[in] new_block Index page to move to
2784 @param[in] block Index page
2785 @param[in,out] rec Record on page: this is the first record not copied
2786 @param[in] old_end Old previous-to-last record on new_page before the records
2787 were copied */
2788 void lock_move_rec_list_start(const buf_block_t *new_block,
2789 const buf_block_t *block, const rec_t *rec,
2790 const rec_t *old_end) {
2791 const auto comp = page_rec_is_comp(rec);
2792
2793 ut_ad(block->frame == page_align(rec));
2794 ut_ad(new_block->frame == page_align(old_end));
2795 ut_ad(comp == page_rec_is_comp(old_end));
2796
2797 {
2798 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *block, *new_block};
2799 lock_sys->rec_hash.find_on_block(block, [&](lock_t *lock) {
2800 const rec_t *rec1;
2801 const rec_t *rec2;
2802 const ulint type_mode = lock->type_mode;
2803
2804 if (comp) {
2805 rec1 = page_rec_get_next_low(
2806 buf_block_get_frame(block) + PAGE_NEW_INFIMUM, true);
2807 rec2 = page_rec_get_next_low(old_end, true);
2808 } else {
2809 rec1 = page_rec_get_next_low(
2810 buf_block_get_frame(block) + PAGE_OLD_INFIMUM, false);
2811 rec2 = page_rec_get_next_low(old_end, false);
2812 }
2813
2814 /* Copy lock requests on user records to new page and
2815 reset the lock bits on the old */
2816
2817 while (rec1 != rec) {
2818 ulint rec1_heap_no;
2819 ulint rec2_heap_no;
2820
2821 if (comp) {
2822 rec1_heap_no = rec_get_heap_no_new(rec1);
2823 rec2_heap_no = rec_get_heap_no_new(rec2);
2824
2825 rec1 = page_rec_get_next_low(rec1, true);
2826 rec2 = page_rec_get_next_low(rec2, true);
2827 } else {
2828 rec1_heap_no = rec_get_heap_no_old(rec1);
2829 rec2_heap_no = rec_get_heap_no_old(rec2);
2830
2831 ut_ad(!memcmp(rec1, rec2, rec_get_data_size_old(rec2)));
2832
2833 rec1 = page_rec_get_next_low(rec1, false);
2834 rec2 = page_rec_get_next_low(rec2, false);
2835 }
2836
2837 if (rec1_heap_no < lock->rec_lock.n_bits &&
2838 lock_rec_clear_request_no_wakeup(lock, rec1_heap_no)) {
2839 lock_rec_add_to_queue(type_mode, new_block, rec2_heap_no, lock->index,
2840 lock->trx);
2841 }
2842 }
2843
2844 #ifdef UNIV_DEBUG
2845 if (page_rec_is_supremum(rec)) {
2846 ulint i;
2847
2848 for (i = PAGE_HEAP_NO_USER_LOW; i < lock_rec_get_n_bits(lock); i++) {
2849 ut_a(!lock_rec_get_nth_bit(lock, i));
2850 }
2851 }
2852 #endif /* UNIV_DEBUG */
2853 return false;
2854 });
2855 } /* Shard_latches_guard */
2856
2857 #ifdef UNIV_DEBUG_LOCK_VALIDATE
2858 ut_d(lock_rec_validate_page(block));
2859 #endif /* UNIV_DEBUG_LOCK_VALIDATE */
2860 }
2861
2862 /** Moves the explicit locks on user records to another page if a record
2863 list start is moved to another page.
2864 @param[in] new_block Index page to move to
2865 @param[in] block Index page
2866 @param[in] rec_move Recording records moved
2867 @param[in] num_move Num of rec to move */
2868 void lock_rtr_move_rec_list(const buf_block_t *new_block,
2869 const buf_block_t *block, rtr_rec_move_t *rec_move,
2870 ulint num_move) {
2871 if (!num_move) {
2872 return;
2873 }
2874
2875 auto comp = page_rec_is_comp(rec_move[0].old_rec);
2876
2877 ut_ad(block->frame == page_align(rec_move[0].old_rec));
2878 ut_ad(new_block->frame == page_align(rec_move[0].new_rec));
2879 ut_ad(comp == page_rec_is_comp(rec_move[0].new_rec));
2880
2881 {
2882 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *new_block, *block};
2883 lock_sys->rec_hash.find_on_block(block, [&](lock_t *lock) {
2884 ulint moved = 0;
2885 const rec_t *rec1;
2886 const rec_t *rec2;
2887 const ulint type_mode = lock->type_mode;
2888
2889 /* Copy lock requests on user records to new page and
2890 reset the lock bits on the old */
2891
2892 while (moved < num_move) {
2893 ulint rec1_heap_no;
2894 ulint rec2_heap_no;
2895
2896 rec1 = rec_move[moved].old_rec;
2897 rec2 = rec_move[moved].new_rec;
2898
2899 if (comp) {
2900 rec1_heap_no = rec_get_heap_no_new(rec1);
2901 rec2_heap_no = rec_get_heap_no_new(rec2);
2902
2903 } else {
2904 rec1_heap_no = rec_get_heap_no_old(rec1);
2905 rec2_heap_no = rec_get_heap_no_old(rec2);
2906
2907 ut_ad(!memcmp(rec1, rec2, rec_get_data_size_old(rec2)));
2908 }
2909
2910 if (rec1_heap_no < lock->rec_lock.n_bits &&
2911 lock_rec_clear_request_no_wakeup(lock, rec1_heap_no)) {
2912 lock_rec_add_to_queue(type_mode, new_block, rec2_heap_no, lock->index,
2913 lock->trx);
2914
2915 rec_move[moved].moved = true;
2916 }
2917
2918 moved++;
2919 }
2920 return false;
2921 });
2922 } /* Shard_latches_guard */
2923
2924 #ifdef UNIV_DEBUG_LOCK_VALIDATE
2925 ut_d(lock_rec_validate_page(block));
2926 #endif
2927 }
2928
2929 /** Updates the lock table when a page is split to the right.
2930 @param[in] right_block Right page
2931 @param[in] left_block Left page */
2932 void lock_update_split_right(const buf_block_t *right_block,
2933 const buf_block_t *left_block) {
2934 const auto heap_no = lock_get_min_heap_no(right_block);
2935
2936 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *left_block,
2937 *right_block};
2938
2939 /* Move the locks on the supremum of the left page to the supremum
2940 of the right page */
2941
2942 lock_rec_move(right_block, left_block, PAGE_HEAP_NO_SUPREMUM,
2943 PAGE_HEAP_NO_SUPREMUM);
2944
2945 /* Inherit the locks to the supremum of left page from the successor
2946 of the infimum on right page */
2947
2948 lock_rec_inherit_to_gap(left_block, right_block, PAGE_HEAP_NO_SUPREMUM,
2949 heap_no);
2950 }
2951
2952 /** Updates the lock table when a page is merged to the right.
2953 @param[in] right_block Right page to which merged
2954 @param[in] orig_succ Original successor of infimum on the right page before
2955 merge
2956 @param[in] left_block Merged index page which will be discarded */
2957 void lock_update_merge_right(const buf_block_t *right_block,
2958 const rec_t *orig_succ,
2959 const buf_block_t *left_block) {
2960 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *left_block,
2961 *right_block};
2962
2963 /* Inherit the locks from the supremum of the left page to the original
2964 successor of infimum on the right page, to which the left page was merged. */
2965
2966 lock_rec_inherit_to_gap(right_block, left_block,
2967 page_rec_get_heap_no(orig_succ),
2968 PAGE_HEAP_NO_SUPREMUM);
2969
2970 /* Reset the locks on the supremum of the left page, releasing waiting
2971 transactions. */
2972
2973 lock_rec_reset_and_release_wait_low(lock_sys->rec_hash, left_block,
2974 PAGE_HEAP_NO_SUPREMUM);
2975
2976 /* There should exist no page lock on the left page, otherwise, it will be
2977 blocked from merge. */
2978
2979 ut_ad(!lock_rec_has_any(lock_sys->prdt_page_hash, left_block->get_page_id()));
2980
2981 lock_rec_free_all_from_discard_page(left_block);
2982 }
2983
2984 /** Updates the lock table when the root page is copied to another in
2985 btr_root_raise_and_insert. Note that we leave lock structs on the
2986 root page, even though they do not make sense on other than leaf
2987 pages: the reason is that in a pessimistic update the infimum record
2988 of the root page will act as a dummy carrier of the locks of the record
2989 to be updated. */
2990 void lock_update_root_raise(
2991 const buf_block_t *block, /*!< in: index page to which copied */
2992 const buf_block_t *root) /*!< in: root page */
2993 {
2994 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *block, *root};
2995
2996 /* Move the locks on the supremum of the root to the supremum
2997 of block */
2998
2999 lock_rec_move(block, root, PAGE_HEAP_NO_SUPREMUM, PAGE_HEAP_NO_SUPREMUM);
3000 }
3001
3002 /** Updates the lock table when a page is copied to another and the original
3003 page is removed from the chain of leaf pages, except if page is the root!
3004 @param[in] new_block Index page to which copied
3005 @param[in] block Index page; not the root! */
3006 void lock_update_copy_and_discard(const buf_block_t *new_block,
3007 const buf_block_t *block) {
3008 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *new_block, *block};
3009
3010 /* Move the locks on the supremum of the old page to the supremum
3011 of new_page */
3012
3013 lock_rec_move(new_block, block, PAGE_HEAP_NO_SUPREMUM, PAGE_HEAP_NO_SUPREMUM);
3014 lock_rec_free_all_from_discard_page(block);
3015 }
3016
3017 void lock_update_split_point(const buf_block_t *right_block,
3018 const buf_block_t *left_block) {
3019 const auto heap_no = lock_get_min_heap_no(right_block);
3020
3021 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *left_block,
3022 *right_block};
3023
3024 /* Inherit locks from the gap before supremum of the left page to the gap
3025 before the successor of the infimum of the right page */
3026 lock_rec_inherit_to_gap(right_block, left_block, heap_no,
3027 PAGE_HEAP_NO_SUPREMUM);
3028 }
3029
3030 /** Updates the lock table when a page is split to the left.
3031 @param[in] right_block Right page
3032 @param[in] left_block Left page */
3033 void lock_update_split_left(const buf_block_t *right_block,
3034 const buf_block_t *left_block) {
3035 const auto heap_no = lock_get_min_heap_no(right_block);
3036
3037 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *left_block,
3038 *right_block};
3039
3040 /* Inherit the locks to the supremum of the left page from the
3041 successor of the infimum on the right page */
3042
3043 lock_rec_inherit_to_gap(left_block, right_block, PAGE_HEAP_NO_SUPREMUM,
3044 heap_no);
3045 }
3046
3047 /** Updates the lock table when a page is merged to the left.
3048 @param[in] left_block Left page to which merged
3049 @param[in] orig_pred Original predecessor of supremum on the left page before
3050 merge
3051 @param[in] right_block Merged index page which will be discarded */
3052 void lock_update_merge_left(const buf_block_t *left_block,
3053 const rec_t *orig_pred,
3054 const buf_block_t *right_block) {
3055 const rec_t *left_next_rec;
3056
3057 ut_ad(left_block->frame == page_align(orig_pred));
3058
3059 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *left_block,
3060 *right_block};
3061
3062 left_next_rec = page_rec_get_next_const(orig_pred);
3063
3064 if (!page_rec_is_supremum(left_next_rec)) {
3065 /* Inherit the locks on the supremum of the left page to the
3066 first record which was moved from the right page */
3067
3068 lock_rec_inherit_to_gap(left_block, left_block,
3069 page_rec_get_heap_no(left_next_rec),
3070 PAGE_HEAP_NO_SUPREMUM);
3071
3072 /* Reset the locks on the supremum of the left page,
3073 releasing waiting transactions */
3074
3075 lock_rec_reset_and_release_wait_low(lock_sys->rec_hash, left_block,
3076 PAGE_HEAP_NO_SUPREMUM);
3077 }
3078
3079 /* Move the locks from the supremum of right page to the supremum
3080 of the left page */
3081
3082 lock_rec_move(left_block, right_block, PAGE_HEAP_NO_SUPREMUM,
3083 PAGE_HEAP_NO_SUPREMUM);
3084
3085 /* there should exist no page lock on the right page,
3086 otherwise, it will be blocked from merge */
3087 ut_ad(
3088 !lock_rec_has_any(lock_sys->prdt_page_hash, right_block->get_page_id()));
3089
3090 lock_rec_free_all_from_discard_page(right_block);
3091 }
3092
3093 /** Resets the original locks on heir and replaces them with gap type locks
3094 inherited from rec.
3095 @param[in] heir_block Block containing the record which inherits
3096 @param[in] block Block containing the record from which inherited; does not
3097 reset the locks on this record
3098 @param[in] heir_heap_no Heap_no of the inheriting record
3099 @param[in] heap_no Heap_no of the donating record */
3100 void lock_rec_reset_and_inherit_gap_locks(const buf_block_t *heir_block,
3101 const buf_block_t *block,
3102 ulint heir_heap_no, ulint heap_no) {
3103 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *heir_block, *block};
3104
3105 lock_rec_reset_and_release_wait(heir_block, heir_heap_no);
3106
3107 lock_rec_inherit_to_gap(heir_block, block, heir_heap_no, heap_no);
3108 }
3109
3110 /** Updates the lock table when a page is discarded.
3111 @param[in] heir_block Index page which will inherit the locks
3112 @param[in] heir_heap_no Heap_no of the record which will inherit the locks
3113 @param[in] block Index page which will be discarded */
3114 void lock_update_discard(const buf_block_t *heir_block, ulint heir_heap_no,
3115 const buf_block_t *block) {
3116 const rec_t *rec;
3117 ulint heap_no;
3118 const page_t *page = block->frame;
3119
3120 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *heir_block, *block};
3121 const auto discarded_page_id = block->get_page_id();
3122 if (!lock_rec_has_any(lock_sys->rec_hash, discarded_page_id) &&
3123 (!lock_rec_has_any(lock_sys->prdt_page_hash, discarded_page_id)) &&
3124 (!lock_rec_has_any(lock_sys->prdt_hash, discarded_page_id))) {
3125 /* No locks exist on page, nothing to do */
3126
3127 return;
3128 }
3129
3130 /* Inherit all the locks on the page to the record and reset all
3131 the locks on the page */
3132
3133 if (page_is_comp(page)) {
3134 rec = page + PAGE_NEW_INFIMUM;
3135
3136 do {
3137 heap_no = rec_get_heap_no_new(rec);
3138
3139 lock_rec_inherit_to_gap(heir_block, block, heir_heap_no, heap_no);
3140
3141 lock_rec_reset_and_release_wait(block, heap_no);
3142
3143 rec = page + rec_get_next_offs(rec, true);
3144 } while (heap_no != PAGE_HEAP_NO_SUPREMUM);
3145 } else {
3146 rec = page + PAGE_OLD_INFIMUM;
3147
3148 do {
3149 heap_no = rec_get_heap_no_old(rec);
3150
3151 lock_rec_inherit_to_gap(heir_block, block, heir_heap_no, heap_no);
3152
3153 lock_rec_reset_and_release_wait(block, heap_no);
3154
3155 rec = page + rec_get_next_offs(rec, false);
3156 } while (heap_no != PAGE_HEAP_NO_SUPREMUM);
3157 }
3158
3159 lock_rec_free_all_from_discard_page(block);
3160 }
3161
3162 /** Updates the lock table when a new user record is inserted. */
3163 void lock_update_insert(
3164 const buf_block_t *block, /*!< in: buffer block containing rec */
3165 const rec_t *rec) /*!< in: the inserted record */
3166 {
3167 uint16_t receiver_heap_no;
3168 uint16_t donator_heap_no;
3169
3170 ut_ad(block->frame == page_align(rec));
3171
3172 /* Inherit the gap-locking locks for rec, in gap mode, from the next
3173 record */
3174
3175 if (page_rec_is_comp(rec)) {
3176 receiver_heap_no = rec_get_heap_no_new(rec);
3177 donator_heap_no = rec_get_heap_no_new(page_rec_get_next_low(rec, true));
3178 } else {
3179 receiver_heap_no = rec_get_heap_no_old(rec);
3180 donator_heap_no = rec_get_heap_no_old(page_rec_get_next_low(rec, false));
3181 }
3182
3183 lock_rec_inherit_to_gap_if_gap_lock(block, receiver_heap_no, donator_heap_no);
3184 }
3185
3186 /** Updates the lock table when a record is removed.
3187 @param[in] block Buffer block containing rec
3188 @param[in] rec The record to be removed */
3189 void lock_update_delete(const buf_block_t *block, const rec_t *rec) {
3190 const page_t *page = block->frame;
3191 ulint heap_no;
3192 ulint next_heap_no;
3193
3194 ut_ad(page == page_align(rec));
3195
3196 if (page_is_comp(page)) {
3197 heap_no = rec_get_heap_no_new(rec);
3198 next_heap_no = rec_get_heap_no_new(page + rec_get_next_offs(rec, true));
3199 } else {
3200 heap_no = rec_get_heap_no_old(rec);
3201 next_heap_no = rec_get_heap_no_old(page + rec_get_next_offs(rec, false));
3202 }
3203
3204 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
3205
3206 /* Let the next record inherit the locks from rec, in gap mode */
3207
3208 lock_rec_inherit_to_gap(block, block, next_heap_no, heap_no);
3209
3210 /* Reset the lock bits on rec and release waiting transactions */
3211
3212 lock_rec_reset_and_release_wait(block, heap_no);
3213 }
3214
3215 /** Stores on the page infimum record the explicit locks of another record.
3216 This function is used to store the lock state of a record when it is
3217 updated and the size of the record changes in the update. The record
3218 is moved in such an update, perhaps to another page. The infimum record
3219 acts as a dummy carrier record, taking care of lock releases while the
3220 actual record is being moved. */
3221 void lock_rec_store_on_page_infimum(
3222 const buf_block_t *block, /*!< in: buffer block containing rec */
3223 const rec_t *rec) /*!< in: record whose lock state
3224 is stored on the infimum
3225 record of the same page; lock
3226 bits are reset on the
3227 record */
3228 {
3229 ulint heap_no = page_rec_get_heap_no(rec);
3230
3231 ut_ad(block->frame == page_align(rec));
3232
3233 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
3234
3235 lock_rec_move(block, block, PAGE_HEAP_NO_INFIMUM, heap_no);
3236 }
3237
3238 /** Restores the state of explicit lock requests on a single record, where the
3239 state was stored on the infimum of the page.
3240 @param[in] block Buffer block containing rec
3241 @param[in] rec Record whose lock state is restored
3242 @param[in] donator Page (rec is not necessarily on this page) whose infimum
3243 stored the lock state; lock bits are reset on the infimum */
3244 void lock_rec_restore_from_page_infimum(const buf_block_t *block,
3245 const rec_t *rec,
3246 const buf_block_t *donator) {
3247 DEBUG_SYNC_C("lock_rec_restore_from_page_infimum_will_latch");
3248 ulint heap_no = page_rec_get_heap_no(rec);
3249
3250 locksys::Shard_latches_guard guard{UT_LOCATION_HERE, *block, *donator};
3251
3252 lock_rec_move(block, donator, heap_no, PAGE_HEAP_NO_INFIMUM);
3253 }
3254
3255 /*========================= TABLE LOCKS ==============================*/
3256
3257 /** Creates a table lock object and adds it as the last in the lock queue
3258 of the table. Does NOT check for deadlocks or lock compatibility.
3259 @return own: new lock object */
3260 static inline lock_t *lock_table_create(
3261 dict_table_t *table, /*!< in/out: database table
3262 in dictionary cache */
3263 ulint type_mode, /*!< in: lock mode possibly ORed with
3264 LOCK_WAIT */
3265 trx_t *trx) /*!< in: trx */
3266 {
3267 lock_t *lock;
3268
3269 ut_ad(table && trx);
3270 ut_ad(locksys::owns_table_shard(*table));
3271 ut_ad(trx_mutex_own(trx));
3272 ut_ad(trx_can_be_handled_by_current_thread(trx));
3273
3274 check_trx_state(trx);
3275 ++table->count_by_mode[type_mode & LOCK_MODE_MASK];
3276 /* For AUTOINC locking we reuse the lock instance only if
3277 there is no wait involved else we allocate the waiting lock
3278 from the transaction lock heap. */
3279 if (type_mode == LOCK_AUTO_INC) {
3280 lock = table->autoinc_lock;
3281 ut_ad(table->autoinc_trx == nullptr);
3282 table->autoinc_trx = trx;
3283
3284 ib_vector_push(trx->lock.autoinc_locks, &lock);
3285
3286 } else if (trx->lock.table_cached < trx->lock.table_pool.size()) {
3287 lock = trx->lock.table_pool[trx->lock.table_cached++];
3288 } else {
3289 lock = lock_alloc_from_heap(trx->lock.lock_heap);
3290 }
3291 lock->type_mode = uint32_t(type_mode | LOCK_TABLE);
3292 lock->trx = trx;
3293 ut_d(lock->m_seq = lock_sys->m_seq.fetch_add(1));
3294
3295 lock->tab_lock.table = table;
3296
3297 ut_ad(table->n_ref_count > 0 || !table->can_be_evicted);
3298
3299 #ifdef HAVE_PSI_THREAD_INTERFACE
3300 #ifdef HAVE_PSI_DATA_LOCK_INTERFACE
3301 /* The performance schema THREAD_ID and EVENT_ID
3302 are used only when DATA_LOCKS are exposed. */
3303 PSI_THREAD_CALL(get_current_thread_event_id)
3304 (&lock->m_psi_internal_thread_id, &lock->m_psi_event_id);
3305 #endif /* HAVE_PSI_DATA_LOCK_INTERFACE */
3306 #endif /* HAVE_PSI_THREAD_INTERFACE */
3307
3308 locksys::add_to_trx_locks(lock);
3309
3310 ut_list_append(table->locks, lock);
3311
3312 if (type_mode & LOCK_WAIT) {
3313 lock_set_lock_and_trx_wait(lock);
3314 }
3315
3316 MONITOR_INC(MONITOR_TABLELOCK_CREATED);
3317 MONITOR_INC(MONITOR_NUM_TABLELOCK);
3318
3319 return (lock);
3320 }
3321
3322 /** Pops autoinc lock requests from the transaction's autoinc_locks. We
3323 handle the case where there are gaps in the array and they need to
3324 be popped off the stack. */
3325 static inline void lock_table_pop_autoinc_locks(
3326 trx_t *trx) /*!< in/out: transaction that owns the AUTOINC locks */
3327 {
3328 /* We will access and modify trx->lock.autoinc_locks so we need trx->mutex */
3329 ut_ad(trx_mutex_own(trx));
3330 ut_ad(!ib_vector_is_empty(trx->lock.autoinc_locks));
3331
3332 /* Skip any gaps, gaps are NULL lock entries in the
3333 trx->autoinc_locks vector. */
3334
3335 do {
3336 ib_vector_pop(trx->lock.autoinc_locks);
3337
3338 if (ib_vector_is_empty(trx->lock.autoinc_locks)) {
3339 return;
3340 }
3341
3342 } while (*(lock_t **)ib_vector_get_last(trx->lock.autoinc_locks) == nullptr);
3343 }
3344
3345 /** Removes an autoinc lock request from the transaction's autoinc_locks. */
3346 static inline void lock_table_remove_autoinc_lock(
3347 lock_t *lock, /*!< in: table lock */
3348 trx_t *trx) /*!< in/out: transaction that owns the lock */
3349 {
3350 /* We will access and modify trx->lock.autoinc_locks so we need trx->mutex */
3351 ut_ad(trx_mutex_own(trx));
3352 lock_t *autoinc_lock;
3353 lint i = ib_vector_size(trx->lock.autoinc_locks) - 1;
3354
3355 ut_ad(lock_get_mode(lock) == LOCK_AUTO_INC);
3356 ut_ad(lock_get_type_low(lock) & LOCK_TABLE);
3357 ut_ad(locksys::owns_table_shard(*lock->tab_lock.table));
3358 ut_ad(!ib_vector_is_empty(trx->lock.autoinc_locks));
3359
3360 /* With stored functions and procedures the user may drop
3361 a table within the same "statement". This special case has
3362 to be handled by deleting only those AUTOINC locks that were
3363 held by the table being dropped. */
3364
3365 autoinc_lock =
3366 *static_cast<lock_t **>(ib_vector_get(trx->lock.autoinc_locks, i));
3367
3368 /* This is the default fast case. */
3369
3370 if (autoinc_lock == lock) {
3371 lock_table_pop_autoinc_locks(trx);
3372 } else {
3373 /* The last element should never be NULL */
3374 ut_a(autoinc_lock != nullptr);
3375
3376 /* Handle freeing the locks from within the stack. */
3377
3378 while (--i >= 0) {
3379 autoinc_lock =
3380 *static_cast<lock_t **>(ib_vector_get(trx->lock.autoinc_locks, i));
3381
3382 if (autoinc_lock == lock) {
3383 void *null_var = nullptr;
3384 ib_vector_set(trx->lock.autoinc_locks, i, &null_var);
3385 return;
3386 }
3387 }
3388
3389 /* Must find the autoinc lock. */
3390 ut_error;
3391 }
3392 }
3393
3394 lock_guid_t::lock_guid_t(const lock_t &lock)
3395 : m_trx_guid(*(lock.trx)),
3396 m_immutable_id(reinterpret_cast<uint64_t>(&lock)) {}
3397
3398 /** Removes a table lock request from the queue and the trx list of locks;
3399 this is a low-level function which does NOT check if waiting requests
3400 can now be granted. */
3401 static inline void lock_table_remove_low(
3402 lock_t *lock) /*!< in/out: table lock */
3403 {
3404 trx_t *trx;
3405 dict_table_t *table;
3406
3407 trx = lock->trx;
3408 /* We will modify trx->lock.trx_locks so we need trx->mutex */
3409 ut_ad(trx_mutex_own(trx));
3410 table = lock->tab_lock.table;
3411 ut_ad(locksys::owns_table_shard(*table));
3412 const auto lock_mode = lock_get_mode(lock);
3413 /* Remove the table from the transaction's AUTOINC vector, if
3414 the lock that is being released is an AUTOINC lock. */
3415 if (lock_mode == LOCK_AUTO_INC) {
3416 /* The table's AUTOINC lock could not be granted to us yet. */
3417 ut_ad(table->autoinc_trx == trx || lock->is_waiting());
3418 if (table->autoinc_trx == trx) {
3419 table->autoinc_trx = nullptr;
3420 }
3421
3422 /* The locks must be freed in the reverse order from
3423 the one in which they were acquired. This is to avoid
3424 traversing the AUTOINC lock vector unnecessarily.
3425
3426 We only store locks that were granted in the
3427 trx->autoinc_locks vector (see lock_table_create()
3428 and lock_grant()). */
3429
3430 if (!lock_get_wait(lock)) {
3431 lock_table_remove_autoinc_lock(lock, trx);
3432 }
3433 }
3434 ut_a(0 < table->count_by_mode[lock_mode]);
3435 --table->count_by_mode[lock_mode];
3436
3437 locksys::remove_from_trx_locks(lock);
3438
3439 ut_list_remove(table->locks, lock);
3440
3441 MONITOR_INC(MONITOR_TABLELOCK_REMOVED);
3442 MONITOR_DEC(MONITOR_NUM_TABLELOCK);
3443 }
3444
3445 /** Enqueues a waiting request for a table lock which cannot be granted
3446 immediately. Checks for deadlocks.
3447 @param[in] mode lock mode this transaction is requesting
3448 @param[in] table the table to be locked
3449 @param[in] thr the query thread requesting the lock
3450 @param[in] blocking_lock the lock which is the reason this request has to wait
3451 @return DB_LOCK_WAIT or DB_DEADLOCK */
3452 static dberr_t lock_table_enqueue_waiting(ulint mode, dict_table_t *table,
3453 que_thr_t *thr,
3454 const lock_t *blocking_lock) {
3455 trx_t *trx;
3456
3457 ut_ad(locksys::owns_table_shard(*table));
3458 ut_ad(!srv_read_only_mode);
3459
3460 trx = thr_get_trx(thr);
3461 ut_ad(trx_mutex_own(trx));
3462
3463 /* Test if there already is some other reason to suspend thread:
3464 we do not enqueue a lock request if the query thread should be
3465 stopped anyway */
3466
3467 if (que_thr_stop(thr)) {
3468 ut_error;
3469 }
3470
3471 switch (trx_get_dict_operation(trx)) {
3472 case TRX_DICT_OP_NONE:
3473 break;
3474 case TRX_DICT_OP_TABLE:
3475 case TRX_DICT_OP_INDEX:
3476 ib::error(ER_IB_MSG_642) << "A table lock wait happens in a dictionary"
3477 " operation. Table "
3478 << table->name << ". " << BUG_REPORT_MSG;
3479 ut_d(ut_error);
3480 }
3481
3482 if (trx->in_innodb & TRX_FORCE_ROLLBACK) {
3483 return (DB_DEADLOCK);
3484 }
3485
3486 /* Enqueue the lock request that will wait to be granted */
3487 lock_t *lock = lock_table_create(table, mode | LOCK_WAIT, trx);
3488
3489 trx->lock.que_state = TRX_QUE_LOCK_WAIT;
3490
3491 trx->lock.wait_started =
3492 std::chrono::system_clock::from_time_t(time(nullptr));
3493 trx->lock.was_chosen_as_deadlock_victim = false;
3494
3495 auto stopped = que_thr_stop(thr);
3496 ut_a(stopped);
3497
3498 MONITOR_INC(MONITOR_TABLELOCK_WAIT);
3499 lock_create_wait_for_edge(lock, blocking_lock);
3500 return (DB_LOCK_WAIT);
3501 }
3502
3503 /** Checks if other transactions have an incompatible mode lock request in
3504 the lock queue.
3505 @return lock or NULL */
3506 static inline const lock_t *lock_table_other_has_incompatible(
3507 const trx_t *trx, /*!< in: transaction, or NULL if all
3508 transactions should be included */
3509 ulint wait, /*!< in: LOCK_WAIT if also
3510 waiting locks are taken into
3511 account, or 0 if not */
3512 const dict_table_t *table, /*!< in: table */
3513 lock_mode mode) /*!< in: lock mode */
3514 {
3515 const lock_t *lock;
3516
3517 ut_ad(locksys::owns_table_shard(*table));
3518
3519 // According to lock_compatibility_matrix, an intention lock can wait only
3520 // for LOCK_S or LOCK_X. If there are no LOCK_S nor LOCK_X locks in the queue,
3521 // then we can avoid iterating through the list and return immediately.
3522 // This might help in OLTP scenarios, with no DDL queries,
3523 // as then there are almost no LOCK_S nor LOCK_X, but many DML queries still
3524 // need to get an intention lock to perform their action - while this never
3525 // causes them to wait for a "data lock", it might cause them to wait for
3526 // lock_sys table shard latch for the duration of table lock queue operation.
3527
3528 if ((mode == LOCK_IS || mode == LOCK_IX) &&
3529 table->count_by_mode[LOCK_S] == 0 && table->count_by_mode[LOCK_X] == 0) {
3530 return nullptr;
3531 }
3532
3533 for (lock = UT_LIST_GET_LAST(table->locks); lock != nullptr;
3534 lock = UT_LIST_GET_PREV(tab_lock.locks, lock)) {
3535 if (lock->trx != trx && !lock_mode_compatible(lock_get_mode(lock), mode) &&
3536 (wait || !lock_get_wait(lock))) {
3537 return (lock);
3538 }
3539 }
3540
3541 return (nullptr);
3542 }
3543
3544 /** Locks the specified database table in the mode given. If the lock cannot
3545 be granted immediately, the query thread is put to wait.
3546 @return DB_SUCCESS, DB_LOCK_WAIT, or DB_DEADLOCK */
3547 dberr_t lock_table(ulint flags, /*!< in: if BTR_NO_LOCKING_FLAG bit is set,
3548 does nothing */
3549 dict_table_t *table, /*!< in/out: database table
3550 in dictionary cache */
3551 lock_mode mode, /*!< in: lock mode */
3552 que_thr_t *thr) /*!< in: query thread */
3553 {
3554 trx_t *trx;
3555 dberr_t err;
3556 const lock_t *wait_for;
3557
3558 ut_ad(table && thr);
3559
3560 /* Given limited visibility of temp-table we can avoid
3561 locking overhead */
3562 if ((flags & BTR_NO_LOCKING_FLAG) || srv_read_only_mode ||
3563 table->is_temporary()) {
3564 return (DB_SUCCESS);
3565 }
3566
3567 ut_a(flags == 0);
3568
3569 trx = thr_get_trx(thr);
3570
3571 /* Look for equal or stronger locks the same trx already has on the table.
3572 Even though lock_table_has() takes trx->mutex internally, it does not protect
3573 us at all from "higher-level" races - for instance the state could change in
3574 theory after we exit lock_table_has() and before we return DB_SUCCESS, or
3575 before somebody who called us reacts to the DB_SUCCESS.
3576 In theory table locks can be modified in:
3577 lock_release_autoinc_last_lock
3578 lock_release_autoinc_locks
3579 lock_cancel_waiting_and_release
3580 (this one seems to be called only when trx is waiting and not running)
3581 lock_unlock_table_autoinc
3582 (this one seems to be called from the thread running the transaction)
3583 lock_remove_all_on_table_for_trx
3584 lock_remove_all_on_table
3585 row_drop_table_for_mysql
3586 (this one is mysterious, as it is not obvious to me why do we expect
3587 that someone will drop a table while there are locks on it)
3588 row_mysql_table_id_reassign
3589 row_discard_tablespace
3590 (there is some long explanation starting with "How do we prevent
3591 crashes caused by ongoing operations...")
3592 lock_remove_recovered_trx_record_locks
3593 (this seems to be used to remove locks of recovered transactions from
3594 table being dropped, and recovered transactions shouldn't call lock_table)
3595 Also the InnoDB Memcached plugin causes a callchain:
3596 innodb_store -> innodb_conn_init -> innodb_api_begin -> innodb_cb_cursor_lock
3597 -> ib_cursor_set_lock_mode -> ib_cursor_lock -> ib_trx_lock_table_with_retry
3598 -> lock_table_for_trx -> lock_table -> lock_table_has
3599 in which lock_table_has sees trx->mysqld_thd different than current_thd.
3600 In practice this call to lock_table_has was never protected in any way before,
3601 so the situation now, after protecting it with trx->mutex, can't be worse. */
3602
3603 if (lock_table_has(trx, table, mode)) {
3604 /* In Debug mode we assert the same condition again, to help catch cases of
3605 race condition, if it is possible at all, for further analysis. */
3606 ut_ad(lock_table_has(trx, table, mode));
3607 return (DB_SUCCESS);
3608 }
3609
3610 /* Read only transactions can write to temp tables, we don't want
3611 to promote them to RW transactions. Their updates cannot be visible
3612 to other transactions. Therefore we can keep them out
3613 of the read views. */
3614
3615 if ((mode == LOCK_IX || mode == LOCK_X) && !trx->read_only &&
3616 trx->rsegs.m_redo.rseg == nullptr) {
3617 trx_set_rw_mode(trx);
3618 }
3619
3620 locksys::Shard_latch_guard table_latch_guard{UT_LOCATION_HERE, *table};
3621
3622 /* We have to check if the new lock is compatible with any locks
3623 other transactions have in the table lock queue. */
3624
3625 wait_for = lock_table_other_has_incompatible(trx, LOCK_WAIT, table, mode);
3626
3627 trx_mutex_enter(trx);
3628
3629 /* Another trx has a request on the table in an incompatible
3630 mode: this trx may have to wait */
3631
3632 if (wait_for != nullptr) {
3633 err = lock_table_enqueue_waiting(mode | flags, table, thr, wait_for);
3634 } else {
3635 lock_table_create(table, mode | flags, trx);
3636
3637 ut_a(!flags || mode == LOCK_S || mode == LOCK_X);
3638
3639 err = DB_SUCCESS;
3640 }
3641
3642 trx_mutex_exit(trx);
3643
3644 ut_ad(err == DB_SUCCESS || err == DB_LOCK_WAIT || err == DB_DEADLOCK);
3645 return (err);
3646 }
3647
3648 /** Creates a table IX lock object for a resurrected transaction.
3649 @param[in,out] table Table
3650 @param[in,out] trx Transaction */
3651 void lock_table_ix_resurrect(dict_table_t *table, trx_t *trx) {
3652 ut_ad(trx->is_recovered);
3653
3654 if (lock_table_has(trx, table, LOCK_IX)) {
3655 return;
3656 }
3657 locksys::Shard_latch_guard table_latch_guard{UT_LOCATION_HERE, *table};
3658 /* We have to check if the new lock is compatible with any locks
3659 other transactions have in the table lock queue. */
3660
3661 ut_ad(!lock_table_other_has_incompatible(trx, LOCK_WAIT, table, LOCK_IX));
3662
3663 trx_mutex_enter(trx);
3664 lock_table_create(table, LOCK_IX, trx);
3665 trx_mutex_exit(trx);
3666 }
3667
3668 /** Checks if a waiting table lock request still has to wait in a queue.
3669 @param[in] wait_lock Waiting table lock
3670 @param[in] blocking_trx If not nullptr, it restricts the search to only the
3671 locks held by the blocking_trx, which is useful in
3672 case when there might be multiple reasons for waiting
3673 in queue, but we need to report the specific one.
3674 Useful when reporting a deadlock cycle. (optional)
3675 @return The conflicting lock which is the reason wait_lock has to wait
3676 or nullptr if it can be granted now */
3677 static const lock_t *lock_table_has_to_wait_in_queue(
3678 const lock_t *wait_lock, const trx_t *blocking_trx = nullptr) {
3679 const dict_table_t *table;
3680
3681 ut_ad(lock_get_wait(wait_lock));
3682
3683 table = wait_lock->tab_lock.table;
3684 ut_ad(locksys::owns_table_shard(*table));
3685
3686 const auto mode = lock_get_mode(wait_lock);
3687
3688 // According to lock_compatibility_matrix, an intention lock can wait only
3689 // for LOCK_S or LOCK_X. If there are no LOCK_S nor LOCK_X locks in the queue,
3690 // then we can avoid iterating through the list and return immediately.
3691 // This might help in OLTP scenarios, with no DDL queries,
3692 // as then there are almost no LOCK_S nor LOCK_X, but many DML queries still
3693 // need to get an intention lock to perform their action. When an occasional
3694 // DDL finishes and releases the LOCK_S or LOCK_X, it has to scan the queue
3695 // and grant any locks which were blocked by it. This can take Omega(n^2) if
3696 // each of intention locks has to verify that all the other locks.
3697
3698 if ((mode == LOCK_IS || mode == LOCK_IX) &&
3699 table->count_by_mode[LOCK_S] == 0 && table->count_by_mode[LOCK_X] == 0) {
3700 return (nullptr);
3701 }
3702 for (auto lock : table->locks) {
3703 if (lock == wait_lock) break;
3704 if ((blocking_trx == nullptr || blocking_trx == lock->trx) &&
3705 lock_has_to_wait(wait_lock, lock)) {
3706 return (lock);
3707 }
3708 }
3709
3710 return (nullptr);
3711 }
3712
3713 /** Checks if a waiting lock request still has to wait in a queue.
3714 @param[in] wait_lock Waiting lock
3715 @param[in] blocking_trx If not nullptr, it restricts the search to only the
3716 locks held by the blocking_trx, which is useful in
3717 case when there might be multiple reasons for waiting
3718 in queue, but we need to report the specific one.
3719 Useful when reporting a deadlock cycle.
3720 @return The conflicting lock which is the reason wait_lock has to wait
3721 or nullptr if it can be granted now */
3722 static const lock_t *lock_has_to_wait_in_queue(const lock_t *wait_lock,
3723 const trx_t *blocking_trx) {
3724 if (lock_get_type_low(wait_lock) == LOCK_REC) {
3725 return lock_rec_has_to_wait_in_queue(wait_lock, blocking_trx);
3726 } else {
3727 return lock_table_has_to_wait_in_queue(wait_lock, blocking_trx);
3728 }
3729 }
3730
3731 /** Removes a table lock request, waiting or granted, from the queue and grants
3732 locks to other transactions in the queue, if they now are entitled to a
3733 lock. */
3734 static void lock_table_dequeue(
3735 lock_t *in_lock) /*!< in/out: table lock object; transactions waiting
3736 behind will get their lock requests granted, if
3737 they are now qualified to it */
3738 {
3739 /* This is needed for lock_table_remove_low(), but it's easier to understand
3740 the code if we assert it here as well */
3741 ut_ad(trx_mutex_own(in_lock->trx));
3742 ut_ad(locksys::owns_table_shard(*in_lock->tab_lock.table));
3743 ut_a(lock_get_type_low(in_lock) == LOCK_TABLE);
3744
3745 const auto mode = lock_get_mode(in_lock);
3746 const auto table = in_lock->tab_lock.table;
3747
3748 lock_t *lock = UT_LIST_GET_NEXT(tab_lock.locks, in_lock);
3749 /* This call can remove the last lock on the table, in which case it's unsafe
3750 to access the table object in the code below, because it can get freed as soon
3751 as the last lock on it is removed (@see lock_table_has_locks). */
3752 lock_table_remove_low(in_lock);
3753
3754 // According to lock_compatibility_matrix, an intention lock can block only
3755 // LOCK_S or LOCK_X from being granted, and thus, releasing of an intention
3756 // lock can help in granting only LOCK_S or LOCK_X. If there are no LOCK_S nor
3757 // LOCK_X locks in the queue, then we can avoid iterating through the list and
3758 // return immediately. This might help in OLTP scenarios, with no DDL queries,
3759 // as then there are almost no LOCK_S nor LOCK_X, but many DML queries still
3760 // need to get an intention lock to perform their action - while this never
3761 // causes them to wait for a "data lock", it might cause them to wait for
3762 // lock_sys table shard latch for the duration of table lock queue operation.
3763 if (!lock || ((mode == LOCK_IS || mode == LOCK_IX) &&
3764 table->count_by_mode[LOCK_S] == 0 &&
3765 table->count_by_mode[LOCK_X] == 0)) {
3766 return;
3767 }
3768
3769 /* Check if waiting locks in the queue can now be granted: grant
3770 locks if there are no conflicting locks ahead. */
3771
3772 for (/* No op */; lock != nullptr;
3773 lock = UT_LIST_GET_NEXT(tab_lock.locks, lock)) {
3774 lock_grant_or_update_wait_for_edge_if_waiting(lock, in_lock->trx);
3775 }
3776 }
3777
3778 /** Sets a lock on a table based on the given mode.
3779 @param[in] table table to lock
3780 @param[in,out] trx transaction
3781 @param[in] mode LOCK_X or LOCK_S
3782 @return error code or DB_SUCCESS. */
3783 dberr_t lock_table_for_trx(dict_table_t *table, trx_t *trx,
3784 enum lock_mode mode) {
3785 mem_heap_t *heap;
3786 que_thr_t *thr;
3787 dberr_t err;
3788 sel_node_t *node;
3789 heap = mem_heap_create(512, UT_LOCATION_HERE);
3790
3791 node = sel_node_create(heap);
3792 thr = pars_complete_graph_for_exec(node, trx, heap, nullptr);
3793 thr->graph->state = QUE_FORK_ACTIVE;
3794
3795 /* We use the select query graph as the dummy graph needed
3796 in the lock module call */
3797
3798 thr = static_cast<que_thr_t *>(que_fork_get_first_thr(
3799 static_cast<que_fork_t *>(que_node_get_parent(thr))));
3800
3801 que_thr_move_to_run_state_for_mysql(thr, trx);
3802
3803 run_again:
3804 thr->run_node = thr;
3805 thr->prev_node = thr->common.parent;
3806
3807 err = lock_table(0, table, mode, thr);
3808
3809 trx->error_state = err;
3810
3811 if (err == DB_SUCCESS) {
3812 que_thr_stop_for_mysql_no_error(thr, trx);
3813 } else {
3814 que_thr_stop_for_mysql(thr);
3815
3816 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, nullptr);
3817
3818 if (was_lock_wait) {
3819 goto run_again;
3820 }
3821 }
3822
3823 que_graph_free(thr->graph);
3824 trx->op_info = "";
3825
3826 return (err);
3827 }
3828
3829 /*=========================== LOCK RELEASE ==============================*/
3830
3831 /** Grant a lock to waiting transactions.
3832 @param[in] lock Lock that was unlocked
3833 @param[in] heap_no Heap no within the page for the lock. */
3834 static void lock_rec_release(lock_t *lock, ulint heap_no) {
3835 ut_ad(locksys::owns_page_shard(lock->rec_lock.page_id));
3836 ut_ad(!lock_get_wait(lock));
3837 ut_ad(lock_get_type_low(lock) == LOCK_REC);
3838 ut_ad(lock_rec_get_nth_bit(lock, heap_no));
3839 lock_rec_reset_nth_bit(lock, heap_no);
3840
3841 lock_rec_grant_by_heap_no(lock, heap_no);
3842 MONITOR_INC(MONITOR_RECLOCK_GRANT_ATTEMPTS);
3843 }
3844
3845 /** Removes a granted record lock of a transaction from the queue and grants
3846 locks to other transactions waiting in the queue if they now are entitled
3847 to a lock.
3848 This function is meant to be used only by row_try_unlock, and it assumes
3849 that the lock we are looking for has LOCK_REC_NOT_GAP flag.
3850 */
3851 void lock_rec_unlock(
3852 trx_t *trx, /*!< in/out: transaction that has
3853 set a record lock */
3854 const buf_block_t *block, /*!< in: buffer block containing rec */
3855 const rec_t *rec, /*!< in: record */
3856 lock_mode lock_mode) /*!< in: LOCK_S or LOCK_X */
3857 {
3858 ut_ad(block->frame == page_align(rec));
3859 ut_ad(trx_state_eq(trx, TRX_STATE_ACTIVE));
3860 ut_ad(lock_mode == LOCK_S || lock_mode == LOCK_X);
3861
3862 const auto heap_no = (uint16_t)page_rec_get_heap_no(rec);
3863 const RecID rec_id{block->get_page_id(), heap_no};
3864 {
3865 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
3866 trx_mutex_enter_first_of_two(trx);
3867 ut_ad(!trx->lock.wait_lock);
3868
3869 /* Find the last lock with the same lock_mode and transaction
3870 on the record. */
3871
3872 lock_t *lock = lock_sys->rec_hash.find_on_record(rec_id, [&](lock_t *lock) {
3873 return lock->trx == trx && lock_get_mode(lock) == lock_mode &&
3874 lock_rec_get_rec_not_gap(lock);
3875 });
3876
3877 if (lock != nullptr) {
3878 /* Since we actually found the first, not the last lock, lets check
3879 that it is also the last one */
3880
3881 ut_ad(lock_sys->rec_hash.find_on_record(rec_id, [&](lock_t *lock2) {
3882 return lock2 != lock && lock2->trx == trx &&
3883 lock_get_mode(lock2) == lock_mode &&
3884 lock_rec_get_rec_not_gap(lock2);
3885 }) == nullptr);
3886
3887 lock_rec_release(lock, heap_no);
3888
3889 trx_mutex_exit(trx);
3890
3891 return;
3892 }
3893
3894 trx_mutex_exit(trx);
3895 } /* Shard_latch_guard */
3896
3897 {
3898 size_t stmt_len;
3899
3900 auto stmt = innobase_get_stmt_unsafe(trx->mysql_thd, &stmt_len);
3901
3902 ib::error err(ER_IB_MSG_1228);
3903
3904 err << "Unlock row could not find a " << lock_mode
3905 << " mode lock on the record. Current statement: ";
3906
3907 err.write(stmt, stmt_len);
3908 }
3909 }
3910
3911 /** Unlock the GAP Lock part of a Next Key Lock and grant it to waiters (if any)
3912 @param[in,out] lock lock object */
3913 static void lock_release_gap_lock(lock_t *lock) {
3914 /* 1. Remove GAP lock for all records */
3915 lock->unlock_gap_lock();
3916
3917 /* 2. Grant locks for all records */
3918 lock_rec_grant(lock);
3919
3920 /* 3. Release explicitly all locks on supremum record. This is required
3921 because supremum record lock is always considered a GAP Lock, but the lock
3922 mode can be set to Next Key Lock for sharing lock objects with other records.
3923
3924 We could not release all locks on supremum record in step [1] & [2] because
3925 currently lock_rec_grant accepts `lock` object as input which is also part of
3926 the lock queue. If we unlock supremum record (reset the BIT) in step-1, then
3927 step-2 would fail to grant locks because SUPREMUM record would be missing from
3928 input `lock` record bit set. */
3929 if (lock->includes_supremum()) {
3930 lock_rec_release(lock, PAGE_HEAP_NO_SUPREMUM);
3931 }
3932 }
3933
3934 /** Used to release a lock during PREPARE. The lock is only
3935 released if rules permit it.
3936 @param[in] lock the lock that we consider releasing
3937 @param[in] only_gap true if we don't want to release records,
3938 just the gaps between them
3939 @return true iff the function did release (maybe a part of) a lock
3940 */
3941 static bool lock_release_read_lock(lock_t *lock, bool only_gap) {
3942 /* Keep in sync with lock_edge_may_survive_prepare() */
3943 if (!lock->is_record_lock() || lock->is_insert_intention() ||
3944 lock->is_predicate()) {
3945 /* DO NOTHING */
3946 return false;
3947 } else if (lock->is_gap()) {
3948 /* Release any GAP only lock. */
3949 lock_rec_dequeue_from_page(lock);
3950 return true;
3951 } else if (lock->is_record_not_gap() && only_gap) {
3952 /* Don't release any non-GAP lock if not asked.*/
3953 return false;
3954 } else if (lock->mode() == LOCK_S && !only_gap) {
3955 /* Release Shared Next Key Lock(SH + GAP) if asked for */
3956 lock_rec_dequeue_from_page(lock);
3957 return true;
3958 } else {
3959 /* Release GAP lock from Next Key lock */
3960 lock_release_gap_lock(lock);
3961 return true;
3962 }
3963 }
3964
3965 namespace locksys {
3966
3967 /** A helper function which solves a chicken-and-egg problem occurring when one
3968 needs to iterate over trx's locks and perform some actions on them. Iterating
3969 over this list requires trx->mutex (or exclusive global lock_sys latch), and
3970 operating on a lock requires lock_sys latches, yet the latching order requires
3971 lock_sys latches to be taken before trx->mutex.
3972 One way around it is to use exclusive global lock_sys latch, which heavily
3973 deteriorates concurrency. Another is to try to reacquire the latches in needed
3974 order, veryfing that the list wasn't modified meanwhile.
3975 This function performs following steps:
3976 1. releases trx->mutex,
3977 2. acquires proper lock_sys shard latch for given lock,
3978 3. reaquires trx->mutex
3979 4. executes f unless trx's locks list has changed
3980 Before and after this function following should hold:
3981 - the shared global lock_sys latch is held
3982 - the trx->mutex is held
3983 @param[in] lock the lock we are interested in
3984 @param[in] f the function to execute when the shard is latched
3985 @return true if f was called, false if it couldn't be called because trx locks
3986 have changed while relatching trx->mutex
3987 */
3988 template <typename F>
3989 static bool try_relatch_trx_and_shard_and_do(const lock_t *lock, F &&f) {
3990 ut_ad(locksys::owns_shared_global_latch());
3991 const trx_t *trx = lock->trx;
3992 ut_ad(trx_mutex_own(trx));
3993
3994 const auto expected_version = trx->lock.trx_locks_version;
3995 return latch_peeked_shard_and_do(lock, [&]() {
3996 ut_ad(trx_mutex_own(trx));
3997 /* Check that list was not modified while we were reacquiring latches */
3998 if (expected_version != trx->lock.trx_locks_version) {
3999 /* Someone has modified the list while we were re-acquiring the latches
4000 so, it is unsafe to operate on the lock. It might have been released, or
4001 maybe even assigned to another transaction (in case of AUTOINC lock). More
4002 importantly, we need to let know the caller that the list it is iterating
4003 over has been modified, which affects next/prev pointers. */
4004 return false;
4005 }
4006 std::forward<F>(f)();
4007 ut_ad(trx_mutex_own(trx));
4008 return true;
4009 });
4010 }
4011
4012 /** We don't want to hold the Global latch for too long, even in S mode, not to
4013 starve threads waiting for X-latch on it such as lock_wait_timeout_thread().
4014 This defines the longest allowed critical section duration. */
4015 constexpr auto MAX_CS_DURATION = std::chrono::seconds{1};
4016
4017 /** Tries to release read locks of a transaction without latching the whole
4018 lock sys. This may fail, if there are many concurrent threads editing the
4019 list of locks of this transaction (for example due to B-tree pages being
4020 merged or split, or due to implicit-to-explicit conversion).
4021 It is called during XA prepare to release locks early.
4022 @param[in,out] trx transaction
4023 @param[in] only_gap release only GAP locks
4024 @return true if and only if it succeeded to do the job*/
4025 [[nodiscard]] static bool try_release_read_locks_in_s_mode(trx_t *trx,
4026 bool only_gap) {
4027 /* In order to access trx->lock.trx_locks safely we need to hold trx->mutex.
4028 So, conceptually we'd love to hold trx->mutex while iterating through
4029 trx->lock.trx_locks.
4030 However the latching order only allows us to obtain trx->mutex AFTER any
4031 lock_sys latch.
4032 One way around this problem is to simply latch the whole lock_sys in exclusive
4033 mode (which also prevents any changes to trx->lock.trx_locks), however this
4034 impacts performance in appliers (TPS drops by up to 10%).
4035 Here we use a different approach:
4036 1. we extract lock from the list when holding the trx->mutex,
4037 2. identify the shard of lock_sys it belongs to,
4038 3. store the current version of trx->lock.trx_locks
4039 4. release the trx->mutex,
4040 5. acquire the lock_sys shard's latch,
4041 6. and reacquire the trx->mutex,
4042 7. verify that the version of trx->lock.trx_locks has not changed
4043 8. and only then perform any action on the lock.
4044 */
4045 locksys::Global_shared_latch_guard shared_latch_guard{UT_LOCATION_HERE};
4046 trx_mutex_enter(trx);
4047 ut_ad(trx->lock.wait_lock == nullptr);
4048
4049 bool made_progress{false};
4050 for (auto lock : trx->lock.trx_locks.removable()) {
4051 ut_ad(trx_mutex_own(trx));
4052 /* We didn't latch the lock_sys shard this `lock` is in, so we only read a
4053 bare minimum set of information from the `lock`, such as the type, space,
4054 page_no, and next pointer, which, as long as we hold trx->mutex, should be
4055 immutable.
4056 */
4057 const auto release_read_lock = [lock, only_gap, &made_progress]() {
4058 /* Note: The |= does not short-circut. We want the RHS called.*/
4059 made_progress |= lock_release_read_lock(lock, only_gap);
4060 };
4061 if (lock_get_type_low(lock) == LOCK_REC) {
4062 /* Following call temporarily releases trx->mutex */
4063 if (!try_relatch_trx_and_shard_and_do(lock, release_read_lock) ||
4064 (made_progress && shared_latch_guard.is_x_blocked_by_us())) {
4065 /* Someone has modified the list while we were re-acquiring the latches,
4066 or someone is waiting for x-latch and we've already made some progress,
4067 so we need to start over again. */
4068 trx_mutex_exit(trx);
4069 return false;
4070 }
4071 }
4072 /* As we have verified that the version was not changed by another thread,
4073 we can safely continue iteration even if we have removed the lock.*/
4074 }
4075 trx_mutex_exit(trx);
4076 return true;
4077 }
4078
4079 /** Release read locks of a transaction latching the whole lock-sys in
4080 exclusive mode, which is a bit too expensive to do by default.
4081 It is called during XA prepare to release locks early.
4082 @param[in,out] trx transaction
4083 @param[in] only_gap release only GAP locks
4084 @return true if and only if it succeeded to do the job*/
4085 [[nodiscard]] static bool try_release_read_locks_in_x_mode(trx_t *trx,
4086 bool only_gap) {
4087 ut_ad(!trx_mutex_own(trx));
4088 /* We will iterate over locks from various shards. */
4089 Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
4090 const auto started_at = std::chrono::steady_clock::now();
4091 trx_mutex_enter_first_of_two(trx);
4092
4093 for (auto lock : trx->lock.trx_locks.removable()) {
4094 if (MAX_CS_DURATION < std::chrono::steady_clock::now() - started_at) {
4095 trx_mutex_exit(trx);
4096 return false;
4097 }
4098 DEBUG_SYNC_C("lock_trx_release_read_locks_in_x_mode_will_release");
4099
4100 lock_release_read_lock(lock, only_gap);
4101 }
4102
4103 trx_mutex_exit(trx);
4104 return true;
4105 }
4106 } // namespace locksys
4107
4108 void lock_trx_release_read_locks(trx_t *trx, bool only_gap) {
4109 ut_ad(trx_can_be_handled_by_current_thread(trx));
4110
4111 const size_t MAX_FAILURES = 5;
4112
4113 for (size_t failures = 0; failures < MAX_FAILURES; ++failures) {
4114 if (locksys::try_release_read_locks_in_s_mode(trx, only_gap)) {
4115 return;
4116 }
4117 std::this_thread::yield();
4118 }
4119
4120 while (!locksys::try_release_read_locks_in_x_mode(trx, only_gap)) {
4121 std::this_thread::yield();
4122 }
4123 }
4124
4125 namespace locksys {
4126 /** Releases transaction locks, and releases possible other transactions waiting
4127 because of these locks.
4128 @param[in,out] trx transaction
4129 @return true if and only if it succeeded to do the job*/
4130 [[nodiscard]] static bool try_release_all_locks(trx_t *trx) {
4131 lock_t *lock;
4132 ut_ad(!locksys::owns_exclusive_global_latch());
4133 ut_ad(!trx_mutex_own(trx));
4134 ut_ad(!trx->is_dd_trx);
4135 /* The length of the list is an atomic and the number of locks can't change
4136 from zero to non-zero or vice-versa, see explanation below. */
4137 if (UT_LIST_GET_LEN(trx->lock.trx_locks) == 0) {
4138 return true;
4139 }
4140 Global_shared_latch_guard shared_latch_guard{UT_LOCATION_HERE};
4141 /* In order to access trx->lock.trx_locks safely we need to hold trx->mutex.
4142 The transaction is already in TRX_STATE_COMMITTED_IN_MEMORY state and is no
4143 longer referenced, so we are not afraid of implicit-to-explicit conversions,
4144 nor a cancellation of a wait_lock (we are running, not waiting). Still, there
4145 might be some B-tree merge or split operations running in parallel which cause
4146 locks to be moved from one page to another, which at the low level means that
4147 a new lock is created (and added to trx->lock.trx_locks) and the old one is
4148 removed (also from trx->lock.trx_locks) in that specific order.
4149 So, conceptually we'd love to hold trx->mutex while iterating through
4150 trx->lock.trx_locks.
4151 However the latching order only allows us to obtain trx->mutex AFTER any
4152 lock_sys latch. One way around this problem is to simply latch the whole
4153 lock_sys in exclusive mode (which also prevents any changes to
4154 trx->lock.trx_locks), however this impacts performance (TPS drops on
4155 sysbench {pareto,uniform}-2S-{128,1024}-usrs tests by 3% to 11%) Here we
4156 use a different approach:
4157 1. we extract lock from the list when holding the trx->mutex,
4158 2. identify the shard of lock_sys it belongs to,
4159 3. release the trx->mutex,
4160 4. acquire the lock_sys shard's latch,
4161 5. and reacquire the trx->mutex,
4162 6. verify that the lock pointer is still in trx->lock.trx_locks (so it is
4163 safe to access it),
4164 7. and only then perform any action on the lock.
4165 */
4166 trx_mutex_enter(trx);
4167
4168 ut_ad(trx->lock.wait_lock == nullptr);
4169 while ((lock = UT_LIST_GET_LAST(trx->lock.trx_locks)) != nullptr) {
4170 /* Following call temporarily releases trx->mutex */
4171 try_relatch_trx_and_shard_and_do(lock, [=]() {
4172 if (lock_get_type_low(lock) == LOCK_REC) {
4173 lock_rec_dequeue_from_page(lock);
4174 } else {
4175 lock_table_dequeue(lock);
4176 }
4177 });
4178 if (shared_latch_guard.is_x_blocked_by_us()) {
4179 trx_mutex_exit(trx);
4180 return false;
4181 }
4182 }
4183
4184 trx_mutex_exit(trx);
4185 return true;
4186 }
4187 } // namespace locksys
4188
4189 /* True if a lock mode is S or X */
4190 static inline bool IS_LOCK_S_OR_X(lock_t *lock) {
4191 return lock_get_mode(lock) == LOCK_S || lock_get_mode(lock) == LOCK_X;
4192 }
4193
4194 /** Removes locks of a transaction on a table to be dropped.
4195 If remove_also_table_sx_locks is true then table-level S and X locks are
4196 also removed in addition to other table-level and record-level locks.
4197 No lock that is going to be removed is allowed to be a wait lock. */
4198 static void lock_remove_all_on_table_for_trx(
4199 dict_table_t *table, /*!< in: table to be dropped */
4200 trx_t *trx, /*!< in: a transaction */
4201 bool remove_also_table_sx_locks) /*!< in: also removes
4202 table S and X locks */
4203 {
4204 lock_t *lock;
4205 lock_t *prev_lock;
4206
4207 /* This is used when we drop a table and indeed have exclusive lock_sys
4208 access. */
4209 ut_ad(locksys::owns_exclusive_global_latch());
4210 /* We need trx->mutex to iterate over trx->lock.trx_lock and it is needed by
4211 lock_table_remove_low() but we haven't acquired it yet. */
4212 ut_ad(!trx_mutex_own(trx));
4213 trx_mutex_enter(trx);
4214
4215 for (lock = UT_LIST_GET_LAST(trx->lock.trx_locks); lock != nullptr;
4216 lock = prev_lock) {
4217 prev_lock = UT_LIST_GET_PREV(trx_locks, lock);
4218
4219 if (lock_get_type_low(lock) == LOCK_REC && lock->index->table == table) {
4220 ut_a(!lock_get_wait(lock));
4221
4222 lock_rec_discard(lock);
4223 } else if (lock_get_type_low(lock) & LOCK_TABLE &&
4224 lock->tab_lock.table == table &&
4225 (remove_also_table_sx_locks || !IS_LOCK_S_OR_X(lock))) {
4226 ut_a(!lock_get_wait(lock));
4227
4228 lock_table_remove_low(lock);
4229 }
4230 }
4231
4232 trx_mutex_exit(trx);
4233 }
4234
4235 /** Remove any explicit record locks held by recovering transactions on
4236 the table.
4237 @return number of recovered transactions examined */
4238 static ulint lock_remove_recovered_trx_record_locks(
4239 dict_table_t *table) /*!< in: check if there are any locks
4240 held on records in this table or on the
4241 table itself */
4242 {
4243 ut_a(table != nullptr);
4244 /* We need exclusive lock_sys latch, as we are about to iterate over locks
4245 held by multiple transactions while they might be operating. */
4246 ut_ad(locksys::owns_exclusive_global_latch());
4247
4248 ulint n_recovered_trx = 0;
4249
4250 mutex_enter(&trx_sys->mutex);
4251
4252 for (trx_t *trx : trx_sys->rw_trx_list) {
4253 assert_trx_in_rw_list(trx);
4254
4255 if (!trx->is_recovered) {
4256 continue;
4257 }
4258 /* We need trx->mutex to iterate over trx->lock.trx_lock and it is needed by
4259 lock_table_remove_low() but we haven't acquired it yet. */
4260 ut_ad(!trx_mutex_own(trx));
4261 trx_mutex_enter(trx);
4262 /* Because we are holding the exclusive global lock_sys latch,
4263 implicit locks cannot be converted to explicit ones
4264 while we are scanning the explicit locks. */
4265
4266 for (auto lock : trx->lock.trx_locks.removable()) {
4267 ut_a(lock->trx == trx);
4268
4269 /* Recovered transactions can't wait on a lock. */
4270
4271 ut_a(!lock_get_wait(lock));
4272
4273 switch (lock_get_type_low(lock)) {
4274 default:
4275 ut_error;
4276 case LOCK_TABLE:
4277 if (lock->tab_lock.table == table) {
4278 lock_table_remove_low(lock);
4279 }
4280 break;
4281 case LOCK_REC:
4282 if (lock->index->table == table) {
4283 lock_rec_discard(lock);
4284 }
4285 }
4286 }
4287
4288 trx_mutex_exit(trx);
4289 ++n_recovered_trx;
4290 }
4291
4292 mutex_exit(&trx_sys->mutex);
4293
4294 return (n_recovered_trx);
4295 }
4296
4297 /** Removes locks on a table to be dropped.
4298 If remove_also_table_sx_locks is true then table-level S and X locks are
4299 also removed in addition to other table-level and record-level locks.
4300 No lock, that is going to be removed, is allowed to be a wait lock. */
4301 void lock_remove_all_on_table(
4302 dict_table_t *table, /*!< in: table to be dropped
4303 or discarded */
4304 bool remove_also_table_sx_locks) /*!< in: also removes
4305 table S and X locks */
4306 {
4307 /* We will iterate over locks (including record locks) from various shards */
4308 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
4309
4310 for (auto lock : table->locks.removable()) {
4311 /* If we should remove all locks (remove_also_table_sx_locks
4312 is true), or if the lock is not table-level S or X lock,
4313 then check we are not going to remove a wait lock. */
4314 if (remove_also_table_sx_locks ||
4315 !(lock_get_type(lock) == LOCK_TABLE && IS_LOCK_S_OR_X(lock))) {
4316 ut_a(!lock_get_wait(lock));
4317 }
4318
4319 lock_remove_all_on_table_for_trx(table, lock->trx,
4320 remove_also_table_sx_locks);
4321 }
4322
4323 /* Note: Recovered transactions don't have table level IX or IS locks
4324 but can have implicit record locks that have been converted to explicit
4325 record locks. Such record locks cannot be freed by traversing the
4326 transaction lock list in dict_table_t (as above). */
4327
4328 if (!lock_sys->rollback_complete &&
4329 lock_remove_recovered_trx_record_locks(table) == 0) {
4330 lock_sys->rollback_complete = true;
4331 }
4332 }
4333
4334 /*===================== VALIDATION AND DEBUGGING ====================*/
4335
4336 /** Prints info of a table lock. */
4337 static void lock_table_print(FILE *file, /*!< in: file where to print */
4338 const lock_t *lock) /*!< in: table type lock */
4339 {
4340 ut_a(lock_get_type_low(lock) == LOCK_TABLE);
4341 /* We actually hold exclusive latch here, but we require just the shard */
4342 ut_ad(locksys::owns_table_shard(*lock->tab_lock.table));
4343
4344 fputs("TABLE LOCK table ", file);
4345 ut_print_name(file, lock->trx, lock->tab_lock.table->name.m_name);
4346 fprintf(file, " trx id " TRX_ID_FMT, trx_get_id_for_print(lock->trx));
4347
4348 if (lock_get_mode(lock) == LOCK_S) {
4349 fputs(" lock mode S", file);
4350 } else if (lock_get_mode(lock) == LOCK_X) {
4351 ut_ad(lock->trx->id != 0);
4352 fputs(" lock mode X", file);
4353 } else if (lock_get_mode(lock) == LOCK_IS) {
4354 fputs(" lock mode IS", file);
4355 } else if (lock_get_mode(lock) == LOCK_IX) {
4356 ut_ad(lock->trx->id != 0);
4357 fputs(" lock mode IX", file);
4358 } else if (lock_get_mode(lock) == LOCK_AUTO_INC) {
4359 fputs(" lock mode AUTO-INC", file);
4360 } else {
4361 fprintf(file, " unknown lock mode %lu", (ulong)lock_get_mode(lock));
4362 }
4363
4364 if (lock_get_wait(lock)) {
4365 fputs(" waiting", file);
4366 }
4367
4368 putc('\n', file);
4369 }
4370
4371 /** Prints info of a record lock. */
4372 static void lock_rec_print(FILE *file, /*!< in: file where to print */
4373 const lock_t *lock) /*!< in: record type lock */
4374 {
4375 mtr_t mtr;
4376 Rec_offsets offsets;
4377
4378 ut_a(lock_get_type_low(lock) == LOCK_REC);
4379 const auto page_id = lock->rec_lock.page_id;
4380 /* We actually hold exclusive latch here, but we require just the shard */
4381 ut_ad(locksys::owns_page_shard(page_id));
4382
4383 fprintf(file,
4384 "RECORD LOCKS space id %lu page no %lu n bits %llu "
4385 "index %s of table ",
4386 ulong{page_id.space()}, ulong{page_id.page_no()},
4387 ulonglong{lock_rec_get_n_bits(lock)}, lock->index->name());
4388 ut_print_name(file, lock->trx, lock->index->table_name);
4389 fprintf(file, " trx id " TRX_ID_FMT, trx_get_id_for_print(lock->trx));
4390
4391 if (lock_get_mode(lock) == LOCK_S) {
4392 fputs(" lock mode S", file);
4393 } else if (lock_get_mode(lock) == LOCK_X) {
4394 fputs(" lock_mode X", file);
4395 } else {
4396 ut_error;
4397 }
4398
4399 if (lock_rec_get_gap(lock)) {
4400 fputs(" locks gap before rec", file);
4401 }
4402
4403 if (lock_rec_get_rec_not_gap(lock)) {
4404 fputs(" locks rec but not gap", file);
4405 }
4406
4407 if (lock_rec_get_insert_intention(lock)) {
4408 fputs(" insert intention", file);
4409 }
4410
4411 if (lock_get_wait(lock)) {
4412 fputs(" waiting", file);
4413 }
4414
4415 mtr_start(&mtr);
4416
4417 putc('\n', file);
4418
4419 const buf_block_t *block;
4420
4421 block = buf_page_try_get(page_id, UT_LOCATION_HERE, &mtr);
4422
4423 for (ulint i = 0; i < lock_rec_get_n_bits(lock); ++i) {
4424 if (!lock_rec_get_nth_bit(lock, i)) {
4425 continue;
4426 }
4427
4428 fprintf(file, "Record lock, heap no %lu", (ulong)i);
4429
4430 if (block) {
4431 const rec_t *rec;
4432
4433 rec = page_find_rec_with_heap_no(buf_block_get_frame(block), i);
4434
4435 putc(' ', file);
4436 rec_print_new(file, rec, offsets.compute(rec, lock->index));
4437 }
4438
4439 putc('\n', file);
4440 }
4441
4442 mtr_commit(&mtr);
4443 }
4444
4445 #ifdef UNIV_DEBUG
4446 /* Print the number of lock structs from lock_print_info_summary() only
4447 in non-production builds for performance reasons, see
4448 http://bugs.mysql.com/36942 */
4449 #define PRINT_NUM_OF_LOCK_STRUCTS
4450 #endif /* UNIV_DEBUG */
4451
4452 #ifdef PRINT_NUM_OF_LOCK_STRUCTS
4453 /** Calculates the number of record lock structs in the record lock hash table.
4454 @return number of record locks */
4455 static size_t lock_get_n_rec_locks(void) {
4456 size_t n_locks = 0;
4457
4458 /* We need exclusive access to lock_sys to iterate over all hash cells. */
4459 ut_ad(locksys::owns_exclusive_global_latch());
4460 lock_sys->rec_hash.find([&](lock_t *) {
4461 n_locks++;
4462 return false;
4463 });
4464 return n_locks;
4465 }
4466 #endif /* PRINT_NUM_OF_LOCK_STRUCTS */
4467
4468 void lock_print_info_summary(FILE *file) {
4469 ut_ad(locksys::owns_exclusive_global_latch());
4470
4471 if (lock_deadlock_found) {
4472 fputs(
4473 "------------------------\n"
4474 "LATEST DETECTED DEADLOCK\n"
4475 "------------------------\n",
4476 file);
4477
4478 if (!srv_read_only_mode) {
4479 ut_copy_file(file, lock_latest_err_file);
4480 }
4481 }
4482
4483 fputs(
4484 "------------\n"
4485 "TRANSACTIONS\n"
4486 "------------\n",
4487 file);
4488
4489 fprintf(file, "Trx id counter " TRX_ID_FMT "\n",
4490 trx_sys_get_next_trx_id_or_no());
4491
4492 fprintf(file,
4493 "Purge done for trx's n:o < " TRX_ID_FMT " undo n:o < " TRX_ID_FMT
4494 " state: ",
4495 purge_sys->iter.trx_no, purge_sys->iter.undo_no);
4496
4497 /* Note: We are reading the state without the latch. One because it
4498 will violate the latching order and two because we are merely querying
4499 the state of the variable for display. */
4500
4501 switch (purge_sys->state) {
4502 case PURGE_STATE_INIT:
4503 /* Should never be in this state while the system is running. */
4504 fprintf(file, "initializing");
4505 break;
4506
4507 case PURGE_STATE_EXIT:
4508 fprintf(file, "exited");
4509 break;
4510
4511 case PURGE_STATE_DISABLED:
4512 fprintf(file, "disabled");
4513 break;
4514
4515 case PURGE_STATE_RUN:
4516 fprintf(file, "running");
4517 /* Check if it is waiting for more data to arrive. */
4518 if (!purge_sys->running) {
4519 fprintf(file, " but idle");
4520 }
4521 break;
4522
4523 case PURGE_STATE_STOP:
4524 fprintf(file, "stopped");
4525 break;
4526 }
4527
4528 fprintf(file, "\n");
4529
4530 fprintf(file, "History list length " UINT64PF "\n",
4531 trx_sys->rseg_history_len.load());
4532
4533 #ifdef PRINT_NUM_OF_LOCK_STRUCTS
4534 fprintf(file, "Total number of lock structs in row lock hash table %zu\n",
4535 lock_get_n_rec_locks());
4536 #endif /* PRINT_NUM_OF_LOCK_STRUCTS */
4537 }
4538
4539 /** Functor to print not-started transaction from the mysql_trx_list. */
4540 struct PrintNotStarted {
4541 PrintNotStarted(FILE *file) : m_file(file) {}
4542
4543 void operator()(const trx_t *trx) {
4544 /* We require exclusive access to lock_sys */
4545 ut_ad(locksys::owns_exclusive_global_latch());
4546 ut_ad(trx->in_mysql_trx_list);
4547 ut_ad(mutex_own(&trx_sys->mutex));
4548
4549 /* See state transitions and locking rules in trx0trx.h */
4550
4551 trx_mutex_enter(trx);
4552 if (trx_state_eq(trx, TRX_STATE_NOT_STARTED)) {
4553 fputs("---", m_file);
4554 trx_print_latched(m_file, trx, 600);
4555 }
4556 trx_mutex_exit(trx);
4557 }
4558
4559 FILE *m_file;
4560 };
4561
4562 /** Iterate over a transaction's locks. Keeping track of the
4563 iterator using an ordinal value. */
4564 class TrxLockIterator {
4565 public:
4566 TrxLockIterator() { rewind(); }
4567
4568 /** Get the m_index(th) lock of a transaction.
4569 @return current lock or 0 */
4570 const lock_t *current(const trx_t *trx) const {
4571 ulint i = 0;
4572 /* Writes to trx->lock.trx_locks are protected by trx->mutex combined with a
4573 shared lock_sys global latch, and we assume we have the exclusive latch on
4574 lock_sys here. */
4575 ut_ad(locksys::owns_exclusive_global_latch());
4576 for (auto lock : trx->lock.trx_locks) {
4577 if (i++ == m_index) {
4578 return lock;
4579 }
4580 }
4581 return nullptr;
4582 }
4583
4584 /** Set the ordinal value to 0 */
4585 void rewind() { m_index = 0; }
4586
4587 /** Increment the ordinal value.
4588 @return the current index value */
4589 ulint next() { return (++m_index); }
4590
4591 private:
4592 /** Current iterator position */
4593 ulint m_index;
4594 };
4595
4596 /** This iterates over RW trx_sys lists only. We need to keep
4597 track where the iterator was up to and we do that using an ordinal value. */
4598
4599 class TrxListIterator {
4600 public:
4601 TrxListIterator() : m_index() {
4602 /* We iterate over the RW trx list only. */
4603
4604 m_trx_list = &trx_sys->rw_trx_list;
4605 }
4606
4607 /** Get the current transaction whose ordinality is m_index.
4608 @return current transaction or 0 */
4609
4610 const trx_t *current() { return (reposition()); }
4611
4612 /** Advance the transaction current ordinal value and reset the
4613 transaction lock ordinal value */
4614
4615 void next() {
4616 ++m_index;
4617 m_lock_iter.rewind();
4618 }
4619
4620 TrxLockIterator &lock_iter() { return (m_lock_iter); }
4621
4622 private:
4623 /** Reposition the "cursor" on the current transaction. If it
4624 is the first time then the "cursor" will be positioned on the
4625 first transaction.
4626
4627 @return transaction instance or 0 */
4628 const trx_t *reposition() const {
4629 ulint i = 0;
4630
4631 /* Make the transaction at the ordinal value of m_index
4632 the current transaction. ie. reposition/restore */
4633
4634 for (auto trx : *m_trx_list) {
4635 if (i++ == m_index) {
4636 return trx;
4637 }
4638 check_trx_state(trx);
4639 }
4640
4641 return nullptr;
4642 }
4643
4644 /** Ordinal value of the transaction in the current transaction list */
4645 ulint m_index;
4646
4647 /** Current transaction list */
4648 decltype(trx_sys->rw_trx_list) *m_trx_list;
4649
4650 /** For iterating over a transaction's locks */
4651 TrxLockIterator m_lock_iter;
4652 };
4653
4654 /** Prints transaction lock wait and MVCC state.
4655 @param[in,out] file file where to print
4656 @param[in] trx transaction */
4657 void lock_trx_print_wait_and_mvcc_state(FILE *file, const trx_t *trx) {
4658 /* We require exclusive lock_sys access so that trx->lock.wait_lock is
4659 not being modified, and to access trx->lock.wait_started without trx->mutex.*/
4660 ut_ad(locksys::owns_exclusive_global_latch());
4661 fprintf(file, "---");
4662
4663 trx_print_latched(file, trx, 3000);
4664
4665 const ReadView *read_view = trx_get_read_view(trx);
4666
4667 if (read_view != nullptr) {
4668 read_view->print_limits(file);
4669 }
4670
4671 if (trx->lock.que_state == TRX_QUE_LOCK_WAIT) {
4672 fprintf(file,
4673 "------- TRX HAS BEEN WAITING %" PRId64
4674 " SEC FOR THIS LOCK TO BE GRANTED:\n",
4675 static_cast<int64_t>(
4676 std::chrono::duration_cast<std::chrono::seconds>(
4677 std::chrono::system_clock::now() - trx->lock.wait_started)
4678 .count()));
4679
4680 if (lock_get_type_low(trx->lock.wait_lock) == LOCK_REC) {
4681 lock_rec_print(file, trx->lock.wait_lock);
4682 } else {
4683 lock_table_print(file, trx->lock.wait_lock);
4684 }
4685
4686 fprintf(file, "------------------\n");
4687 }
4688 }
4689
4690 /** Reads the page containing the record protected by the given lock.
4691 This function will temporarily release the exclusive global latch and the
4692 trx_sys_t::mutex if the page was read from disk.
4693 @param[in] lock the record lock
4694 @return true if a page was successfully read from the tablespace */
4695 static bool lock_rec_fetch_page(const lock_t *lock) {
4696 ut_ad(lock_get_type_low(lock) == LOCK_REC);
4697
4698 const page_id_t page_id = lock->rec_lock.page_id;
4699 const space_id_t space_id = page_id.space();
4700 fil_space_t *space;
4701 bool found;
4702 const page_size_t &page_size = fil_space_get_page_size(space_id, &found);
4703
4704 /* Check if the .ibd file exists. */
4705 if (found) {
4706 mtr_t mtr;
4707
4708 locksys::Unsafe_global_latch_manipulator::exclusive_unlatch();
4709
4710 mutex_exit(&trx_sys->mutex);
4711
4712 DEBUG_SYNC_C("innodb_monitor_before_lock_page_read");
4713
4714 /* Check if the space is exists or not. only
4715 when the space is valid, try to get the page. */
4716 space = fil_space_acquire_silent(space_id);
4717 if (space) {
4718 mtr_start(&mtr);
4719 buf_page_get_gen(page_id, page_size, RW_NO_LATCH, nullptr,
4720 Page_fetch::POSSIBLY_FREED, UT_LOCATION_HERE, &mtr);
4721 mtr_commit(&mtr);
4722 fil_space_release(space);
4723 }
4724
4725 locksys::Unsafe_global_latch_manipulator::exclusive_latch(UT_LOCATION_HERE);
4726
4727 mutex_enter(&trx_sys->mutex);
4728
4729 return (true);
4730 }
4731
4732 return (false);
4733 }
4734
4735 /** Prints info of locks for a transaction.
4736 @return true if all printed, false if latches were released. */
4737 static bool lock_trx_print_locks(
4738 FILE *file, /*!< in/out: File to write */
4739 const trx_t *trx, /*!< in: current transaction */
4740 TrxLockIterator &iter, /*!< in: transaction lock iterator */
4741 bool load_block) /*!< in: if true then read block
4742 from disk */
4743 {
4744 const lock_t *lock;
4745 /* We require exclusive access to lock_sys */
4746 ut_ad(locksys::owns_exclusive_global_latch());
4747
4748 /* Iterate over the transaction's locks. */
4749 while ((lock = iter.current(trx)) != nullptr) {
4750 if (lock_get_type_low(lock) == LOCK_REC) {
4751 if (load_block) {
4752 /* Note: lock_rec_fetch_page() will release both the exclusive global
4753 latch and the trx_sys_t::mutex if it does a read from disk. */
4754
4755 if (lock_rec_fetch_page(lock)) {
4756 /* We need to resync the
4757 current transaction. */
4758 return (false);
4759 }
4760
4761 /* It is a single table tablespace
4762 and the .ibd file is missing
4763 (DISCARD TABLESPACE probably stole the
4764 locks): just print the lock without
4765 attempting to load the page in the
4766 buffer pool. */
4767
4768 fprintf(file,
4769 "RECORD LOCKS on non-existing"
4770 " space %u\n",
4771 lock->rec_lock.page_id.space());
4772 }
4773
4774 /* Print all the record locks on the page from
4775 the record lock bitmap */
4776
4777 lock_rec_print(file, lock);
4778
4779 load_block = true;
4780
4781 } else {
4782 ut_ad(lock_get_type_low(lock) & LOCK_TABLE);
4783
4784 lock_table_print(file, lock);
4785 }
4786
4787 if (iter.next() >= 10) {
4788 fprintf(file,
4789 "10 LOCKS PRINTED FOR THIS TRX:"
4790 " SUPPRESSING FURTHER PRINTS\n");
4791
4792 break;
4793 }
4794 }
4795
4796 return (true);
4797 }
4798
4799 void lock_print_info_all_transactions(FILE *file) {
4800 /* We require exclusive access to lock_sys */
4801 ut_ad(locksys::owns_exclusive_global_latch());
4802
4803 fprintf(file, "LIST OF TRANSACTIONS FOR EACH SESSION:\n");
4804
4805 mutex_enter(&trx_sys->mutex);
4806
4807 /* First print info on non-active transactions */
4808
4809 /* NOTE: information of auto-commit non-locking read-only
4810 transactions will be omitted here. The information will be
4811 available from INFORMATION_SCHEMA.INNODB_TRX. */
4812
4813 PrintNotStarted print_not_started(file);
4814 ut_list_map(trx_sys->mysql_trx_list, print_not_started);
4815
4816 const trx_t *trx;
4817 TrxListIterator trx_iter;
4818 const trx_t *prev_trx = nullptr;
4819
4820 /* Control whether a block should be fetched from the buffer pool. */
4821 bool load_block = true;
4822 bool monitor = srv_print_innodb_lock_monitor;
4823
4824 while ((trx = trx_iter.current()) != nullptr) {
4825 check_trx_state(trx);
4826
4827 if (trx != prev_trx) {
4828 lock_trx_print_wait_and_mvcc_state(file, trx);
4829 prev_trx = trx;
4830
4831 /* The transaction that read in the page is no
4832 longer the one that read the page in. We need to
4833 force a page read. */
4834 load_block = true;
4835 }
4836
4837 /* If we need to print the locked record contents then we
4838 need to fetch the containing block from the buffer pool. */
4839 if (monitor) {
4840 /* Print the locks owned by the current transaction. */
4841 TrxLockIterator &lock_iter = trx_iter.lock_iter();
4842
4843 if (!lock_trx_print_locks(file, trx, lock_iter, load_block)) {
4844 /* Resync trx_iter, the trx_sys->mutex and exclusive global latch were
4845 temporarily released. A page was successfully read in. We need to print
4846 its contents on the next call to lock_trx_print_locks(). On the next
4847 call to lock_trx_print_locks() we should simply print the contents of
4848 the page just read in.*/
4849 load_block = false;
4850
4851 continue;
4852 }
4853 }
4854
4855 load_block = true;
4856
4857 /* All record lock details were printed without fetching
4858 a page from disk, or we didn't need to print the detail. */
4859 trx_iter.next();
4860 }
4861
4862 mutex_exit(&trx_sys->mutex);
4863 }
4864
4865 #ifdef UNIV_DEBUG
4866
4867 /** Validates the lock queue on a table.
4868 @return true if ok */
4869 static bool lock_table_queue_validate(
4870 const dict_table_t *table) /*!< in: table */
4871 {
4872 /* We actually hold exclusive latch here, but we require just the shard */
4873 ut_ad(locksys::owns_table_shard(*table));
4874 ut_ad(trx_sys_mutex_own());
4875
4876 for (auto lock : table->locks) {
4877 /* lock->trx->state cannot change to NOT_STARTED until transaction released
4878 its table locks and that is prevented here by the locksys shard's mutex. */
4879 ut_ad(trx_assert_started(lock->trx));
4880
4881 if (!lock_get_wait(lock)) {
4882 ut_a(!lock_table_other_has_incompatible(lock->trx, 0, table,
4883 lock_get_mode(lock)));
4884 } else {
4885 ut_a(lock_table_has_to_wait_in_queue(lock));
4886 }
4887 }
4888
4889 return (true);
4890 }
4891 namespace locksys {
4892 /** Validates the lock queue on a single record.
4893 @param[in] block buffer block containing rec
4894 @param[in] rec record to look at
4895 @param[in] index index, or NULL if not known
4896 @param[in] offsets rec_get_offsets(rec, index) */
4897 static void rec_queue_validate_latched(const buf_block_t *block,
4898 const rec_t *rec,
4899 const dict_index_t *index,
4900 const ulint *offsets) {
4901 ut_ad(owns_page_shard(block->get_page_id()));
4902 ut_ad(mutex_own(&trx_sys->mutex));
4903 ut_a(rec);
4904 ut_a(block->frame == page_align(rec));
4905 ut_ad(rec_offs_validate(rec, index, offsets));
4906 ut_ad(!page_rec_is_comp(rec) == !rec_offs_comp(offsets));
4907 ut_ad(!index || index->is_clustered() || !dict_index_is_online_ddl(index));
4908
4909 ulint heap_no = page_rec_get_heap_no(rec);
4910 RecID rec_id{block, heap_no};
4911
4912 if (!page_rec_is_user_rec(rec)) {
4913 lock_sys->rec_hash.find_on_record(rec_id, [&](lock_t *lock) {
4914 ut_ad(!trx_is_ac_nl_ro(lock->trx));
4915
4916 if (lock->is_waiting()) {
4917 ut_a(lock_rec_has_to_wait_in_queue(lock));
4918 }
4919
4920 if (index != nullptr) {
4921 ut_a(lock->index == index);
4922 }
4923
4924 return false;
4925 });
4926
4927 return;
4928 }
4929
4930 if (index == nullptr) {
4931 /* Nothing we can do */
4932
4933 } else if (index->is_clustered()) {
4934 trx_id_t trx_id;
4935
4936 /* Unlike the non-debug code, this invariant can only succeed
4937 if the check and assertion are covered by the lock_sys latch. */
4938
4939 trx_id = lock_clust_rec_some_has_impl(rec, index, offsets);
4940
4941 trx_sys->latch_and_execute_with_active_trx(
4942 trx_id,
4943 [&](const trx_t *impl_trx) {
4944 if (impl_trx != nullptr) {
4945 ut_ad(owns_page_shard(block->get_page_id()));
4946 /* impl_trx cannot become TRX_STATE_COMMITTED_IN_MEMORY nor removed
4947 from active_rw_trxs.by_id until we release Trx_shard's mutex, which
4948 means that currently all other threads in the system consider this
4949 impl_trx active and thus should respect implicit locks held by
4950 impl_trx*/
4951
4952 const lock_t *other_lock = lock_rec_other_has_expl_req(
4953 LOCK_S, block, true, heap_no, impl_trx);
4954
4955 /* The impl_trx is holding an implicit lock on the given 'rec'.
4956 So there cannot be another explicit granted lock. Also, there can
4957 be another explicit waiting lock only if the impl_trx has an
4958 explicit granted lock. */
4959
4960 if (other_lock != nullptr) {
4961 ut_a(lock_get_wait(other_lock));
4962 ut_a(lock_rec_has_expl(LOCK_X | LOCK_REC_NOT_GAP, block, heap_no,
4963 impl_trx));
4964 }
4965 }
4966 },
4967 UT_LOCATION_HERE);
4968 }
4969 lock_sys->rec_hash.find_on_record(rec_id, [&](lock_t *lock) {
4970 ut_ad(!trx_is_ac_nl_ro(lock->trx));
4971
4972 if (index != nullptr) {
4973 ut_a(lock->index == index);
4974 }
4975
4976 if (!lock->is_gap() && !lock->is_waiting()) {
4977 lock_mode mode;
4978
4979 if (lock_get_mode(lock) == LOCK_S) {
4980 mode = LOCK_X;
4981 } else {
4982 mode = LOCK_S;
4983 }
4984
4985 const lock_t *other_lock =
4986 lock_rec_other_has_expl_req(mode, block, false, heap_no, lock->trx);
4987
4988 ut_a(!other_lock);
4989
4990 } else if (lock->is_waiting() && !lock->is_gap()) {
4991 ut_a(lock_rec_has_to_wait_in_queue(lock));
4992 }
4993
4994 return false;
4995 });
4996 }
4997
4998 /** Validates the lock queue on a single record.
4999 @param[in] block buffer block containing rec
5000 @param[in] rec record to look at
5001 @param[in] index index, or NULL if not known
5002 @param[in] offsets rec_get_offsets(rec, index) */
5003 static void rec_queue_latch_and_validate(const buf_block_t *block,
5004 const rec_t *rec,
5005 const dict_index_t *index,
5006 const ulint *offsets) {
5007 ut_ad(!owns_exclusive_global_latch());
5008 ut_ad(!mutex_own(&trx_sys->mutex));
5009
5010 Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5011 mutex_enter(&trx_sys->mutex);
5012 rec_queue_validate_latched(block, rec, index, offsets);
5013 mutex_exit(&trx_sys->mutex);
5014 }
5015
5016 /** Validates the lock queue on a single record.
5017 @param[in] block buffer block containing rec
5018 @param[in] rec record to look at
5019 @param[in] index index, or NULL if not known */
5020 static void rec_queue_latch_and_validate(const buf_block_t *block,
5021 const rec_t *rec,
5022 const dict_index_t *index) {
5023 rec_queue_latch_and_validate(block, rec, index,
5024 Rec_offsets().compute(rec, index));
5025 }
5026 } // namespace locksys
5027
5028 static void lock_rec_validate_page(
5029 const buf_block_t *block) /*!< in: buffer block */
5030 {
5031 Rec_offsets offsets;
5032
5033 ut_ad(!locksys::owns_exclusive_global_latch());
5034
5035 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5036
5037 mutex_enter(&trx_sys->mutex);
5038
5039 lock_sys->rec_hash.find_on_block(block, [&](lock_t *lock) {
5040 ut_ad(!block->page.file_page_was_freed);
5041 ut_ad(!trx_is_ac_nl_ro(lock->trx));
5042 /* If this thread is holding the file space latch (fil_space_t::latch), the
5043 following check WILL break the latching order and may cause a deadlock of
5044 threads. */
5045 if (!sync_check_find(SYNC_FSP)) {
5046 for (size_t i = 0; i < lock_rec_get_n_bits(lock); i++) {
5047 if (i == PAGE_HEAP_NO_SUPREMUM || lock_rec_get_nth_bit(lock, i)) {
5048 const rec_t *rec = page_find_rec_with_heap_no(block->frame, i);
5049 ut_a(rec);
5050 locksys::rec_queue_validate_latched(
5051 block, rec, lock->index, offsets.compute(rec, lock->index));
5052 }
5053 }
5054 }
5055 return false;
5056 });
5057
5058 mutex_exit(&trx_sys->mutex);
5059 }
5060
5061 /** Validates the table locks. */
5062 static void lock_validate_table_locks() {
5063 /* We need exclusive access to lock_sys to iterate over trxs' locks */
5064 ut_ad(locksys::owns_exclusive_global_latch());
5065 ut_ad(trx_sys_mutex_own());
5066
5067 for (const trx_t *trx : trx_sys->rw_trx_list) {
5068 check_trx_state(trx);
5069
5070 for (const lock_t *lock : trx->lock.trx_locks) {
5071 if (lock_get_type_low(lock) & LOCK_TABLE) {
5072 lock_table_queue_validate(lock->tab_lock.table);
5073 }
5074 }
5075 }
5076 }
5077
5078 /** Validate a record lock's block */
5079 static void lock_rec_block_validate(const page_id_t &page_id) {
5080 /* The lock and the block that it is referring to may be freed at
5081 this point. We pass Page_fetch::POSSIBLY_FREED to skip a debug check.
5082 If the lock exists in lock_rec_validate_page() we assert
5083 !block->page.file_page_was_freed. */
5084
5085 buf_block_t *block;
5086 mtr_t mtr;
5087
5088 /* Make sure that the tablespace is not deleted while we are
5089 trying to access the page. */
5090 if (fil_space_t *space = fil_space_acquire_silent(page_id.space())) {
5091 mtr_start(&mtr);
5092
5093 block = buf_page_get_gen(page_id, page_size_t(space->flags), RW_X_LATCH,
5094 nullptr, Page_fetch::POSSIBLY_FREED,
5095 UT_LOCATION_HERE, &mtr);
5096
5097 buf_block_dbg_add_level(block, SYNC_NO_ORDER_CHECK);
5098
5099 ut_d(lock_rec_validate_page(block));
5100 mtr_commit(&mtr);
5101
5102 fil_space_release(space);
5103 }
5104 }
5105
5106 bool lock_validate() {
5107 typedef std::set<page_id_t, std::less<page_id_t>, ut::allocator<page_id_t>>
5108 page_addr_set;
5109
5110 page_addr_set pages;
5111 {
5112 /* lock_validate_table_locks() needs exclusive global latch, and we will
5113 inspect record locks from all shards */
5114 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
5115 mutex_enter(&trx_sys->mutex);
5116
5117 lock_validate_table_locks();
5118
5119 /* Iterate over all the record locks and validate the locks. We
5120 don't want to hog the lock_sys global latch and the trx_sys_t::mutex.
5121 Thus we release both latches before the validation check. */
5122 lock_sys->rec_hash.find([&](lock_t *lock) {
5123 ut_ad(!trx_is_ac_nl_ro(lock->trx));
5124 ut_ad(lock_get_type(lock) == LOCK_REC);
5125 pages.emplace(lock->rec_lock.page_id);
5126 return false;
5127 });
5128
5129 mutex_exit(&trx_sys->mutex);
5130 }
5131 std::for_each(pages.cbegin(), pages.cend(), lock_rec_block_validate);
5132
5133 return (true);
5134 }
5135 #endif /* UNIV_DEBUG */
5136 /*============ RECORD LOCK CHECKS FOR ROW OPERATIONS ====================*/
5137
5138 /** Checks if locks of other transactions prevent an immediate insert of
5139 a record. If they do, first tests if the query thread should anyway
5140 be suspended for some reason; if not, then puts the transaction and
5141 the query thread to the lock wait state and inserts a waiting request
5142 for a gap x-lock to the lock queue.
5143 @return DB_SUCCESS, DB_LOCK_WAIT, or DB_DEADLOCK */
5144 dberr_t lock_rec_insert_check_and_lock(
5145 ulint flags, /*!< in: if BTR_NO_LOCKING_FLAG bit is
5146 set, does nothing */
5147 const rec_t *rec, /*!< in: record after which to insert */
5148 buf_block_t *block, /*!< in/out: buffer block of rec */
5149 dict_index_t *index, /*!< in: index */
5150 que_thr_t *thr, /*!< in: query thread */
5151 mtr_t *mtr, /*!< in/out: mini-transaction */
5152 bool *inherit) /*!< out: set to true if the new
5153 inserted record maybe should inherit
5154 LOCK_GAP type locks from the successor
5155 record */
5156 {
5157 ut_ad(block->frame == page_align(rec));
5158 ut_ad(!dict_index_is_online_ddl(index) || index->is_clustered() ||
5159 (flags & BTR_CREATE_FLAG));
5160
5161 if (flags & BTR_NO_LOCKING_FLAG) {
5162 return (DB_SUCCESS);
5163 }
5164
5165 ut_ad(!index->table->is_temporary());
5166
5167 dberr_t err = DB_SUCCESS;
5168 auto inherit_in = *inherit;
5169 trx_t *trx = thr_get_trx(thr);
5170 const rec_t *next_rec = page_rec_get_next_const(rec);
5171 ulint heap_no = page_rec_get_heap_no(next_rec);
5172
5173 {
5174 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5175
5176 /* When inserting a record into an index, the table must be at
5177 least IX-locked. When we are building an index, we would pass
5178 BTR_NO_LOCKING_FLAG and skip the locking altogether. */
5179 ut_ad(lock_table_has(trx, index->table, LOCK_IX));
5180
5181 /* Spatial index does not use GAP lock protection. It uses
5182 "predicate lock" to protect the "range" */
5183 ut_ad(!dict_index_is_spatial(index));
5184
5185 if (!lock_rec_has_any(lock_sys->rec_hash, block->get_page_id(), heap_no)) {
5186 *inherit = false;
5187 } else {
5188 *inherit = true;
5189
5190 /* If another transaction has an explicit lock request which locks
5191 the gap, waiting or granted, on the successor, the insert has to wait.
5192
5193 An exception is the case where the lock by the another transaction
5194 is a gap type lock which it placed to wait for its turn to insert. We
5195 do not consider that kind of a lock conflicting with our insert. This
5196 eliminates an unnecessary deadlock which resulted when 2 transactions
5197 had to wait for their insert. Both had waiting gap type lock requests
5198 on the successor, which produced an unnecessary deadlock. */
5199
5200 const ulint type_mode = LOCK_X | LOCK_GAP | LOCK_INSERT_INTENTION;
5201
5202 const auto conflicting =
5203 lock_rec_other_has_conflicting(type_mode, block, heap_no, trx);
5204
5205 /* LOCK_INSERT_INTENTION locks can not be allowed to bypass waiting locks,
5206 because they allow insertion of a record which splits the gap which would
5207 lead to duplication of the waiting lock, violating the constraint that
5208 each transaction can wait for at most one lock at any given time */
5209 ut_a(!conflicting.bypassed);
5210
5211 if (conflicting.wait_for != nullptr) {
5212 RecLock rec_lock(thr, index, block, heap_no, type_mode);
5213
5214 trx_mutex_enter(trx);
5215
5216 err = rec_lock.add_to_waitq(conflicting.wait_for);
5217
5218 trx_mutex_exit(trx);
5219 }
5220 }
5221 } /* Shard_latch_guard */
5222
5223 switch (err) {
5224 case DB_SUCCESS_LOCKED_REC:
5225 err = DB_SUCCESS;
5226 [[fallthrough]];
5227 case DB_SUCCESS:
5228 if (!inherit_in || index->is_clustered()) {
5229 break;
5230 }
5231
5232 /* Update the page max trx id field */
5233 page_update_max_trx_id(block, buf_block_get_page_zip(block), trx->id,
5234 mtr);
5235 default:
5236 /* We only care about the two return values. */
5237 break;
5238 }
5239
5240 ut_d(locksys::rec_queue_latch_and_validate(block, next_rec, index));
5241 ut_ad(err == DB_SUCCESS || err == DB_LOCK_WAIT || err == DB_DEADLOCK);
5242
5243 return (err);
5244 }
5245
5246 /** Creates an explicit record lock for a running transaction that currently
5247 only has an implicit lock on the record. The transaction instance must have a
5248 reference count > 0 so that it can't be committed and freed before this
5249 function has completed. */
5250 static void lock_rec_convert_impl_to_expl_for_trx(
5251 const buf_block_t *block, /*!< in: buffer block of rec */
5252 const rec_t *rec, /*!< in: user record on page */
5253 dict_index_t *index, /*!< in: index of record */
5254 const ulint *offsets, /*!< in: rec_get_offsets(rec, index) */
5255 trx_t *trx, /*!< in/out: active transaction */
5256 ulint heap_no) /*!< in: rec heap number to lock */
5257 {
5258 ut_ad(trx_is_referenced(trx));
5259
5260 DEBUG_SYNC_C("before_lock_rec_convert_impl_to_expl_for_trx");
5261 {
5262 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5263 /* This trx->mutex acquisition here is not really needed.
5264 Its purpose is to prevent a state transition between calls to trx_state_eq()
5265 and lock_rec_add_to_queue().
5266 But one can prove, that even if the state did change, it is not
5267 a big problem, because we still keep reference count from dropping
5268 to zero, so the trx object is still in use, and we hold the shard latched,
5269 so trx can not release its explicit lock (if it has any) so we will
5270 notice the explicit lock in lock_rec_has_expl.
5271 On the other hand if trx does not have explicit lock, then we would create
5272 one on its behalf, which is wasteful, but does not cause a problem, as once
5273 the reference count drops to zero the trx will notice and remove this new
5274 explicit lock. Also, even if some other trx had observed that trx is already
5275 removed from rw trxs list and thus ignored the implicit lock and decided to
5276 add its own lock, it will still have to wait for shard latch before adding
5277 her lock. However it does not cost us much to simply take the trx->mutex
5278 and avoid this whole shaky reasoning. */
5279 trx_mutex_enter(trx);
5280
5281 ut_ad(!index->is_clustered() ||
5282 trx->id ==
5283 lock_clust_rec_some_has_impl(
5284 rec, index,
5285 offsets ? offsets : Rec_offsets().compute(rec, index)));
5286
5287 ut_ad(!trx_state_eq(trx, TRX_STATE_NOT_STARTED));
5288
5289 if (!trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY) &&
5290 !lock_rec_has_expl(LOCK_X | LOCK_REC_NOT_GAP, block, heap_no, trx)) {
5291 ulint type_mode;
5292
5293 type_mode = (LOCK_REC | LOCK_X | LOCK_REC_NOT_GAP);
5294
5295 lock_rec_add_to_queue(type_mode, block, heap_no, index, trx, true);
5296 }
5297
5298 trx_mutex_exit(trx);
5299 }
5300
5301 trx_release_reference(trx);
5302
5303 DEBUG_SYNC_C("after_lock_rec_convert_impl_to_expl_for_trx");
5304 }
5305
5306 void lock_rec_convert_impl_to_expl(const buf_block_t *block, const rec_t *rec,
5307 dict_index_t *index, const ulint *offsets) {
5308 trx_t *trx;
5309
5310 ut_ad(!locksys::owns_exclusive_global_latch());
5311 ut_ad(page_rec_is_user_rec(rec));
5312 ut_ad(rec_offs_validate(rec, index, offsets));
5313 ut_ad(!page_rec_is_comp(rec) == !rec_offs_comp(offsets));
5314
5315 DEBUG_SYNC_C("lock_rec_convert_impl_to_expl");
5316
5317 if (index->is_clustered()) {
5318 trx_id_t trx_id;
5319
5320 trx_id = lock_clust_rec_some_has_impl(rec, index, offsets);
5321
5322 trx = trx_rw_is_active(trx_id, true);
5323 } else {
5324 ut_ad(!dict_index_is_online_ddl(index));
5325
5326 trx = lock_sec_rec_some_has_impl(rec, index, offsets);
5327 if (trx) {
5328 DEBUG_SYNC_C("lock_rec_convert_impl_to_expl_will_validate");
5329 ut_ad(!lock_rec_other_trx_holds_expl(LOCK_S | LOCK_REC_NOT_GAP, trx, rec,
5330 block));
5331 }
5332 }
5333
5334 if (trx != nullptr) {
5335 ulint heap_no = page_rec_get_heap_no(rec);
5336
5337 ut_ad(trx_is_referenced(trx));
5338
5339 /* If the transaction is still active and has no
5340 explicit x-lock set on the record, set one for it.
5341 trx cannot be committed until the ref count is zero. */
5342
5343 lock_rec_convert_impl_to_expl_for_trx(block, rec, index, offsets, trx,
5344 heap_no);
5345 }
5346 }
5347
5348 /** Checks if locks of other transactions prevent an immediate modify (update,
5349 delete mark, or delete unmark) of a clustered index record. If they do,
5350 first tests if the query thread should anyway be suspended for some
5351 reason; if not, then puts the transaction and the query thread to the
5352 lock wait state and inserts a waiting request for a record x-lock to the
5353 lock queue.
5354 @return DB_SUCCESS, DB_LOCK_WAIT, or DB_DEADLOCK */
5355 dberr_t lock_clust_rec_modify_check_and_lock(
5356 ulint flags, /*!< in: if BTR_NO_LOCKING_FLAG
5357 bit is set, does nothing */
5358 const buf_block_t *block, /*!< in: buffer block of rec */
5359 const rec_t *rec, /*!< in: record which should be
5360 modified */
5361 dict_index_t *index, /*!< in: clustered index */
5362 const ulint *offsets, /*!< in: rec_get_offsets(rec, index) */
5363 que_thr_t *thr) /*!< in: query thread */
5364 {
5365 dberr_t err;
5366 ulint heap_no;
5367
5368 ut_ad(rec_offs_validate(rec, index, offsets));
5369 ut_ad(index->is_clustered());
5370 ut_ad(block->frame == page_align(rec));
5371
5372 if (flags & BTR_NO_LOCKING_FLAG) {
5373 return (DB_SUCCESS);
5374 }
5375 ut_ad(!index->table->is_temporary());
5376
5377 heap_no = rec_offs_comp(offsets) ? rec_get_heap_no_new(rec)
5378 : rec_get_heap_no_old(rec);
5379
5380 /* If a transaction has no explicit x-lock set on the record, set one
5381 for it */
5382
5383 lock_rec_convert_impl_to_expl(block, rec, index, offsets);
5384
5385 {
5386 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5387 ut_ad(lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
5388
5389 err = lock_rec_lock(true, SELECT_ORDINARY, LOCK_X | LOCK_REC_NOT_GAP, block,
5390 heap_no, index, thr);
5391
5392 MONITOR_INC(MONITOR_NUM_RECLOCK_REQ);
5393 }
5394
5395 ut_d(locksys::rec_queue_latch_and_validate(block, rec, index, offsets));
5396
5397 if (err == DB_SUCCESS_LOCKED_REC) {
5398 err = DB_SUCCESS;
5399 }
5400 ut_ad(err == DB_SUCCESS || err == DB_LOCK_WAIT || err == DB_DEADLOCK);
5401 return (err);
5402 }
5403
5404 /** Checks if locks of other transactions prevent an immediate modify (delete
5405 mark or delete unmark) of a secondary index record.
5406 @return DB_SUCCESS, DB_LOCK_WAIT, or DB_DEADLOCK */
5407 dberr_t lock_sec_rec_modify_check_and_lock(
5408 ulint flags, /*!< in: if BTR_NO_LOCKING_FLAG
5409 bit is set, does nothing */
5410 buf_block_t *block, /*!< in/out: buffer block of rec */
5411 const rec_t *rec, /*!< in: record which should be
5412 modified; NOTE: as this is a secondary
5413 index, we always have to modify the
5414 clustered index record first: see the
5415 comment below */
5416 dict_index_t *index, /*!< in: secondary index */
5417 que_thr_t *thr, /*!< in: query thread
5418 (can be NULL if BTR_NO_LOCKING_FLAG) */
5419 mtr_t *mtr) /*!< in/out: mini-transaction */
5420 {
5421 dberr_t err;
5422 ulint heap_no;
5423
5424 ut_ad(!index->is_clustered());
5425 ut_ad(!dict_index_is_online_ddl(index) || (flags & BTR_CREATE_FLAG));
5426 ut_ad(block->frame == page_align(rec));
5427
5428 if (flags & BTR_NO_LOCKING_FLAG) {
5429 return (DB_SUCCESS);
5430 }
5431 ut_ad(!index->table->is_temporary());
5432
5433 heap_no = page_rec_get_heap_no(rec);
5434
5435 /* Another transaction cannot have an implicit lock on the record,
5436 because when we come here, we already have modified the clustered
5437 index record, and this would not have been possible if another active
5438 transaction had modified this secondary index record. */
5439 {
5440 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5441
5442 ut_ad(lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
5443
5444 err = lock_rec_lock(true, SELECT_ORDINARY, LOCK_X | LOCK_REC_NOT_GAP, block,
5445 heap_no, index, thr);
5446
5447 MONITOR_INC(MONITOR_NUM_RECLOCK_REQ);
5448 }
5449
5450 ut_d(locksys::rec_queue_latch_and_validate(block, rec, index));
5451
5452 if (err == DB_SUCCESS || err == DB_SUCCESS_LOCKED_REC) {
5453 /* Update the page max trx id field */
5454 /* It might not be necessary to do this if
5455 err == DB_SUCCESS (no new lock created),
5456 but it should not cost too much performance. */
5457 page_update_max_trx_id(block, buf_block_get_page_zip(block),
5458 thr_get_trx(thr)->id, mtr);
5459 err = DB_SUCCESS;
5460 }
5461 ut_ad(err == DB_SUCCESS || err == DB_LOCK_WAIT || err == DB_DEADLOCK);
5462 return (err);
5463 }
5464
5465 dberr_t lock_sec_rec_read_check_and_lock(
5466 const lock_duration_t duration, const buf_block_t *block, const rec_t *rec,
5467 dict_index_t *index, const ulint *offsets, const select_mode sel_mode,
5468 const lock_mode mode, const ulint gap_mode, que_thr_t *thr) {
5469 dberr_t err;
5470 ulint heap_no;
5471
5472 ut_ad(!index->is_clustered());
5473 ut_ad(!dict_index_is_online_ddl(index));
5474 ut_ad(block->frame == page_align(rec));
5475 ut_ad(page_rec_is_user_rec(rec) || page_rec_is_supremum(rec));
5476 ut_ad(rec_offs_validate(rec, index, offsets));
5477 ut_ad(mode == LOCK_X || mode == LOCK_S);
5478
5479 if (srv_read_only_mode || index->table->is_temporary()) {
5480 return (DB_SUCCESS);
5481 }
5482
5483 heap_no = page_rec_get_heap_no(rec);
5484
5485 if (!page_rec_is_supremum(rec)) {
5486 lock_rec_convert_impl_to_expl(block, rec, index, offsets);
5487 }
5488 {
5489 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5490
5491 if (duration == lock_duration_t::AT_LEAST_STATEMENT) {
5492 lock_protect_locks_till_statement_end(thr);
5493 }
5494
5495 ut_ad(mode != LOCK_X ||
5496 lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
5497 ut_ad(mode != LOCK_S ||
5498 lock_table_has(thr_get_trx(thr), index->table, LOCK_IS));
5499
5500 err = lock_rec_lock(false, sel_mode, mode | gap_mode, block, heap_no, index,
5501 thr);
5502
5503 MONITOR_INC(MONITOR_NUM_RECLOCK_REQ);
5504 }
5505 DEBUG_SYNC_C("lock_sec_rec_read_check_and_lock_has_locked");
5506
5507 ut_d(locksys::rec_queue_latch_and_validate(block, rec, index, offsets));
5508 ut_ad(err == DB_SUCCESS || err == DB_SUCCESS_LOCKED_REC ||
5509 err == DB_LOCK_WAIT || err == DB_DEADLOCK || err == DB_SKIP_LOCKED ||
5510 err == DB_LOCK_NOWAIT);
5511 return (err);
5512 }
5513
5514 dberr_t lock_clust_rec_read_check_and_lock(
5515 const lock_duration_t duration, const buf_block_t *block, const rec_t *rec,
5516 dict_index_t *index, const ulint *offsets, const select_mode sel_mode,
5517 const lock_mode mode, const ulint gap_mode, que_thr_t *thr) {
5518 dberr_t err;
5519 ulint heap_no;
5520 DEBUG_SYNC_C("before_lock_clust_rec_read_check_and_lock");
5521 ut_ad(index->is_clustered());
5522 ut_ad(block->frame == page_align(rec));
5523 ut_ad(page_rec_is_user_rec(rec) || page_rec_is_supremum(rec));
5524 ut_ad(gap_mode == LOCK_ORDINARY || gap_mode == LOCK_GAP ||
5525 gap_mode == LOCK_REC_NOT_GAP);
5526 ut_ad(rec_offs_validate(rec, index, offsets));
5527
5528 if (srv_read_only_mode || index->table->is_temporary()) {
5529 return (DB_SUCCESS);
5530 }
5531
5532 heap_no = page_rec_get_heap_no(rec);
5533
5534 if (heap_no != PAGE_HEAP_NO_SUPREMUM) {
5535 lock_rec_convert_impl_to_expl(block, rec, index, offsets);
5536 }
5537
5538 DEBUG_SYNC_C("after_lock_clust_rec_read_check_and_lock_impl_to_expl");
5539 {
5540 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
5541
5542 if (duration == lock_duration_t::AT_LEAST_STATEMENT) {
5543 lock_protect_locks_till_statement_end(thr);
5544 }
5545
5546 ut_ad(mode != LOCK_X ||
5547 lock_table_has(thr_get_trx(thr), index->table, LOCK_IX));
5548 ut_ad(mode != LOCK_S ||
5549 lock_table_has(thr_get_trx(thr), index->table, LOCK_IS));
5550
5551 err = lock_rec_lock(false, sel_mode, mode | gap_mode, block, heap_no, index,
5552 thr);
5553
5554 MONITOR_INC(MONITOR_NUM_RECLOCK_REQ);
5555 }
5556 DEBUG_SYNC_C("after_lock_clust_rec_read_check_and_lock");
5557
5558 ut_d(locksys::rec_queue_latch_and_validate(block, rec, index, offsets));
5559
5560 ut_ad(err == DB_SUCCESS || err == DB_SUCCESS_LOCKED_REC ||
5561 err == DB_LOCK_WAIT || err == DB_DEADLOCK || err == DB_SKIP_LOCKED ||
5562 err == DB_LOCK_NOWAIT);
5563 return (err);
5564 }
5565 /** Checks if locks of other transactions prevent an immediate read, or passing
5566 over by a read cursor, of a clustered index record. If they do, first tests
5567 if the query thread should anyway be suspended for some reason; if not, then
5568 puts the transaction and the query thread to the lock wait state and inserts a
5569 waiting request for a record lock to the lock queue. Sets the requested mode
5570 lock on the record. This is an alternative version of
5571 lock_clust_rec_read_check_and_lock() that does not require the parameter
5572 "offsets".
5573 @return DB_SUCCESS, DB_LOCK_WAIT, or DB_DEADLOCK */
5574 dberr_t lock_clust_rec_read_check_and_lock_alt(
5575 const buf_block_t *block, /*!< in: buffer block of rec */
5576 const rec_t *rec, /*!< in: user record or page
5577 supremum record which should
5578 be read or passed over by a
5579 read cursor */
5580 dict_index_t *index, /*!< in: clustered index */
5581 lock_mode mode, /*!< in: mode of the lock which
5582 the read cursor should set on
5583 records: LOCK_S or LOCK_X; the
5584 latter is possible in
5585 SELECT FOR UPDATE */
5586 ulint gap_mode, /*!< in: LOCK_ORDINARY, LOCK_GAP, or
5587 LOCK_REC_NOT_GAP */
5588 que_thr_t *thr) /*!< in: query thread */
5589 {
5590 dberr_t err = lock_clust_rec_read_check_and_lock(
5591 lock_duration_t::REGULAR, block, rec, index,
5592 Rec_offsets().compute(rec, index), SELECT_ORDINARY, mode, gap_mode, thr);
5593
5594 if (err == DB_SUCCESS_LOCKED_REC) {
5595 err = DB_SUCCESS;
5596 }
5597 ut_ad(err == DB_SUCCESS || err == DB_LOCK_WAIT || err == DB_DEADLOCK);
5598 return (err);
5599 }
5600
5601 /** Release the last lock from the transaction's autoinc locks.
5602 @param[in] trx trx which vector of AUTOINC locks to modify */
5603 static inline void lock_release_autoinc_last_lock(trx_t *trx) {
5604 ulint last;
5605 lock_t *lock;
5606
5607 /* We will access trx->lock.autoinc_locks which requires trx->mutex */
5608 ut_ad(trx_mutex_own(trx));
5609 ib_vector_t *autoinc_locks = trx->lock.autoinc_locks;
5610
5611 /* Since we do not know for which table the trx has created the last lock
5612 we can not narrow the required latch to any particular shard, and thus we
5613 require exclusive access to lock_sys here */
5614 ut_ad(locksys::owns_exclusive_global_latch());
5615 ut_a(!ib_vector_is_empty(autoinc_locks));
5616
5617 /* The lock to be release must be the last lock acquired. */
5618 last = ib_vector_size(autoinc_locks) - 1;
5619 lock = *static_cast<lock_t **>(ib_vector_get(autoinc_locks, last));
5620
5621 /* Should have only AUTOINC locks in the vector. */
5622 ut_a(lock_get_mode(lock) == LOCK_AUTO_INC);
5623 ut_a(lock_get_type(lock) == LOCK_TABLE);
5624
5625 ut_a(lock->tab_lock.table != nullptr);
5626
5627 /* This will remove the lock from the trx autoinc_locks too. */
5628 lock_table_dequeue(lock);
5629 }
5630
5631 /** Check if a transaction holds any autoinc locks.
5632 @return true if the transaction holds any AUTOINC locks. */
5633 static bool lock_trx_holds_autoinc_locks(
5634 const trx_t *trx) /*!< in: transaction */
5635 {
5636 /* We will access trx->lock.autoinc_locks which requires trx->mutex */
5637 ut_ad(trx_mutex_own(trx));
5638 ut_a(trx->lock.autoinc_locks != nullptr);
5639
5640 return (!ib_vector_is_empty(trx->lock.autoinc_locks));
5641 }
5642
5643 /** Release all the transaction's autoinc locks. */
5644 static void lock_release_autoinc_locks(trx_t *trx) /*!< in/out: transaction */
5645 {
5646 /* Since we do not know for which table(s) the trx has created the lock(s)
5647 we can not narrow the required latch to any particular shard, and thus we
5648 require exclusive access to lock_sys here */
5649 ut_ad(locksys::owns_exclusive_global_latch());
5650 ut_ad(trx_mutex_own(trx));
5651
5652 ut_a(trx->lock.autoinc_locks != nullptr);
5653
5654 /* We release the locks in the reverse order. This is to
5655 avoid searching the vector for the element to delete at
5656 the lower level. See (lock_table_remove_low()) for details. */
5657 while (!ib_vector_is_empty(trx->lock.autoinc_locks)) {
5658 /* lock_table_remove_low() will also remove the lock from
5659 the transaction's autoinc_locks vector. */
5660 lock_release_autoinc_last_lock(trx);
5661 }
5662
5663 /* Should release all locks. */
5664 ut_a(ib_vector_is_empty(trx->lock.autoinc_locks));
5665 }
5666
5667 /** Gets the type of a lock. Non-inline version for using outside of the
5668 lock module.
5669 @return LOCK_TABLE or LOCK_REC */
5670 uint32_t lock_get_type(const lock_t *lock) /*!< in: lock */
5671 {
5672 return (lock_get_type_low(lock));
5673 }
5674
5675 trx_id_t lock_get_trx_id(const lock_t *lock) {
5676 return (trx_get_id_for_print(lock->trx));
5677 }
5678
5679 /** Get the performance schema event (thread_id, event_id)
5680 that created the lock.
5681 @param[in] lock Lock
5682 @param[out] thread_id Thread ID that created the lock
5683 @param[out] event_id Event ID that created the lock
5684 */
5685 void lock_get_psi_event(const lock_t *lock, ulonglong *thread_id,
5686 ulonglong *event_id) {
5687 #if defined(HAVE_PSI_THREAD_INTERFACE) && defined(HAVE_PSI_DATA_LOCK_INTERFACE)
5688 *thread_id = lock->m_psi_internal_thread_id;
5689 *event_id = lock->m_psi_event_id;
5690 #else
5691 *thread_id = 0;
5692 *event_id = 0;
5693 #endif
5694 }
5695
5696 /** Gets the mode of a lock in a human readable string.
5697 The string should not be free()'d or modified.
5698 This functions is a bit complex for following reasons:
5699 - the way it is used in performance schema requires that the memory pointed
5700 by the return value is accessible for a long time
5701 - the caller never frees the memory
5702 - so, we need to maintain a pool of these strings or use string literals
5703 - there are many possible combinations of flags and thus it is impractical
5704 to maintain the list of all possible literals and if/else logic
5705 - moreover, sometimes performance_schema.data_locks is used precisely to
5706 investigate some unexpected situation, thus limiting output of this function
5707 only to expected combinations of flags might be misleading
5708 @return lock mode */
5709 const char *lock_get_mode_str(const lock_t *lock) /*!< in: lock */
5710 {
5711 std::lock_guard<std::mutex> guard(lock_cached_lock_mode_names_mutex);
5712
5713 const auto type_mode = lock->type_mode;
5714 const auto mode = lock->mode();
5715 const auto type = lock->type();
5716 /* type_mode is type + mode + flags actually.
5717 We are interested in flags here.
5718 And we are not interested in LOCK_WAIT. */
5719 const auto flags = (type_mode & (~(uint)LOCK_WAIT)) - mode - type;
5720
5721 /* Search for a cached string */
5722 const auto key = flags | mode;
5723 const auto found = lock_cached_lock_mode_names.find(key);
5724 if (found != lock_cached_lock_mode_names.end()) {
5725 return (found->second);
5726 }
5727 /* A new, unseen yet, mode of lock. We need to create new string. */
5728 ut::ostringstream name_stream;
5729 /* lock_mode_string can be used to describe mode, however the LOCK_ prefix in
5730 return mode name makes the string a bit too verbose for our purpose, as
5731 performance_schema.data_locks LOCK_MODE is a varchar(32), so we strip the
5732 prefix */
5733 const char *mode_string = lock_mode_string(mode);
5734 const char *LOCK_PREFIX = "LOCK_";
5735 if (!strncmp(mode_string, LOCK_PREFIX, strlen(LOCK_PREFIX))) {
5736 mode_string = mode_string + strlen(LOCK_PREFIX);
5737 }
5738 name_stream << mode_string;
5739 /* We concatenate constants in ascending order. */
5740 uint recognized_flags = 0;
5741 for (const auto &lock_constant : lock_constant_names) {
5742 const auto value = lock_constant.first;
5743 /* Constants have to be single bit only for this algorithm to work */
5744 ut_ad((value & (value - 1)) == 0);
5745 if (flags & value) {
5746 recognized_flags += value;
5747 name_stream << ',' << lock_constant.second;
5748 }
5749 }
5750 if (flags != recognized_flags) {
5751 return "UNKNOWN";
5752 }
5753 auto name_string = name_stream.str();
5754 char *name_buffer = (char *)ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY,
5755 name_string.length() + 1);
5756 strcpy(name_buffer, name_string.c_str());
5757 lock_cached_lock_mode_names[key] = name_buffer;
5758 return (name_buffer);
5759 }
5760
5761 /** Gets the type of a lock in a human readable string.
5762 The string should not be free()'d or modified.
5763 @return lock type */
5764 const char *lock_get_type_str(const lock_t *lock) /*!< in: lock */
5765 {
5766 switch (lock_get_type_low(lock)) {
5767 case LOCK_REC:
5768 return ("RECORD");
5769 case LOCK_TABLE:
5770 return ("TABLE");
5771 default:
5772 return ("UNKNOWN");
5773 }
5774 }
5775
5776 /** Gets the table on which the lock is.
5777 @return table */
5778 static inline dict_table_t *lock_get_table(const lock_t *lock) /*!< in: lock */
5779 {
5780 switch (lock_get_type_low(lock)) {
5781 case LOCK_REC:
5782 ut_ad(lock->index->is_clustered() ||
5783 !dict_index_is_online_ddl(lock->index));
5784 return (lock->index->table);
5785 case LOCK_TABLE:
5786 return (lock->tab_lock.table);
5787 default:
5788 ut_error;
5789 }
5790 }
5791
5792 /** Gets the id of the table on which the lock is.
5793 @return id of the table */
5794 table_id_t lock_get_table_id(const lock_t *lock) /*!< in: lock */
5795 {
5796 dict_table_t *table;
5797
5798 table = lock_get_table(lock);
5799
5800 return (table->id);
5801 }
5802
5803 /** Determine which table a lock is associated with.
5804 @param[in] lock the lock
5805 @return name of the table */
5806 const table_name_t &lock_get_table_name(const lock_t *lock) {
5807 return (lock_get_table(lock)->name);
5808 }
5809
5810 /** For a record lock, gets the index on which the lock is.
5811 @return index */
5812 const dict_index_t *lock_rec_get_index(const lock_t *lock) /*!< in: lock */
5813 {
5814 ut_a(lock_get_type_low(lock) == LOCK_REC);
5815 ut_ad(lock->index->is_clustered() || !dict_index_is_online_ddl(lock->index));
5816
5817 return (lock->index);
5818 }
5819
5820 /** For a record lock, gets the name of the index on which the lock is.
5821 The string should not be free()'d or modified.
5822 @return name of the index */
5823 const char *lock_rec_get_index_name(const lock_t *lock) /*!< in: lock */
5824 {
5825 ut_a(lock_get_type_low(lock) == LOCK_REC);
5826 ut_ad(lock->index->is_clustered() || !dict_index_is_online_ddl(lock->index));
5827
5828 return (lock->index->name);
5829 }
5830
5831 page_id_t lock_rec_get_page_id(const lock_t *lock) {
5832 ut_a(lock_get_type_low(lock) == LOCK_REC);
5833 return lock->rec_lock.page_id;
5834 }
5835
5836 void lock_cancel_waiting_and_release(trx_t *trx) {
5837 ut_ad(trx_mutex_own(trx));
5838 const auto lock = trx->lock.wait_lock.load();
5839 ut_ad(locksys::owns_lock_shard(lock));
5840
5841 if (lock_get_type_low(lock) == LOCK_REC) {
5842 lock_rec_dequeue_from_page(lock);
5843 } else {
5844 ut_ad(lock_get_type_low(lock) & LOCK_TABLE);
5845
5846 lock_table_dequeue(lock);
5847 }
5848
5849 lock_reset_wait_and_release_thread_if_suspended(lock);
5850 }
5851
5852 /** Unlocks AUTO_INC type locks that were possibly reserved by a trx. This
5853 function should be called at the the end of an SQL statement, by the
5854 connection thread that owns the transaction (trx->mysql_thd). */
5855 void lock_unlock_table_autoinc(trx_t *trx) /*!< in/out: transaction */
5856 {
5857 ut_ad(!locksys::owns_exclusive_global_latch());
5858 ut_ad(!trx_mutex_own(trx));
5859
5860 /* This can be invoked on NOT_STARTED, ACTIVE, PREPARED,
5861 but not COMMITTED transactions. */
5862
5863 ut_ad(trx_state_eq(trx, TRX_STATE_NOT_STARTED) ||
5864 trx_state_eq(trx, TRX_STATE_FORCED_ROLLBACK) ||
5865 !trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY));
5866
5867 /* The trx->lock.autoinc_locks are protected by trx->mutex and in principle
5868 can be modified by other threads:
5869 1. When the other thread calls lock_grant on trx->lock.wait_lock.
5870 (This is impossible here, because we've verified !trx->lock.wait_lock)
5871 2. During recovery lock_remove_recoverd_trx_record_locks ->
5872 lock_table_remove_low -> lock_table_remove_autoinc_lock ->
5873 lock_table_pop_autoinc_lock.
5874 (But AFAIK recovery is a single-threaded process)
5875 3. During DROP TABLE lock_remove_all_on_table_for_trx ->
5876 lock_table_remove_low ...
5877 (I'm unsure if this is possible to happen in parallel to our trx)
5878 Please note, that from this list only lock_grant tries to add something
5879 to the trx->lock.autoinc_locks (namely the granted AUTOINC lock), and the
5880 others try to remove something. This means that we can treat the result of
5881 lock_trx_holds_autoinc_locks(trx) as a heuristic. If it returns true,
5882 then it might or (with small probability) might not hold locks, so we better
5883 call lock_release_autoinc_locks with proper latching.
5884 If it returns false, then it is guaranteed that the vector will remain empty.
5885 If we like risk, we could even call lock_trx_holds_autoinc_locks without
5886 trx->mutex protection, but:
5887 1. why risk? It is not obvious how thread-safe our vector implementation is
5888 2. trx->mutex is cheap
5889 */
5890 trx_mutex_enter(trx);
5891 ut_ad(!trx->lock.wait_lock);
5892 bool might_have_autoinc_locks = lock_trx_holds_autoinc_locks(trx);
5893 trx_mutex_exit(trx);
5894
5895 if (might_have_autoinc_locks) {
5896 /* lock_release_autoinc_locks() requires exclusive global latch as the
5897 AUTOINC locks might be on tables from different shards. Identifying and
5898 latching them in correct order would complicate this rarely-taken path. */
5899 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
5900 trx_mutex_enter(trx);
5901 lock_release_autoinc_locks(trx);
5902 trx_mutex_exit(trx);
5903 }
5904 }
5905
5906 /** Releases a transaction's locks, and releases possible other transactions
5907 waiting because of these locks. Change the state of the transaction to
5908 TRX_STATE_COMMITTED_IN_MEMORY. */
5909 void lock_trx_release_locks(trx_t *trx) /*!< in/out: transaction */
5910 {
5911 DEBUG_SYNC_C("before_lock_trx_release_locks");
5912
5913 trx_mutex_enter(trx);
5914
5915 check_trx_state(trx);
5916 ut_ad(trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY));
5917 ut_ad(!trx->in_rw_trx_list);
5918
5919 if (trx_is_referenced(trx)) {
5920 while (trx_is_referenced(trx)) {
5921 trx_mutex_exit(trx);
5922
5923 DEBUG_SYNC_C("waiting_trx_is_not_referenced");
5924
5925 /** Doing an implicit to explicit conversion
5926 should not be expensive. */
5927 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
5928
5929 trx_mutex_enter(trx);
5930 }
5931 }
5932
5933 ut_ad(!trx_is_referenced(trx));
5934 trx_mutex_exit(trx);
5935
5936 while (!locksys::try_release_all_locks(trx)) {
5937 std::this_thread::yield();
5938 }
5939
5940 /* We don't free the locks one by one for efficiency reasons.
5941 We simply empty the heap one go. Similarly we reset n_rec_locks count to 0.
5942 At this point there should be no one else interested in our trx's
5943 locks as we've released and removed all of them, and the trx is no longer
5944 referenced so nobody will attempt implicit to explicit conversion neither.
5945 Please note that we are either the thread which runs the transaction, or we
5946 are the thread of a high priority transaction which decided to kill trx, in
5947 which case it had to first make sure that it is no longer running in InnoDB.
5948 So no race is expected to happen.
5949 All that being said, it does not cost us anything in terms of performance to
5950 protect these operations with trx->mutex, which makes some class of errors
5951 impossible even if the above reasoning was wrong. */
5952 trx_mutex_enter(trx);
5953 trx->lock.n_rec_locks.store(0);
5954
5955 ut_a(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0);
5956 ut_a(ib_vector_is_empty(trx->lock.autoinc_locks));
5957
5958 mem_heap_empty(trx->lock.lock_heap);
5959 trx_mutex_exit(trx);
5960 }
5961
5962 bool lock_cancel_if_waiting_and_release(const TrxVersion trx_version) {
5963 trx_t &trx{*trx_version.m_trx};
5964 bool realeased = false;
5965 locksys::run_if_waiting(trx_version, [&]() {
5966 ut_ad(trx_mutex_own(&trx));
5967 ut_a(trx_version.m_version == trx.version.load());
5968 if ((trx.in_innodb & TRX_FORCE_ROLLBACK) != 0) {
5969 /* A HP transaction wants to wake up and rollback trx by pretending it
5970 has been chosen a deadlock victim while waiting for a lock. */
5971 #ifdef UNIV_DEBUG
5972 ib::info(ER_IB_MSG_639, to_string(trx.killed_by).c_str(),
5973 ulonglong{trx.id});
5974 #endif /* UNIV_DEBUG */
5975 trx.lock.was_chosen_as_deadlock_victim = true;
5976 } else {
5977 /* This case is currently used by kill_connection. Canceling the
5978 wait and waking up the transaction will have the effect that its
5979 thread will continue without the lock acquired, which is unsafe,
5980 unless it will notice that it has been interrupted and give up. */
5981 ut_ad(trx_is_interrupted(&trx));
5982 }
5983 lock_cancel_waiting_and_release(&trx);
5984 realeased = true;
5985 });
5986 return realeased;
5987 }
5988
5989 #ifdef UNIV_DEBUG
5990 /** Scans all locks of all transactions in the rw_trx_list searching for any
5991 lock (table or rec) against the table.
5992 @param[in] table the table for which we perform the search
5993 @return lock if found */
5994 static const lock_t *lock_table_locks_lookup(const dict_table_t *table) {
5995 ut_a(table != nullptr);
5996 /* We are going to iterate over multiple transactions, so even though we know
5997 which table we are looking for we can not narrow required latch to just the
5998 shard which contains the table, because accessing trx->lock.trx_locks would be
5999 unsafe */
6000 ut_ad(locksys::owns_exclusive_global_latch());
6001 ut_ad(trx_sys_mutex_own());
6002
6003 for (auto trx : trx_sys->rw_trx_list) {
6004 check_trx_state(trx);
6005
6006 for (auto lock : trx->lock.trx_locks) {
6007 ut_a(lock->trx == trx);
6008
6009 if (lock_get_type_low(lock) == LOCK_REC) {
6010 ut_ad(!dict_index_is_online_ddl(lock->index) ||
6011 lock->index->is_clustered());
6012 if (lock->index->table == table) {
6013 return (lock);
6014 }
6015 } else if (lock->tab_lock.table == table) {
6016 return (lock);
6017 }
6018 }
6019 }
6020
6021 return (nullptr);
6022 }
6023 #endif /* UNIV_DEBUG */
6024
6025 bool lock_table_has_locks(const dict_table_t *table) {
6026 /** The n_rec_locks field might be modified by operation on any page shard.
6027 This function is called in contexts where we believe that the number of
6028 locks should either be zero or decreasing.
6029 For such scenario of usage, we can read the n_rec_locks without any latch
6030 and restrict latch just to the table's shard and release it before return,
6031 which means `true` could be a false-positive, but `false` is certain. */
6032
6033 bool has_locks = table->n_rec_locks.load() > 0;
6034 if (!has_locks) {
6035 /* As soon as we return false the caller might free the table object, so it
6036 is crucial that when lock_table_dequeue() removes the last lock on the table
6037 then the thread calling it won't dereference the table pointer anymore. */
6038 has_locks = UT_LIST_GET_LEN(table->locks) > 0;
6039 }
6040
6041 #ifdef UNIV_DEBUG
6042 if (!has_locks) {
6043 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
6044 mutex_enter(&trx_sys->mutex);
6045
6046 ut_ad(!lock_table_locks_lookup(table));
6047
6048 mutex_exit(&trx_sys->mutex);
6049 }
6050 #endif /* UNIV_DEBUG */
6051
6052 return (has_locks);
6053 }
6054 /** Set the lock system timeout event. */
6055 void lock_set_timeout_event() { os_event_set(lock_sys->timeout_event); }
6056
6057 #ifdef UNIV_DEBUG
6058
6059 bool lock_trx_has_rec_x_lock(que_thr_t *thr, const dict_table_t *table,
6060 const buf_block_t *block, ulint heap_no) {
6061 ut_ad(heap_no > PAGE_HEAP_NO_SUPREMUM);
6062
6063 const trx_t *trx = thr_get_trx(thr);
6064 locksys::Shard_latch_guard guard{UT_LOCATION_HERE, block->get_page_id()};
6065 ut_a(lock_table_has(trx, table, LOCK_IX) || table->is_temporary());
6066 ut_a(lock_rec_has_expl(LOCK_X | LOCK_REC_NOT_GAP, block, heap_no, trx) ||
6067 table->is_temporary());
6068 return (true);
6069 }
6070 #endif /* UNIV_DEBUG */
6071
6072 /** rewind(3) the file used for storing the latest detected deadlock and
6073 print a heading message to stderr if printing of all deadlocks to stderr
6074 is enabled. */
6075 void Deadlock_notifier::start_print() {
6076 /* I/O operations on lock_latest_err_file require exclusive latch on
6077 lock_sys */
6078 ut_ad(locksys::owns_exclusive_global_latch());
6079
6080 rewind(lock_latest_err_file);
6081 ut_print_timestamp(lock_latest_err_file);
6082
6083 if (srv_print_all_deadlocks) {
6084 ib::info(ER_IB_MSG_643) << "Transactions deadlock detected, dumping"
6085 << " detailed information.";
6086 }
6087 }
6088
6089 /** Print a message to the deadlock file and possibly to stderr.
6090 @param msg message to print */
6091 void Deadlock_notifier::print(const char *msg) {
6092 /* I/O operations on lock_latest_err_file require exclusive latch on
6093 lock_sys */
6094 ut_ad(locksys::owns_exclusive_global_latch());
6095 fputs(msg, lock_latest_err_file);
6096
6097 if (srv_print_all_deadlocks) {
6098 ib::info(ER_IB_MSG_644) << msg;
6099 }
6100 }
6101
6102 /** Print transaction data to the deadlock file and possibly to stderr.
6103 @param trx transaction
6104 @param max_query_len max query length to print */
6105 void Deadlock_notifier::print(const trx_t *trx, ulint max_query_len) {
6106 /* We need exclusive latch on lock_sys because:
6107 1. I/O operations on lock_latest_err_file
6108 2. lock_number_of_rows_locked()
6109 3. Accessing trx->lock fields requires either holding trx->mutex or latching
6110 the lock sys. */
6111 ut_ad(locksys::owns_exclusive_global_latch());
6112
6113 trx_mutex_enter(trx);
6114 ulint n_rec_locks = lock_number_of_rows_locked(&trx->lock);
6115 ulint n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks);
6116 ulint heap_size = mem_heap_get_size(trx->lock.lock_heap);
6117 trx_mutex_exit(trx);
6118
6119 mutex_enter(&trx_sys->mutex);
6120
6121 trx_print_low(lock_latest_err_file, trx, max_query_len, n_rec_locks,
6122 n_trx_locks, heap_size);
6123
6124 if (srv_print_all_deadlocks) {
6125 trx_print_low(stderr, trx, max_query_len, n_rec_locks, n_trx_locks,
6126 heap_size);
6127 }
6128
6129 mutex_exit(&trx_sys->mutex);
6130 }
6131
6132 /** Print lock data to the deadlock file and possibly to stderr.
6133 @param lock record or table type lock */
6134 void Deadlock_notifier::print(const lock_t *lock) {
6135 /* I/O operations on lock_latest_err_file require exclusive latch on
6136 lock_sys. */
6137 ut_ad(locksys::owns_exclusive_global_latch());
6138
6139 if (lock_get_type_low(lock) == LOCK_REC) {
6140 lock_rec_print(lock_latest_err_file, lock);
6141
6142 if (srv_print_all_deadlocks) {
6143 lock_rec_print(stderr, lock);
6144 }
6145 } else {
6146 lock_table_print(lock_latest_err_file, lock);
6147
6148 if (srv_print_all_deadlocks) {
6149 lock_table_print(stderr, lock);
6150 }
6151 }
6152 }
6153
6154 void Deadlock_notifier::print_title(size_t pos_on_cycle, const char *title) {
6155 /* I/O operations on lock_latest_err_file require exclusive latch on
6156 lock_sys */
6157 ut_ad(locksys::owns_exclusive_global_latch());
6158 ut::ostringstream buff;
6159 buff << "\n*** (" << (pos_on_cycle + 1) << ") " << title << ":\n";
6160 print(buff.str().c_str());
6161 }
6162
6163 void Deadlock_notifier::notify(const ut::vector<const trx_t *> &trxs_on_cycle,
6164 const trx_t *victim_trx) {
6165 ut_ad(locksys::owns_exclusive_global_latch());
6166
6167 start_print();
6168 const auto n = trxs_on_cycle.size();
6169 for (size_t i = 0; i < n; ++i) {
6170 const trx_t *trx = trxs_on_cycle[i];
6171 const trx_t *blocked_trx = trxs_on_cycle[0 < i ? i - 1 : n - 1];
6172 const lock_t *blocking_lock =
6173 lock_has_to_wait_in_queue(blocked_trx->lock.wait_lock, trx);
6174 ut_a(blocking_lock);
6175
6176 print_title(i, "TRANSACTION");
6177 print(trx, 3000);
6178
6179 print_title(i, "HOLDS THE LOCK(S)");
6180 print(blocking_lock);
6181
6182 print_title(i, "WAITING FOR THIS LOCK TO BE GRANTED");
6183 print(trx->lock.wait_lock);
6184 }
6185 const auto victim_it =
6186 std::find(trxs_on_cycle.begin(), trxs_on_cycle.end(), victim_trx);
6187 ut_ad(victim_it != trxs_on_cycle.end());
6188 const auto victim_pos = std::distance(trxs_on_cycle.begin(), victim_it);
6189 ut::ostringstream buff;
6190 buff << "*** WE ROLL BACK TRANSACTION (" << (victim_pos + 1) << ")\n";
6191 print(buff.str().c_str());
6192 DBUG_PRINT("ib_lock", ("deadlock detected"));
6193
6194 #ifdef UNIV_DEBUG
6195 /* We perform this check only after information is output, to give a
6196 developer as much information as we can for debugging the problem */
6197 for (const trx_t *trx : trxs_on_cycle) {
6198 ut_ad(is_allowed_to_be_on_cycle(trx->lock.wait_lock));
6199 }
6200 #endif /* UNIV_DEBUG */
6201
6202 lock_deadlock_found = true;
6203 }
6204
6205 #ifdef UNIV_DEBUG
6206
6207 bool Deadlock_notifier::is_allowed_to_be_on_cycle(const lock_t *lock) {
6208 /* The original purpose of this validation is to check record locks from
6209 DD & SDI tables only, because we think a deadlock for these locks should be
6210 prevented by MDL and proper updating order, but later, some exemptions were
6211 introduced (for more context see comment to this function).
6212 In particular, we don't check table locks here, since there never was any
6213 guarantee saying a deadlock is impossible for table locks. */
6214 if (!lock->is_record_lock()) {
6215 return (true);
6216 }
6217 /* The only places where we don't expect deadlocks are in handling DD
6218 tables, and since WL#9538 also in code handling SDI tables.
6219 Therefore the second condition is that we only pay attention to DD and SDI
6220 tables. */
6221 const bool is_dd_or_sdi = (lock->index->table->is_dd_table ||
6222 dict_table_is_sdi(lock->index->table->id));
6223 if (!is_dd_or_sdi) {
6224 return (true);
6225 }
6226
6227 /* If we are still here, the lock is a record lock on some DD or SDI table.
6228 There are some such tables though, for which a deadlock is somewhat expected,
6229 for various reasons specific to these particular tables.
6230 So, we have a list of exceptions here:
6231
6232 innodb_table_stats and innodb_index_stats
6233 These two tables are visible to the end user, so can take part in
6234 quite arbitrary queries and transactions, so deadlock is possible.
6235 Therefore we need to allow such deadlocks, as otherwise a user
6236 could crash a debug build of a server by issuing a specific sequence of
6237 queries. DB_DEADLOCK error in dict0stats is either handled (see for
6238 example dict_stats_rename_table), or ignored silently (for example in
6239 dict_stats_process_entry_from_recalc_pool), but I am not aware of any
6240 situation in which DB_DEADLOCK could cause a serious problem.
6241 Most such queries are performed via dict_stats_exec_sql() which logs an
6242 ERROR in case of a DB_DEADLOCK, and also returns error code to the caller,
6243 so both the end user and a developer should be aware of a problem in case
6244 they want to do something about it.
6245
6246 table_stats and index_stats
6247 These two tables take part in queries which are issued by background
6248 threads, and the code which performs these queries can handle failures
6249 such as deadlocks, because they were expected at design phase. */
6250
6251 const char *name = lock->index->table->name.m_name;
6252 return (!strcmp(name, "mysql/innodb_table_stats") ||
6253 !strcmp(name, "mysql/innodb_index_stats") ||
6254 !strcmp(name, "mysql/table_stats") ||
6255 !strcmp(name, "mysql/index_stats"));
6256 }
6257 #endif /* UNIV_DEBUG */
6258
6259 /**
6260 Allocate cached locks for the transaction.
6261 @param trx allocate cached record locks for this transaction */
6262 void lock_trx_alloc_locks(trx_t *trx) {
6263 /* We will create trx->lock.table_pool and rec_pool which are protected by
6264 trx->mutex. In theory nobody else should use the trx object while it is being
6265 constructed, but how can we (the lock-sys) "know" about it and why risk? */
6266 trx_mutex_enter(trx);
6267 ulint sz = REC_LOCK_SIZE * REC_LOCK_CACHE;
6268 byte *ptr = reinterpret_cast<byte *>(
6269 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sz));
6270
6271 /* We allocate one big chunk and then distribute it among
6272 the rest of the elements. The allocated chunk pointer is always
6273 at index 0. */
6274
6275 for (ulint i = 0; i < REC_LOCK_CACHE; ++i, ptr += REC_LOCK_SIZE) {
6276 ut_a(ut::is_aligned_as<lock_t>(ptr));
6277 trx->lock.rec_pool.push_back(reinterpret_cast<ib_lock_t *>(ptr));
6278 }
6279
6280 sz = TABLE_LOCK_SIZE * TABLE_LOCK_CACHE;
6281 ptr = reinterpret_cast<byte *>(
6282 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sz));
6283
6284 for (ulint i = 0; i < TABLE_LOCK_CACHE; ++i, ptr += TABLE_LOCK_SIZE) {
6285 ut_a(ut::is_aligned_as<lock_t>(ptr));
6286 trx->lock.table_pool.push_back(reinterpret_cast<ib_lock_t *>(ptr));
6287 }
6288 trx_mutex_exit(trx);
6289 }
6290
6291 void lock_notify_about_deadlock(const ut::vector<const trx_t *> &trxs_on_cycle,
6292 const trx_t *victim_trx) {
6293 Deadlock_notifier::notify(trxs_on_cycle, victim_trx);
6294 }