Debian Codegraph @

storage/innobase/sync/sync0arr.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4 Copyright (c) 2008, Google Inc.
5
6 Portions of this file contain modifications contributed and copyrighted by
7 Google, Inc. Those modifications are gratefully acknowledged and are described
8 briefly in the InnoDB documentation. The contributions by Google are
9 incorporated with their permission, and subject to the conditions contained in
10 the file COPYING.Google.
11
12 This program is free software; you can redistribute it and/or modify it under
13 the terms of the GNU General Public License, version 2.0, as published by the
14 Free Software Foundation.
15
16 This program is designed to work with certain software (including
17 but not limited to OpenSSL) that is licensed under separate terms,
18 as designated in a particular file or component or in included license
19 documentation. The authors of MySQL hereby grant you an additional
20 permission to link the program and your derivative works with the
21 separately licensed software that they have either included with
22 the program or referenced in the documentation.
23
24 This program is distributed in the hope that it will be useful, but WITHOUT
25 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
26 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
27 for more details.
28
29 You should have received a copy of the GNU General Public License along with
30 this program; if not, write to the Free Software Foundation, Inc.,
31 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
32
33 *****************************************************************************/
34
35 /** @file sync/sync0arr.cc
36 The wait array used in synchronization primitives
37
38 Created 9/5/1995 Heikki Tuuri
39 *******************************************************/
40
41 #include "sync0arr.h"
42
43 #include <sys/types.h>
44 #include <time.h>
45
46 #ifndef UNIV_NO_ERR_MSGS
47 #include "lock0lock.h"
48 #endif /* !UNIV_NO_ERR_MSGS */
49
50 #include "os0event.h"
51 #include "os0file.h"
52 #include "srv0srv.h"
53 #include "sync0arr_impl.h"
54 #include "sync0debug.h"
55 #include "sync0sync.h"
56
57 /** User configured sync array size */
58 ulong srv_sync_array_size = 1;
59
60 /** Locally stored copy of srv_sync_array_size */
61 ulint sync_array_size;
62
63 /** The global array of wait cells for implementation of the database's own
64 mutexes and read-write locks */
65 sync_array_t **sync_wait_array;
66
67 /** count of how many times an object has been signalled */
68 static ulint sg_count;
69
70 #define sync_array_exit(a) mutex_exit(&(a)->mutex)
71 #define sync_array_enter(a) mutex_enter(&(a)->mutex)
72
73 /** Detects a deadlock of one or more threads because of waits of semaphores.
74 Reports a fatal error (and thus does not return) in case it finds one.
75 The return value is only used in recursive calls (depth>0).
76 @param[in] arr The wait array we limit our search for cycle to.
77 The caller must own the arr->mutex.
78 @param[in] cell The cell to check
79 @param[in] depth The recursion depth
80 @return true iff deadlock detected (there might be false negatives) */
81 static bool sync_array_detect_deadlock(sync_array_t *arr, sync_cell_t *cell,
82 size_t depth);
83
84 #ifdef UNIV_DEBUG
85 /** Validates the integrity of the wait array. Checks
86 that the number of reserved cells equals the count variable. */
87 static void sync_array_validate(sync_array_t *arr) /*!< in: sync wait array */
88 {
89 ulint count = 0;
90
91 sync_array_enter(arr);
92
93 for (ulint i = 0; i < arr->next_free_slot; i++) {
94 const sync_cell_t *cell;
95
96 cell = &arr->cells[i];
97
98 if (cell->latch.mutex != nullptr) {
99 count++;
100 }
101 }
102
103 ut_a(count == arr->n_reserved);
104
105 sync_array_exit(arr);
106 }
107 #endif /* UNIV_DEBUG */
108
109 /** Constructor
110 Creates a synchronization wait array. It is protected by a mutex
111 which is automatically reserved when the functions operating on it
112 are called.
113 @param[in] num_cells Number of cells to create */
114 sync_array_t::sync_array_t(ulint num_cells) UNIV_NOTHROW : n_reserved(),
115 n_cells(),
116 cells(),
117 mutex(),
118 res_count(),
119 next_free_slot(),
120 first_free_slot() {
121 ut_a(num_cells > 0);
122
123 cells = ut::new_arr_withkey<sync_cell_t>(UT_NEW_THIS_FILE_PSI_KEY,
124 ut::Count{num_cells});
125
126 n_cells = num_cells;
127
128 first_free_slot = ULINT_UNDEFINED;
129
130 /* Then create the mutex to protect the wait array */
131 mutex_create(LATCH_ID_SYNC_ARRAY_MUTEX, &mutex);
132 }
133
134 /** Destructor */
135 sync_array_t::~sync_array_t() UNIV_NOTHROW {
136 ut_a(n_reserved == 0);
137
138 ut_d(sync_array_validate(this));
139
140 /* Release the mutex protecting the wait array */
141
142 mutex_free(&mutex);
143
144 ut::delete_arr(cells);
145 }
146
147 sync_cell_t *sync_array_get_nth_cell(sync_array_t *arr, ulint n) {
148 ut_a(n < arr->n_cells);
149
150 return (&arr->cells[n]);
151 }
152
153 /** Frees the resources in a wait array. */
154 static void sync_array_free(sync_array_t *arr) /*!< in, own: sync wait array */
155 {
156 ut::delete_(arr);
157 }
158
159 /** Returns the event that the thread owning the cell waits for. */
160 static os_event_t sync_cell_get_event(
161 sync_cell_t *cell) /*!< in: non-empty sync array cell */
162 {
163 ulint type = cell->request_type;
164
165 if (type == SYNC_MUTEX) {
166 return (cell->latch.mutex->event());
167
168 } else if (type == SYNC_BUF_BLOCK) {
169 return (cell->latch.bpmutex->event());
170
171 } else if (type == RW_LOCK_X_WAIT) {
172 return (cell->latch.lock->wait_ex_event);
173
174 } else { /* RW_LOCK_S and RW_LOCK_X wait on the same event */
175
176 return (cell->latch.lock->event);
177 }
178 }
179
180 sync_cell_t *sync_array_reserve_cell(sync_array_t *arr, void *object,
181 ulint type, ut::Location location) {
182 sync_cell_t *cell;
183
184 sync_array_enter(arr);
185
186 if (arr->first_free_slot != ULINT_UNDEFINED) {
187 /* Try and find a slot in the free list */
188 ut_ad(arr->first_free_slot < arr->next_free_slot);
189 cell = sync_array_get_nth_cell(arr, arr->first_free_slot);
190 arr->first_free_slot = cell->line;
191 } else if (arr->next_free_slot < arr->n_cells) {
192 /* Try and find a slot after the currently allocated slots */
193 cell = sync_array_get_nth_cell(arr, arr->next_free_slot);
194 ++arr->next_free_slot;
195 } else {
196 sync_array_exit(arr);
197
198 // We should return NULL and if there is more than
199 // one sync array, try another sync array instance.
200 return (nullptr);
201 }
202
203 ++arr->res_count;
204
205 ut_ad(arr->n_reserved < arr->n_cells);
206 ut_ad(arr->next_free_slot <= arr->n_cells);
207
208 ++arr->n_reserved;
209
210 /* Reserve the cell. */
211 ut_ad(cell->latch.mutex == nullptr);
212
213 cell->request_type = type;
214
215 if (cell->request_type == SYNC_MUTEX) {
216 cell->latch.mutex = reinterpret_cast<WaitMutex *>(object);
217 } else if (cell->request_type == SYNC_BUF_BLOCK) {
218 cell->latch.bpmutex = reinterpret_cast<BlockWaitMutex *>(object);
219 } else {
220 cell->latch.lock = reinterpret_cast<rw_lock_t *>(object);
221 }
222
223 cell->waiting = false;
224
225 cell->file = location.filename;
226 cell->line = location.line;
227
228 sync_array_exit(arr);
229
230 cell->thread_id = std::this_thread::get_id();
231
232 cell->reservation_time = std::chrono::steady_clock::now();
233
234 /* Make sure the event is reset and also store the value of
235 signal_count at which the event was reset. */
236 os_event_t event = sync_cell_get_event(cell);
237 cell->signal_count = os_event_reset(event);
238
239 return (cell);
240 }
241
242 /** Frees the cell. NOTE! sync_array_wait_event frees the cell
243 automatically! */
244 void sync_array_free_cell(
245 sync_array_t *arr, /*!< in: wait array */
246 sync_cell_t *&cell) /*!< in/out: the cell in the array */
247 {
248 sync_array_enter(arr);
249
250 ut_a(cell->latch.mutex != nullptr);
251
252 cell->waiting = false;
253 cell->signal_count = 0;
254 cell->latch.mutex = nullptr;
255
256 /* Setup the list of free slots in the array */
257 cell->line = arr->first_free_slot;
258
259 arr->first_free_slot = cell - arr->cells;
260
261 ut_a(arr->n_reserved > 0);
262 arr->n_reserved--;
263
264 if (arr->next_free_slot > arr->n_cells / 2 && arr->n_reserved == 0) {
265 #ifdef UNIV_DEBUG
266 for (ulint i = 0; i < arr->next_free_slot; ++i) {
267 cell = sync_array_get_nth_cell(arr, i);
268
269 ut_ad(!cell->waiting);
270 ut_ad(cell->latch.mutex == nullptr);
271 ut_ad(cell->signal_count == 0);
272 }
273 #endif /* UNIV_DEBUG */
274 arr->next_free_slot = 0;
275 arr->first_free_slot = ULINT_UNDEFINED;
276 }
277 sync_array_exit(arr);
278
279 cell = nullptr;
280 }
281 void sync_array_detect_deadlock() {
282 for (ulint i = 0; i < sync_array_size; ++i) {
283 auto arr = sync_wait_array[i];
284 sync_array_enter(arr);
285 ut_d(rw_lock_debug_mutex_enter());
286 ut_a(arr->last_scan % 2 == 0);
287 ++arr->last_scan;
288 size_t count{0};
289 for (size_t i = 0; count < arr->n_reserved; ++i) {
290 auto cell = sync_array_get_nth_cell(arr, i);
291 if (cell->latch.mutex) {
292 ++count;
293 if (cell->last_scan == arr->last_scan + 1) {
294 continue;
295 }
296 ut_a(cell->last_scan != arr->last_scan);
297 sync_array_detect_deadlock(arr, cell, 0);
298 }
299 }
300 ++arr->last_scan;
301 ut_a(arr->last_scan % 2 == 0);
302 ut_d(rw_lock_debug_mutex_exit());
303 sync_array_exit(arr);
304 }
305 }
306
307 /** This function should be called when a thread starts to wait on
308 a wait array cell. In the debug version this function checks
309 if the wait for a semaphore will result in a deadlock, in which
310 case prints info and asserts. */
311 void sync_array_wait_event(
312 sync_array_t *arr, /*!< in: wait array */
313 sync_cell_t *&cell) /*!< in: index of the reserved cell */
314 {
315 sync_array_enter(arr);
316
317 ut_ad(!cell->waiting);
318 ut_ad(cell->latch.mutex);
319 ut_ad(std::this_thread::get_id() == cell->thread_id);
320
321 cell->waiting = true;
322 #ifdef UNIV_DEBUG
323 /* We use simple enter to the mutex below, because if
324 we cannot acquire it at once, mutex_enter would call
325 recursively sync_array routines, leading to trouble.
326 rw_lock_debug_mutex freezes the debug lists. */
327
328 rw_lock_debug_mutex_enter();
329 ut_a(arr->last_scan % 2 == 0);
330 ++arr->last_scan;
331 sync_array_detect_deadlock(arr, cell, 0);
332 ++arr->last_scan;
333 ut_a(arr->last_scan % 2 == 0);
334 rw_lock_debug_mutex_exit();
335 #endif
336 sync_array_exit(arr);
337
338 os_event_wait_low(sync_cell_get_event(cell), cell->signal_count);
339
340 sync_array_free_cell(arr, cell);
341
342 cell = nullptr;
343 }
344 /** Reports info about a mutex (seen locked a moment ago) into a file.
345 @param[in] file File where to print.
346 @param[in] mutex The mutex to describe.
347 */
348 template <typename Mutex>
349 static void sync_array_mutex_print(FILE *file, const Mutex *mutex) {
350 const auto &policy = mutex->policy();
351 #ifdef UNIV_DEBUG
352 const char *name = policy.get_enter_filename();
353 if (name == nullptr) {
354 /* The mutex might have been released. */
355 name = "NULL";
356 }
357 #endif /* UNIV_DEBUG */
358 const std::thread::id owner = mutex->peek_owner();
359
360 fprintf(file,
361 "Mutex at %p, %s, locked by %s\n"
362 #ifdef UNIV_DEBUG
363 "Last time reserved in file %s line %lu"
364 #endif /* UNIV_DEBUG */
365 "\n",
366 (void *)mutex, policy.to_string().c_str(),
367 (owner == std::thread::id{} ? "nobody" : to_string(owner).c_str())
368 #ifdef UNIV_DEBUG
369 ,
370 name, (ulong)policy.get_enter_line()
371 #endif /* UNIV_DEBUG */
372 );
373 }
374
375 void sync_array_cell_print(FILE *file, const sync_cell_t *cell) {
376 rw_lock_t *rwlock;
377 ulint type;
378 ulint writer;
379
380 type = cell->request_type;
381
382 fprintf(file,
383 "--Thread %s has waited at %s line " ULINTPF " for %" PRId64
384 " seconds the semaphore:\n",
385 to_string(cell->thread_id).c_str(), innobase_basename(cell->file),
386 cell->line,
387 static_cast<int64_t>(
388 std::chrono::duration_cast<std::chrono::seconds>(
389 std::chrono::steady_clock::now() - cell->reservation_time)
390 .count()));
391
392 if (type == SYNC_MUTEX) {
393 sync_array_mutex_print(file, cell->latch.mutex);
394 } else if (type == SYNC_BUF_BLOCK) {
395 sync_array_mutex_print(file, cell->latch.bpmutex);
396 } else if (type == RW_LOCK_X || type == RW_LOCK_X_WAIT ||
397 type == RW_LOCK_SX || type == RW_LOCK_S) {
398 fputs(type == RW_LOCK_X ? "X-lock on"
399 : type == RW_LOCK_X_WAIT ? "X-lock (wait_ex) on"
400 : type == RW_LOCK_SX ? "SX-lock on"
401 : "S-lock on",
402 file);
403
404 rwlock = cell->latch.lock;
405
406 fprintf(file, " RW-latch at %p created in file %s line %lu\n",
407 (void *)rwlock, innobase_basename(rwlock->clocation.filename),
408 (ulong)rwlock->clocation.line);
409
410 writer = rw_lock_get_writer(rwlock);
411
412 if (writer != RW_LOCK_NOT_LOCKED) {
413 fprintf(file, "a writer (thread id %s) has reserved it in mode %s\n",
414 to_string(rwlock->writer_thread.load()).c_str(),
415 writer == RW_LOCK_X
416 ? "exclusive"
417 : (writer == RW_LOCK_SX ? "SX" : "wait exclusive"));
418 }
419
420 const auto readers_count = rw_lock_get_reader_count(rwlock);
421 fprintf(file, "number of readers " ULINTPF, readers_count);
422 if (readers_count == 1) {
423 fprintf(file, " (thread id %s)",
424 to_string(rwlock->reader_thread.recover_if_single()).c_str());
425 }
426 fprintf(file,
427 ", waiters flag %d"
428 ", lock_word: %lx\n"
429 "Last time read locked in file %s line %lu\n"
430 "Last time write locked in file %s line %lu\n",
431 rwlock->waiters.load(),
432 static_cast<ulong>(rwlock->lock_word.load()),
433 innobase_basename(rwlock->last_s_file_name),
434 static_cast<ulong>(rwlock->last_s_line), rwlock->last_x_file_name,
435 static_cast<ulong>(rwlock->last_x_line));
436 } else {
437 ut_error;
438 }
439
440 if (!cell->waiting) {
441 fputs("wait has ended\n", file);
442 }
443 }
444
445 /** Looks for a cell with the given thread id.
446 @return pointer to cell or NULL if not found */
447 static sync_cell_t *sync_array_find_thread(
448 sync_array_t *arr, /*!< in: wait array */
449 std::thread::id thread) /*!< in: thread id */
450 {
451 for (ulint i = 0; i <= arr->next_free_slot; i++) {
452 sync_cell_t *cell;
453
454 cell = sync_array_get_nth_cell(arr, i);
455
456 if (cell->latch.mutex != nullptr && cell->thread_id == thread) {
457 return (cell); /* Found */
458 }
459 }
460
461 return (nullptr); /* Not found */
462 }
463
464 /** Recursion step for deadlock detection.
465 @param[in] arr The wait array we limit our search for cycle to.
466 The caller must own the arr->mutex.
467 @param[in] thread The thread which blocking other threads, which we want to
468 find in the arr, to know if and why it's blocked, too
469 @param[in] depth The recursion depth
470 @return true iff deadlock detected (there might be false negatives) */
471 static bool sync_array_deadlock_step(sync_array_t *arr, std::thread::id thread,
472 size_t depth) {
473 const auto new_cell = sync_array_find_thread(arr, thread);
474 if (new_cell == nullptr) {
475 return false;
476 }
477 if (new_cell->last_scan == arr->last_scan) {
478 /* Deadlock */
479 fputs(
480 "########################################\n"
481 "DEADLOCK of threads detected!\n",
482 stderr);
483
484 return true;
485 }
486 if (new_cell->last_scan == arr->last_scan + 1) {
487 /* Already processed */
488 return false;
489 }
490 return sync_array_detect_deadlock(arr, new_cell, depth + 1);
491 }
492
493 /** A helper for sync_array_detect_deadlock() to handle the case when the cell
494 contains a thread waiting for a mutex.
495 @param[in] mutex the mutex to check
496 @param[in] arr wait array; NOTE! the caller must own the mutex to array
497 @param[in] cell the cell which contains the mutex
498 @param[in] depth recursion depth
499 */
500 template <typename Mutex>
501 static bool sync_array_detect_mutex_deadlock(const Mutex *mutex,
502 sync_array_t *arr,
503 sync_cell_t *cell, size_t depth) {
504 const std::thread::id thread = mutex->peek_owner();
505 if (thread != std::thread::id{}) {
506 if (sync_array_deadlock_step(arr, thread, depth)) {
507 sync_array_cell_print(stderr, cell);
508
509 return true;
510 }
511 }
512
513 /* No deadlock */
514 return false;
515 }
516 template <typename F>
517 bool sync_array_detect_rwlock_deadlock(sync_cell_t *cell, sync_array_t *arr,
518 const size_t depth, F &&conflicts) {
519 auto lock = cell->latch.lock;
520 const auto waiter = cell->thread_id;
521 #ifdef UNIV_DEBUG
522 for (auto debug : lock->debug_list) {
523 /* If pass != 0, then we do not know which threads are responsible for
524 releasing the lock, and no deadlock can be detected. */
525 if (debug->pass) {
526 continue;
527 }
528 const auto holder = debug->thread_id;
529 if (std::forward<F>(conflicts)(debug->lock_type, waiter == holder)) {
530 if (sync_array_deadlock_step(arr, holder, depth)) {
531 sync_array_cell_print(stderr, cell);
532 rw_lock_debug_print(stderr, debug);
533 return true;
534 }
535 }
536 }
537 #else
538 /* We don't have lock->debug_list, so can't identify all threads owning the
539 latch, but we still have some clues available.
540 We can identify the only thread which has (wait) x-lock by looking at
541 lock->writer_thread, unless the lock was passed to another thread which
542 requires the lock->recursive to be false.
543 We don't track all s-locks, but if there is exactly one s-lock, then we can
544 identify its owner with lock->reader_thread.
545 You might be worried about race-condition: could it happen that the holder we
546 identify here, will soon release the latch, and thus we will report a "fake"
547 deadlock? Not really, because the first thing sync_array_deadlock_step() will
548 do is to check if the holder is itself waiting for something in the arr we
549 keep latched - if it isn't waiting, we will ignore it, and if it is, then it's
550 not executing thus can't release the rw_lock we analyze here. */
551 const std::thread::id none{};
552 std::thread::id suspects[2]{};
553 size_t suspects_cnt = 0;
554 {
555 if (lock->recursive.load()) {
556 /* You might be worried about a race-condition: could it happen that the
557 recursive was set to true by some other thread, which now released the
558 lock, and then the writer_thread acquired it to pass it to somebody else,
559 and thus set recursive to false?
560 We double check that recursive is still true after loading writer_thread,
561 and we only report a deadlock if writer_thread is itself not executing.
562 So if a deadlock is reported it must be writer_thread who set recursive to
563 true and is still holding this latch.
564 Note that we always pass RW_LOCK_X as the granted request_type of the
565 blocking thread, even though it could still be waiting for RW_LOCK_WAIT_X.
566 This doesn't really matter as existing callbacks do not differentiate,
567 and more importantly they should rather care about "kind of access right"
568 than "state of latching" (debug_list's lock_type), or "awaited event"
569 (cell's request type). Alas we use the same enum for these concepts.*/
570 const auto thread = lock->writer_thread.load();
571 if (lock->recursive.load() && thread != none &&
572 std::forward<F>(conflicts)(RW_LOCK_X, thread == waiter)) {
573 suspects[suspects_cnt++] = thread;
574 }
575 }
576 }
577 {
578 if (rw_lock_get_reader_count(lock) == 1) {
579 /* You might be worried about a race-condition: could it happen that the
580 number of s-lockers has changed from 1 to say 3, and the XOR we recover in
581 the line below corresponds to some unrelated fourth thread?
582 For example 0x101 xor 0x110 xor 0x111 = 0x100.
583 This isn't a problem in practice, because conflicts(RW_LOCKS,..) is true
584 only if the waiter waits for RW_LOCK_X_WAIT, which means it already has
585 announced its presence via lock_word, so no more s-locks should be granted
586 to not starve it. Thus the number of readers can only decrease. We double
587 check it is still 1 after recovering the xor, so it can't be 0 nor torn.*/
588 const auto thread = lock->reader_thread.recover_if_single();
589 if (rw_lock_get_reader_count(lock) == 1 && thread != none &&
590 std::forward<F>(conflicts)(RW_LOCK_S, thread == waiter)) {
591 suspects[suspects_cnt++] = thread;
592 }
593 }
594 }
595 for (size_t i = 0; i < suspects_cnt; ++i) {
596 if (sync_array_deadlock_step(arr, suspects[i], depth)) {
597 sync_array_cell_print(stderr, cell);
598 return true;
599 }
600 }
601 #endif /* UNIV_DEBUG */
602 return false;
603 }
604
605 static bool sync_array_detect_deadlock_low(sync_array_t *arr, sync_cell_t *cell,
606 size_t depth) {
607 ut_a(arr);
608 ut_a(cell);
609 ut_ad(cell->latch.mutex != nullptr);
610 ut_ad(depth < 100);
611
612 if (!cell->waiting) {
613 /* No deadlock here */
614 return (false);
615 }
616
617 switch (cell->request_type) {
618 case SYNC_MUTEX: {
619 return sync_array_detect_mutex_deadlock(cell->latch.mutex, arr, cell,
620 depth);
621 }
622
623 case SYNC_BUF_BLOCK: {
624 return sync_array_detect_mutex_deadlock(cell->latch.bpmutex, arr, cell,
625 depth);
626 }
627 case RW_LOCK_X:
628 /* The x-lock request can block infinitely only if someone (cannot be the
629 cell thread) has (wait) x-lock or sx-lock, and he is blocked by start
630 thread */
631 return sync_array_detect_rwlock_deadlock(
632 cell, arr, depth, [](auto request_type, bool is_my) {
633 return !is_my && request_type != RW_LOCK_S;
634 });
635 case RW_LOCK_X_WAIT:
636 /* The (wait) x-lock request can block infinitely only if someone (can be
637 also the cell thread) is holding an s-lock */
638 return sync_array_detect_rwlock_deadlock(
639 cell, arr, depth,
640 [](auto request_type, bool) { return request_type == RW_LOCK_S; });
641 case RW_LOCK_SX:
642 /* The sx-lock request can block infinitely only if someone (cannot be
643 the cell thread) is holding a (wait) x-lock or sx-lock, and he is blocked
644 by start thread */
645 return sync_array_detect_rwlock_deadlock(
646 cell, arr, depth, [](auto request_type, bool is_my) {
647 return !is_my && request_type != RW_LOCK_S;
648 });
649 case RW_LOCK_S:
650 /* The s-lock request can block infinitely only if someone (can also be
651 the cell thread) is holding a (wait) x-lock, and he is blocked by start
652 thread */
653 return sync_array_detect_rwlock_deadlock(
654 cell, arr, depth, [](auto request_type, bool) {
655 return request_type == RW_LOCK_X || request_type == RW_LOCK_X_WAIT;
656 });
657 default:
658 ut_error;
659 }
660 }
661 static bool sync_array_detect_deadlock(sync_array_t *const arr,
662 sync_cell_t *const cell, size_t depth) {
663 // there's an ongoing scan
664 ut_a(arr->last_scan % 2 == 1);
665 // do not visit a cell which is already on stack
666 ut_a(cell->last_scan != arr->last_scan);
667 // do not waste time processing already processed cell
668 ut_a(cell->last_scan != arr->last_scan + 1);
669 // mark the fact the cell is on stack
670 cell->last_scan = arr->last_scan;
671 const bool deadlocked = sync_array_detect_deadlock_low(arr, cell, depth);
672 // mark the fact the cell as fully processed;
673 cell->last_scan++;
674 if (deadlocked && depth == 0) {
675 #ifdef UNIV_NO_ERR_MSGS
676 ib::fatal(UT_LOCATION_HERE)
677 #else
678 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_1157)
679 #endif /* UNIV_NO_ERR_MSGS */
680 << "######################################## Deadlock Detected!";
681 }
682 return deadlocked;
683 }
684
685 /** Determines if we can wake up the thread waiting for a semaphore. */
686 static bool sync_arr_cell_can_wake_up(
687 sync_cell_t *cell) /*!< in: cell to search */
688 {
689 rw_lock_t *lock;
690
691 switch (cell->request_type) {
692 case SYNC_MUTEX:
693 return !cell->latch.mutex->is_locked();
694
695 case SYNC_BUF_BLOCK:
696 return !cell->latch.bpmutex->is_locked();
697
698 case RW_LOCK_X:
699 case RW_LOCK_SX:
700 lock = cell->latch.lock;
701
702 os_rmb;
703 if (lock->lock_word > X_LOCK_HALF_DECR) {
704 /* Either unlocked or only read locked. */
705
706 return (true);
707 }
708
709 break;
710
711 case RW_LOCK_X_WAIT:
712
713 lock = cell->latch.lock;
714
715 /* lock_word == 0 means all readers or sx have left */
716 os_rmb;
717 if (lock->lock_word == 0) {
718 return (true);
719 }
720 break;
721
722 case RW_LOCK_S:
723
724 lock = cell->latch.lock;
725
726 /* lock_word > 0 means no writer or reserved writer */
727 os_rmb;
728 if (lock->lock_word > 0) {
729 return (true);
730 }
731 }
732
733 return (false);
734 }
735
736 /** Increments the signalled count. */
737 void sync_array_object_signalled() { ++sg_count; }
738
739 /** If the wakeup algorithm does not work perfectly at semaphore releases,
740 this function will do the waking (see the comment in mutex_exit). This
741 function should be called about every 1 second in the server.
742
743 Note that there's a race condition between this thread and mutex_exit
744 changing the lock_word and calling signal_object, so sometimes this finds
745 threads to wake up even when nothing has gone wrong. */
746 static void sync_array_wake_threads_if_sema_free_low(
747 sync_array_t *arr) /* in/out: wait array */
748 {
749 sync_array_enter(arr);
750
751 for (ulint i = 0; i < arr->next_free_slot; ++i) {
752 sync_cell_t *cell;
753
754 cell = sync_array_get_nth_cell(arr, i);
755
756 if (cell->latch.mutex != nullptr && sync_arr_cell_can_wake_up(cell)) {
757 os_event_t event;
758
759 event = sync_cell_get_event(cell);
760
761 os_event_set(event);
762 }
763 }
764
765 sync_array_exit(arr);
766 }
767
768 /** If the wakeup algorithm does not work perfectly at semaphore releases,
769 this function will do the waking (see the comment in mutex_exit). This
770 function should be called about every 1 second in the server.
771
772 Note that there's a race condition between this thread and mutex_exit
773 changing the lock_word and calling signal_object, so sometimes this finds
774 threads to wake up even when nothing has gone wrong. */
775 void sync_arr_wake_threads_if_sema_free(void) {
776 for (ulint i = 0; i < sync_array_size; ++i) {
777 sync_array_wake_threads_if_sema_free_low(sync_wait_array[i]);
778 }
779 }
780
781 /** Prints warnings of long semaphore waits to stderr.
782 @return true if fatal semaphore wait threshold was exceeded */
783 static bool sync_array_print_long_waits_low(
784 sync_array_t *arr, /*!< in: sync array instance */
785 std::thread::id *waiter, /*!< out: longest waiting thread */
786 const void **sema, /*!< out: longest-waited-for semaphore */
787 bool *noticed) /*!< out: true if long wait noticed */
788 {
789 bool fatal = false;
790 std::chrono::steady_clock::duration longest_diff{};
791 auto fatal_timeout = get_srv_fatal_semaphore_wait_threshold();
792
793 /* For huge tables, skip the check during CHECK TABLE etc... */
794 if (0 < srv_fatal_semaphore_wait_extend.load()) {
795 return false;
796 }
797
798 #ifdef UNIV_DEBUG_VALGRIND
799 /* Increase the timeouts if running under valgrind because it executes
800 extremely slowly. UNIV_DEBUG_VALGRIND does not necessary mean that
801 we are running under valgrind but we have no better way to tell.
802 See Bug#58432 innodb.innodb_bug56143 fails under valgrind
803 for an example */
804 constexpr std::chrono::minutes timeout{40};
805 fatal_timeout *= 10;
806 #else
807 constexpr std::chrono::minutes timeout{4};
808 #endif
809
810 for (ulint i = 0; i < arr->next_free_slot; i++) {
811 sync_cell_t *cell;
812 void *latch;
813
814 cell = sync_array_get_nth_cell(arr, i);
815
816 latch = cell->latch.mutex;
817
818 if (latch == nullptr || !cell->waiting) {
819 continue;
820 }
821
822 const auto time_diff =
823 std::chrono::steady_clock::now() - cell->reservation_time;
824
825 if (time_diff > timeout) {
826 #ifdef UNIV_NO_ERR_MSGS
827 ib::warn()
828 #else
829 ib::warn(ER_IB_MSG_1160)
830 #endif /* UNIV_NO_ERR_MSGS */
831 << "A long semaphore wait:";
832
833 sync_array_cell_print(stderr, cell);
834 *noticed = true;
835 }
836
837 if (time_diff > fatal_timeout) {
838 fatal = true;
839 }
840
841 if (longest_diff < time_diff) {
842 longest_diff = time_diff;
843 *sema = latch;
844 *waiter = cell->thread_id;
845 }
846 }
847
848 return fatal;
849 }
850
851 /** Prints warnings of long semaphore waits to stderr.
852 @return true if fatal semaphore wait threshold was exceeded */
853 bool sync_array_print_long_waits(
854 std::thread::id *waiter, /*!< out: longest waiting thread */
855 const void **sema) /*!< out: longest-waited-for semaphore */
856 {
857 ulint i;
858 bool fatal = false;
859 bool noticed = false;
860
861 for (i = 0; i < sync_array_size; ++i) {
862 sync_array_t *arr = sync_wait_array[i];
863
864 sync_array_enter(arr);
865
866 if (sync_array_print_long_waits_low(arr, waiter, sema, &noticed)) {
867 fatal = true;
868 }
869
870 sync_array_exit(arr);
871 }
872
873 if (noticed) {
874 fprintf(stderr,
875 "InnoDB: ###### Starts InnoDB Monitor"
876 " for 30 secs to print diagnostic info:\n");
877
878 /* If some crucial semaphore is reserved, then also the InnoDB
879 Monitor can hang, and we do not get diagnostics. Since in
880 many cases an InnoDB hang is caused by a pwrite() or a pread()
881 call hanging inside the operating system, let us print right
882 now the values of pending calls of these. */
883
884 fprintf(stderr, "InnoDB: Pending preads %lu, pwrites %lu\n",
885 (ulong)os_n_pending_reads, (ulong)os_n_pending_writes);
886
887 srv_innodb_needs_monitoring++;
888
889 #ifndef UNIV_NO_ERR_MSGS
890 lock_set_timeout_event();
891 #endif /* !UNIV_NO_ERR_MSGS */
892
893 std::this_thread::sleep_for(std::chrono::seconds(30));
894
895 srv_innodb_needs_monitoring--;
896 fprintf(stderr,
897 "InnoDB: ###### Diagnostic info printed"
898 " to the standard error stream\n");
899 }
900
901 return (fatal);
902 }
903
904 /** Prints info of the wait array. */
905 static void sync_array_print_info_low(
906 FILE *file, /*!< in: file where to print */
907 sync_array_t *arr) /*!< in: wait array */
908 {
909 ulint i;
910 ulint count = 0;
911
912 fprintf(file, "OS WAIT ARRAY INFO: reservation count " ULINTPF "\n",
913 arr->res_count);
914
915 for (i = 0; count < arr->n_reserved; ++i) {
916 sync_cell_t *cell;
917
918 cell = sync_array_get_nth_cell(arr, i);
919
920 if (cell->latch.mutex != nullptr) {
921 count++;
922 sync_array_cell_print(file, cell);
923 }
924 }
925 }
926
927 /** Prints info of the wait array. */
928 static void sync_array_print_info(FILE *file, /*!< in: file where to print */
929 sync_array_t *arr) /*!< in: wait array */
930 {
931 sync_array_enter(arr);
932
933 sync_array_print_info_low(file, arr);
934
935 sync_array_exit(arr);
936 }
937
938 /** Create the primary system wait array(s), they are protected by an OS mutex
939 */
940 void sync_array_init(ulint n_threads) /*!< in: Number of slots to
941 create in all arrays */
942 {
943 ut_a(sync_wait_array == nullptr);
944 ut_a(srv_sync_array_size > 0);
945 ut_a(n_threads > 0);
946
947 sync_array_size = srv_sync_array_size;
948
949 sync_wait_array = ut::new_arr_withkey<sync_array_t *>(
950 UT_NEW_THIS_FILE_PSI_KEY, ut::Count{sync_array_size});
951
952 ulint n_slots = 1 + (n_threads - 1) / sync_array_size;
953
954 for (ulint i = 0; i < sync_array_size; ++i) {
955 sync_wait_array[i] =
956 ut::new_withkey<sync_array_t>(UT_NEW_THIS_FILE_PSI_KEY, n_slots);
957 }
958 }
959
960 /** Close sync array wait sub-system. */
961 void sync_array_close(void) {
962 for (ulint i = 0; i < sync_array_size; ++i) {
963 sync_array_free(sync_wait_array[i]);
964 }
965
966 ut::delete_arr(sync_wait_array);
967 sync_wait_array = nullptr;
968 }
969
970 /** Print info about the sync array(s). */
971 void sync_array_print(FILE *file) /*!< in/out: Print to this stream */
972 {
973 for (ulint i = 0; i < sync_array_size; ++i) {
974 sync_array_print_info(file, sync_wait_array[i]);
975 }
976
977 fprintf(file, "OS WAIT ARRAY INFO: signal count " ULINTPF "\n", sg_count);
978 }