Debian Codegraph @

storage/innobase/sync/sync0rw.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/sync0rw.cc
36 The read-write lock (for thread synchronization)
37
38 Created 9/11/1995 Heikki Tuuri
39 *******************************************************/
40
41 #include "sync0rw.h"
42
43 #include <my_sys.h>
44 #include <sys/types.h>
45
46 #include "ha_prototypes.h"
47 #include "mem0mem.h"
48 #include "os0event.h"
49 #include "os0thread.h"
50 #include "srv0mon.h"
51 #include "srv0srv.h"
52 #include "sync0debug.h"
53
54 /*
55 IMPLEMENTATION OF THE RW_LOCK
56 =============================
57 The status of a rw_lock is held in lock_word. The initial value of lock_word is
58 X_LOCK_DECR. lock_word is decremented by 1 for each s-lock and by X_LOCK_DECR
59 or 1 for each x-lock. This describes the lock state for each value of lock_word:
60
61 lock_word == X_LOCK_DECR: Unlocked.
62 X_LOCK_HALF_DECR < lock_word < X_LOCK_DECR:
63 S locked, no waiting writers.
64 (X_LOCK_DECR - lock_word) is the number
65 of S locks.
66 lock_word == X_LOCK_HALF_DECR: SX locked, no waiting writers.
67 0 < lock_word < X_LOCK_HALF_DECR:
68 SX locked AND S locked, no waiting writers.
69 (X_LOCK_HALF_DECR - lock_word) is the number
70 of S locks.
71 lock_word == 0: X locked, no waiting writers.
72 -X_LOCK_HALF_DECR < lock_word < 0:
73 S locked, with a waiting writer.
74 (-lock_word) is the number of S locks.
75 lock_word == -X_LOCK_HALF_DECR: X locked and SX locked, no waiting writers.
76 -X_LOCK_DECR < lock_word < -X_LOCK_HALF_DECR:
77 S locked, with a waiting writer
78 which has SX lock.
79 -(lock_word + X_LOCK_HALF_DECR) is the number
80 of S locks.
81 lock_word == -X_LOCK_DECR: X locked with recursive X lock (2 X locks).
82 -(X_LOCK_DECR + X_LOCK_HALF_DECR) < lock_word < -X_LOCK_DECR:
83 X locked. The number of the X locks is:
84 2 - (lock_word + X_LOCK_DECR)
85 lock_word == -(X_LOCK_DECR + X_LOCK_HALF_DECR):
86 X locked with recursive X lock (2 X locks)
87 and SX locked.
88 lock_word < -(X_LOCK_DECR + X_LOCK_HALF_DECR):
89 X locked and SX locked.
90 The number of the X locks is:
91 2 - (lock_word + X_LOCK_DECR + X_LOCK_HALF_DECR)
92
93 LOCK COMPATIBILITY MATRIX
94 S SX X
95 S + + -
96 SX + - -
97 X - - -
98
99 The lock_word is always read and updated atomically and consistently, so that
100 it always represents the state of the lock, and the state of the lock changes
101 with a single atomic operation. This lock_word holds all of the information
102 that a thread needs in order to determine if it is eligible to gain the lock
103 or if it must spin or sleep. The one exception to this is that writer_thread
104 must be verified before recursive write locks: to solve this scenario, we make
105 writer_thread readable by all threads, but only writeable by the x-lock or
106 sx-lock holder.
107
108 The other members of the lock obey the following rules to remain consistent:
109
110 recursive: This flag is true iff the lock->writer_thread is allowed to take
111 the x or sx lock recursively.
112
113 In particular you should follow these rules:
114 - make sure to change recursive to `false` before
115 releasing the lock
116 - make sure to change recursive to `false` (but do not reset the
117 `writer_thread` as it will remove debug info) before passing
118 the lock to other thread
119 - make sure to put your thread's native handle before setting
120 recursive to `true`
121 - make sure that when you want to read both `recursive` and
122 `writer_thread` you do this in this precise order
123 writer_thread: Is used only in recursive x-locking.
124 This field is initialized to an impossible thread native handle
125 value at lock creation time and is updated atomically when sx or
126 x-lock is being acquired or when move_ownership is called.
127 A thread is only allowed to set the value of this field to its
128 thread_id i.e.: a thread cannot set writer_thread to some other
129 thread's id.
130 The only reasonable way (except reporting in debug info) to use
131 this field is to compare it to own thread's native handle
132 AFTER checking that lock->recursive flag is set, to see if we
133 are the current writer.
134 waiters: May be set to 1 anytime, but to avoid unnecessary wake-up
135 signals, it should only be set to 1 when there are threads
136 waiting on event. Must be 1 when a writer starts waiting to
137 ensure the current x-locking thread sends a wake-up signal
138 during unlock. May only be reset to 0 immediately before a
139 a wake-up signal is sent to event. On most platforms, a
140 memory barrier is required after waiters is set, and before
141 verifying lock_word is still held, to ensure some unlocker
142 really does see the flags new value.
143 event: Threads wait on event for read or writer lock when another
144 thread has an x-lock or an x-lock reservation (wait_ex). A
145 thread may only wait on event after performing the following
146 actions in order:
147 (1) Record the counter value of event (with os_event_reset).
148 (2) Set waiters to 1.
149 (3) Verify lock_word <= 0.
150 (1) must come before (2) to ensure signal is not missed.
151 (2) must come before (3) to ensure a signal is sent.
152 These restrictions force the above ordering.
153 Immediately before sending the wake-up signal, we should:
154 (1) Verify lock_word == X_LOCK_DECR (unlocked)
155 (2) Reset waiters to 0.
156 wait_ex_event: A thread may only wait on the wait_ex_event after it has
157 performed the following actions in order:
158 (1) Decrement lock_word by X_LOCK_DECR.
159 (2) Record counter value of wait_ex_event (os_event_reset,
160 called from sync_array_reserve_cell).
161 (3) Verify that lock_word < 0.
162 (1) must come first to ensures no other threads become reader
163 or next writer, and notifies unlocker that signal must be sent.
164 (2) must come before (3) to ensure the signal is not missed.
165 These restrictions force the above ordering.
166 Immediately before sending the wake-up signal, we should:
167 Verify lock_word == 0 (waiting thread holds x_lock)
168 */
169
170 /** The global list of rw-locks */
171 rw_lock_list_t rw_lock_list{};
172 ib_mutex_t rw_lock_list_mutex;
173
174 #ifdef UNIV_DEBUG
175 /** Creates a debug info struct. */
176 static rw_lock_debug_t *rw_lock_debug_create(void);
177 /** Frees a debug info struct. */
178 static void rw_lock_debug_free(rw_lock_debug_t *info);
179
180 /** Creates a debug info struct.
181 @return own: debug info struct */
182 static rw_lock_debug_t *rw_lock_debug_create(void) {
183 return ((rw_lock_debug_t *)ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY,
184 sizeof(rw_lock_debug_t)));
185 }
186
187 /** Frees a debug info struct. */
188 static void rw_lock_debug_free(rw_lock_debug_t *info) { ut::free(info); }
189 #endif /* UNIV_DEBUG */
190
191 void rw_lock_create_func(rw_lock_t *lock,
192 IF_DEBUG(latch_id_t id, ) ut::Location clocation) {
193 #if !defined(UNIV_PFS_RWLOCK)
194 /* It should have been created in pfs_rw_lock_create_func() */
195 new (lock) rw_lock_t();
196 #endif /* !UNIV_PFS_RWLOCK */
197 ut_ad(lock->magic_n == rw_lock_t::MAGIC_N);
198
199 /* If this is the very first time a synchronization object is
200 created, then the following call initializes the sync system. */
201
202 lock->lock_word = X_LOCK_DECR;
203 lock->waiters = false;
204
205 lock->recursive.store(false, std::memory_order_relaxed);
206 lock->sx_recursive = 0;
207 lock->writer_thread = std::thread::id{};
208
209 #ifdef UNIV_DEBUG
210 lock->m_rw_lock = true;
211
212 lock->m_id = id;
213 ut_a(lock->m_id != LATCH_ID_NONE);
214
215 #endif /* UNIV_DEBUG */
216
217 lock->clocation = clocation;
218
219 /* This should hold in practice. If it doesn't then we need to
220 split the source file anyway. Or create the locks on lines
221 less than 65536. cline is uint16_t. */
222 ut_ad(clocation.line <=
223 std::numeric_limits<decltype(lock->clocation.line)>::max());
224
225 lock->count_os_wait = 0;
226 lock->last_s_file_name = "not yet reserved";
227 lock->last_x_file_name = "not yet reserved";
228 lock->last_s_line = 0;
229 lock->last_x_line = 0;
230 lock->event = os_event_create();
231 lock->wait_ex_event = os_event_create();
232
233 lock->is_block_lock = false;
234
235 mutex_enter(&rw_lock_list_mutex);
236
237 ut_ad(UT_LIST_GET_FIRST(rw_lock_list) == nullptr ||
238 UT_LIST_GET_FIRST(rw_lock_list)->magic_n == rw_lock_t::MAGIC_N);
239
240 UT_LIST_ADD_FIRST(rw_lock_list, lock);
241
242 mutex_exit(&rw_lock_list_mutex);
243 }
244
245 /** Calling this function is obligatory only if the memory buffer containing
246 the rw-lock is freed. Removes an rw-lock object from the global list. The
247 rw-lock is checked to be in the non-locked state. */
248 void rw_lock_free_func(rw_lock_t *lock) /*!< in/out: rw-lock */
249 {
250 /* We did an in-place new in rw_lock_create_func() */
251 lock->~rw_lock_t();
252 }
253
254 rw_lock_t::~rw_lock_t() {
255 os_rmb;
256 ut_ad(rw_lock_validate(this));
257 ut_a(lock_word == X_LOCK_DECR);
258
259 mutex_enter(&rw_lock_list_mutex);
260
261 os_event_destroy(event);
262
263 os_event_destroy(wait_ex_event);
264
265 UT_LIST_REMOVE(rw_lock_list, this);
266
267 mutex_exit(&rw_lock_list_mutex);
268
269 ut_ad(magic_n == MAGIC_N);
270 ut_d(magic_n = 0);
271 }
272
273 void rw_lock_s_lock_spin(rw_lock_t *lock, ulint pass, ut::Location location) {
274 ulint i = 0; /* spin round count */
275 sync_array_t *sync_arr;
276 uint64_t count_os_wait = 0;
277
278 /* We reuse the thread id to index into the counter, cache
279 it here for efficiency. */
280
281 ut_ad(rw_lock_validate(lock));
282
283 lock_loop:
284
285 /* Spin waiting for the writer field to become free */
286 os_rmb;
287 while (i < srv_n_spin_wait_rounds && lock->lock_word <= 0) {
288 if (srv_spin_wait_delay) {
289 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
290 }
291
292 i++;
293 }
294
295 if (i >= srv_n_spin_wait_rounds) {
296 std::this_thread::yield();
297 }
298
299 /* We try once again to obtain the lock */
300 if (rw_lock_s_lock_low(lock, pass, location)) {
301 if (count_os_wait > 0) {
302 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
303 }
304
305 return; /* Success */
306 } else {
307 if (i < srv_n_spin_wait_rounds) {
308 goto lock_loop;
309 }
310
311 ++count_os_wait;
312
313 sync_cell_t *cell;
314
315 sync_arr =
316 sync_array_get_and_reserve_cell(lock, RW_LOCK_S, location, &cell);
317
318 /* Set waiters before checking lock_word to ensure wake-up
319 signal is sent. This may lead to some unnecessary signals. */
320 rw_lock_set_waiter_flag(lock);
321
322 if (rw_lock_s_lock_low(lock, pass, location)) {
323 sync_array_free_cell(sync_arr, cell);
324
325 if (count_os_wait > 0) {
326 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
327 }
328
329 return; /* Success */
330 }
331
332 /* see comments in trx_commit_low() to
333 before_trx_state_committed_in_memory explaining
334 this care to invoke the following sync check.*/
335 #ifdef UNIV_DEBUG
336 if (lock->get_level() != SYNC_DICT_OPERATION) {
337 DEBUG_SYNC_C("rw_s_lock_waiting");
338 }
339 #endif
340 sync_array_wait_event(sync_arr, cell);
341
342 i = 0;
343
344 goto lock_loop;
345 }
346 }
347
348 /** This function is used in the insert buffer to move the ownership of an
349 x-latch on a buffer frame to the current thread. The x-latch was set by
350 the buffer read operation and it protected the buffer frame while the
351 read was done. The ownership is moved because we want that the current
352 thread is able to acquire a second x-latch which is stored in an mtr.
353 This, in turn, is needed to pass the debug checks of index page
354 operations. */
355 void rw_lock_x_lock_move_ownership(
356 rw_lock_t *lock) /*!< in: lock which was x-locked in the
357 buffer read */
358 {
359 ut_ad(rw_lock_is_locked(lock, RW_LOCK_X));
360
361 rw_lock_set_writer_id_and_recursion_flag(lock, true);
362 }
363
364 /** Function for the next writer to call. Waits for readers to exit.
365 The caller must have already decremented lock_word by X_LOCK_DECR.
366 @param[in] lock pointer to rw-lock
367 @param[in] pass pass value; != 0, if the lock will be passed to another thread
368 to unlock
369 @param[in] threshold threshold to wait for
370 @param[in] file_name file name where lock requested
371 @param[in] line line where requested */
372 static inline void rw_lock_x_lock_wait_func(rw_lock_t *lock,
373 IF_DEBUG(ulint pass, )
374 lint threshold,
375 const char *file_name, ulint line) {
376 ulint i = 0;
377 sync_array_t *sync_arr;
378 uint64_t count_os_wait = 0;
379
380 os_rmb;
381 ut_ad(lock->lock_word <= threshold);
382
383 while (lock->lock_word < threshold) {
384 if (srv_spin_wait_delay) {
385 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
386 }
387
388 if (i < srv_n_spin_wait_rounds) {
389 i++;
390 os_rmb;
391 continue;
392 }
393
394 /* If there is still a reader, then go to sleep.*/
395 sync_cell_t *cell;
396
397 sync_arr = sync_array_get_and_reserve_cell(lock, RW_LOCK_X_WAIT,
398 {file_name, line}, &cell);
399
400 i = 0;
401
402 /* Check lock_word to ensure wake-up isn't missed.*/
403 if (lock->lock_word < threshold) {
404 ++count_os_wait;
405
406 /* Add debug info as it is needed to detect possible
407 deadlock. We must add info for WAIT_EX thread for
408 deadlock detection to work properly. */
409 ut_d(rw_lock_add_debug_info(lock, pass, RW_LOCK_X_WAIT,
410 {file_name, line}));
411
412 sync_array_wait_event(sync_arr, cell);
413
414 ut_d(rw_lock_remove_debug_info(lock, pass, RW_LOCK_X_WAIT));
415
416 /* It is possible to wake when lock_word < 0.
417 We must pass the while-loop check to proceed.*/
418
419 } else {
420 sync_array_free_cell(sync_arr, cell);
421 break;
422 }
423 }
424
425 if (count_os_wait > 0) {
426 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
427 }
428 }
429
430 /** Function for the next writer to call. Waits for readers to exit.
431 The caller must have already decremented lock_word by X_LOCK_DECR.
432 @param[in] lock pointer to rw-lock
433 @param[in] pass pass value; != 0, if the lock will be passed to another thread
434 to unlock
435 @param[in] treshold threshold to wait for
436 @param[in] file_name file name where lock requested
437 @param[in] line line where requested */
438 static inline void rw_lock_x_lock_wait(rw_lock_t *lock,
439 ulint pass [[maybe_unused]],
440 lint treshold, const char *file_name,
441 ulint line) {
442 rw_lock_x_lock_wait_func(lock, IF_DEBUG(pass, ) treshold, file_name, line);
443 }
444
445 /** Low-level function for acquiring an exclusive lock.
446 @return false if did not succeed, true if success. */
447 static inline bool rw_lock_x_lock_low(
448 rw_lock_t *lock, /*!< in: pointer to rw-lock */
449 ulint pass, /*!< in: pass value; != 0, if the lock will
450 be passed to another thread to unlock */
451 const char *file_name, /*!< in: file name where lock requested */
452 ulint line) /*!< in: line where requested */
453 {
454 if (rw_lock_lock_word_decr(lock, X_LOCK_DECR, X_LOCK_HALF_DECR)) {
455 /* lock->recursive == true implies that the lock->writer_thread is the
456 current writer. As we are going to write our own thread id in that field it
457 must be the case that the current writer_thread value is not the current
458 writer anymore, thus recursive flag must be false. */
459 ut_a(!lock->recursive.load(std::memory_order_relaxed));
460
461 /* Decrement occurred: we are writer or next-writer. */
462 rw_lock_set_writer_id_and_recursion_flag(lock, !pass);
463
464 rw_lock_x_lock_wait(lock, pass, 0, file_name, line);
465
466 } else {
467 if (!pass && lock->recursive.load(std::memory_order_acquire) &&
468 lock->writer_thread.load(std::memory_order_relaxed) ==
469 std::this_thread::get_id()) {
470 /* Decrement failed: An X or SX lock is held by either
471 this thread or another. Try to relock. */
472 /* Other s-locks can be allowed. If it is request x
473 recursively while holding sx lock, this x lock should
474 be along with the latching-order. */
475
476 /* The existing X or SX lock is from this thread */
477 if (rw_lock_lock_word_decr(lock, X_LOCK_DECR, 0)) {
478 /* There is at least one SX-lock from this
479 thread, but no X-lock. */
480
481 /* Wait for any the other S-locks to be
482 released. */
483 rw_lock_x_lock_wait(lock, pass, -X_LOCK_HALF_DECR, file_name, line);
484
485 } else {
486 /* At least one X lock by this thread already
487 exists. Add another. */
488 if (lock->lock_word == 0 || lock->lock_word == -X_LOCK_HALF_DECR) {
489 lock->lock_word -= X_LOCK_DECR;
490 } else {
491 ut_ad(lock->lock_word <= -X_LOCK_DECR);
492 --lock->lock_word;
493 }
494 }
495 } else {
496 /* Another thread locked before us */
497 return false;
498 }
499 }
500
501 ut_d(rw_lock_add_debug_info(lock, pass, RW_LOCK_X, {file_name, line}));
502
503 lock->last_x_file_name = file_name;
504 ut_ad(line <= std::numeric_limits<decltype(lock->last_x_line)>::max());
505 lock->last_x_line = line;
506
507 return true;
508 }
509
510 bool rw_lock_sx_lock_low(rw_lock_t *lock, ulint pass, ut::Location location) {
511 if (rw_lock_lock_word_decr(lock, X_LOCK_HALF_DECR, X_LOCK_HALF_DECR)) {
512 /* lock->recursive == true implies that the lock->writer_thread is the
513 current writer. As we are going to write our own thread id in that field it
514 must be the case that the current writer_thread value is not the current
515 writer anymore, thus recursive flag must be false. */
516 ut_a(!lock->recursive.load(std::memory_order_relaxed));
517
518 /* Decrement occurred: we are the SX lock owner. */
519 rw_lock_set_writer_id_and_recursion_flag(lock, !pass);
520
521 lock->sx_recursive = 1;
522
523 } else {
524 /* Decrement failed: It already has an X or SX lock by this
525 thread or another thread. If it is this thread, relock,
526 else fail. */
527 if (!pass && lock->recursive.load(std::memory_order_acquire) &&
528 lock->writer_thread.load(std::memory_order_relaxed) ==
529 std::this_thread::get_id()) {
530 /* This thread owns an X or SX lock */
531 if (lock->sx_recursive++ == 0) {
532 /* This thread is making first SX-lock request
533 and it must be holding at least one X-lock here
534 because:
535
536 * There can't be a WAIT_EX thread because we are
537 the thread which has it's thread_id written in
538 the writer_thread field and we are not waiting.
539
540 * Any other X-lock thread cannot exist because
541 it must update recursive flag only after
542 updating the thread_id. Had there been
543 a concurrent X-locking thread which succeeded
544 in decrementing the lock_word it must have
545 written it's thread_id before setting the
546 recursive flag. As we cleared the if()
547 condition above therefore we must be the only
548 thread working on this lock and it is safe to
549 read and write to the lock_word. */
550
551 ut_ad((lock->lock_word == 0) ||
552 ((lock->lock_word <= -X_LOCK_DECR) &&
553 (lock->lock_word > -(X_LOCK_DECR + X_LOCK_HALF_DECR))));
554 lock->lock_word -= X_LOCK_HALF_DECR;
555 }
556 } else {
557 /* Another thread locked before us */
558 return false;
559 }
560 }
561
562 ut_d(rw_lock_add_debug_info(lock, pass, RW_LOCK_SX, location));
563
564 lock->last_x_file_name = location.filename;
565
566 ut_ad(location.line <=
567 std::numeric_limits<decltype(lock->last_x_line)>::max());
568 lock->last_x_line = location.line;
569
570 return true;
571 }
572
573 void rw_lock_x_lock_func(rw_lock_t *lock, ulint pass, ut::Location location) {
574 ulint i = 0;
575 sync_array_t *sync_arr;
576 uint64_t count_os_wait = 0;
577 bool spinning = false;
578
579 ut_ad(rw_lock_validate(lock));
580 ut_ad(!rw_lock_own(lock, RW_LOCK_S));
581
582 lock_loop:
583
584 if (rw_lock_x_lock_low(lock, pass, location.filename, location.line)) {
585 if (count_os_wait > 0) {
586 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
587 }
588
589 /* Locking succeeded */
590 return;
591
592 } else {
593 if (!spinning) {
594 spinning = true;
595 }
596
597 /* Spin waiting for the lock_word to become free */
598 os_rmb;
599 while (i < srv_n_spin_wait_rounds && lock->lock_word <= X_LOCK_HALF_DECR) {
600 if (srv_spin_wait_delay) {
601 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
602 }
603
604 i++;
605 }
606
607 if (i >= srv_n_spin_wait_rounds) {
608 std::this_thread::yield();
609
610 } else {
611 goto lock_loop;
612 }
613 }
614
615 sync_cell_t *cell;
616
617 sync_arr = sync_array_get_and_reserve_cell(lock, RW_LOCK_X, location, &cell);
618
619 /* Waiters must be set before checking lock_word, to ensure signal
620 is sent. This could lead to a few unnecessary wake-up signals. */
621 rw_lock_set_waiter_flag(lock);
622
623 if (rw_lock_x_lock_low(lock, pass, location.filename, location.line)) {
624 sync_array_free_cell(sync_arr, cell);
625
626 if (count_os_wait > 0) {
627 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
628 }
629
630 /* Locking succeeded */
631 return;
632 }
633
634 ++count_os_wait;
635
636 sync_array_wait_event(sync_arr, cell);
637
638 i = 0;
639
640 goto lock_loop;
641 }
642
643 void rw_lock_sx_lock_func(rw_lock_t *lock, ulint pass, ut::Location location) {
644 ulint i = 0;
645 sync_array_t *sync_arr;
646 uint64_t count_os_wait = 0;
647
648 ut_ad(rw_lock_validate(lock));
649 ut_ad(!rw_lock_own(lock, RW_LOCK_S));
650
651 lock_loop:
652
653 if (rw_lock_sx_lock_low(lock, pass, location)) {
654 if (count_os_wait > 0) {
655 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
656 }
657
658 /* Locking succeeded */
659 return;
660
661 } else {
662 /* Spin waiting for the lock_word to become free */
663 os_rmb;
664 while (i < srv_n_spin_wait_rounds && lock->lock_word <= X_LOCK_HALF_DECR) {
665 if (srv_spin_wait_delay) {
666 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
667 }
668
669 i++;
670 }
671
672 if (i >= srv_n_spin_wait_rounds) {
673 std::this_thread::yield();
674
675 } else {
676 goto lock_loop;
677 }
678 }
679
680 sync_cell_t *cell;
681
682 sync_arr = sync_array_get_and_reserve_cell(lock, RW_LOCK_SX, location, &cell);
683
684 /* Waiters must be set before checking lock_word, to ensure signal
685 is sent. This could lead to a few unnecessary wake-up signals. */
686 rw_lock_set_waiter_flag(lock);
687
688 if (rw_lock_sx_lock_low(lock, pass, location)) {
689 sync_array_free_cell(sync_arr, cell);
690
691 if (count_os_wait > 0) {
692 lock->count_os_wait += static_cast<uint32_t>(count_os_wait);
693 }
694
695 /* Locking succeeded */
696 return;
697 }
698
699 ++count_os_wait;
700
701 sync_array_wait_event(sync_arr, cell);
702
703 i = 0;
704
705 goto lock_loop;
706 }
707
708 #ifdef UNIV_DEBUG
709
710 /** Checks that the rw-lock has been initialized and that there are no
711 simultaneous shared and exclusive locks.
712 @return true */
713 bool rw_lock_validate(const rw_lock_t *lock) /*!< in: rw-lock */
714 {
715 int32_t lock_word;
716
717 ut_ad(lock);
718 lock_word = lock->lock_word;
719
720 ut_ad(lock->magic_n == rw_lock_t::MAGIC_N);
721 ut_ad(lock_word > -(2 * X_LOCK_DECR));
722 ut_ad(lock_word <= X_LOCK_DECR);
723
724 return (true);
725 }
726
727 /** Checks if somebody has locked the rw-lock in the specified mode.
728 @return true if locked */
729 bool rw_lock_is_locked(rw_lock_t *lock, /*!< in: rw-lock */
730 ulint lock_type) /*!< in: lock type: RW_LOCK_S,
731 RW_LOCK_X or RW_LOCK_SX */
732 {
733 ut_ad(rw_lock_validate(lock));
734
735 switch (lock_type) {
736 case RW_LOCK_S:
737 return (rw_lock_get_reader_count(lock) > 0);
738
739 case RW_LOCK_X:
740 return (rw_lock_get_writer(lock) == RW_LOCK_X);
741
742 case RW_LOCK_SX:
743 return (rw_lock_get_sx_lock_count(lock) > 0);
744
745 default:
746 ut_error;
747 }
748 }
749
750 void rw_lock_add_debug_info(rw_lock_t *lock, ulint pass, ulint lock_type,
751 ut::Location location) {
752 rw_lock_debug_t *info = rw_lock_debug_create();
753
754 rw_lock_debug_mutex_enter();
755
756 info->pass = pass;
757 info->lock_type = lock_type;
758 info->location = location;
759 info->thread_id = std::this_thread::get_id();
760
761 UT_LIST_ADD_FIRST(lock->debug_list, info);
762
763 rw_lock_debug_mutex_exit();
764
765 const auto lock_word = lock->lock_word.load();
766
767 /*
768 The lock->lock_word and lock->sx_recursive already have been updated to
769 reflect current acquisition before calling this function. We'd like to call
770 sync_check_relock() for recursive acquisition of X or SX, which doesn't really
771 have to wait, because the thread already has relevant access right.
772
773 There are 4 cases to consider:
774
775 1. We already held at least one X, and requested X again.
776 This means lock_type == RW_LOCK_X and lock_word < -X_LOCK_HALF_DECR.
777 Actually, we can even say that lock_word <= -X_LOCK_DECR, as values between
778 -X_LOCK_DECR and -X_LOCK_HALF_DECR only happen while waiting for X and there
779 are still some S granted, which we know can't be true as we hold at least one
780 X.
781 */
782 if (lock_type == RW_LOCK_X && lock_word < -X_LOCK_HALF_DECR) {
783 ut_a(lock_word <= -X_LOCK_DECR);
784 }
785 const bool case1 = lock_type == RW_LOCK_X && lock_word <= -X_LOCK_DECR;
786
787 /*
788 2. We already held at least one X, and requested SX.
789 This means lock_type == RW_LOCK_SX and lock_word < 0.
790 Actually, we can even say that lock_word <= -X_LOCK_HALF_DECR, because values
791 between -X_LOCK_HALF_DECR and 0 only happen while waiting for X and there are
792 still some S granted, which we know can't be true as we hold at least one X.
793 */
794 if (lock_type == RW_LOCK_SX && lock_word < 0) {
795 ut_a(lock_word <= -X_LOCK_HALF_DECR);
796 }
797 const bool case2 = lock_type == RW_LOCK_SX && lock_word <= -X_LOCK_HALF_DECR;
798
799 /*
800 3. We already held at least one SX, and requested SX again.
801 This means lock_type == RW_LOCK_SX and 2 <= lock->sx_recursive.
802 Note that first SX has set lock->sx_recursive to 1, and second incremented
803 it. Also note, that cases 2 and 3 are not mutually exclusive.
804 */
805 const bool case3 = lock_type == RW_LOCK_SX && 2 <= lock->sx_recursive;
806
807 /*
808 4. We already held at least one SX (but no X), and requested X now.
809 This would manifest as
810 lock_type == RW_LOCK_X and lock_word == -X_LOCK_HALF_DECR.
811 This might have to wait for other threads to release their S, and thus is
812 blocking and constitutes an escalation, and thus ...
813 THIS IS NOT CONSIDERED TO BE A RELOCK!
814 */
815
816 if (pass == 0 && lock_type != RW_LOCK_X_WAIT) {
817 if (case1 || case2 || case3) {
818 sync_check_relock(lock);
819 } else {
820 sync_check_lock_validate(lock);
821 sync_check_lock_granted(lock);
822 }
823 }
824 }
825
826 /** Removes a debug information struct for an rw-lock. */
827 void rw_lock_remove_debug_info(rw_lock_t *lock, /*!< in: rw-lock */
828 ulint pass, /*!< in: pass value */
829 ulint lock_type) /*!< in: lock type */
830 {
831 ut_ad(lock);
832
833 if (pass == 0 && lock_type != RW_LOCK_X_WAIT) {
834 sync_check_unlock(lock);
835 }
836
837 rw_lock_debug_mutex_enter();
838
839 for (auto info : lock->debug_list) {
840 if (pass == info->pass &&
841 (pass != 0 || info->thread_id == std::this_thread::get_id()) &&
842 info->lock_type == lock_type) {
843 /* Found! */
844 UT_LIST_REMOVE(lock->debug_list, info);
845
846 rw_lock_debug_mutex_exit();
847
848 rw_lock_debug_free(info);
849
850 return;
851 }
852 }
853
854 rw_lock_debug_mutex_exit();
855 ut_error;
856 }
857
858 bool rw_lock_own(const rw_lock_t *lock, ulint lock_type) {
859 ut_ad(lock);
860 ut_ad(rw_lock_validate(lock));
861
862 rw_lock_debug_mutex_enter();
863
864 for (const rw_lock_debug_t *info : lock->debug_list) {
865 if (info->thread_id == std::this_thread::get_id() && info->pass == 0 &&
866 info->lock_type == lock_type) {
867 rw_lock_debug_mutex_exit();
868 /* Found! */
869
870 return true;
871 }
872 }
873 rw_lock_debug_mutex_exit();
874
875 return false;
876 }
877
878 /** For collecting the debug information for a thread's rw-lock */
879 typedef std::vector<const rw_lock_debug_t *> Infos;
880
881 /** Get the thread debug info
882 @param[in] infos The rw-lock mode owned by the threads
883 @param[in] lock rw-lock to check */
884 static void rw_lock_get_debug_info(const rw_lock_t *lock, Infos *infos) {
885 ut_ad(rw_lock_validate(lock));
886
887 rw_lock_debug_mutex_enter();
888
889 for (auto info : lock->debug_list) {
890 if (info->thread_id == std::this_thread::get_id()) {
891 infos->push_back(info);
892 }
893 }
894
895 rw_lock_debug_mutex_exit();
896 }
897
898 bool rw_lock_own_flagged(const rw_lock_t *lock, rw_lock_flags_t flags) {
899 Infos infos;
900
901 rw_lock_get_debug_info(lock, &infos);
902
903 for (const rw_lock_debug_t *info : infos) {
904 ut_ad(info->thread_id == std::this_thread::get_id());
905
906 if (info->pass != 0) {
907 continue;
908 }
909
910 switch (info->lock_type) {
911 case RW_LOCK_S:
912
913 if (flags & RW_LOCK_FLAG_S) {
914 return (true);
915 }
916 break;
917
918 case RW_LOCK_X:
919
920 if (flags & RW_LOCK_FLAG_X) {
921 return (true);
922 }
923 break;
924
925 case RW_LOCK_SX:
926
927 if (flags & RW_LOCK_FLAG_SX) {
928 return (true);
929 }
930 }
931 }
932
933 return (false);
934 }
935
936 /** Prints debug info of currently locked rw-locks. */
937 void rw_lock_list_print_info(FILE *file) /*!< in: file where to print */
938 {
939 ulint count = 0;
940
941 mutex_enter(&rw_lock_list_mutex);
942
943 fputs(
944 "-------------\n"
945 "RW-LATCH INFO\n"
946 "-------------\n",
947 file);
948
949 for (const rw_lock_t *lock : rw_lock_list) {
950 count++;
951
952 if (lock->lock_word != X_LOCK_DECR) {
953 fprintf(file, "RW-LOCK: %p ", (void *)lock);
954
955 if (rw_lock_get_waiters(lock)) {
956 fputs(" Waiters for the lock exist\n", file);
957 } else {
958 putc('\n', file);
959 }
960
961 rw_lock_debug_mutex_enter();
962
963 for (auto info : lock->debug_list) {
964 rw_lock_debug_print(file, info);
965 }
966
967 rw_lock_debug_mutex_exit();
968 }
969 }
970
971 fprintf(file, "Total number of rw-locks " ULINTPF "\n", count);
972 mutex_exit(&rw_lock_list_mutex);
973 }
974
975 /** Prints info of a debug struct.
976 @param[in] f Output stream
977 @param[in] info Debug struct */
978 void rw_lock_debug_print(FILE *f, const rw_lock_debug_t *info) {
979 ulint rwt = info->lock_type;
980
981 fprintf(f, "Locked: thread %s file %s line %zu ",
982 to_string(info->thread_id).c_str(),
983 sync_basename(info->location.filename), info->location.line);
984
985 switch (rwt) {
986 case RW_LOCK_S:
987 fputs("S-LOCK", f);
988 break;
989 case RW_LOCK_X:
990 fputs("X-LOCK", f);
991 break;
992 case RW_LOCK_SX:
993 fputs("SX-LOCK", f);
994 break;
995 case RW_LOCK_X_WAIT:
996 fputs("WAIT X-LOCK", f);
997 break;
998 default:
999 ut_error;
1000 }
1001
1002 if (info->pass != 0) {
1003 fprintf(f, " pass value %lu", (ulong)info->pass);
1004 }
1005
1006 fprintf(f, "\n");
1007 }
1008
1009 /** Print where it was locked from
1010 @return the string representation */
1011 std::string rw_lock_t::locked_from() const {
1012 /* Note: For X locks it can be locked form multiple places because
1013 the same thread can call X lock recursively. */
1014
1015 std::ostringstream msg;
1016 Infos infos;
1017
1018 rw_lock_get_debug_info(this, &infos);
1019
1020 ulint i = 0;
1021
1022 for (const rw_lock_debug_t *info : infos) {
1023 ut_ad(info->thread_id == std::this_thread::get_id());
1024
1025 if (i++ > 0) {
1026 msg << ", ";
1027 }
1028
1029 msg << info->location.filename << ":" << info->location.line;
1030 }
1031
1032 return (msg.str());
1033 }
1034
1035 /** Print the rw-lock information.
1036 @return the string representation */
1037 std::string rw_lock_t::to_string() const {
1038 std::ostringstream msg;
1039
1040 msg << "RW-LATCH: "
1041 << "thread id " << ::to_string(std::this_thread::get_id())
1042 << " addr: " << this << " Locked from: " << locked_from().c_str();
1043
1044 return (msg.str());
1045 }
1046 #endif /* UNIV_DEBUG */