Debian Codegraph @

storage/innobase/lock/lock0wait.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/lock0wait.cc
29 The transaction lock system
30
31 Created 25/5/2010 Sunny Bains
32 *******************************************************/
33
34 #define LOCK_MODULE_IMPLEMENTATION
35
36 #include <mysql/service_thd_wait.h>
37 #include <sys/types.h>
38
39 #include "ha_prototypes.h"
40 #include "lock0lock.h"
41 #include "lock0priv.h"
42 #include "os0thread-create.h"
43 #include "que0que.h"
44 #include "row0mysql.h"
45 #include "srv0mon.h"
46 #include "srv0start.h"
47
48 #include "my_dbug.h"
49
50 /** Print the contents of the lock_sys_t::waiting_threads array. */
51 static void lock_wait_table_print(void) {
52 ut_ad(lock_wait_mutex_own());
53
54 const srv_slot_t *slot = lock_sys->waiting_threads;
55
56 for (uint32_t i = 0; i < srv_max_n_threads; i++, ++slot) {
57 fprintf(
58 stderr,
59 "Slot %lu: thread type %lu, in use %lu, susp %lu, timeout %" PRIu64
60 ", time %" PRIu64 "\n",
61 (ulong)i, (ulong)slot->type, (ulong)slot->in_use,
62 (ulong)slot->suspended,
63 static_cast<uint64_t>(
64 std::chrono::duration_cast<std::chrono::seconds>(slot->wait_timeout)
65 .count()),
66 static_cast<uint64_t>(
67 std::chrono::duration_cast<std::chrono::seconds>(
68 std::chrono::steady_clock::now() - slot->suspend_time)
69 .count()));
70 }
71 }
72
73 /** Release a slot in the lock_sys_t::waiting_threads. Adjust the array last
74 pointer if there are empty slots towards the end of the table. */
75 static void lock_wait_table_release_slot(
76 srv_slot_t *slot) /*!< in: slot to release */
77 {
78 #ifdef UNIV_DEBUG
79 srv_slot_t *upper = lock_sys->waiting_threads + srv_max_n_threads;
80 #endif /* UNIV_DEBUG */
81
82 lock_wait_mutex_enter();
83 /* We omit trx_mutex_enter and a lock_sys latches here, because we are only
84 going to touch thr->slot, which is a member used only by lock0wait.cc and is
85 sufficiently protected by lock_wait_mutex. Yes, there are readers who read
86 the thr->slot holding only trx->mutex and a lock_sys latch, but they do so,
87 when they are sure that we were not woken up yet, so our thread can't be here.
88 See comments in lock_wait_release_thread_if_suspended() for more details. */
89
90 ut_ad(slot->in_use);
91 ut_ad(slot->thr != nullptr);
92 ut_ad(slot->thr->slot != nullptr);
93 ut_ad(slot->thr->slot == slot);
94
95 /* Must be within the array boundaries. */
96 ut_ad(slot >= lock_sys->waiting_threads);
97 ut_ad(slot < upper);
98
99 slot->thr->slot = nullptr;
100 slot->thr = nullptr;
101 slot->in_use = false;
102
103 /* Scan backwards and adjust the last free slot pointer. */
104 for (slot = lock_sys->last_slot;
105 slot > lock_sys->waiting_threads && !slot->in_use; --slot) {
106 /* No op */
107 }
108
109 /* Either the array is empty or the last scanned slot is in use. */
110 ut_ad(slot->in_use || slot == lock_sys->waiting_threads);
111
112 lock_sys->last_slot = slot + 1;
113
114 /* The last slot is either outside of the array boundary or it's
115 on an empty slot. */
116 ut_ad(lock_sys->last_slot == upper || !lock_sys->last_slot->in_use);
117
118 ut_ad(lock_sys->last_slot >= lock_sys->waiting_threads);
119 ut_ad(lock_sys->last_slot <= upper);
120
121 lock_wait_mutex_exit();
122 }
123
124 /** Counts number of calls to lock_wait_table_reserve_slot.
125 It is protected by lock_wait_mutex.
126 Current value of this counter is stored in the slot a transaction has chosen
127 for sleeping during suspension, and thus serves as "reservation number" which
128 can be used to check if the owner of the slot has changed (perhaps multiple
129 times, in "ABA" manner). */
130 static uint64_t lock_wait_table_reservations = 0;
131
132 /** Reserves a slot in the thread table for the current user OS thread.
133 @return reserved slot */
134 static srv_slot_t *lock_wait_table_reserve_slot(
135 que_thr_t *thr, /*!< in: query thread associated
136 with the user OS thread */
137 std::chrono::steady_clock::duration
138 wait_timeout) /*!< in: lock wait timeout value */
139 {
140 srv_slot_t *slot;
141
142 ut_ad(lock_wait_mutex_own());
143 ut_ad(trx_mutex_own(thr_get_trx(thr)));
144
145 slot = lock_sys->waiting_threads;
146
147 for (uint32_t i = srv_max_n_threads; i--; ++slot) {
148 if (!slot->in_use) {
149 slot->reservation_no = lock_wait_table_reservations++;
150 slot->in_use = true;
151 slot->thr = thr;
152 slot->thr->slot = slot;
153
154 if (slot->event == nullptr) {
155 slot->event = os_event_create();
156 ut_a(slot->event);
157 }
158
159 os_event_reset(slot->event);
160 slot->suspended = true;
161 slot->suspend_time = std::chrono::steady_clock::now();
162 slot->wait_timeout = wait_timeout;
163
164 if (slot == lock_sys->last_slot) {
165 ++lock_sys->last_slot;
166 }
167
168 ut_ad(lock_sys->last_slot <=
169 lock_sys->waiting_threads + srv_max_n_threads);
170
171 /* We call lock_wait_request_check_for_cycles() because the
172 node representing the `thr` only now becomes visible to the thread which
173 analyzes contents of lock_sys->waiting_threads. The edge itself was
174 created by lock_create_wait_for_edge() during RecLock::add_to_waitq() or
175 lock_table(), but at that moment the source of the edge was not yet in the
176 lock_sys->waiting_threads, so the node and the outgoing edge were not yet
177 visible.
178 I hope this explains why we do waste time on calling
179 lock_wait_request_check_for_cycles() from lock_create_wait_for_edge().*/
180 lock_wait_request_check_for_cycles();
181 return (slot);
182 }
183 }
184
185 ib::error(ER_IB_MSG_646)
186 << "There appear to be " << srv_max_n_threads
187 << " user"
188 " threads currently waiting inside InnoDB, which is the upper"
189 " limit. Cannot continue operation. Before aborting, we print"
190 " a list of waiting threads.";
191 lock_wait_table_print();
192
193 ut_error;
194 }
195
196 void lock_wait_request_check_for_cycles() { lock_set_timeout_event(); }
197
198 void lock_wait_suspend_thread(que_thr_t *thr) {
199 srv_slot_t *slot;
200 trx_t *trx;
201 std::chrono::steady_clock::time_point start_time;
202
203 trx = thr_get_trx(thr);
204
205 if (trx->mysql_thd != nullptr) {
206 DEBUG_SYNC_C("lock_wait_suspend_thread_enter");
207 }
208
209 /* InnoDB system transactions (such as the purge, and
210 incomplete transactions that are being rolled back after crash
211 recovery) will use the global value of
212 innodb_lock_wait_timeout, because trx->mysql_thd == NULL. */
213 const auto lock_wait_timeout = trx_lock_wait_timeout_get(trx);
214
215 lock_wait_mutex_enter();
216
217 trx_mutex_enter(trx);
218
219 trx->error_state = DB_SUCCESS;
220
221 if (thr->state == QUE_THR_RUNNING) {
222 ut_ad(thr->is_active);
223
224 /* The lock has already been released or this transaction
225 was chosen as a deadlock victim: no need to suspend */
226
227 if (trx->lock.was_chosen_as_deadlock_victim) {
228 trx->error_state = DB_DEADLOCK;
229 trx->lock.was_chosen_as_deadlock_victim = false;
230
231 ut_d(trx->lock.in_rollback = true);
232 }
233
234 lock_wait_mutex_exit();
235 trx_mutex_exit(trx);
236 return;
237 }
238
239 ut_ad(!thr->is_active);
240
241 slot = lock_wait_table_reserve_slot(thr, lock_wait_timeout);
242
243 if (thr->lock_state == QUE_THR_LOCK_ROW) {
244 srv_stats.n_lock_wait_count.inc();
245 srv_stats.n_lock_wait_current_count.inc();
246
247 start_time = std::chrono::steady_clock::now();
248 }
249
250 lock_wait_mutex_exit();
251
252 /* We hold trx->mutex here, which is required to call
253 lock_set_lock_and_trx_wait. This means that the value in
254 trx->lock.wait_lock_type which we are about to read comes from the latest
255 call to lock_set_lock_and_trx_wait before we obtained the trx->mutex, which is
256 precisely what we want for our stats */
257 auto lock_type = trx->lock.wait_lock_type;
258 trx_mutex_exit(trx);
259
260 ulint had_dict_lock = trx->dict_operation_lock_mode;
261
262 switch (had_dict_lock) {
263 case 0:
264 break;
265 case RW_S_LATCH:
266 /* Release foreign key check latch */
267 row_mysql_unfreeze_data_dictionary(trx);
268
269 DEBUG_SYNC_C("lock_wait_release_s_latch_before_sleep");
270 break;
271 case RW_X_LATCH:
272 /* We may wait for rec lock in dd holding
273 dict_operation_lock for creating FTS AUX table */
274 ut_ad(!dict_sys_mutex_own());
275 rw_lock_x_unlock(dict_operation_lock);
276 break;
277 }
278
279 /* Suspend this thread and wait for the event. */
280
281 auto was_declared_inside_innodb = trx->declared_to_be_inside_innodb;
282
283 if (was_declared_inside_innodb) {
284 /* We must declare this OS thread to exit InnoDB, since a
285 possible other thread holding a lock which this thread waits
286 for must be allowed to enter, sooner or later */
287
288 srv_conc_force_exit_innodb(trx);
289 }
290
291 ut_a(lock_type == LOCK_REC || lock_type == LOCK_TABLE);
292 thd_wait_begin(trx->mysql_thd, lock_type == LOCK_REC ? THD_WAIT_ROW_LOCK
293 : THD_WAIT_TABLE_LOCK);
294
295 DEBUG_SYNC_C("lock_wait_will_wait");
296
297 os_event_wait(slot->event);
298
299 DEBUG_SYNC_C("lock_wait_has_finished_waiting");
300
301 thd_wait_end(trx->mysql_thd);
302
303 /* After resuming, reacquire the data dictionary latch if
304 necessary. */
305
306 if (was_declared_inside_innodb) {
307 /* Return back inside InnoDB */
308
309 srv_conc_force_enter_innodb(trx);
310 }
311
312 if (had_dict_lock == RW_S_LATCH) {
313 row_mysql_freeze_data_dictionary(trx, UT_LOCATION_HERE);
314 } else if (had_dict_lock == RW_X_LATCH) {
315 rw_lock_x_lock(dict_operation_lock, UT_LOCATION_HERE);
316 }
317
318 /* Release the slot for others to use */
319
320 lock_wait_table_release_slot(slot);
321
322 if (thr->lock_state == QUE_THR_LOCK_ROW) {
323 const auto diff_time = std::chrono::steady_clock::now() - start_time;
324
325 srv_stats.n_lock_wait_current_count.dec();
326 srv_stats.n_lock_wait_time.add(
327 std::chrono::duration_cast<std::chrono::microseconds>(diff_time)
328 .count());
329
330 if (diff_time > lock_sys->n_lock_max_wait_time) {
331 lock_sys->n_lock_max_wait_time = diff_time;
332 }
333
334 /* Record the lock wait time for this thread */
335 thd_set_lock_wait_time(trx->mysql_thd, diff_time);
336
337 DBUG_EXECUTE_IF("lock_instrument_slow_query_log",
338 std::this_thread::sleep_for(std::chrono::milliseconds(1)););
339 }
340
341 /* The transaction is chosen as deadlock victim during sleep. */
342 if (trx->error_state == DB_DEADLOCK) {
343 ut_d(trx->lock.in_rollback = true);
344 return;
345 }
346
347 if (trx->error_state == DB_LOCK_WAIT_TIMEOUT) {
348 MONITOR_INC(MONITOR_TIMEOUT);
349 }
350
351 if (trx_is_interrupted(trx)) {
352 trx->error_state = DB_INTERRUPTED;
353 }
354 }
355
356 /** Releases a user OS thread waiting for a lock to be released, if the
357 thread is already suspended. Please do not call it directly, but rather use the
358 lock_reset_wait_and_release_thread_if_suspended() wrapper.
359 @param[in] thr query thread associated with the user OS thread */
360 static void lock_wait_release_thread_if_suspended(que_thr_t *thr) {
361 auto trx = thr_get_trx(thr);
362 /* We need a guarantee that for each time a thread is suspended there is at
363 most one time it gets released - or more precisely: that there is at most
364 one reason for it to be woken up. Otherwise it could happen that two
365 different threads will think that they successfully woken up the transaction
366 and that the transaction understands the reason it was woken up is the one
367 they had in mind, say: one thread woken it up because of deadlock and another
368 because of timeout. If the two reasons require different behavior after
369 waking up, then we will be in trouble. Current implementation makes sure
370 that we wake up a thread only once by observing several rules:
371 1. the only way to wake up a trx is to call os_event_set
372 2. the only call to os_event_set is in lock_wait_release_thread_if_suspended
373 3. calls to lock_wait_release_thread_if_suspended are always performed after
374 a call to lock_reset_lock_and_trx_wait(lock), and the sequence of the two is
375 in a critical section guarded by lock_sys latch for the shard containing the
376 waiting lock
377 4. the lock_reset_lock_and_trx_wait(lock) asserts that
378 lock->trx->lock.wait_lock == lock and sets lock->trx->lock.wait_lock = NULL
379 Together all this facts imply, that it is impossible for a single trx to be
380 woken up twice (unless it got to sleep again) because doing so requires
381 resetting wait_lock to NULL.
382
383 We now hold either an exclusive lock_sys latch, or just for the shard which
384 contains the lock which used to be trx->lock.wait_lock, but we can not assert
385 that because trx->lock.wait_lock is now NULL so we don't know for which shard
386 we hold the latch here. So, please imagine something like:
387
388 ut_ad(locksys::owns_lock_shard(lock->trx->lock.wait_lock));
389 */
390
391 ut_ad(trx_mutex_own(trx));
392
393 /* We don't need the lock_wait_mutex here, because we know that the thread
394 had a reason to go to sleep (we have seen trx->lock.wait_lock !=NULL), and we
395 know that we are the first ones to wake it up (we are the thread which has
396 changed the trx->lock.wait_lock to NULL), so it either sleeps, or did not
397 yet started the sleep. We hold the trx->mutex which is required to go to
398 sleep. So, while holding the trx->mutex we can check if thr->slot is already
399 assigned and if so, then we need to wake up the thread. If the thr->slot is
400 not yet assigned, then we know that the thread had not yet gone to sleep, and
401 we know that before doing so, it will need to acquire trx->mutex and will
402 verify once more if it has to go to sleep by checking if thr->state is
403 QUE_THR_RUNNING which we indeed have already set before calling
404 lock_wait_release_thread_if_suspended, so we don't need to do anything in this
405 case - trx will simply not go to sleep. */
406 ut_ad(thr->state == QUE_THR_RUNNING);
407 ut_ad(trx->lock.wait_lock == nullptr);
408
409 if (thr->slot != nullptr && thr->slot->in_use && thr->slot->thr == thr) {
410 if (trx->lock.was_chosen_as_deadlock_victim) {
411 trx->error_state = DB_DEADLOCK;
412 trx->lock.was_chosen_as_deadlock_victim = false;
413
414 ut_d(trx->lock.in_rollback = true);
415 }
416
417 os_event_set(thr->slot->event);
418 }
419 }
420
421 void lock_reset_wait_and_release_thread_if_suspended(lock_t *lock) {
422 ut_ad(locksys::owns_lock_shard(lock));
423 ut_ad(trx_mutex_own(lock->trx));
424 ut_ad(lock->trx->lock.wait_lock == lock);
425
426 /* We clear blocking_trx here and not in lock_reset_lock_and_trx_wait(), as
427 lock_reset_lock_and_trx_wait() is called also when the wait_lock is being
428 moved from one page to another during B-tree reorganization, in which case
429 blocking_trx should not change - in such cases a new wait lock is created
430 and assigned to trx->lock.wait_lock, but the information about blocking trx
431 is not so easy to restore, so it is easier to simply not clear blocking_trx
432 until we are 100% sure that we want to wake up the trx, which is now.
433 Clearing blocking_trx helps with:
434 1. performance optimization, as lock_wait_snapshot_waiting_threads() can omit
435 this trx when building wait-for-graph
436 2. debugging, as resetting blocking_trx makes it easier to spot it was not
437 properly set on subsequent waits.
438 3. helping lock_make_trx_hit_list() notice that HP trx is no longer waiting
439 for a lock, so it can take a fast path
440 Also, lock_wait_check_and_cancel() looks if block_trx become nullptr to figure
441 out if wait_lock become nullptr only temporarily (for B-tree reorg) or
442 permanently (due to lock_reset_wait_and_release_thread_if_suspended()) */
443 lock->trx->lock.blocking_trx.store(nullptr);
444
445 /* We only release locks for which someone is waiting, and we posses a latch
446 on the shard in which the lock is stored, and the trx which decided to wait
447 for the lock should have already set trx->lock.que_state to TRX_QUE_LOCK_WAIT
448 and called que_thr_stop() before releasing the latch on this shard. */
449 ut_ad(lock->trx_que_state() == TRX_QUE_LOCK_WAIT);
450
451 /* The following function releases the trx from lock wait */
452
453 que_thr_t *thr = que_thr_end_lock_wait(lock->trx);
454
455 /* Reset the wait flag and the back pointer to lock in trx.
456 It is important to call it only after we obtain lock->trx->mutex, because
457 trx_mutex_enter makes some assertions based on trx->lock.wait_lock value */
458 lock_reset_lock_and_trx_wait(lock);
459
460 if (thr != nullptr) {
461 lock_wait_release_thread_if_suspended(thr);
462 }
463 }
464 static void lock_wait_try_cancel(trx_t *trx, bool timeout) {
465 ut_a(trx->lock.wait_lock != nullptr);
466 ut_ad(locksys::owns_lock_shard(trx->lock.wait_lock));
467 ut_a(trx->lock.que_state == TRX_QUE_LOCK_WAIT);
468 if (trx_is_high_priority(trx)) {
469 /* We know that wait_lock is non-null and have its shard latches, so we can
470 safely read the blocking_trx and assert its not null. */
471 const trx_t *blocker = trx->lock.blocking_trx.load();
472 ut_ad(blocker != nullptr);
473 /* An HP trx should not give up if the blocker is not HP. */
474 if (!trx_is_high_priority(blocker)) {
475 return;
476 }
477 }
478 ut_ad(trx_mutex_own(trx));
479 if (timeout) {
480 /* Make sure we are not overwriting the DB_DEADLOCK which would be more
481 important to report as it rolls back whole transaction, not just the
482 current query. We set error_state to DB_DEADLOCK only:
483 1) before the transaction reserves a slot. But, we know it's in a slot.
484 2) when wait_lock is already set to nullptr. But, it's not nullptr. */
485 ut_ad(trx->error_state != DB_DEADLOCK);
486 trx->error_state = DB_LOCK_WAIT_TIMEOUT;
487 /* This flag can't be set, as we always call the
488 lock_cancel_waiting_and_release() immediately after setting it, which
489 either prevents the trx from going to sleep or resets the wait_lock, and
490 we've ruled out both of these possibilities. This means that the
491 subsequent call to lock_cancel_waiting_and_release() shouldn't overwrite
492 the error_state we've just set. This isn't a crucial property, but makes
493 reasoning simpler, I hope, hence this assert. */
494 ut_ad(!trx->lock.was_chosen_as_deadlock_victim);
495 }
496 /* Cancel the lock request queued by the transaction and release possible
497 other transactions waiting behind. */
498 lock_cancel_waiting_and_release(trx);
499 }
500 /** Check if the thread lock wait has timed out. Release its locks if the
501 wait has actually timed out. */
502 static void lock_wait_check_and_cancel(
503 const srv_slot_t *slot) /*!< in: slot reserved by a user
504 thread when the wait started */
505 {
506 const auto wait_time = std::chrono::steady_clock::now() - slot->suspend_time;
507 /* Timeout exceeded or a wrap-around in system time counter */
508 const auto timeout = slot->wait_timeout < std::chrono::seconds{100000000} &&
509 wait_time > slot->wait_timeout;
510 trx_t *trx = thr_get_trx(slot->thr);
511
512 if (!trx_is_interrupted(trx) && !timeout) {
513 return;
514 }
515 /* We don't expect trx to commit (change version) as we hold lock_wait mutex
516 preventing the trx from leaving the slot. */
517 locksys::run_if_waiting({trx}, [&]() { lock_wait_try_cancel(trx, timeout); });
518 }
519
520 /** A snapshot of information about a single slot which was in use at the moment
521 of taking the snapshot */
522 struct waiting_trx_info_t {
523 /** The transaction which was using this slot. */
524 trx_t *trx;
525 /** The transaction for which the owner of the slot is waiting for. */
526 trx_t *waits_for;
527 /** The slot this info is about */
528 srv_slot_t *slot;
529 /** The slot->reservation_no at the moment of taking the snapshot */
530 uint64_t reservation_no;
531 };
532
533 /** As we want to quickly find a given trx_t within the snapshot, we use a
534 sorting criterion which is based on trx only. We use the pointer address, as
535 any deterministic rule without ties will do. */
536 bool operator<(const waiting_trx_info_t &a, const waiting_trx_info_t &b) {
537 return std::less<trx_t *>{}(a.trx, b.trx);
538 }
539
540 /** Check all slots for user threads that are waiting on locks, and if they have
541 exceeded the time limit. */
542 static void lock_wait_check_slots_for_timeouts() {
543 ut_ad(!lock_wait_mutex_own());
544 lock_wait_mutex_enter();
545
546 for (auto slot = lock_sys->waiting_threads; slot < lock_sys->last_slot;
547 ++slot) {
548 /* We are doing a read without latching the lock_sys or the trx mutex.
549 This is OK, because a slot can't be freed or reserved without the lock wait
550 mutex. */
551 if (slot->in_use) {
552 lock_wait_check_and_cancel(slot);
553 }
554 }
555
556 lock_wait_mutex_exit();
557 }
558
559 /** Takes a snapshot of the content of slots which are in use
560 @param[out] infos Will contain the information about slots which are in use
561 @return value of lock_wait_table_reservations before taking the snapshot
562 */
563 static uint64_t lock_wait_snapshot_waiting_threads(
564 ut::vector<waiting_trx_info_t> &infos) {
565 ut_ad(!lock_wait_mutex_own());
566 infos.clear();
567 lock_wait_mutex_enter();
568 /*
569 We own lock_wait_mutex, which protects lock_wait_table_reservations and
570 reservation_no.
571 We want to make a snapshot of the wait-for graph as quick as possible to not
572 keep the lock_wait_mutex too long.
573 Anything more fancy than push_back seems to impact performance.
574
575 Note: one should be able to prove that we don't really need a "consistent"
576 snapshot - the algorithm should still work if we split the loop into several
577 smaller "chunks" snapshotted independently and stitch them together. Care must
578 be taken to "merge" duplicates keeping the freshest version (reservation_no)
579 of slot for each trx.
580 So, if (in future) this loop turns out to be a bottleneck (say, by increasing
581 congestion on lock_wait_mutex), one can try to release and require the lock
582 every X iterations and modify the lock_wait_build_wait_for_graph() to handle
583 duplicates in a smart way.
584 */
585 const auto table_reservations = lock_wait_table_reservations;
586 for (auto slot = lock_sys->waiting_threads; slot < lock_sys->last_slot;
587 ++slot) {
588 if (slot->in_use) {
589 auto from = thr_get_trx(slot->thr);
590 auto to = from->lock.blocking_trx.load();
591 if (to != nullptr) {
592 infos.push_back({from, to, slot, slot->reservation_no});
593 }
594 }
595 }
596 lock_wait_mutex_exit();
597 return table_reservations;
598 }
599
600 /** Used to initialize schedule weights of nodes in wait-for-graph for the
601 computation. Initially all nodes have weight 1, except for nodes which waited
602 very long, for which we set the weight to WEIGHT_BOOST
603 @param[in] infos information about all waiting transactions
604 @param[in] table_reservations value of lock_wait_table_reservations at
605 before taking the `infos` snapshot
606 @param[out] new_weights place to store initial weights of nodes
607 */
608 static void lock_wait_compute_initial_weights(
609 const ut::vector<waiting_trx_info_t> &infos,
610 const uint64_t table_reservations,
611 ut::vector<trx_schedule_weight_t> &new_weights) {
612 const size_t n = infos.size();
613 ut_ad(n <= std::numeric_limits<trx_schedule_weight_t>::max());
614
615 /*
616 We want to boost transactions which waited too long, according to a heuristic,
617 that if 2*n transactions got suspended during our wait, and the current number
618 of waiters is n, then it means that at least n transactions bypassed us, which
619 seems unfair. Also, in a fair world, where suspensions and wake-ups are
620 balanced, 2*n suspensions mean around 2*n wake-ups, and one would expect
621 around n other transactions to wake up, until it is our turn to wake up.
622 A boost increases weight from 1 to WEIGHT_BOOST for the node.
623 We want a boosted transaction to have weight higher than weight of any other
624 transaction which is not boosted and does not cause any boosted trx to wait.
625 For this it would suffice to set WEIGHT_BOOST to n.
626 But, we sum weights of nodes that wait for us, to come up with final value of
627 schedule_weight, so to avoid overflow, we must ensure that WEIGHT_BOOST*n is
628 small enough to fit in signed 32-bit.
629 We thus clamp WEIGHT_BOOST to 1e9 / n just to be safe.
630 */
631 const trx_schedule_weight_t WEIGHT_BOOST =
632 n == 0 ? 1 : std::min<trx_schedule_weight_t>(n, 1e9 / n);
633 new_weights.clear();
634 new_weights.resize(n, 1);
635 const uint64_t MAX_FAIR_WAIT = 2 * n;
636 for (size_t from = 0; from < n; ++from) {
637 if (infos[from].reservation_no + MAX_FAIR_WAIT < table_reservations) {
638 new_weights[from] = WEIGHT_BOOST;
639 }
640 }
641 }
642
643 /** Analyzes content of the snapshot with information about slots in use, and
644 builds a (subset of) list of edges from waiting transactions to blocking
645 transactions, such that for each waiter we have one outgoing edge.
646 @param[in] infos information about all waiting transactions
647 @param[out] outgoing The outgoing[from] will contain either the index such
648 that infos[outgoing[from]].trx is the reason
649 infos[from].trx has to wait, or -1 if the reason for
650 waiting is not among transactions in infos[].trx. */
651 static void lock_wait_build_wait_for_graph(
652 ut::vector<waiting_trx_info_t> &infos, ut::vector<int> &outgoing) {
653 /** We are going to use int and uint to store positions within infos */
654 ut_ad(infos.size() < std::numeric_limits<uint>::max());
655 const auto n = static_cast<uint>(infos.size());
656 ut_ad(n < static_cast<uint>(std::numeric_limits<int>::max()));
657 outgoing.clear();
658 outgoing.resize(n, -1);
659 /* This particular implementation sorts infos by ::trx, and then uses
660 lower_bound to find index in infos corresponding to ::wait_for, which has
661 O(nlgn) complexity and modifies infos, but has a nice property of avoiding any
662 allocations.
663 An alternative O(n) approach would be to use a hash table to map infos[i].trx
664 to i.
665 Using unordered_map<trx_t*,int> however causes too much (de)allocations as
666 its bucket chains are implemented as a linked lists - overall it works much
667 slower than sort.
668 The fastest implementation was to use custom implementation of a hash table
669 with open addressing and double hashing with a statically allocated
670 2 * srv_max_n_threads buckets. This however did not increase transactions per
671 second, so introducing a custom implementation seems unjustified here. */
672 sort(infos.begin(), infos.end());
673 waiting_trx_info_t needle{};
674 for (uint from = 0; from < n; ++from) {
675 /* Assert that the order used by sort and lower_bound depends only on the
676 trx field, as this is the only one we will initialize in the needle. */
677 ut_ad(from == 0 ||
678 std::less<trx_t *>{}(infos[from - 1].trx, infos[from].trx));
679 needle.trx = infos[from].waits_for;
680 auto it = std::lower_bound(infos.begin(), infos.end(), needle);
681
682 if (it == infos.end() || it->trx != needle.trx) {
683 continue;
684 }
685 auto to = it - infos.begin();
686 ut_ad(from != static_cast<uint>(to));
687 outgoing[from] = static_cast<int>(to);
688 }
689 }
690
691 /** Notifies the chosen_victim that it should roll back
692 @param[in,out] chosen_victim the transaction that should be rolled back */
693 static void lock_wait_rollback_deadlock_victim(trx_t *chosen_victim) {
694 ut_ad(!trx_mutex_own(chosen_victim));
695 /* We need to latch the shard containing wait_lock to read it and access
696 the lock itself.*/
697 ut_ad(locksys::owns_exclusive_global_latch());
698 trx_mutex_enter(chosen_victim);
699 chosen_victim->lock.was_chosen_as_deadlock_victim = true;
700 ut_a(chosen_victim->lock.wait_lock != nullptr);
701 ut_a(chosen_victim->lock.que_state == TRX_QUE_LOCK_WAIT);
702 lock_cancel_waiting_and_release(chosen_victim);
703 trx_mutex_exit(chosen_victim);
704 }
705
706 /** Given the `infos` about transactions and indexes in `infos` which form a
707 deadlock cycle, identifies the transaction with the largest `reservation_no`,
708 that is the one which was the latest to join the cycle.
709 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
710 deadlock cycle
711 @param[in] infos information about all waiting transactions
712 @return position in cycle_ids, such that infos[cycle_ids[pos]].reservation_no is
713 the largest */
714 static size_t lock_wait_find_latest_pos_on_cycle(
715 const ut::vector<uint> &cycle_ids,
716 const ut::vector<waiting_trx_info_t> &infos) {
717 size_t latest_pos = 0;
718 for (size_t pos = 1; pos < cycle_ids.size(); ++pos) {
719 if (infos[cycle_ids[latest_pos]].reservation_no <
720 infos[cycle_ids[pos]].reservation_no) {
721 latest_pos = pos;
722 }
723 }
724 return latest_pos;
725 }
726
727 /** Rotates the deadlock cycle so that it starts from desired item.
728 @param[in] first_pos the position which should become first after rotation
729 @param[in] cycle_ids the array to rotate
730 @return a copy of cycle_ids rotated in such a way, that the element which
731 was at position `first_pos` is now the first */
732 static ut::vector<uint> lock_wait_rotate_so_pos_is_first(
733 size_t first_pos, const ut::vector<uint> &cycle_ids) {
734 ut_ad(first_pos < cycle_ids.size());
735 auto rotated_ids = cycle_ids;
736 std::rotate(rotated_ids.begin(), rotated_ids.begin() + first_pos,
737 rotated_ids.end());
738 return rotated_ids;
739 }
740
741 /** A helper, which extracts transactions with given indexes from the `infos`
742 array.
743 @param[in] ids indexes of transactions in the `infos` array to extract
744 @param[in] infos information about all waiting transactions
745 @return An array formed by infos[ids[i]].trx */
746 template <typename T>
747 static ut::vector<T> lock_wait_map_ids_to_trxs(
748 const ut::vector<uint> &ids, const ut::vector<waiting_trx_info_t> &infos) {
749 ut::vector<T> trxs;
750 trxs.reserve(ids.size());
751 for (auto id : ids) {
752 trxs.push_back(infos[id].trx);
753 }
754 return trxs;
755 }
756
757 /** Orders the transactions from deadlock cycle in such a backward-compatible
758 way, from the point of view of algorithm with picks the victim. From correctness
759 point of view this could be a no-op, but we have test cases which assume some
760 determinism in that which trx is selected as the victim. These tests usually
761 depend on the old behaviour in which the order in which trxs attempted to wait
762 was meaningful. In the past we have only considered two candidates for victim:
763 (a) the transaction which closed the cycle by adding last wait-for edge
764 (b) the transaction which is waiting for (a)
765 and it favored to pick (a) in case of ties.
766 To make these test pass we find the trx with most recent reservation_no (a),
767 and the one before it in the cycle (b), and move them to the end of collection
768 So that we consider them in order: ...,...,...,(b),(a), resolving ties by
769 picking the latest one as victim.
770 In other words we rotate the cycle so that the most recent waiter becomes the
771 last.
772 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
773 deadlock cycle
774 @param[in] infos information about all waiting transactions
775 @return transactions from the deadlock cycle sorted in the optimal way for
776 choosing a victim */
777 static ut::vector<trx_t *> lock_wait_order_for_choosing_victim(
778 const ut::vector<uint> &cycle_ids,
779 const ut::vector<waiting_trx_info_t> &infos) {
780 size_t latest_pos = lock_wait_find_latest_pos_on_cycle(cycle_ids, infos);
781 size_t first_pos = (latest_pos + 1) % cycle_ids.size();
782 return lock_wait_map_ids_to_trxs<trx_t *>(
783 lock_wait_rotate_so_pos_is_first(first_pos, cycle_ids), infos);
784 }
785
786 /** Performs new_weights[parent_id] += new_weights[child_id] with sanity checks.
787 @param[in,out] new_weights schedule weights of transactions initialized and
788 perhaps partially accumulated already.
789 This function will modify new_weights[parent_id]
790 by adding new_weights[child_id] to it.
791 @param[in] parent_id index of the node to update
792 @param[in] child_id index of the node which weight should be added
793 to the parent's weight.
794 */
795 static void lock_wait_add_subtree_weight(
796 ut::vector<trx_schedule_weight_t> &new_weights, const size_t parent_id,
797 const size_t child_id) {
798 const trx_schedule_weight_t child_weight = new_weights[child_id];
799 trx_schedule_weight_t &old_parent_weight = new_weights[parent_id];
800 /* We expect incoming_weight to be positive
801 @see lock_wait_compute_initial_weights() */
802 ut_ad(0 < child_weight);
803 /* The trx_schedule_weight_t is unsigned type, so overflows are well defined,
804 but we don't expect them as lock_wait_compute_initial_weights() sets the
805 initial weights to small enough that sum of whole subtree should never
806 overflow */
807 static_assert(
808 std::is_unsigned<trx_schedule_weight_t>::value,
809 "The trx_schedule_weight_t should be unsigned to minimize impact "
810 "of overflows");
811 ut_ad(old_parent_weight < old_parent_weight + child_weight);
812 old_parent_weight += child_weight;
813 }
814
815 /** Given a graph with at most one outgoing edge per node, and initial weight
816 for each node, this function will compute for each node a partial sum of initial
817 weights of the node and all nodes that can reach it in the graph.
818 @param[in,out] incoming_count The value of incoming_count[id] should match
819 the number of edges incoming to the node id.
820 In other words |x : outgoing[x] == id|.
821 This function will modify entries in this
822 array, so that after the call, nodes on cycles
823 will have value 1, and others will have 0.
824 @param[in,out] new_weights Should contain initial weight for each node.
825 This function will modify entries for nodes
826 which are not on cycles, so that
827 new_weights[id] will be the sum of initial
828 weights of the node `id` and all nodes that
829 can reach it by one or more outgoing[] edges.
830 @param[in] outgoing The ids of edge endpoints.
831 If outgoing[id] == -1, then there is no edge
832 going out of id, otherwise there is an edge
833 from id to outgoing[id].
834 */
835 static void lock_wait_accumulate_weights(
836 ut::vector<uint> &incoming_count,
837 ut::vector<trx_schedule_weight_t> &new_weights,
838 const ut::vector<int> &outgoing) {
839 ut_a(incoming_count.size() == outgoing.size());
840 ut::vector<size_t> ready;
841 ready.clear();
842 const size_t n = incoming_count.size();
843 for (size_t id = 0; id < n; ++id) {
844 if (!incoming_count[id]) {
845 ready.push_back(id);
846 }
847 }
848
849 while (!ready.empty()) {
850 size_t id = ready.back();
851 ready.pop_back();
852 if (outgoing[id] != -1) {
853 lock_wait_add_subtree_weight(new_weights, outgoing[id], id);
854 if (!--incoming_count[outgoing[id]]) {
855 ready.push_back(outgoing[id]);
856 }
857 }
858 }
859 }
860
861 /** Checks if info[id].slot is still in use and has not been freed and reserved
862 again since we took the info snapshot ("ABA" type of race condition).
863 @param[in] infos information about all waiting transactions
864 @param[in] id index to retrieve
865 @return info[id].slot if the slot was reserved whole time since taking the info
866 snapshot. Otherwise: nullptr.
867 */
868 static const srv_slot_t *lock_wait_get_slot_if_still_reserved(
869 const ut::vector<waiting_trx_info_t> &infos, const size_t id) {
870 ut_ad(lock_wait_mutex_own());
871 const auto slot = infos[id].slot;
872 if (slot->in_use && slot->reservation_no == infos[id].reservation_no) {
873 return slot;
874 }
875 return nullptr;
876 }
877
878 /** Copies the newly computed schedule weights to the transactions fields.
879 Ignores transactions which take part in cycles, because for them we don't have a
880 final value of the schedule weight yet.
881 @param[in] is_on_cycle A positive value is_on_cycle[id] means that `id` is on
882 a cycle in the graph.
883 @param[in] infos information about all waiting transactions
884 @param[in] new_weights schedule weights of transactions computed for all
885 transactions except those which are on a cycle.
886 */
887 static void lock_wait_publish_new_weights(
888 const ut::vector<uint> &is_on_cycle,
889 const ut::vector<waiting_trx_info_t> &infos,
890 const ut::vector<trx_schedule_weight_t> &new_weights) {
891 ut_ad(!lock_wait_mutex_own());
892 ut_a(infos.size() == new_weights.size());
893 ut_a(infos.size() == is_on_cycle.size());
894 const size_t n = infos.size();
895 lock_wait_mutex_enter();
896 for (size_t id = 0; id < n; ++id) {
897 if (is_on_cycle[id]) {
898 continue;
899 }
900 const auto slot = lock_wait_get_slot_if_still_reserved(infos, id);
901 if (!slot) {
902 continue;
903 }
904 ut_ad(thr_get_trx(slot->thr) == infos[id].trx);
905 const auto schedule_weight = new_weights[id];
906 infos[id].trx->lock.schedule_weight.store(schedule_weight,
907 std::memory_order_relaxed);
908 }
909 lock_wait_mutex_exit();
910 }
911
912 /** Given an array with information about all waiting transactions and indexes
913 in it which form a deadlock cycle, picks the transaction to rollback.
914 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
915 deadlock cycle
916 @param[in] infos information about all waiting transactions
917 @return the transaction chosen as a victim */
918 static trx_t *lock_wait_choose_victim(
919 const ut::vector<uint> &cycle_ids,
920 const ut::vector<waiting_trx_info_t> &infos) {
921 /* We are iterating over various transactions comparing their trx_weight_ge,
922 which is computed based on number of locks held thus we need exclusive latch
923 on the whole lock_sys. In theory number of locks should not change while the
924 transaction is waiting, but instead of proving that they can not wake up, it
925 is easier to assert that we hold the mutex */
926 ut_ad(locksys::owns_exclusive_global_latch());
927 ut_ad(!cycle_ids.empty());
928 trx_t *chosen_victim = nullptr;
929 auto sorted_trxs = lock_wait_order_for_choosing_victim(cycle_ids, infos);
930
931 for (auto *trx : sorted_trxs) {
932 if (chosen_victim == nullptr) {
933 chosen_victim = trx;
934 continue;
935 }
936
937 if (trx_is_high_priority(chosen_victim) || trx_is_high_priority(trx)) {
938 auto victim = trx_arbitrate(trx, chosen_victim);
939
940 if (victim != nullptr) {
941 if (victim == trx) {
942 chosen_victim = trx;
943 } else {
944 ut_a(victim == chosen_victim);
945 }
946 continue;
947 }
948 }
949
950 if (trx_weight_ge(chosen_victim, trx)) {
951 /* The joining transaction is 'smaller',
952 choose it as the victim and roll it back. */
953 chosen_victim = trx;
954 }
955 }
956
957 ut_a(chosen_victim);
958 return chosen_victim;
959 }
960
961 /** Given an array with information about all waiting transactions and indexes
962 in it which form a deadlock cycle, checks if the transactions allegedly forming
963 the deadlock have actually stayed in slots since we've last checked, as opposed
964 to say, not leaving a slot, and/or re-entering the slot ("ABA" situation).
965 This is done by comparing the current reservation_no for each slot, with the
966 reservation_no from the `info` snapshot.
967 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
968 deadlock cycle
969 @param[in] infos information about all waiting transactions
970 @return true if all given transactions resided in their slots for the whole time
971 since the snapshot was taken, and in particular are still there right now */
972 static bool lock_wait_trxs_are_still_in_slots(
973 const ut::vector<uint> &cycle_ids,
974 const ut::vector<waiting_trx_info_t> &infos) {
975 ut_ad(lock_wait_mutex_own());
976 for (auto id : cycle_ids) {
977 const auto slot = lock_wait_get_slot_if_still_reserved(infos, id);
978 if (!slot) {
979 return false;
980 }
981 ut_ad(thr_get_trx(slot->thr) == infos[id].trx);
982 }
983 return true;
984 }
985
986 /** Given an array with information about all waiting transactions and indexes
987 in it which form a deadlock cycle, checks if the transactions allegedly forming
988 the deadlock have actually still wait for a lock, as opposed to being already
989 notified about lock being granted or timeout, but still being present in the
990 slot. This is done by checking trx->lock.wait_lock under exclusive global
991 lock_sys latch.
992 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
993 deadlock cycle
994 @param[in] infos information about all waiting transactions
995 @return true if all given transactions are still waiting for locks*/
996 static bool lock_wait_trxs_are_still_waiting(
997 const ut::vector<uint> &cycle_ids,
998 const ut::vector<waiting_trx_info_t> &infos) {
999 ut_ad(lock_wait_mutex_own());
1000 /* We are iterating over various transaction which may have locks in different
1001 tables/rows, thus we need exclusive latch on the whole lock_sys to make sure
1002 no one will wake them up (say, a high priority trx could abort them) or change
1003 the wait_lock to NULL temporarily during B-tree page reorganization. */
1004 ut_ad(locksys::owns_exclusive_global_latch());
1005
1006 for (auto id : cycle_ids) {
1007 const auto trx = infos[id].trx;
1008 if (trx->lock.wait_lock == nullptr) {
1009 /* trx is on its way to being woken up, so this cycle is a false positive.
1010 As this particular cycle will resolve itself, we ignore it. */
1011 return false;
1012 }
1013 ut_a(trx->lock.que_state == TRX_QUE_LOCK_WAIT);
1014 }
1015 return true;
1016 }
1017
1018 /* A helper function which rotates the deadlock cycle, so that the order of
1019 transactions in it is suitable for notification. From correctness perspective
1020 this could be a no-op, but we have test cases which assume some determinism in
1021 that in which order trx from cycle are reported. These tests usually depend on
1022 the old behaviour in which the order in which transactions attempted to wait was
1023 meaningful. In the past we reported:
1024 - the transaction which closed the cycle by adding last wait-for edge as (2)
1025 - the transaction which is waiting for (2) as (1)
1026 To make these test pass we find the trx with most recent reservation_no (2),
1027 and the one before it in the cycle (1), and move (1) to the beginning.
1028 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
1029 deadlock cycle
1030 @param[in] infos information about all waiting transactions
1031 @return the indexes from cycle_ids sorted rotated in backward-compatible way
1032 */
1033 static ut::vector<uint> lock_wait_rotate_cycle_ids_for_notification(
1034 const ut::vector<uint> &cycle_ids,
1035 const ut::vector<waiting_trx_info_t> &infos) {
1036 size_t latest_pos = lock_wait_find_latest_pos_on_cycle(cycle_ids, infos);
1037 size_t previous_pos = (latest_pos - 1 + cycle_ids.size()) % cycle_ids.size();
1038 return lock_wait_rotate_so_pos_is_first(previous_pos, cycle_ids);
1039 }
1040
1041 /** A helper function which rotates the deadlock cycle, so that the specified
1042 trx is the first one on the cycle.
1043 @param[in] trx The transaction we wish to be the first after the
1044 rotation. There must exist x, such that
1045 infos[cycle_ids[x]].trx == trx.
1046 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
1047 deadlock cycle
1048 @param[in] infos information about all waiting transactions
1049 @return Assuming that infos[cycle_ids[x]].trx == trx the result will be a copy
1050 of [cycle_ids[x],cycle_ids[x+1 mod N],...,cycle_ids[x-1+N mod N]].
1051 */
1052 static ut::vector<uint> lock_wait_rotate_cycle_ids_to_so_trx_is_first(
1053 const trx_t *trx, const ut::vector<uint> &cycle_ids,
1054 const ut::vector<waiting_trx_info_t> &infos) {
1055 auto first_pos = std::distance(
1056 cycle_ids.begin(),
1057 std::find_if(cycle_ids.begin(), cycle_ids.end(),
1058 [&](uint id) { return infos[id].trx == trx; }));
1059 return lock_wait_rotate_so_pos_is_first(first_pos, cycle_ids);
1060 }
1061
1062 /** Finalizes the computation of new schedule weights, by providing missing
1063 information about transactions located on a deadlock cycle. Assuming that we
1064 know the list of transactions on a cycle, which transaction will be chosen as a
1065 victim, and what are the weights of trees hanging off the cycle, it computes
1066 the final schedule weight for each of transactions to be equal to its weight in
1067 a graph with the victim's node missing
1068 @param[in] chosen_victim The transaction chosen to be rolled back
1069 @param[in] cycle_ids indexes in `infos` array, of transactions
1070 forming the deadlock cycle
1071 @param[in] infos information about all waiting transactions
1072 @param[in,out] new_weights schedule weights of transactions computed for
1073 all transactions except those which are on a
1074 cycle. This function will update the new_weights
1075 entries for transactions involved in deadlock
1076 cycle (as it will unfold to a path, and schedule
1077 weight can be thus computed)
1078 */
1079 static void lock_wait_update_weights_on_cycle(
1080 const trx_t *chosen_victim, const ut::vector<uint> &cycle_ids,
1081 const ut::vector<waiting_trx_info_t> &infos,
1082 ut::vector<trx_schedule_weight_t> &new_weights) {
1083 auto rotated_cycle_id = lock_wait_rotate_cycle_ids_to_so_trx_is_first(
1084 chosen_victim, cycle_ids, infos);
1085 ut_ad(infos[rotated_cycle_id[0]].trx == chosen_victim);
1086 /* Recall that chosen_victim is in rotated_cycle_id[0].
1087 Imagine that it will become rolled back, which means that it will vanish,
1088 and the cycle will unfold into a path. This path will start with the
1089 transaction for which chosen_victim was waiting, and for which the computed
1090 new_weight is already correct. We need to update the new_weights[] for
1091 following transactions, accumulating their weights along the path.
1092 We also need to publish the new_weights to trx->cat_weight fields for
1093 all transactions on the path.
1094 */
1095 new_weights[rotated_cycle_id[0]] = 0;
1096 for (uint i = 1; i + 1 < rotated_cycle_id.size(); ++i) {
1097 lock_wait_add_subtree_weight(new_weights, rotated_cycle_id[i + 1],
1098 rotated_cycle_id[i]);
1099 }
1100 for (auto id : rotated_cycle_id) {
1101 infos[id].trx->lock.schedule_weight.store(new_weights[id],
1102 std::memory_order_relaxed);
1103 }
1104 }
1105
1106 /** A helper function which rotates the deadlock cycle, so that the order of
1107 transactions in it is suitable for notification. From correctness perspective
1108 this could be a no-op, but we have tests which depend on deterministic output
1109 from such notifications, and we want to be backward compatible.
1110 @param[in] cycle_ids indexes in `infos` array, of transactions forming the
1111 deadlock cycle
1112 @param[in] infos information about all waiting transactions
1113 @return the transactions from cycle_ids rotated in backward-compatible way */
1114 static ut::vector<const trx_t *> lock_wait_trxs_rotated_for_notification(
1115 const ut::vector<uint> &cycle_ids,
1116 const ut::vector<waiting_trx_info_t> &infos) {
1117 return lock_wait_map_ids_to_trxs<const trx_t *>(
1118 lock_wait_rotate_cycle_ids_for_notification(cycle_ids, infos), infos);
1119 }
1120
1121 /** Handles a deadlock found, by notifying about it, rolling back the chosen
1122 victim and updating schedule weights of transactions on the deadlock cycle.
1123 @param[in,out] chosen_victim the transaction to roll back
1124 @param[in] cycle_ids indexes in `infos` array, of transactions forming
1125 the deadlock cycle
1126 @param[in] infos information about all waiting transactions
1127 @param[in,out] new_weights schedule weights of transactions computed for all
1128 transactions except those which are on a cycle.
1129 This function will update the new_weights entries
1130 for transactions involved in deadlock cycle (as it
1131 will unfold to a path, and schedule weight can be
1132 thus computed) */
1133 static void lock_wait_handle_deadlock(
1134 trx_t *chosen_victim, const ut::vector<uint> &cycle_ids,
1135 const ut::vector<waiting_trx_info_t> &infos,
1136 ut::vector<trx_schedule_weight_t> &new_weights) {
1137 /* We now update the `schedule_weight`s on the cycle taking into account that
1138 chosen_victim will be rolled back.
1139 This is mostly for "correctness" as the impact on performance is negligible
1140 (actually it looks like it is slowing us down). */
1141 lock_wait_update_weights_on_cycle(chosen_victim, cycle_ids, infos,
1142 new_weights);
1143
1144 lock_notify_about_deadlock(
1145 lock_wait_trxs_rotated_for_notification(cycle_ids, infos), chosen_victim);
1146
1147 lock_wait_rollback_deadlock_victim(chosen_victim);
1148 }
1149
1150 /** Given an array with information about all waiting transactions and indexes
1151 in it which form a deadlock cycle, checks if the transactions allegedly forming
1152 the deadlock cycle, indeed are still waiting, and if so, chooses a victim and
1153 handles the deadlock.
1154 @param[in] cycle_ids indexes in `infos` array, of transactions forming
1155 the deadlock cycle
1156 @param[in] infos information about all waiting transactions
1157 @param[in,out] new_weights schedule weights of transactions computed for all
1158 transactions except those which are on the cycle.
1159 In case it is a real deadlock cycle, this function
1160 will update the new_weights entries for transactions
1161 involved in this cycle (as it will unfold to a path,
1162 and schedule weight can be thus computed)
1163 @return true if the cycle found was indeed a deadlock cycle, false if it was a
1164 false positive */
1165 static bool lock_wait_check_candidate_cycle(
1166 ut::vector<uint> &cycle_ids, const ut::vector<waiting_trx_info_t> &infos,
1167 ut::vector<trx_schedule_weight_t> &new_weights) {
1168 ut_ad(!lock_wait_mutex_own());
1169 ut_ad(!locksys::owns_exclusive_global_latch());
1170 lock_wait_mutex_enter();
1171 /*
1172 We have released all mutexes after we have built the `infos` snapshot and
1173 before we've got here. So, while it is true that the edges form a cycle, it
1174 may also be true that some of these transactions were already rolled back, and
1175 memory pointed by infos[i].trx or infos[i].waits_for is no longer the trx it
1176 used to be (as we reuse trx_t objects). It may even segfault if we try to
1177 access it (because trx_t object could be freed). So we need to somehow verify
1178 that the pointer is still valid without accessing it. We do that by checking
1179 if slot->reservation_no has changed since taking a snapshot.
1180 If it has not changed, then we know that the trx's pointer still points to the
1181 same trx as the trx is sleeping, and thus has not finished and wasn't freed.
1182 So, we start by first checking that the slots still contain the trxs we are
1183 interested in. This requires lock_wait_mutex, but does not require the
1184 exclusive global latch. */
1185 if (!lock_wait_trxs_are_still_in_slots(cycle_ids, infos)) {
1186 lock_wait_mutex_exit();
1187 return false;
1188 }
1189 /*
1190 At this point we are sure that we can access memory pointed by infos[i].trx
1191 and that transactions are still in their slots. (And, as `cycle_ids` is a
1192 cycle, we also know that infos[cycle_ids[i]].wait_for is equal to
1193 infos[cycle_ids[i+1]].trx, so infos[cycle_ids[i]].wait_for can also be safely
1194 accessed).
1195 This however does not mean necessarily that they are still waiting.
1196 They might have been already notified that they should wake up (by calling
1197 lock_wait_release_thread_if_suspended()), but they had not yet chance to act
1198 upon it (it is the trx being woken up who is responsible for cleaning up the
1199 `slot` it used).
1200 So, the slot can be still in use and contain a transaction, which was already
1201 decided to be rolled back for example. However, we can recognize this
1202 situation by looking at trx->lock.wait_lock, as each call to
1203 lock_wait_release_thread_if_suspended() is performed only after
1204 lock_reset_lock_and_trx_wait() resets trx->lock.wait_lock to NULL.
1205 Checking trx->lock.wait_lock in reliable way requires global exclusive latch.
1206 */
1207 locksys::Global_exclusive_latch_guard gurad{UT_LOCATION_HERE};
1208 if (!lock_wait_trxs_are_still_waiting(cycle_ids, infos)) {
1209 lock_wait_mutex_exit();
1210 return false;
1211 }
1212
1213 /*
1214 We can now release lock_wait_mutex, because:
1215
1216 1. we have verified that trx->lock.wait_lock is not NULL for cycle_ids
1217 2. we hold exclusive global lock_sys latch
1218 3. lock_sys latch is required to change trx->lock.wait_lock to NULL
1219 4. only after changing trx->lock.wait_lock to NULL a trx can finish
1220
1221 So as long as we hold exclusive global lock_sys latch we can access trxs.
1222 */
1223
1224 lock_wait_mutex_exit();
1225
1226 trx_t *const chosen_victim = lock_wait_choose_victim(cycle_ids, infos);
1227 ut_a(chosen_victim);
1228
1229 lock_wait_handle_deadlock(chosen_victim, cycle_ids, infos, new_weights);
1230
1231 return true;
1232 }
1233
1234 /** Generates a list of `cycle_ids` by following `outgoing` edges from the
1235 `start`.
1236 @param[in,out] cycle_ids will contain the list of ids on cycle
1237 @param[in] start the first id on the cycle
1238 @param[in] outgoing the ids of edge endpoints: id -> outgoing[id] */
1239 static void lock_wait_extract_cycle_ids(ut::vector<uint> &cycle_ids,
1240 const uint start,
1241 const ut::vector<int> &outgoing) {
1242 cycle_ids.clear();
1243 uint id = start;
1244 do {
1245 cycle_ids.push_back(id);
1246 id = outgoing[id];
1247 } while (id != start);
1248 }
1249
1250 /** Assuming that `infos` contains information about all waiting transactions,
1251 and `outgoing[i]` is the endpoint of wait-for edge going out of infos[i].trx,
1252 or -1 if the transaction is not waiting, it identifies and handles all cycles
1253 in the wait-for graph
1254 @param[in] infos Information about all waiting transactions
1255 @param[in] outgoing The ids of edge endpoints. If outgoing[id] == -1,
1256 then there is no edge going out of id, otherwise
1257 infos[id].trx waits for infos[outgoing[id]].trx
1258 @param[in,out] new_weights schedule weights of transactions computed for all
1259 transactions except those which are on a cycle.
1260 In case we find a real deadlock cycle, and decide
1261 to rollback one of transactions, this function
1262 will update the new_weights entries for
1263 transactions involved in this cycle (as it will
1264 unfold to a path, and schedule weight can be thus
1265 computed) */
1266 static void lock_wait_find_and_handle_deadlocks(
1267 const ut::vector<waiting_trx_info_t> &infos,
1268 const ut::vector<int> &outgoing,
1269 ut::vector<trx_schedule_weight_t> &new_weights) {
1270 ut_ad(infos.size() == new_weights.size());
1271 ut_ad(infos.size() == outgoing.size());
1272 /** We are going to use int and uint to store positions within infos */
1273 ut_ad(infos.size() < std::numeric_limits<uint>::max());
1274 const auto n = static_cast<uint>(infos.size());
1275 ut_ad(n < static_cast<uint>(std::numeric_limits<int>::max()));
1276 ut::vector<uint> cycle_ids;
1277 cycle_ids.clear();
1278 ut::vector<uint> colors;
1279 colors.clear();
1280 colors.resize(n, 0);
1281 uint current_color = 0;
1282 for (uint start = 0; start < n; ++start) {
1283 if (colors[start] != 0) {
1284 /* This node was already fully processed*/
1285 continue;
1286 }
1287 ++current_color;
1288 for (int id = start; 0 <= id; id = outgoing[id]) {
1289 /* We don't expect transaction to deadlock with itself only
1290 and we do not handle cycles of length=1 correctly */
1291 ut_ad(id != outgoing[id]);
1292 if (colors[id] == 0) {
1293 /* This node was never visited yet */
1294 colors[id] = current_color;
1295 continue;
1296 }
1297 /* This node was already visited:
1298 - either it has current_color which means we've visited it during current
1299 DFS descend, which means we have found a cycle, which we need to verify,
1300 - or, it has a color used in a previous DFS which means that current DFS
1301 path merges into an already processed portion of wait-for graph, so we
1302 can stop now */
1303 if (colors[id] == current_color) {
1304 /* found a candidate cycle! */
1305 lock_wait_extract_cycle_ids(cycle_ids, id, outgoing);
1306 if (lock_wait_check_candidate_cycle(cycle_ids, infos, new_weights)) {
1307 MONITOR_INC(MONITOR_DEADLOCK);
1308 } else {
1309 MONITOR_INC(MONITOR_DEADLOCK_FALSE_POSITIVES);
1310 }
1311 }
1312 break;
1313 }
1314 }
1315 MONITOR_INC(MONITOR_DEADLOCK_ROUNDS);
1316 MONITOR_SET(MONITOR_LOCK_THREADS_WAITING, n);
1317 }
1318
1319 /** Computes the number of incoming edges for each node of a given graph, in
1320 which each node has zero or one outgoing edge.
1321 @param[in] outgoing The ids of edge endpoints. If outgoing[id] == -1,
1322 then there is no edge going out of id, otherwise
1323 there is an edge from id to outgoing[id].
1324 @param[out] incoming_count The place to store the results. After the call the
1325 incoming_count[id] will be the number of edges
1326 ending in id.
1327 */
1328 static void lock_wait_compute_incoming_count(const ut::vector<int> &outgoing,
1329 ut::vector<uint> &incoming_count) {
1330 incoming_count.clear();
1331 const size_t n = outgoing.size();
1332 incoming_count.resize(n, 0);
1333 for (size_t id = 0; id < n; ++id) {
1334 const auto to = outgoing[id];
1335 if (to != -1) {
1336 incoming_count[to]++;
1337 }
1338 }
1339 }
1340
1341 /** Given the `infos` snapshot about transactions, the value of
1342 lock_wait_table_reservations before taking the snapshot and the edges of the
1343 wait-for-graph relation between the transactions in the snapshot, computes the
1344 schedule weight for each transaction, which is the sum of initial weight of the
1345 transaction and all transactions that are blocked by it. This definition does
1346 not apply to transactions on deadlock cycles, thus this function will not
1347 compute the final schedule weight for transactions on the cycle, but rather
1348 leave it as the partial sum of the tree rooted at the transaction hanging off
1349 the cycle.
1350 @param[in] infos Information about all waiting transactions
1351 @param[in] table_reservations value of lock_wait_table_reservations at
1352 before taking the `infos`snapshot
1353 @param[in] outgoing The ids of edge endpoints.
1354 If outgoing[id] == -1, then there is no edge
1355 going out of id, otherwise infos[id].trx
1356 waits for infos[outgoing[id]].trx
1357 @param[out] new_weights schedule weights of transactions computed
1358 for all transactions except those which are
1359 on a cycle. For those on cycle we only
1360 compute the partial sum of the weights in
1361 the tree hanging off the cycle.
1362 */
1363 static void lock_wait_compute_and_publish_weights_except_cycles(
1364 const ut::vector<waiting_trx_info_t> &infos,
1365 const uint64_t table_reservations, const ut::vector<int> &outgoing,
1366 ut::vector<trx_schedule_weight_t> &new_weights) {
1367 lock_wait_compute_initial_weights(infos, table_reservations, new_weights);
1368 ut::vector<uint> incoming_count;
1369 lock_wait_compute_incoming_count(outgoing, incoming_count);
1370 lock_wait_accumulate_weights(incoming_count, new_weights, outgoing);
1371 /* We don't update trx->lock.schedule_weight for trx on a cycle */
1372 lock_wait_publish_new_weights(incoming_count, infos, new_weights);
1373 MONITOR_INC(MONITOR_SCHEDULE_REFRESHES);
1374 }
1375
1376 /** Takes a snapshot of transactions in waiting currently in slots, updates
1377 their schedule weights, searches for deadlocks among them and resolves them. */
1378 static void lock_wait_update_schedule_and_check_for_deadlocks() {
1379 /*
1380 Note: I was tempted to declare `infos` as `static`, or at least
1381 declare it in lock_wait_timeout_thread() and reuse the same instance
1382 over and over again to avoid allocator calls caused by push_back()
1383 calls inside lock_wait_snapshot_waiting_threads() while we hold
1384 lock_sys->lock_wait_mutex. I was afraid, that allocator might need
1385 to block on some internal mutex in order to synchronize with other
1386 threads using allocator, and this could in turn cause contention on
1387 lock_wait_mutex. I hoped, that since vectors never shrink,
1388 and only grow, then keeping a single instance of `infos` alive for the whole
1389 lifetime of the thread should increase performance, because after some
1390 initial period of growing, the allocations will never have to occur again.
1391 But, I've run many many various experiments, with/without static,
1392 with infos declared outside, with reserve(n) using various values of n
1393 (128, srv_max_n_threads, even a simple ML predictor), and nothing, NOTHING
1394 was faster than just using local vector as we do here (at least on
1395 tetra01, tetra02, when comparing ~70 runs of each algorithm on uniform,
1396 pareto, 128 and 1024 usrs).
1397 This was counter-intuitive to me, so I've checked how malloc is implemented
1398 and it turns out that modern malloc is a variant of ptmalloc2 and uses a
1399 large number of independent arenas (larger than number of threads), and
1400 various smart heuristics to map threads to these arenas in a way which
1401 avoids blocking.
1402 So, before changing the way we handle allocation of memory in these
1403 lock_wait_* routines, please, PLEASE, first check empirically if it really
1404 helps by running many tests and checking for statistical significance,
1405 as variance seems to be large.
1406 (And the downside of using `static` is that it is not very obvious
1407 how our custom deallocator, which tries to update some stats, would
1408 behave during shutdown).
1409 Anyway, in case some tests will indicate that taking a snapshot is a
1410 bottleneck, one can check if declaring this vectors as static solves the
1411 issue.
1412 */
1413 ut::vector<waiting_trx_info_t> infos;
1414 ut::vector<int> outgoing;
1415 ut::vector<trx_schedule_weight_t> new_weights;
1416
1417 auto table_reservations = lock_wait_snapshot_waiting_threads(infos);
1418 lock_wait_build_wait_for_graph(infos, outgoing);
1419
1420 /* We don't update trx->lock.schedule_weight for trxs on cycles. */
1421 lock_wait_compute_and_publish_weights_except_cycles(infos, table_reservations,
1422 outgoing, new_weights);
1423
1424 if (innobase_deadlock_detect) {
1425 /* This will also update trx->lock.schedule_weight for trxs on cycles. */
1426 lock_wait_find_and_handle_deadlocks(infos, outgoing, new_weights);
1427 }
1428 }
1429
1430 /** A thread which wakes up threads whose lock wait may have lasted too long,
1431 analyzes wait-for-graph changes, checks for deadlocks and resolves them, and
1432 updates schedule weights. */
1433 void lock_wait_timeout_thread() {
1434 int64_t sig_count = 0;
1435 os_event_t event = lock_sys->timeout_event;
1436
1437 ut_ad(!srv_read_only_mode);
1438
1439 /** The last time we've checked for timeouts. */
1440 auto last_checked_for_timeouts_at = std::chrono::steady_clock::now();
1441 do {
1442 auto current_time = std::chrono::steady_clock::now(); /* Calling this more
1443 often than once a second isn't needed, as lock timeouts are specified with
1444 one second resolution, so probably nobody cares if we wake up after T or
1445 T+0.99, when T itself can't be precise. */
1446 if (std::chrono::seconds(1) <=
1447 current_time - last_checked_for_timeouts_at) {
1448 last_checked_for_timeouts_at = current_time;
1449 lock_wait_check_slots_for_timeouts();
1450 }
1451
1452 lock_wait_update_schedule_and_check_for_deadlocks();
1453
1454 /* When someone is waiting for a lock, we wake up every second (at worst)
1455 and check if a timeout has passed for a lock wait */
1456 os_event_wait_time_low(event, std::chrono::seconds{1}, sig_count);
1457 sig_count = os_event_reset(event);
1458
1459 } while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP);
1460 }