Debian Codegraph @

storage/innobase/os/os0event.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2012, 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 os/os0event.cc
29 The interface to the operating system condition variables.
30
31 Created 2012-09-23 Sunny Bains
32 *******************************************************/
33
34 #include "os0event.h"
35
36 #include <errno.h>
37 #include <time.h>
38
39 #include "ha_prototypes.h"
40 #include "ut0mutex.h"
41 #include "ut0new.h"
42
43 #ifdef _WIN32
44 #include <windows.h>
45 #endif /* _WIN32 */
46
47 /** The number of microseconds in a second. */
48 static const uint64_t MICROSECS_IN_A_SECOND = 1000000;
49
50 /** The number of nanoseconds in a second. */
51 static const uint64_t NANOSECS_IN_A_SECOND [[maybe_unused]] =
52 1000 * MICROSECS_IN_A_SECOND;
53
54 #ifdef _WIN32
55 /** Native condition variable. */
56 typedef CONDITION_VARIABLE os_cond_t;
57 #else
58 /** Native condition variable */
59 typedef pthread_cond_t os_cond_t;
60 #endif /* _WIN32 */
61
62 /** InnoDB condition variable. */
63 struct os_event {
64 os_event() UNIV_NOTHROW;
65
66 ~os_event() UNIV_NOTHROW;
67
68 friend void os_event_global_init();
69 friend void os_event_global_destroy();
70
71 /**
72 Destroys a condition variable */
73 void destroy() UNIV_NOTHROW {
74 #ifndef _WIN32
75 int ret = pthread_cond_destroy(&cond_var);
76 ut_a(ret == 0);
77 #endif /* !_WIN32 */
78
79 mutex.destroy();
80
81 ut_ad(n_objects_alive.fetch_sub(1) != 0);
82 }
83
84 /** Set the event */
85 void set() UNIV_NOTHROW {
86 mutex.enter();
87
88 if (!m_set) {
89 broadcast();
90 }
91
92 mutex.exit();
93 }
94
95 bool try_set() UNIV_NOTHROW {
96 if (mutex.try_lock()) {
97 if (!m_set) {
98 broadcast();
99 }
100
101 mutex.exit();
102
103 return (true);
104 }
105
106 return (false);
107 }
108
109 int64_t reset() UNIV_NOTHROW {
110 mutex.enter();
111
112 if (m_set) {
113 m_set = false;
114 }
115
116 int64_t ret = signal_count;
117
118 mutex.exit();
119
120 return (ret);
121 }
122
123 /**
124 Waits for an event object until it is in the signaled state.
125
126 Typically, if the event has been signalled after the os_event_reset()
127 we'll return immediately because event->m_set == true.
128 There are, however, situations (e.g.: sync_array code) where we may
129 lose this information. For example:
130
131 thread A calls os_event_reset()
132 thread B calls os_event_set() [event->m_set == true]
133 thread C calls os_event_reset() [event->m_set == false]
134 thread A calls os_event_wait() [infinite wait!]
135 thread C calls os_event_wait() [infinite wait!]
136
137 Where such a scenario is possible, to avoid infinite wait, the
138 value returned by reset() should be passed in as
139 reset_sig_count. */
140 void wait_low(int64_t reset_sig_count) UNIV_NOTHROW;
141
142 /** Waits for an event object until it is in the signaled state or
143 a timeout is exceeded.
144 @param timeout Timeout in microseconds, or
145 std::chrono::microseconds::max()
146 @param reset_sig_count Zero or the value returned by previous call of
147 os_event_reset().
148 @return 0 if success, OS_SYNC_TIME_EXCEEDED if timeout was exceeded */
149 ulint wait_time_low(std::chrono::microseconds timeout,
150 int64_t reset_sig_count) UNIV_NOTHROW;
151
152 /** @return true if the event is in the signalled state. */
153 bool is_set() const UNIV_NOTHROW { return (m_set); }
154
155 private:
156 /**
157 Initialize a condition variable */
158 void init() UNIV_NOTHROW {
159 mutex.init();
160
161 #ifdef _WIN32
162 InitializeConditionVariable(&cond_var);
163 #else
164 {
165 int ret;
166
167 ret = pthread_cond_init(&cond_var, &cond_attr);
168 ut_a(ret == 0);
169 }
170 #endif /* _WIN32 */
171
172 ut_d(n_objects_alive.fetch_add(1));
173 }
174
175 /**
176 Wait on condition variable */
177 void wait() UNIV_NOTHROW {
178 #ifdef _WIN32
179 if (!SleepConditionVariableCS(&cond_var, mutex, INFINITE)) {
180 ut_error;
181 }
182 #else
183 {
184 int ret;
185
186 ret = pthread_cond_wait(&cond_var, mutex);
187 ut_a(ret == 0);
188 }
189 #endif /* _WIN32 */
190 }
191
192 /**
193 Wakes all threads waiting for condition variable */
194 void broadcast() UNIV_NOTHROW {
195 m_set = true;
196 ++signal_count;
197
198 #ifdef _WIN32
199 WakeAllConditionVariable(&cond_var);
200 #else
201 {
202 int ret;
203
204 ret = pthread_cond_broadcast(&cond_var);
205 ut_a(ret == 0);
206 }
207 #endif /* _WIN32 */
208 }
209
210 /**
211 Wakes one thread waiting for condition variable */
212 void signal() UNIV_NOTHROW {
213 #ifdef _WIN32
214 WakeConditionVariable(&cond_var);
215 #else
216 {
217 int ret;
218
219 ret = pthread_cond_signal(&cond_var);
220 ut_a(ret == 0);
221 }
222 #endif /* _WIN32 */
223 }
224
225 /**
226 Do a timed wait on condition variable.
227 @return true if timed out, false otherwise */
228 bool timed_wait(
229 #ifndef _WIN32
230 const timespec *abstime /*!< Timeout. */
231 #else
232 DWORD time_in_ms /*!< Timeout in milliseconds. */
233 #endif /* !_WIN32 */
234 );
235
236 #ifndef _WIN32
237 /** Returns absolute time until which we should wait if
238 we wanted to wait for timeout since now.
239 This method could be removed if we switched to the usage
240 of std::condition_variable. */
241 struct timespec get_wait_timelimit(std::chrono::microseconds timeout);
242 #endif /* !_WIN32 */
243
244 private:
245 bool m_set; /*!< this is true when the
246 event is in the signaled
247 state, i.e., a thread does
248 not stop if it tries to wait
249 for this event */
250 int64_t signal_count; /*!< this is incremented
251 each time the event becomes
252 signaled */
253 EventMutex mutex; /*!< this mutex protects
254 the next fields */
255
256 os_cond_t cond_var; /*!< condition variable is
257 used in waiting for the event */
258
259 #ifndef _WIN32
260 /** Attributes object passed to pthread_cond_* functions.
261 Defines usage of the monotonic clock if it's available.
262 Initialized once, in the os_event::global_init(), and
263 destroyed in the os_event::global_destroy(). */
264 static pthread_condattr_t cond_attr;
265
266 /** True iff usage of the monotonic clock has been successfully
267 enabled for the cond_attr object. */
268 static bool cond_attr_has_monotonic_clock;
269 #endif /* !_WIN32 */
270 static bool global_initialized;
271
272 #ifdef UNIV_DEBUG
273 static std::atomic_size_t n_objects_alive;
274 #endif /* UNIV_DEBUG */
275
276 protected:
277 // Disable copying
278 os_event(const os_event &);
279 os_event &operator=(const os_event &);
280 };
281
282 bool os_event::timed_wait(
283 #ifndef _WIN32
284 const timespec *abstime
285 #else
286 DWORD time_in_ms
287 #endif /* !_WIN32 */
288 ) {
289 #ifdef _WIN32
290 BOOL ret;
291
292 ret = SleepConditionVariableCS(&cond_var, mutex, time_in_ms);
293
294 if (!ret) {
295 DWORD err = GetLastError();
296
297 /* FQDN=msdn.microsoft.com
298 @see http://$FQDN/en-us/library/ms686301%28VS.85%29.aspx,
299
300 "Condition variables are subject to spurious wakeups
301 (those not associated with an explicit wake) and stolen wakeups
302 (another thread manages to run before the woken thread)."
303 Check for both types of timeouts.
304 Conditions are checked by the caller.*/
305 if (err == WAIT_TIMEOUT || err == ERROR_TIMEOUT) {
306 return (true);
307 }
308 }
309
310 ut_a(ret);
311
312 return (false);
313 #else
314 int ret;
315
316 ret = pthread_cond_timedwait(&cond_var, mutex, abstime);
317
318 switch (ret) {
319 case 0:
320 case ETIMEDOUT:
321 /* We play it safe by checking for EINTR even though
322 according to the POSIX documentation it can't return EINTR. */
323 case EINTR:
324 break;
325
326 default:
327 #ifdef UNIV_NO_ERR_MSGS
328 ib::error()
329 #else
330 ib::error(ER_IB_MSG_742)
331 #endif /* !UNIV_NO_ERR_MSGS */
332 << "pthread_cond_timedwait() returned: " << ret << ": abstime={"
333 << abstime->tv_sec << "," << abstime->tv_nsec << "}";
334 ut_error;
335 }
336
337 return (ret == ETIMEDOUT);
338 #endif /* _WIN32 */
339 }
340
341 /**
342 Waits for an event object until it is in the signaled state.
343
344 Typically, if the event has been signalled after the os_event_reset()
345 we'll return immediately because event->m_set == true.
346 There are, however, situations (e.g.: sync_array code) where we may
347 lose this information. For example:
348
349 thread A calls os_event_reset()
350 thread B calls os_event_set() [event->m_set == true]
351 thread C calls os_event_reset() [event->m_set == false]
352 thread A calls os_event_wait() [infinite wait!]
353 thread C calls os_event_wait() [infinite wait!]
354
355 Where such a scenario is possible, to avoid infinite wait, the
356 value returned by reset() should be passed in as
357 reset_sig_count. */
358 void os_event::wait_low(int64_t reset_sig_count) UNIV_NOTHROW {
359 mutex.enter();
360
361 if (!reset_sig_count) {
362 reset_sig_count = signal_count;
363 }
364
365 while (!m_set && signal_count == reset_sig_count) {
366 wait();
367
368 /* Spurious wakeups may occur: we have to check if the
369 event really has been signaled after we came here to wait. */
370 }
371
372 mutex.exit();
373 }
374
375 #ifndef _WIN32
376
377 struct timespec os_event::get_wait_timelimit(
378 std::chrono::microseconds timeout) {
379 /* We could get rid of this function if we switched to std::condition_variable
380 from the pthread_cond_. The std::condition_variable::wait_for relies on the
381 steady_clock internally and accepts timeout (not time increased by the
382 timeout). */
383 for (int i = 0;; i++) {
384 ut_a(i < 10);
385 #ifdef HAVE_CLOCK_GETTIME
386 if (cond_attr_has_monotonic_clock) {
387 struct timespec tp;
388 if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1) {
389 const auto errno_clock_gettime = errno;
390
391 #ifndef UNIV_NO_ERR_MSGS
392 ib::error(ER_IB_MSG_CLOCK_GETTIME_FAILED,
393 strerror(errno_clock_gettime));
394 #endif /* !UNIV_NO_ERR_MSGS */
395
396 std::this_thread::sleep_for(std::chrono::milliseconds(100));
397 errno = errno_clock_gettime;
398
399 } else {
400 const auto increased =
401 tp.tv_nsec +
402 std::chrono::duration_cast<std::chrono::nanoseconds>(timeout)
403 .count();
404 if (increased >= static_cast<std::remove_cv<decltype(increased)>::type>(
405 NANOSECS_IN_A_SECOND)) {
406 tp.tv_sec += increased / NANOSECS_IN_A_SECOND;
407 tp.tv_nsec = increased % NANOSECS_IN_A_SECOND;
408 } else {
409 tp.tv_nsec = increased;
410 }
411 return (tp);
412 }
413
414 } else
415 #endif /* HAVE_CLOCK_GETTIME */
416 {
417 struct timeval tv;
418 if (gettimeofday(&tv, nullptr) == -1) {
419 const auto errno_gettimeofday = errno;
420
421 #ifndef UNIV_NO_ERR_MSGS
422 ib::error(ER_IB_MSG_1213, strerror(errno_gettimeofday));
423 #endif /* !UNIV_NO_ERR_MSGS */
424
425 std::this_thread::sleep_for(std::chrono::milliseconds(100));
426 errno = errno_gettimeofday;
427
428 } else {
429 const auto increased = tv.tv_usec + timeout.count();
430
431 if (increased >= static_cast<std::remove_cv<decltype(increased)>::type>(
432 MICROSECS_IN_A_SECOND)) {
433 tv.tv_sec += increased / MICROSECS_IN_A_SECOND;
434 tv.tv_usec = increased % MICROSECS_IN_A_SECOND;
435 } else {
436 tv.tv_usec = increased;
437 }
438
439 struct timespec abstime;
440 abstime.tv_sec = tv.tv_sec;
441 abstime.tv_nsec = tv.tv_usec * 1000;
442 return (abstime);
443 }
444 }
445 }
446 }
447
448 #endif /* !_WIN32 */
449
450 ulint os_event::wait_time_low(std::chrono::microseconds timeout,
451 int64_t reset_sig_count) UNIV_NOTHROW {
452 bool timed_out = false;
453
454 #ifdef _WIN32
455 DWORD time_in_ms;
456
457 if (timeout != std::chrono::microseconds::max()) {
458 time_in_ms = static_cast<DWORD>(
459 std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count());
460 } else {
461 time_in_ms = INFINITE;
462 }
463 #else
464 struct timespec abstime;
465
466 if (timeout != std::chrono::microseconds::max()) {
467 abstime = os_event::get_wait_timelimit(timeout);
468 } else {
469 abstime.tv_nsec = 999999999;
470 abstime.tv_sec = std::numeric_limits<time_t>::max();
471 }
472
473 ut_a(abstime.tv_nsec <= 999999999);
474
475 #endif /* _WIN32 */
476
477 mutex.enter();
478
479 if (!reset_sig_count) {
480 reset_sig_count = signal_count;
481 }
482
483 do {
484 if (m_set || signal_count != reset_sig_count) {
485 break;
486 }
487
488 #ifndef _WIN32
489 timed_out = timed_wait(&abstime);
490 #else
491 timed_out = timed_wait(time_in_ms);
492 #endif /* !_WIN32 */
493
494 } while (!timed_out);
495
496 mutex.exit();
497
498 return (timed_out ? OS_SYNC_TIME_EXCEEDED : 0);
499 }
500
501 /** Constructor */
502 os_event::os_event() UNIV_NOTHROW {
503 ut_a(global_initialized);
504 init();
505
506 m_set = false;
507
508 /* We return this value in os_event_reset(),
509 which can then be be used to pass to the
510 os_event_wait_low(). The value of zero is
511 reserved in os_event_wait_low() for the case
512 when the caller does not want to pass any
513 signal_count value. To distinguish between
514 the two cases we initialize signal_count
515 to 1 here. */
516
517 signal_count = 1;
518 }
519
520 /** Destructor */
521 os_event::~os_event() UNIV_NOTHROW { destroy(); }
522
523 /**
524 Creates an event semaphore, i.e., a semaphore which may just have two
525 states: signaled and nonsignaled. The created event is manual reset: it
526 must be reset explicitly by calling sync_os_reset_event.
527 @return the event handle */
528 os_event_t os_event_create() {
529 os_event_t ret = (ut::new_withkey<os_event>(UT_NEW_THIS_FILE_PSI_KEY));
530 /**
531 On SuSE Linux we get spurious EBUSY from pthread_mutex_destroy()
532 unless we grab and release the mutex here. Current OS version:
533 openSUSE Leap 15.0
534 Linux xxx 4.12.14-lp150.12.25-default #1 SMP
535 Thu Nov 1 06:14:23 UTC 2018 (3fcf457) x86_64 x86_64 x86_64 GNU/Linux */
536 #if defined(LINUX_SUSE)
537 os_event_reset(ret);
538 #endif
539 return ret;
540 }
541
542 /**
543 Check if the event is set.
544 @return true if set */
545 bool os_event_is_set(const os_event_t event) /*!< in: event to test */
546 {
547 return (event->is_set());
548 }
549
550 /**
551 Sets an event semaphore to the signaled state: lets waiting threads
552 proceed. */
553 void os_event_set(os_event_t event) /*!< in/out: event to set */
554 {
555 event->set();
556 }
557
558 bool os_event_try_set(os_event_t event) { return (event->try_set()); }
559
560 /**
561 Resets an event semaphore to the nonsignaled state. Waiting threads will
562 stop to wait for the event.
563 The return value should be passed to os_even_wait_low() if it is desired
564 that this thread should not wait in case of an intervening call to
565 os_event_set() between this os_event_reset() and the
566 os_event_wait_low() call. See comments for os_event_wait_low().
567 @return current signal_count. */
568 int64_t os_event_reset(os_event_t event) /*!< in/out: event to reset */
569 {
570 return (event->reset());
571 }
572
573 ulint os_event_wait_time_low(os_event_t event,
574 std::chrono::microseconds timeout,
575 int64_t reset_sig_count) {
576 return (event->wait_time_low(timeout, reset_sig_count));
577 }
578
579 /**
580 Waits for an event object until it is in the signaled state.
581
582 Where such a scenario is possible, to avoid infinite wait, the
583 value returned by os_event_reset() should be passed in as
584 reset_sig_count. */
585 void os_event_wait_low(os_event_t event, /*!< in: event to wait */
586 int64_t reset_sig_count) /*!< in: zero or the value
587 returned by previous call of
588 os_event_reset(). */
589 {
590 event->wait_low(reset_sig_count);
591 }
592
593 /**
594 Frees an event object. */
595 void os_event_destroy(os_event_t &event) /*!< in/own: event to free */
596
597 {
598 if (event != nullptr) {
599 ut::delete_(event);
600 event = nullptr;
601 }
602 }
603
604 #ifndef _WIN32
605 pthread_condattr_t os_event::cond_attr;
606 bool os_event::cond_attr_has_monotonic_clock{false};
607 #endif /* !_WIN32 */
608 bool os_event::global_initialized{false};
609
610 #ifdef UNIV_DEBUG
611 std::atomic_size_t os_event::n_objects_alive{0};
612 #endif /* UNIV_DEBUG */
613
614 void os_event_global_init(void) {
615 ut_ad(os_event::n_objects_alive.load() == 0);
616 #ifndef _WIN32
617 int ret = pthread_condattr_init(&os_event::cond_attr);
618 ut_a(ret == 0);
619
620 #ifdef UNIV_LINUX /* MacOS does not have support. */
621 #ifdef HAVE_CLOCK_GETTIME
622 ret = pthread_condattr_setclock(&os_event::cond_attr, CLOCK_MONOTONIC);
623 if (ret == 0) {
624 os_event::cond_attr_has_monotonic_clock = true;
625 }
626 #endif /* HAVE_CLOCK_GETTIME */
627
628 #ifndef UNIV_NO_ERR_MSGS
629 if (!os_event::cond_attr_has_monotonic_clock) {
630 ib::warn(ER_IB_MSG_CLOCK_MONOTONIC_UNSUPPORTED);
631 }
632 #endif /* !UNIV_NO_ERR_MSGS */
633
634 #endif /* UNIV_LINUX */
635 #endif /* !_WIN32 */
636 os_event::global_initialized = true;
637 }
638
639 void os_event_global_destroy(void) {
640 ut_a(os_event::global_initialized);
641 ut_ad(os_event::n_objects_alive.load() == 0);
642 #ifndef _WIN32
643 os_event::cond_attr_has_monotonic_clock = false;
644 #ifdef UNIV_DEBUG
645 const int ret =
646 #endif /* UNIV_DEBUG */
647 pthread_condattr_destroy(&os_event::cond_attr);
648 ut_ad(ret == 0);
649 #endif /* !_WIN32 */
650 os_event::global_initialized = false;
651 }