Debian Codegraph @

storage/innobase/log/log0write.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4 Copyright (c) 2009, Google Inc.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is designed to work with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have either included with
16 the program or referenced in the documentation.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License, version 2.0, for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26
27 *****************************************************************************/
28
29 /**************************************************/ /**
30 @file log/log0write.cc
31
32 Redo log writing and flushing, including functions for:
33 1. Waiting for the log written / flushed up to provided lsn.
34 2. Redo log write threads: log_writer, log_flusher,
35 log_write_notifier, log_flush_notifier.
36
37 @author Paweł Olchawa
38
39 *******************************************************/
40
41 #ifndef UNIV_HOTBACKUP
42
43 /* std::memory_order_* */
44 #include <atomic>
45
46 /* thd_wait_begin() / thd_wait_end() */
47 #include <mysql/service_thd_wait.h>
48
49 /* std::memcpy, std::memset */
50 #include <cstring>
51
52 /* arch_log_sys */
53 #include "arch0arch.h"
54
55 /* page_id_t */
56 #include "buf0types.h"
57
58 /* log_update_buf_limit, ... */
59 #include "log0buf.h"
60
61 /* log_request_checkpoint */
62 #include "log0chkp.h"
63
64 /* Log_files_capacity::soft_logical_capacity, ... */
65 #include "log0files_capacity.h"
66
67 /* log_files_produce_file, ... */
68 #include "log0files_governor.h"
69
70 /* log_limits_mutex_enter, ... */
71 #include "log0log.h"
72
73 /* redo_log_archive_produce */
74 #include "log0meb.h"
75
76 /* recv_no_ibuf_operations */
77 #include "log0recv.h"
78
79 /* log_t::X */
80 #include "log0sys.h"
81
82 /* log_sync_point */
83 #include "log0test.h"
84
85 /* Log_file::offset, OS_FILE_LOG_BLOCK_SIZE */
86 #include "log0types.h"
87
88 /* log_writer_mutex */
89 #include "log0write.h"
90
91 /* create_internal_thd, destroy_internal_thd */
92 #include "sql/sql_thd_internal_api.h"
93
94 /* MONITOR_INC, ... */
95 #include "srv0mon.h"
96
97 /* srv_read_only_mode */
98 #include "srv0srv.h"
99
100 /* ut_uint64_align_down */
101 #include "ut0byte.h"
102
103 // clang-format off
104 /**************************************************/ /**
105 @page PAGE_INNODB_REDO_LOG_THREADS Background redo log threads
106
107 Three background log threads are responsible for writes of new data to disk:
108
109 -# [Log writer](@ref sect_redo_log_writer) - writes from the log buffer or
110 write-ahead buffer to OS buffers.
111
112 -# [Log flusher](@ref sect_redo_log_flusher) - writes from OS buffers to disk
113 (fsyncs).
114
115 -# [Log write_notifier](@ref sect_redo_log_write_notifier) - notifies user
116 threads about completed writes to disk (when write_lsn is advanced).
117
118 -# [Log flush_notifier](@ref sect_redo_log_flush_notifier) - notifies user
119 threads about completed fsyncs (when flushed_to_disk_lsn is advanced).
120
121 Two background log threads are responsible for checkpoints (reclaiming space
122 in log files):
123
124 -# [Log checkpointer](@ref sect_redo_log_checkpointer) - determines
125 @ref subsect_redo_log_available_for_checkpoint_lsn and writes checkpoints.
126
127
128 @section sect_redo_log_writer Thread: log writer
129
130 This thread is responsible for writing data from the log buffer to disk
131 (to the log files). However, it's not responsible for doing fsync() calls.
132 It copies data to system buffers. It is the log flusher thread, which is
133 responsible for doing fsync().
134
135 There are following points that need to be addressed by the log writer thread:
136
137 -# %Find out how much data is ready in the log buffer, which is concurrently
138 filled in by multiple user threads.
139
140 In the log recent written buffer, user threads set links for every finished
141 write to the log buffer. Each such link is represented as a number of bytes
142 written, starting from a _start_lsn_. The link is stored in the slot assigned
143 to the _start_lsn_ of the write.
144
145 The log writer thread tracks links in the recent written buffer, traversing
146 a connected path created by the links. It stops when it encounters a missing
147 outgoing link. In such case the next fragment of the log buffer is still
148 being written (or the maximum assigned lsn was reached).
149
150 It also stops as soon as it has traversed by more than 4kB, in which case
151 it is enough for a next write (unless we decided again to do fsyncs from
152 inside the log writer thread). After traversing links and clearing slots
153 occupied by the links (in the recent written buffer), the log writer thread
154 updates @ref subsect_redo_log_buf_ready_for_write_lsn.
155
156 @diafile storage/innobase/log/recent_written_buffer.dia "Example of links in the recent written buffer"
157
158 @note The log buffer has no holes up to the _log.buf_ready_for_write_lsn_
159 (all concurrent writes for smaller lsn have been finished).
160
161 If there were no links to traverse, _log.buf_ready_for_write_lsn_ was not
162 advanced and the log writer thread needs to wait. In such case it first
163 uses spin delay and afterwards switches to wait on the _writer_event_.
164
165
166 -# Prepare log blocks for writing - update their headers and footers.
167
168 The log writer thread detects completed log blocks in the log buffer.
169 Such log blocks will not receive any more writes. Hence their headers
170 and footers could be easily updated (e.g. checksum is calculated).
171
172 @diafile storage/innobase/log/log_writer_complete_blocks.dia "Complete blocks are detected and written"
173
174 If any complete blocks were detected, they are written directly from
175 the log buffer (after updating headers and footers). Afterwards the
176 log writer thread retries the previous step before making next decisions.
177 For each write consisting of one or more complete blocks, the
178 _MONITOR_LOG_FULL_BLOCK_WRITES_ is incremented by one.
179
180 @note There is a special case - when write-ahead is required, data needs
181 to be copied to the write-ahead buffer and the last incomplete block could
182 also be copied and written. For details read below and check the next point.
183
184 The special case is also for the last, incomplete log block. Note that
185 @ref subsect_redo_log_buf_ready_for_write_lsn could be in the middle of
186 such block. In such case, next writes are likely incoming to the log block.
187
188 @diafile storage/innobase/log/log_writer_incomplete_block.dia "Incomplete block is copied"
189
190 For performance reasons we often need to write the last incomplete block.
191 That's because it turned out, that we should try to reclaim user threads
192 as soon as possible, allowing them to handle next transactions and provide
193 next data.
194
195 In such case:
196 - the last log block is first copied to the dedicated buffer, up to the
197 @ref subsect_redo_log_buf_ready_for_write_lsn,
198 - the remaining part of the block in the dedicated buffer is filled in
199 with _0x00_ bytes,
200 - header fields are updated,
201 - checksum is calculated and stored in the block's footer,
202 - the block is written from the dedicated buffer,
203 - the _MONITOR_LOG_PARTIAL_BLOCK_WRITES_ is incremented by one.
204
205 @note The write-ahead buffer is used as the dedicated buffer for writes
206 of the last incomplete block. That's because, whenever we needed a next
207 write-ahead (even for complete blocks), we possibly can also write the
208 last incomplete block during the write-ahead. The monitor counters for
209 full/partial block writes are incremented before the logic related to
210 writing ahead is applied. Hence the counter of partial block writes is
211 not incremented if a full block write was possible (in which case only
212 requirement for write-ahead could be the reason of writing the incomplete
213 block).
214
215 @remarks The log writer thread never updates
216 [first_rec_group](@ref a_redo_log_block_first_rec_group) field.
217 It has to be set by user threads before the block is allowed to be written.
218 That's because only user threads know where are the boundaries between
219 groups of log records. The user thread which has written data ending at
220 lsn which needs to be pointed as _first_rec_group_, is the one responsible
221 for setting the field. User thread which has written exactly up to the end
222 of log block, is considered ending at lsn after the header of the next log
223 block. That's because after such write, the log writer is allowed to write
224 the next empty log block (_buf_ready_for_write_lsn_ points then to such lsn).
225 The _first_rec_group_ field is updated before the link is added to the log
226 recent written buffer.
227
228
229 -# Avoid read-on-write issue.
230
231 The log writer thread is also responsible for writing ahead to avoid
232 the read-on-write problem. It tracks up to which point the write ahead
233 has been done. When a write would go further:
234
235 - If we were trying to write more than size of single write-ahead
236 region, we limit the write to completed write-ahead sized regions,
237 and postpone writing the last fragment for later (retrying with the
238 first step and updating the _buf_ready_for_write_lsn_).
239
240 @note If we needed to write complete regions of write-ahead bytes,
241 they are ready in the log buffer and could be written directly from
242 there. Such writes would not cause read-on-write problem, because
243 size of the writes is divisible by write-ahead region.
244
245 - Else, we copy data to special write-ahead buffer, from which
246 we could safely write the whole single write-ahead sized region.
247 After copying the data, the write-ahead buffer is completed with
248 _0x00_ bytes.
249
250 @note The write-ahead buffer is also used for copying the last
251 incomplete log block, which was described in the previous point.
252
253
254 -# Update write_lsn.
255
256 After doing single write (single log_data_blocks_write()), the log writer
257 thread updates @ref subsect_redo_log_write_lsn and fallbacks to its main
258 loop. That's because a lot more data could be prepared in meantime, as
259 the write operation could take significant time.
260
261 That's why the general rule is that after doing log_data_blocks_write(),
262 we need to update @ref subsect_redo_log_buf_ready_for_write_lsn before
263 making next decisions on how much to write within next such call.
264
265
266 -# Notify [log writer_notifier thread](@ref sect_redo_log_write_notifier)
267 using os_event_set on the _write_notifier_event_.
268
269 @see @ref sect_redo_log_waiting_for_writer
270
271
272 -# Notify [log flusher thread](@ref sect_redo_log_flusher) using os_event_set()
273 on the _flusher_event_.
274
275
276 @section sect_redo_log_flusher Thread: log flusher
277
278 The log flusher thread is responsible for doing fsync() of the log files.
279
280 When the fsync() calls are finished, the log flusher thread updates the
281 @ref subsect_redo_log_flushed_to_disk_lsn and notifies the
282 [log flush_notifier thread](@ref sect_redo_log_flush_notifier) using
283 os_event_set() on the _flush_notifier_event_.
284
285 @remarks
286 Small optimization has been applied - if there was only a single log block
287 flushed since the previous flush, then the log flusher thread notifies user
288 threads directly (instead of notifying the log flush_notifier thread).
289 Impact of the optimization turned out to be positive for some scenarios and
290 negative for other, so further investigation is required. However, because
291 the change seems to make sense from logical point of view, it has been
292 preserved.
293
294 If the log flusher thread detects that none of the conditions is satisfied,
295 it simply waits and retries the checks. After initial spin delay, it waits
296 on the _flusher_event_.
297
298
299 @section sect_redo_log_flush_notifier Thread: log flush_notifier
300
301 The log flush_notifier thread is responsible for notifying all user threads
302 that are waiting for @ref subsect_redo_log_flushed_to_disk_lsn >= lsn, when
303 the condition is satisfied.
304
305 @remarks
306 It also notifies when it is very likely to be satisfied (lsn values are
307 within the same log block). It is allowed to make mistakes and it is
308 responsibility of the notified user threads to ensure, that
309 the _flushed_to_disk_lsn_ is advanced sufficiently.
310
311 The log flush_notifier thread waits for the advanced _flushed_to_disk_lsn_
312 in loop, using os_event_wait_time_low() on the _flush_notifier_event_.
313 When it gets notified by the [log flusher](@ref sect_redo_log_flusher),
314 it ensures that the _flushed_to_disk_lsn_ has been advanced (single new
315 byte is enough though).
316
317 It notifies user threads waiting on all events between (inclusive):
318 - event for a block with the previous value of _flushed_to_disk_lsn_,
319 - event for a block containing the new value of _flushed_to_disk_lsn_.
320
321 Events are assigned per blocks in the circular array of events using mapping:
322
323 event_slot = (lsn-1) / OS_FILE_LOG_BLOCK_SIZE % S
324
325 where S is size of the array (number of slots with events). Each slot has
326 single event, which groups all user threads waiting for flush up to any lsn
327 within the same log block (or log block with number greater by S*i).
328
329 @diafile storage/innobase/log/log_notifier_notifications.dia "Notifications executed on slots"
330
331 Internal mutex in event is used, to avoid missed notifications (these would
332 be worse than the false notifications).
333
334 However, there is also maximum timeout defined for the waiting on the event.
335 After the timeout was reached (default: 1ms), the _flushed_to_disk_lsn_ is
336 re-checked in the user thread (just in case).
337
338 @note Because flushes are possible for @ref subsect_redo_log_write_lsn set in
339 the middle of log block, it is likely that the same slot for the same block
340 will be notified multiple times in a row. We tried delaying notifications for
341 the last block, but the results were only worse then. It turned out that
342 latency is extremely important here.
343
344 @see @ref sect_redo_log_waiting_for_flusher
345
346
347 @section sect_redo_log_write_notifier Thread: log write_notifier
348
349 The log write_notifier thread is responsible for notifying all user threads
350 that are waiting for @ref subsect_redo_log_write_lsn >= lsn, when the condition
351 is satisfied.
352
353 @remarks
354 It also notifies when it is very likely to be satisfied (lsn values are
355 within the same log block). It is allowed to make mistakes and it is
356 responsibility of the notified user threads to ensure, that the _write_lsn_
357 is advanced sufficiently.
358
359 The log write_notifier thread waits for the advanced _write_lsn_ in loop,
360 using os_event_wait_time_low() on the _write_notifier_event_.
361 When it gets notified (by the [log writer](@ref sect_redo_log_writer)),
362 it ensures that the _write_lsn_ has been advanced (single new byte is enough).
363 Then it notifies user threads waiting on all events between (inclusive):
364 - event for a block with the previous value of _write_lsn_,
365 - event for a block containing the new value of _write_lsn_.
366
367 Events are assigned per blocks in the circular array of events using mapping:
368
369 event_slot = (lsn-1) / OS_FILE_LOG_BLOCK_SIZE % S
370
371 where S is size of the array (number of slots with events). Each slot has
372 single event, which groups all user threads waiting for write up to any lsn
373 within the same log block (or log block with number greater by S*i).
374
375 Internal mutex in event is used, to avoid missed notifications (these would
376 be worse than the false notifications).
377
378 However, there is also maximum timeout defined for the waiting on the event.
379 After the timeout was reached (default: 1ms), the _write_lsn_ is re-checked
380 in the user thread (just in case).
381
382 @note Because writes are possible for @ref subsect_redo_log_write_lsn set in
383 the middle of log block, it is likely that the same slot for the same block
384 will be notified multiple times in a row.
385
386 @see @ref sect_redo_log_waiting_for_writer
387
388
389 @section sect_redo_log_checkpointer Thread: log checkpointer
390
391 The log checkpointer thread is responsible for:
392
393 -# Checking if a checkpoint write is required (to decrease checkpoint age
394 before it gets too big).
395
396 -# Checking if synchronous flush of dirty pages should be forced on page
397 cleaner threads, because of space in redo log or age of the oldest page.
398
399 -# Writing checkpoints (it's the only thread allowed to do it!).
400
401 This thread has been introduced at the very end. It was not required for
402 the performance, but it makes the design more consistent after we have
403 introduced other log threads. That's because user threads are not doing
404 any writes to the log files themselves then. Previously they were writing
405 checkpoints when needed, which required synchronization between them.
406
407 The log checkpointer thread updates log.available_for_checkpoint_lsn,
408 which is calculated as:
409
410 min(log.buf_dirty_pages_added_up_to_lsn, max(0, oldest_lsn - L))
411
412 where:
413 - oldest_lsn = min(oldest modification of the earliest page from each
414 flush list),
415 - L is a number of slots in the log recent closed buffer.
416
417 The special case is when there is no dirty page in flush lists - then it's
418 basically set to the _log.buf_dirty_pages_added_up_to_lsn_.
419
420 @note Note that previously, all user threads were trying to calculate this
421 lsn concurrently, causing contention on flush_list mutex, which is required
422 to read the _oldest_modification_ of the earliest added page. Now the lsn
423 is updated in single thread.
424
425
426 @section sect_redo_log_waiting_for_writer Waiting until log has been written to
427 disk
428
429 User has to wait until the [log writer thread](@ref sect_redo_log_writer)
430 has written data from the log buffer to disk for lsn >= _end_lsn_ of log range
431 used by the user, which is true when:
432
433 write_lsn >= end_lsn
434
435 The @ref subsect_redo_log_write_lsn is updated by the log writer thread.
436
437 The waiting is solved using array of events. The user thread waiting for
438 a given lsn, waits using the event at position:
439
440 slot = (end_lsn - 1) / OS_FILE_LOG_BLOCK_SIZE % S
441
442 where _S_ is number of entries in the array. Therefore the event corresponds
443 to log block which contains the _end_lsn_.
444
445 The [log write_notifier thread](@ref sect_redo_log_write_notifier) tracks how
446 the @ref subsect_redo_log_write_lsn is advanced and notifies user threads for
447 consecutive slots.
448
449 @remarks
450 When the _write_lsn_ is in the middle of log block, all user threads waiting
451 for lsn values within the whole block are notified. When user thread is
452 notified, it checks if the current value of the _write_lsn_ is sufficient and
453 retries waiting if not. To avoid missed notifications, event's internal mutex
454 is used.
455
456
457 @section sect_redo_log_waiting_for_flusher Waiting until log has been flushed
458 to disk
459
460 If a user need to assure the log persistence in case of crash (e.g. on COMMIT
461 of a transaction), he has to wait until [log flusher](@ref
462 sect_redo_log_flusher) has flushed log files to disk for lsn >= _end_lsn_ of
463 log range used by the user, which is true when:
464
465 flushed_to_disk_lsn >= end_lsn
466
467 The @ref subsect_redo_log_flushed_to_disk_lsn is updated by the log flusher
468 thread.
469
470 The waiting is solved using array of events. The user thread waiting for
471 a given lsn, waits using the event at position:
472
473 slot = (end_lsn - 1) / OS_FILE_LOG_BLOCK_SIZE % S
474
475 where _S_ is number of entries in the array. Therefore the event corresponds
476 to log block which contains the _end_lsn_.
477
478 The [log flush_notifier thread](@ref sect_redo_log_flush_notifier) tracks how
479 the
480 @ref subsect_redo_log_flushed_to_disk_lsn is advanced and notifies user
481 threads for consecutive slots.
482
483 @remarks
484 When the _flushed_to_disk_lsn_ is in the middle of log block, all
485 user threads waiting for lsn values within the whole block are notified.
486 When user thread is notified, it checks if the current value of the
487 _flushed_to_disk_lsn_ is sufficient and retries waiting if not.
488 To avoid missed notifications, event's internal mutex is used.
489
490
491 @page PAGE_INNODB_REDO_LOG_FORMAT Format of redo log
492
493 @section sect_redo_log_format_overview Overview
494
495 Redo log contains multiple log files, each has the same format. Consecutive
496 files have data for consecutive ranges of lsn values. When a file ends at
497 _end_lsn_, the next log file begins at the _end_lsn_. There is a fixed number
498 of log files, they are re-used in circular manner. That is, for the last
499 log file, the first log file is a successor.
500
501 @note A single big file would remain fully cached for some of file systems,
502 even if only a small fragment of the file is being modified. Hence multiple
503 log files are used to make evictions always possible. Keep in mind though
504 that log files are used in circular manner (lsn modulo size of redo log files,
505 when size is calculated except the log file headers).
506
507 The log file names are: _#ib_redo0_, _#ib_redo1_, ... and they are stored in
508 subdirectory #innodb_redo, which is located inside the directory specified by
509 the innodb_log_group_home_dir (or in the datadir if not specified).
510
511 Whenever a new log file is being created, it is created first with the _tmp
512 suffix in its name. When the file is prepared, it becomes renamed (the suffix
513 is removed from the name).
514
515 When a new data directory is being initialized, all log files that are being
516 created, have LOG_HEADER_FLAG_NOT_INITIALIZED flag enabled in the log_flags
517 field in the header. After the data directory is initialized, this flag is
518 disabled (file header is re-flushed for the newest log file then).
519
520 File header contains the log_uuid field. It is a randomly chosen value when
521 the data directory is being initialized. It is used to detect situation,
522 in which user mixed log files from different data directories.
523
524 File header contains also start_lsn - this is start_lsn of the first log block
525 within that file.
526
527 @section sect_redo_log_format_file Log file format
528
529 @subsection subsect_redo_log_format_header Header of log file
530
531 %Log file starts with a header of _LOG_FILE_HDR_SIZE_ bytes. It contains:
532
533 - Initial block of _OS_FILE_LOG_BLOCK_SIZE_ (512) bytes, which has:
534
535 - Binding of an offset within the file to the lsn value.
536
537 This binding allows to map any lsn value which is represented
538 within the file to corresponding lsn value.
539
540 - Format of redo log - remains the same as before the patch.
541
542 - Checksum of the block.
543
544 - Two checkpoint blocks - _LOG_CHECKPOINT_1_ and _LOG_CHECKPOINT_2_.
545
546 Each checkpoint block contains _OS_FILE_LOG_BLOCK_SIZE_ bytes:
547
548 - _checkpoint_lsn_ - lsn to start recovery at.
549
550 @note In earlier versions than 8.0, checkpoint_lsn pointed
551 directly to the beginning of the first log record group,
552 which should be recovered (but still the related page could
553 have been flushed). However since 8.0 this value might point
554 to some byte inside a log record. In such case, recovery is
555 supposed to skip the group of log records which contains
556 the checkpoint lsn (and start at the beginning of the next).
557 We cannot easily determine beginning of the next group.
558 There are two cases:
559
560 - block with _checkpoint_lsn_ has no beginning of group at all
561 (first_rec_group = 0) - then we search forward for the first
562 block that has non-zero first_rec_group and there we have
563 the next group's start,
564
565 - block with _checkpoint_lsn_ has one or more groups of records
566 starting inside the block - then we start parsing at the first
567 group that starts in the block and keep parsing consecutive
568 groups until we passed checkpoint_lsn; we don't apply these
569 groups of records (we must not because of fil renames); after
570 we passed checkpoint_lsn, the next group that starts is the
571 one we were looking for to start recovery at; it is possible
572 that the next group begins in the next block (if there was no
573 more groups starting after checkpoint_lsn within the block)
574
575 - _checkpoint_no_ - checkpoint number - when checkpoint is
576 being written, a next checkpoint number is assigned.
577
578 - _log.buf_size_ - size of the log buffer when the checkpoint
579 write was started.
580
581 It remains a mystery, why do we need that. It's neither used
582 by the recovery, nor required for MEB. Some rumours say that
583 maybe it could be useful for auto-config external tools to
584 detect what configuration of MySQL should be used.
585
586 @note
587 Note that size of the log buffer could be decreased in runtime,
588 after writing the checkpoint (which was not the case, when this
589 field was being introduced).
590
591 There are two checkpoint headers, because they are updated alternately.
592 In case of crash in the middle of any such update, the alternate header
593 would remain valid (so it's the same reason for which double write buffer
594 is used for pages).
595
596 @remarks
597 Each log file has its own header. Checkpoints defined in checkpoint headers
598 always refer to LSN values within that file. During the recovery one should
599 find the file with the newest checkpoint.
600
601 @subsection subsect_redo_log_format_blocks Log blocks
602
603 After the header, there are consecutive log blocks. Each log block has the same
604 format and consists of _OS_FILE_LOG_BLOCK_SIZE_ bytes (512). These bytes are
605 enumerated by lsn values.
606
607 @note Bytes used by [headers of log files](@ref subsect_redo_log_format_header)
608 are NOT included in lsn sequence.
609
610 Each log block contains:
611 - header - _LOG_BLOCK_HDR_SIZE_ bytes (12):
612
613 - @anchor a_redo_log_block_hdr_no hdr_no
614
615 This is a block number. Consecutive blocks have consecutive numbers.
616 Hence this is basically lsn divided by _OS_FILE_LOG_BLOCK_SIZE_.
617 However it is also wrapped at 1G (due to limited size of the field).
618 It should be possible to wrap it at 2G (only the single flush bit is
619 reserved as the highest bit) but for historical reasons it is 1G.
620
621 - @anchor a_redo_log_block_data_len data_len
622
623 Number of bytes within the log block. Possible values:
624
625 - _0_ - this is an empty block (end the recovery).
626
627 - _OS_FILE_LOG_BLOCK_SIZE_ - this is a full block.
628
629 - value within [_LOG_BLOCK_HDR_SIZE_,
630 _OS_FILE_LOG_BLOCK_SIZE_ - _LOG_BLOCK_TRL_SIZE_),
631 which means that this is the last block and it is an
632 incomplete block.
633
634 This could be then considered an offset, which points
635 to the end of the data within the block. This value
636 includes _LOG_BLOCK_HDR_SIZE_ bytes of the header.
637
638 - @anchor a_redo_log_block_first_rec_group first_rec_group
639
640 Offset within the log block to the beginning of the first group
641 of log records that starts within the block or 0 if none starts.
642 This offset includes _LOG_BLOCK_HDR_SIZE_ bytes of the header.
643
644 - @anchor a_redo_log_block_epoch_no epoch_no
645
646 Log epoch number. Set by the log writer thread just before a write
647 starts for the block. For details @see LOG_BLOCK_HDR_EPOCH_NO.
648
649 It could be used during recovery to detect that we have read
650 old block of redo log (tail) because of the wrapped log files.
651
652 - data part - bytes up to [data_len](@ref a_redo_log_block_data_len) byte.
653
654 Actual data bytes are followed by _0x00_ if the block is incomplete.
655
656 @note Bytes within this fragment of the block, are enumerated by _sn_
657 sequence (whereas bytes of header and trailer are NOT). This is the
658 only difference between _sn_ and _lsn_ sequences (_lsn_ enumerates
659 also bytes of header and trailer).
660
661 - trailer - _LOG_BLOCK_TRL_SIZE_ bytes (4):
662
663 - checksum
664
665 Algorithm used for the checksum depends on the configuration.
666 Note that there is a potential problem if a crash happened just
667 after switching to "checksums enabled". During recovery some log
668 blocks would have checksum = LOG_NO_CHECKSUM_MAGIC and some would
669 have a valid checksum. Then recovery with enabled checksums would
670 point problems for the blocks without valid checksum. User would
671 have to disable checksums for the recovery then.
672
673
674
675 @remarks
676 All fields except [first_rec_group](@ref a_redo_log_block_first_rec_group)
677 are updated by the [log writer thread](@ref sect_redo_log_writer) just before
678 writing the block.
679
680 *******************************************************/
681 // clang-format on
682
683 /** Writes a given fragment of the log buffer to the current redo log file,
684 unless the file is full, in which case a new file is produced and function
685 exits (note, that the new log file's header is flushed in such case).
686 After data to the current log file has been written (log_data_blocks_write()),
687 the log.write_lsn is advanced accordingly to the number of written bytes,
688 which might be smaller than the requested number of bytes to write.
689 That's because this function exits after doing a single write operation.
690 That's because it might make sense to advance the lsn up to which data
691 is ready in the log buffer (for writing), before making decision about
692 next write (e.g. then the next write could be done for full blocks only).
693 @param[in] log redo log
694 @param[in] buffer the beginning of first log block to write
695 @param[in] buffer_size number of bytes to write since 'buffer'
696 @param[in] start_lsn lsn corresponding to first block start
697 @return DB_SUCCESS or error */
698 static dberr_t log_write_buffer(log_t &log, byte *buffer, size_t buffer_size,
699 lsn_t start_lsn);
700
701 /** Called when the redo log writer enters the extra_margin.
702 Requirement: log.writer_mutex acquired and log.m_write_inside_extra_margin
703 being false, before calling this function.
704 @param[in,out] log redo log */
705 static void log_writer_enter_extra_margin(log_t &log);
706
707 /** Called when the redo log writer exits the extra_margin.
708 Requirement: log.writer_mutex acquired and log.m_write_inside_extra_margin
709 being true, before calling this function.
710 @param[in,out] log redo log */
711 static void log_writer_exit_extra_margin(log_t &log);
712
713 /* Waits until there is free space in log files for log_writer to proceed.
714 @param[in] log redo log
715 @param[in] last_write_lsn previous log.write_lsn
716 @param[in] next_write_lsn next log.write_lsn
717 @return lsn up to which possible write is limited */
718 static lsn_t log_writer_wait_on_checkpoint(log_t &log, lsn_t last_write_lsn,
719 lsn_t next_write_lsn);
720
721 /* Waits until the archiver has archived enough for log_writer to proceed
722 or until the archiver becomes aborted.
723 @param[in] log redo log
724 @param[in] next_write_lsn next log.write_lsn */
725 static void log_writer_wait_on_archiver(log_t &log, lsn_t next_write_lsn);
726
727 /** Called after a write to the redo log file failed. If the reason was not
728 related to missing free space or busy file-lock, emits fatal error.
729 @param[in,out] log redo log
730 @param[in] err error code (non-zero) */
731 static void log_writer_write_failed(log_t &log, dberr_t err);
732
733 /** Writes fragment of the log buffer, not further than up to provided lsn.
734 Stops after the first call to log_data_blocks_write() or after producing
735 a new log file or if it notices that some other thread has written to the
736 redo log meanwhile. If some data was written, the log.write_lsn is advanced.
737 For more details see @see log_write_buffer().
738 @param[in] log redo log
739 @param[in] next_write_lsn write up to this lsn value */
740 static void log_writer_write_buffer(log_t &log, lsn_t next_write_lsn);
741
742 /** Executes a synchronous flush of the log files (doing fsyncs).
743 Advances log.flushed_to_disk_lsn and notifies log flush_notifier thread.
744 Note: if only a single log block was flushed to disk, user threads
745 waiting for lsns within the block are notified directly from here,
746 and log flush_notifier thread is not notified! (optimization)
747 @param[in,out] log redo log */
748 static void log_flush_low(log_t &log);
749
750 /**************************************************/ /**
751
752 @name Waiting for redo log written or flushed up to lsn
753
754 *******************************************************/
755
756 /** @{ */
757
758 /** Computes index of a slot (in array of "wait events"), which should
759 be used when waiting until redo reached provided lsn.
760 @param[in] lsn lsn up to which waiting takes place
761 @param[in] events_n size of the array (number of slots)
762 @return index of the slot (integer in range 0 .. events_n-1) */
763 static inline size_t log_compute_wait_event_slot(lsn_t lsn, size_t events_n) {
764 /* We subtract one from lsn, because it is better to assign right boundary
765 of a log block to the slot representing the given block. If write or flush
766 happens within block, all threads interested in some lsn in that block should
767 be notified.
768
769 Suppose lsn % 512 == 0 (this is the only case for which subtracting 1 makes
770 any difference here). All threads waiting for some lsn in (lsn-1)/512 must
771 be notified anyway (previous lsn was smaller so the block wasn't closed yet).
772 On the other hand, it is useless to notify threads waiting for lsn values
773 within lsn / 512, because these are larger lsn values, except threads which
774 are waiting exactly at this lsn. That's why this group of threads it's better
775 to move to the slot corresponding to (lsn-1)/512 and then we could avoid
776 waking up those in lsn/512. Note that this scenario (lsn % 512 == 0) happens
777 often because our strategy is to prefer writes of full log blocks only,
778 leaving the incomplete last block for next write (unless there are no full
779 blocks). */
780 return ((lsn - 1) / OS_FILE_LOG_BLOCK_SIZE) & (events_n - 1);
781 }
782
783 /** Computes index of a slot (in array of "wait events"), which should
784 be used when waiting in log.write_events (for redo written up to lsn).
785 @param[in] log redo log
786 @param[in] lsn lsn up to which waiting (for log.write_lsn)
787 @return index of the slot (integer in range 0 .. log.write_events_size-1) */
788 static inline size_t log_compute_write_event_slot(const log_t &log, lsn_t lsn) {
789 return log_compute_wait_event_slot(lsn, log.write_events_size);
790 }
791
792 /** Computes index of a slot (in array of "wait events"), which should
793 be used when waiting in log.flush_events (for redo flushed up to lsn).
794 @param[in] log redo log
795 @param[in] lsn lsn up to which waiting (for log.flushed_to_disk_lsn)
796 @return index of the slot (integer in range 0 .. log.flush_events_size-1) */
797 static inline size_t log_compute_flush_event_slot(const log_t &log, lsn_t lsn) {
798 return log_compute_wait_event_slot(lsn, log.flush_events_size);
799 }
800
801 /** Computes maximum number of spin rounds which should be used when waiting
802 in user thread (for written or flushed redo) or 0 if busy waiting should not
803 be used at all.
804 @param[in] min_non_zero_value minimum allowed value (unless 0 is returned)
805 @return maximum number of spin rounds or 0 */
806 static inline uint64_t log_max_spins_when_waiting_in_user_thread(
807 uint64_t min_non_zero_value) {
808 uint64_t max_spins;
809
810 /* Get current cpu usage. */
811 const double cpu = srv_cpu_usage.utime_pct;
812
813 /* Get high-watermark - when cpu usage is higher, don't spin! */
814 const uint32_t hwm = srv_log_spin_cpu_pct_hwm;
815
816 if (srv_cpu_usage.utime_abs < srv_log_spin_cpu_abs_lwm || cpu >= hwm) {
817 /* Don't spin because either cpu usage is too high or it's
818 almost idle so no reason to bother. */
819 max_spins = 0;
820
821 } else if (cpu >= hwm / 2) {
822 /* When cpu usage is more than 50% of the hwm, use the minimum allowed
823 number of spin rounds, not to increase cpu usage too much (risky). */
824 max_spins = min_non_zero_value;
825
826 } else {
827 /* When cpu usage is less than 50% of the hwm, choose maximum spin rounds
828 in range [minimum, 10*minimum]. Smaller usage of cpu is, more spin rounds
829 might be used. */
830 const double r = 1.0 * (hwm / 2 - cpu) / (hwm / 2);
831
832 max_spins =
833 static_cast<uint64_t>(min_non_zero_value + r * min_non_zero_value * 9);
834 }
835
836 return max_spins;
837 }
838
839 /** Waits until redo log is written up to provided lsn (or greater).
840 We do not care if it's flushed or not.
841 @param[in] log redo log
842 @param[in] lsn wait until log.write_lsn >= lsn
843 @param[in,out] interrupted if true, was interrupted, needs retry.
844 @return statistics related to waiting inside */
845 static Wait_stats log_wait_for_write(const log_t &log, lsn_t lsn,
846 bool *interrupted) {
847 os_event_set(log.writer_event);
848
849 const uint64_t max_spins = log_max_spins_when_waiting_in_user_thread(
850 srv_log_wait_for_write_spin_delay);
851
852 auto stop_condition = [&log, lsn, interrupted](bool wait) {
853 if (log.write_lsn.load() >= lsn) {
854 *interrupted = false;
855 return true;
856 }
857
858 if (UNIV_UNLIKELY(
859 log.writer_threads_paused.load(std::memory_order_relaxed))) {
860 *interrupted = true;
861 return true;
862 }
863
864 if (wait) {
865 os_event_set(log.writer_event);
866 }
867
868 ut_d(log_background_write_threads_active_validate(log));
869 return false;
870 };
871
872 const size_t slot = log_compute_write_event_slot(log, lsn);
873
874 const auto wait_stats =
875 os_event_wait_for(log.write_events[slot], max_spins,
876 get_srv_log_wait_for_write_timeout(), stop_condition);
877
878 MONITOR_INC_WAIT_STATS(MONITOR_LOG_ON_WRITE_, wait_stats);
879
880 return wait_stats;
881 }
882
883 /** Waits until redo log is flushed up to provided lsn (or greater).
884 @param[in] log redo log
885 @param[in] lsn wait until log.flushed_to_disk_lsn >= lsn
886 @param[in,out] interrupted if true, was interrupted, needs retry.
887 @return statistics related to waiting inside */
888 static Wait_stats log_wait_for_flush(const log_t &log, lsn_t lsn,
889 bool *interrupted) {
890 if (log.write_lsn.load(std::memory_order_relaxed) < lsn) {
891 os_event_set(log.writer_event);
892 }
893 os_event_set(log.flusher_event);
894
895 uint64_t max_spins = log_max_spins_when_waiting_in_user_thread(
896 srv_log_wait_for_flush_spin_delay);
897
898 if (log.flush_avg_time >= srv_log_wait_for_flush_spin_hwm) {
899 max_spins = 0;
900 }
901
902 auto stop_condition = [&log, lsn, interrupted](bool wait) {
903 log_sync_point("log_wait_for_flush_before_flushed_to_disk_lsn");
904
905 if (log.flushed_to_disk_lsn.load() >= lsn) {
906 *interrupted = false;
907 return true;
908 }
909
910 if (UNIV_UNLIKELY(
911 log.writer_threads_paused.load(std::memory_order_relaxed))) {
912 *interrupted = true;
913 return true;
914 }
915
916 if (wait) {
917 if (log.write_lsn.load(std::memory_order_relaxed) < lsn) {
918 os_event_set(log.writer_event);
919 }
920
921 os_event_set(log.flusher_event);
922 }
923
924 log_sync_point("log_wait_for_flush_before_wait");
925 return false;
926 };
927
928 const size_t slot = log_compute_flush_event_slot(log, lsn);
929
930 thd_wait_begin(nullptr, THD_WAIT_GROUP_COMMIT);
931 const auto wait_stats =
932 os_event_wait_for(log.flush_events[slot], max_spins,
933 get_srv_log_wait_for_flush_timeout(), stop_condition);
934
935 thd_wait_end(nullptr);
936
937 MONITOR_INC_WAIT_STATS(MONITOR_LOG_ON_FLUSH_, wait_stats);
938
939 return wait_stats;
940 }
941
942 /** Write the redo log up to a provided lsn by itself, if necessary.
943 @param[in] log redo log
944 @param[in] end_lsn lsn to write for
945 @param[in] flush_to_disk whether the written log should also be flushed
946 @param[in,out] interrupted if true, was interrupted, needs retry
947 @return statistics about waiting inside */
948 static Wait_stats log_self_write_up_to(log_t &log, lsn_t end_lsn,
949 bool flush_to_disk, bool *interrupted) {
950 ut_ad(!mutex_own(&(log.writer_mutex)));
951
952 uint32_t waits = 0;
953 *interrupted = false;
954
955 lsn_t ready_lsn = log_buffer_ready_for_write_lsn(log);
956 ulong i = 0;
957 /* must wait for (ready_lsn >= end_lsn) at first */
958 while (i < srv_n_spin_wait_rounds && ready_lsn < end_lsn) {
959 if (srv_spin_wait_delay) {
960 ut_delay(ut::random_from_interval_fast(0, srv_spin_wait_delay));
961 }
962 i++;
963 ready_lsn = log_buffer_ready_for_write_lsn(log);
964 }
965 if (ready_lsn < end_lsn) {
966 log.recent_written.advance_tail();
967 ready_lsn = log_buffer_ready_for_write_lsn(log);
968 }
969 if (ready_lsn < end_lsn) {
970 std::this_thread::yield();
971 ready_lsn = log_buffer_ready_for_write_lsn(log);
972 }
973 while (ready_lsn < end_lsn) {
974 /* wait using event */
975 log_closer_mutex_enter(log);
976 if (log.current_ready_waiting_lsn == 0 &&
977 os_event_is_set(log.closer_event)) {
978 log.current_ready_waiting_lsn = end_lsn;
979 log.current_ready_waiting_sig_count = os_event_reset(log.closer_event);
980 }
981 const auto sig_count = log.current_ready_waiting_sig_count;
982 log_closer_mutex_exit(log);
983 ++waits;
984 os_event_wait_time_low(log.closer_event, std::chrono::milliseconds{100},
985 sig_count);
986 log.recent_written.advance_tail();
987 ready_lsn = log_buffer_ready_for_write_lsn(log);
988 }
989
990 /* NOTE: Currently doesn't do dirty read for (flush_to_disk == true) case,
991 because the mutex contention also works as the arbitrator for write-IO
992 (fsync) bandwidth between log files and data files. */
993 if (!flush_to_disk &&
994 log.write_lsn.load(std::memory_order_acquire) >= end_lsn) {
995 return Wait_stats{waits};
996 }
997
998 /* mysql-test compatibility */
999 log_sync_point("log_wait_for_flush_before_flushed_to_disk_lsn");
1000 log_sync_point("log_wait_for_flush_before_wait");
1001
1002 log_writer_mutex_enter(log);
1003
1004 if (UNIV_UNLIKELY(
1005 !log.writer_threads_paused.load(std::memory_order_relaxed))) {
1006 log_writer_mutex_exit(log);
1007 *interrupted = true;
1008 return Wait_stats{waits};
1009 }
1010
1011 /* write to ready_lsn */
1012 lsn_t write_lsn = log.write_lsn.load(std::memory_order_relaxed);
1013 for (uint64_t step = 0; write_lsn < ready_lsn; ++step) {
1014 if (step % 1024 == 0) {
1015 /* The first loop or just after std::this_thread::yield() */
1016 const lsn_t limit_lsn =
1017 flush_to_disk
1018 ? log.flushed_to_disk_lsn.load(std::memory_order_acquire)
1019 : write_lsn;
1020 if (limit_lsn >= end_lsn) {
1021 log_writer_mutex_exit(log);
1022 return Wait_stats{waits};
1023 }
1024 }
1025
1026 log_writer_write_buffer(log, log_buffer_ready_for_write_lsn(log));
1027
1028 if ((step + 1) % 1024 == 0) {
1029 /* approximate per srv_log_write_ahead_size * 1024 written. */
1030 log_writer_mutex_exit(log);
1031 std::this_thread::yield();
1032 log_writer_mutex_enter(log);
1033 }
1034
1035 write_lsn = log.write_lsn.load(std::memory_order_relaxed);
1036 }
1037
1038 /* If it is a write call we should just go ahead and do it
1039 as we checked that write_lsn is not where we'd like it to
1040 be. If we have to flush as well then we check if there is a
1041 pending flush and based on that we wait for it to finish
1042 before proceeding further. */
1043 if (flush_to_disk) {
1044 if (!os_event_is_set(log.old_flush_event)) {
1045 const auto sig_count = log.current_flush_sig_count;
1046 log_writer_mutex_exit(log);
1047 ++waits;
1048 os_event_wait_low(log.old_flush_event, sig_count);
1049 /* Needs to confirm actual value,
1050 because the log writer threads might be resumed. */
1051 if (log.flushed_to_disk_lsn.load(std::memory_order_relaxed) < end_lsn) {
1052 *interrupted = true;
1053 }
1054 return Wait_stats{waits};
1055 } else {
1056 log.current_flush_sig_count = os_event_reset(log.old_flush_event);
1057 }
1058 }
1059
1060 log_writer_mutex_exit(log);
1061
1062 if (flush_to_disk) {
1063 /* basically, no other flushers */
1064 if (UNIV_UNLIKELY(log_flusher_mutex_enter_nowait(log))) {
1065 if (!log.writer_threads_paused.load(std::memory_order_relaxed)) {
1066 os_event_set(log.old_flush_event);
1067 *interrupted = true;
1068 return Wait_stats{waits};
1069 }
1070 log_flusher_mutex_enter(log);
1071 }
1072 log_flush_low(log);
1073 log_flusher_mutex_exit(log);
1074
1075 /* mysql-test compatibility */
1076 log_sync_point("log_flush_notifier_after_event_reset");
1077 log_sync_point("log_flush_notifier_before_check");
1078 log_sync_point("log_flush_notifier_before_wait");
1079 log_sync_point("log_flush_notifier_before_flushed_to_disk_lsn");
1080 log_sync_point("log_flush_notifier_before_notify");
1081 }
1082
1083 return Wait_stats{waits};
1084 }
1085
1086 Wait_stats log_write_up_to(log_t &log, lsn_t end_lsn, bool flush_to_disk) {
1087 ut_a(!srv_read_only_mode);
1088
1089 /* If we were updating log.flushed_to_disk_lsn while parsing redo log
1090 during recovery, we would have valid value here and we would not need
1091 to explicitly exit because of the recovery. However we do not update
1092 the log.flushed_to_disk during recovery (it is zero).
1093
1094 On the other hand, when we apply log records during recovery, we modify
1095 pages and update their oldest/newest_modification. The modified pages
1096 become dirty. When size of the buffer pool is too small, some pages
1097 have to be flushed from LRU, to reclaim a free page for a next read.
1098
1099 When flushing such dirty pages, we notice that newest_modification != 0,
1100 so the redo log has to be flushed up to the newest_modification, before
1101 flushing the page. In such case we end up here during recovery.
1102
1103 Note that redo log is actually flushed, because changes to the page
1104 are caused by applying the redo. */
1105
1106 if (recv_no_ibuf_operations) {
1107 /* Recovery is running and no operations on the log files are
1108 allowed yet, which is implicitly deduced from the fact, that
1109 still ibuf merges are disallowed. */
1110 return Wait_stats{0};
1111 }
1112
1113 /* We do not need to have exact numbers and we do not care if we
1114 lost some increments for heavy workload. The value only has usage
1115 when it is low workload and we need to discover that we request
1116 redo write or flush only from time to time. In such case we prefer
1117 to avoid spinning in log threads to save on CPU power usage. */
1118 log.write_to_file_requests_total.store(
1119 log.write_to_file_requests_total.load(std::memory_order_relaxed) + 1,
1120 std::memory_order_relaxed);
1121
1122 ut_a(end_lsn != LSN_MAX);
1123
1124 ut_a(end_lsn % OS_FILE_LOG_BLOCK_SIZE == 0 ||
1125 end_lsn % OS_FILE_LOG_BLOCK_SIZE >= LOG_BLOCK_HDR_SIZE);
1126
1127 ut_a(end_lsn % OS_FILE_LOG_BLOCK_SIZE <=
1128 OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_TRL_SIZE);
1129
1130 ut_ad(end_lsn <= log_get_lsn(log));
1131
1132 Wait_stats wait_stats{0};
1133 bool interrupted = false;
1134
1135 retry:
1136 if (log.writer_threads_paused.load(std::memory_order_acquire)) {
1137 /* the log writer threads are paused not to waste CPU resource. */
1138 wait_stats +=
1139 log_self_write_up_to(log, end_lsn, flush_to_disk, &interrupted);
1140
1141 if (UNIV_UNLIKELY(interrupted)) {
1142 /* the log writer threads might be working. retry. */
1143 goto retry;
1144 }
1145
1146 DEBUG_SYNC_C("log_flushed_by_self");
1147 return wait_stats;
1148 }
1149
1150 /* the log writer threads are working for high concurrency scale */
1151 if (flush_to_disk) {
1152 if (log.flushed_to_disk_lsn.load() >= end_lsn) {
1153 DEBUG_SYNC_C("log_flushed_by_writer");
1154 return wait_stats;
1155 }
1156
1157 if (srv_flush_log_at_trx_commit != 1) {
1158 /* We need redo flushed, but because trx != 1, we have
1159 disabled notifications sent from log_writer to log_flusher.
1160
1161 The log_flusher might be sleeping for 1 second, and we need
1162 quick response here. Log_writer avoids waking up log_flusher,
1163 so we must do it ourselves here.
1164
1165 However, before we wake up log_flusher, we must ensure that
1166 log.write_lsn >= lsn. Otherwise log_flusher could flush some
1167 data which was ready for lsn values smaller than end_lsn and
1168 return to sleeping for next 1 second. */
1169
1170 if (log.write_lsn.load() < end_lsn) {
1171 wait_stats += log_wait_for_write(log, end_lsn, &interrupted);
1172 }
1173 }
1174
1175 /* Wait until log gets flushed up to end_lsn. */
1176 wait_stats += log_wait_for_flush(log, end_lsn, &interrupted);
1177
1178 if (UNIV_UNLIKELY(interrupted)) {
1179 /* the log writer threads might be paused. retry. */
1180 goto retry;
1181 }
1182
1183 DEBUG_SYNC_C("log_flushed_by_writer");
1184 } else {
1185 if (log.write_lsn.load() >= end_lsn) {
1186 return wait_stats;
1187 }
1188
1189 /* Wait until log gets written up to end_lsn. */
1190 wait_stats += log_wait_for_write(log, end_lsn, &interrupted);
1191
1192 if (UNIV_UNLIKELY(interrupted)) {
1193 /* the log writer threads might be paused. retry. */
1194 goto retry;
1195 }
1196 }
1197
1198 return wait_stats;
1199 }
1200
1201 /** @} */
1202
1203 /**************************************************/ /**
1204
1205 @name Log threads waiting strategy
1206
1207 *******************************************************/
1208
1209 /** @{ */
1210
1211 /** Small utility which is used inside log threads when they have to wait for
1212 next interesting event to happen. For performance reasons, it might make sense
1213 to use spin-delay in front of the wait on event in such cases. The strategy is
1214 first to spin and then to fallback to the wait on event. However, for idle
1215 servers or work-loads which do not need redo being flushed as often, we prefer
1216 to avoid spinning. This utility solves such problems and provides waiting
1217 mechanism. */
1218 struct Log_thread_waiting {
1219 Log_thread_waiting(const log_t &log, os_event_t event, uint64_t spin_delay,
1220 std::chrono::microseconds min_timeout)
1221 : m_log(log),
1222 m_event{event},
1223 m_spin_delay{static_cast<uint32_t>(std::min(
1224 uint64_t(std::numeric_limits<uint32_t>::max()), spin_delay))},
1225 m_min_timeout{/* No more than 1s */
1226 std::min<std::chrono::microseconds>(
1227 std::chrono::seconds{1}, min_timeout)} {}
1228
1229 template <typename Stop_condition>
1230 inline Wait_stats wait(Stop_condition stop_condition) {
1231 auto spin_delay = m_spin_delay;
1232 auto min_timeout = m_min_timeout;
1233
1234 /** We might read older value, it just decides on spinning.
1235 Correctness does not depend on this. Only local performance might depend on
1236 this but it's anyway heuristic and depends on average which by definition
1237 has lag. No reason to make extra barriers here. */
1238
1239 const auto req_interval =
1240 m_log.write_to_file_requests_interval.load(std::memory_order_relaxed);
1241
1242 if (srv_cpu_usage.utime_abs < srv_log_spin_cpu_abs_lwm ||
1243 !log_write_to_file_requests_are_frequent(req_interval)) {
1244 /* Either:
1245 1. CPU usage is very low on the server, which means the server is most
1246 likely idle or almost idle.
1247 2. Request to write/flush redo to disk comes only once per 1ms in average
1248 or even less often.
1249 In both cases we prefer not to spend on CPU power, because there is no
1250 real gain from spinning in log threads then. */
1251
1252 spin_delay = 0;
1253 min_timeout = std::min<std::chrono::microseconds>(
1254 req_interval, std::chrono::milliseconds{1});
1255 }
1256
1257 const auto wait_stats =
1258 os_event_wait_for(m_event, spin_delay, min_timeout, stop_condition);
1259
1260 return wait_stats;
1261 }
1262
1263 private:
1264 const log_t &m_log;
1265 os_event_t m_event;
1266 const uint32_t m_spin_delay;
1267 const std::chrono::microseconds m_min_timeout;
1268 };
1269
1270 struct Log_write_to_file_requests_monitor {
1271 explicit Log_write_to_file_requests_monitor(log_t &log)
1272 : m_log(log), m_last_requests_value{0}, m_request_interval{0} {
1273 m_last_requests_time = Log_clock::now();
1274 }
1275
1276 void update() {
1277 const auto requests_value =
1278 m_log.write_to_file_requests_total.load(std::memory_order_relaxed);
1279
1280 const auto current_time = Log_clock::now();
1281 if (current_time < m_last_requests_time) {
1282 m_last_requests_time = current_time;
1283 return;
1284 }
1285
1286 const auto delta_time = current_time - m_last_requests_time;
1287
1288 if (requests_value > m_last_requests_value) {
1289 const auto delta_requests = requests_value - m_last_requests_value;
1290 const auto request_interval = delta_time / delta_requests;
1291 m_request_interval =
1292 std::chrono::duration_cast<std::chrono::microseconds>(
1293 (m_request_interval * 63 + request_interval) / 64);
1294
1295 } else if (delta_time > std::chrono::milliseconds{100}) {
1296 /* Last call to log_write_up_to() was longer than 100ms ago, so consider
1297 this as maximum time between calls we can expect. Tracking higher values
1298 does not make sense, because it is for sure already higher than any
1299 reasonable threshold which can be
1300 used to differ different activity modes. */
1301
1302 m_request_interval = std::chrono::milliseconds{100};
1303
1304 } else {
1305 /* No progress in number of requests and still no more than 1second since
1306 last progress. Postpone any decision. */
1307 return;
1308 }
1309
1310 m_log.write_to_file_requests_interval.store(m_request_interval,
1311 std::memory_order_relaxed);
1312
1313 MONITOR_SET(MONITOR_LOG_WRITE_TO_FILE_REQUESTS_INTERVAL,
1314 m_request_interval.count());
1315
1316 m_last_requests_time = current_time;
1317 m_last_requests_value = requests_value;
1318 }
1319
1320 private:
1321 log_t &m_log;
1322 uint64_t m_last_requests_value;
1323 Log_clock_point m_last_requests_time;
1324 std::chrono::microseconds m_request_interval;
1325 };
1326
1327 /** @} */
1328
1329 /**************************************************/ /**
1330
1331 @name Log writer thread
1332
1333 *******************************************************/
1334
1335 /** @{ */
1336
1337 namespace Log_files_write_impl {
1338
1339 static inline void validate_buffer(const log_t &log, const byte *buffer,
1340 size_t buffer_size) {
1341 ut_a(buffer >= log.buf);
1342 ut_a(buffer_size > 0);
1343 ut_a(buffer + buffer_size <= log.buf + log.buf_size);
1344 }
1345
1346 static inline void validate_start_lsn(const log_t &log, lsn_t start_lsn,
1347 size_t buffer_size) {
1348 /* start_lsn corresponds to block, it must be aligned to 512 */
1349 ut_a(start_lsn % OS_FILE_LOG_BLOCK_SIZE == 0);
1350
1351 /* Either full log block writes are possible or partial writes,
1352 which have to cover full header of log block then. */
1353 ut_a((start_lsn + buffer_size) % OS_FILE_LOG_BLOCK_SIZE >=
1354 LOG_BLOCK_HDR_SIZE ||
1355 (start_lsn + buffer_size) % OS_FILE_LOG_BLOCK_SIZE == 0);
1356
1357 /* Partial writes do not touch footer of log block. */
1358 ut_a((start_lsn + buffer_size) % OS_FILE_LOG_BLOCK_SIZE <
1359 OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_TRL_SIZE);
1360
1361 /* There are no holes. Note that possibly start_lsn is smaller,
1362 because it always points to the beginning of log block. */
1363 ut_a(start_lsn <= log.write_lsn.load());
1364 }
1365
1366 static inline bool current_file_has_space(const log_t &log, os_offset_t offset,
1367 size_t size) {
1368 return offset + size <= log.m_current_file.m_size_in_bytes;
1369 }
1370
1371 static dberr_t start_next_file(log_t &log, lsn_t start_lsn) {
1372 ut_ad(log_writer_mutex_own(log));
1373
1374 IB_mutex_guard files_latch{&(log.m_files_mutex), UT_LOCATION_HERE};
1375
1376 const dberr_t err = log_files_produce_file(log);
1377
1378 if (err != DB_SUCCESS) {
1379 return err;
1380 }
1381
1382 ut_a(start_lsn == log.m_current_file.m_start_lsn);
1383
1384 MONITOR_INC(MONITOR_LOG_NEXT_FILE);
1385
1386 log.write_ahead_end_offset = 0;
1387
1388 return DB_SUCCESS;
1389 }
1390
1391 static inline bool write_ahead_enough(os_offset_t write_ahead_end,
1392 os_offset_t offset, size_t size) {
1393 return write_ahead_end >= offset + size;
1394 }
1395
1396 static inline bool current_write_ahead_enough(const log_t &log,
1397 os_offset_t offset, size_t size) {
1398 return write_ahead_enough(log.write_ahead_end_offset, offset, size);
1399 }
1400
1401 static inline os_offset_t compute_next_write_ahead_end(
1402 os_offset_t real_offset) {
1403 const auto last_wa =
1404 ut_uint64_align_down(real_offset, srv_log_write_ahead_size);
1405
1406 const auto next_wa = last_wa + srv_log_write_ahead_size;
1407
1408 ut_a(next_wa > real_offset);
1409 ut_a(next_wa % srv_log_write_ahead_size == 0);
1410
1411 return next_wa;
1412 }
1413
1414 static inline size_t compute_how_much_to_write(const log_t &log,
1415 os_offset_t real_offset,
1416 size_t buffer_size,
1417 bool &write_from_log_buffer) {
1418 size_t write_size;
1419
1420 /* First we ensure, that we will write within single log file.
1421 If we had more to write and cannot fit the current log file,
1422 we first write what fits, then stops and returns to the main
1423 loop of the log writer thread. Then, the log writer will update
1424 maximum lsn up to which, it has data ready in the log buffer,
1425 and request next write operation according to its strategy. */
1426 if (!current_file_has_space(log, real_offset, buffer_size)) {
1427 /* The end of write would not fit the current log file. */
1428
1429 /* But the beginning is guaranteed to fit or to be placed
1430 at the first byte of the next file. */
1431 ut_a(current_file_has_space(log, real_offset, 0));
1432
1433 if (!current_file_has_space(log, real_offset, 1)) {
1434 /* The beginning of write is at the first byte
1435 of the next log file. Flush header of the next
1436 log file, advance current log file to the next,
1437 stop and return to the main loop of log writer. */
1438 write_from_log_buffer = false;
1439 return 0;
1440
1441 } else {
1442 /* We write across at least two consecutive log files.
1443 Limit current write to the first one and then retry for
1444 next_file. */
1445
1446 /* If the condition for real_offset + buffer_size holds,
1447 then the expression below is < buffer_size, which is
1448 size_t, so the typecast is ok. */
1449 write_size =
1450 static_cast<size_t>(log.m_current_file.m_size_in_bytes - real_offset);
1451
1452 ut_a(write_size <= buffer_size);
1453 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE == 0);
1454 }
1455
1456 } else {
1457 write_size = buffer_size;
1458
1459 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE >= LOG_BLOCK_HDR_SIZE ||
1460 write_size % OS_FILE_LOG_BLOCK_SIZE == 0);
1461
1462 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE <
1463 OS_FILE_LOG_BLOCK_SIZE - LOG_BLOCK_TRL_SIZE);
1464 }
1465
1466 /* Now, we know we can write write_size bytes from the buffer,
1467 and we will do the write within single log file - current one. */
1468
1469 ut_a(write_size > 0);
1470 ut_a(real_offset + write_size <= log.m_current_file.m_size_in_bytes);
1471
1472 /* We are interested in writing from log buffer only,
1473 if we had at least one completed block for write.
1474 Still we might decide not to write from the log buffer,
1475 because write-ahead is needed. In such case we could write
1476 together with the last incomplete block after copying. */
1477 write_from_log_buffer = write_size >= OS_FILE_LOG_BLOCK_SIZE;
1478
1479 if (write_from_log_buffer) {
1480 MONITOR_INC(MONITOR_LOG_FULL_BLOCK_WRITES);
1481 } else {
1482 MONITOR_INC(MONITOR_LOG_PARTIAL_BLOCK_WRITES);
1483 }
1484
1485 /* Check how much we have written ahead to avoid read-on-write. */
1486
1487 if (!current_write_ahead_enough(log, real_offset, write_size)) {
1488 if (!current_write_ahead_enough(log, real_offset, 1)) {
1489 /* Current write-ahead region has no space at all. */
1490
1491 const auto next_wa = compute_next_write_ahead_end(real_offset);
1492
1493 if (!write_ahead_enough(next_wa, real_offset, write_size)) {
1494 /* ... and also the next write-ahead is too small.
1495 Therefore we have more data to write than size of
1496 the write-ahead. We write from the log buffer,
1497 skipping last fragment for which the write ahead
1498 is required. */
1499
1500 ut_a(write_from_log_buffer);
1501
1502 write_size = next_wa - real_offset;
1503
1504 ut_a((real_offset + write_size) % srv_log_write_ahead_size == 0);
1505
1506 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE == 0);
1507
1508 } else {
1509 /* We copy data to write_ahead buffer,
1510 and write from there doing write-ahead
1511 of the bigger region in the same time. */
1512 write_from_log_buffer = false;
1513 }
1514
1515 } else {
1516 /* We limit write up to the end of region
1517 we have written ahead already. */
1518 write_size =
1519 static_cast<size_t>(log.write_ahead_end_offset - real_offset);
1520
1521 ut_a(write_size >= OS_FILE_LOG_BLOCK_SIZE);
1522 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE == 0);
1523 }
1524
1525 } else {
1526 if (write_from_log_buffer) {
1527 write_size = ut_uint64_align_down(write_size, OS_FILE_LOG_BLOCK_SIZE);
1528 }
1529 }
1530
1531 return write_size;
1532 }
1533
1534 static inline void prepare_full_blocks(const log_t &log, byte *buffer,
1535 size_t size, lsn_t start_lsn) {
1536 /* Prepare all completed blocks which are going to be written.
1537
1538 Note, that completed blocks are always prepared in the log buffer,
1539 even if they are later copied to write_ahead buffer.
1540
1541 This guarantees that finally we should have all blocks prepared
1542 in the log buffer (incomplete blocks will be rewritten once they
1543 became completed). */
1544
1545 size_t buffer_offset;
1546
1547 for (buffer_offset = 0; buffer_offset + OS_FILE_LOG_BLOCK_SIZE <= size;
1548 buffer_offset += OS_FILE_LOG_BLOCK_SIZE) {
1549 byte *ptr;
1550
1551 ptr = buffer + buffer_offset;
1552
1553 ut_a(ptr >= log.buf);
1554
1555 ut_a(ptr + OS_FILE_LOG_BLOCK_SIZE <= log.buf + log.buf_size);
1556
1557 const lsn_t block_lsn = start_lsn + buffer_offset;
1558
1559 Log_data_block_header block_header;
1560 block_header.set_lsn(block_lsn);
1561 block_header.m_data_len = OS_FILE_LOG_BLOCK_SIZE;
1562 block_header.m_first_rec_group = log_block_get_first_rec_group(ptr);
1563 log_data_block_header_serialize(block_header, ptr);
1564 }
1565 }
1566
1567 static inline dberr_t write_blocks(log_t &log, byte *write_buf,
1568 size_t write_size, os_offset_t real_offset) {
1569 ut_a(write_size >= OS_FILE_LOG_BLOCK_SIZE);
1570 ut_a(write_size % OS_FILE_LOG_BLOCK_SIZE == 0);
1571 ut_a(real_offset / UNIV_PAGE_SIZE <= PAGE_NO_MAX);
1572
1573 ut_a(log.write_ahead_end_offset % srv_log_write_ahead_size == 0);
1574
1575 ut_a(real_offset + write_size <= log.write_ahead_end_offset ||
1576 (real_offset + write_size) % srv_log_write_ahead_size == 0);
1577
1578 const dberr_t err = log_data_blocks_write(log.m_current_file_handle,
1579 real_offset, write_size, write_buf);
1580
1581 if (err != DB_SUCCESS) {
1582 return err;
1583 }
1584
1585 meb::redo_log_archive_produce(write_buf, write_size);
1586
1587 return DB_SUCCESS;
1588 }
1589
1590 static inline void notify_about_advanced_write_lsn(log_t &log,
1591 lsn_t old_write_lsn,
1592 lsn_t new_write_lsn) {
1593 if (!log.writer_threads_paused.load(std::memory_order_acquire)) {
1594 if (srv_flush_log_at_trx_commit == 1) {
1595 os_event_set(log.flusher_event);
1596 }
1597
1598 const auto first_slot =
1599 log_compute_write_event_slot(log, old_write_lsn + 1);
1600
1601 const auto last_slot = log_compute_write_event_slot(log, new_write_lsn);
1602
1603 if (first_slot == last_slot) {
1604 log_sync_point("log_write_before_users_notify");
1605 os_event_set(log.write_events[first_slot]);
1606 } else {
1607 log_sync_point("log_write_before_notifier_notify");
1608 os_event_set(log.write_notifier_event);
1609 }
1610 }
1611
1612 if (arch_log_sys && arch_log_sys->is_active()) {
1613 os_event_set(log_archiver_thread_event);
1614 }
1615 }
1616
1617 static inline void copy_to_write_ahead_buffer(log_t &log, const byte *buffer,
1618 size_t &size, lsn_t start_lsn) {
1619 ut_a(size <= srv_log_write_ahead_size);
1620
1621 ut_a(buffer >= log.buf);
1622 ut_a(buffer + size <= log.buf + log.buf_size);
1623
1624 byte *write_buf = log.write_ahead_buf;
1625
1626 log_sync_point("log_writer_before_copy_to_write_ahead_buffer");
1627
1628 std::memcpy(write_buf, buffer, size);
1629
1630 size_t completed_blocks_size;
1631 byte *incomplete_block;
1632 size_t incomplete_size;
1633
1634 completed_blocks_size = ut_uint64_align_down(size, OS_FILE_LOG_BLOCK_SIZE);
1635
1636 incomplete_block = write_buf + completed_blocks_size;
1637
1638 incomplete_size = size % OS_FILE_LOG_BLOCK_SIZE;
1639
1640 ut_a(incomplete_block + incomplete_size <=
1641 write_buf + srv_log_write_ahead_size);
1642
1643 if (incomplete_size != 0) {
1644 /* Prepare the incomplete (last) block. */
1645 ut_a(incomplete_size >= LOG_BLOCK_HDR_SIZE);
1646
1647 const lsn_t block_lsn = start_lsn + completed_blocks_size;
1648
1649 Log_data_block_header block_header;
1650 block_header.set_lsn(block_lsn);
1651 block_header.m_data_len = incomplete_size;
1652 block_header.m_first_rec_group =
1653 log_block_get_first_rec_group(incomplete_block);
1654 if (block_header.m_first_rec_group > incomplete_size) {
1655 block_header.m_first_rec_group = 0;
1656 }
1657 log_data_block_header_serialize(block_header, incomplete_block);
1658
1659 std::memset(incomplete_block + incomplete_size, 0x00,
1660 OS_FILE_LOG_BLOCK_SIZE - incomplete_size);
1661
1662 log_block_store_checksum(incomplete_block);
1663
1664 size = completed_blocks_size + OS_FILE_LOG_BLOCK_SIZE;
1665 }
1666
1667 /* Since now, size is about completed blocks always. */
1668 ut_a(size % OS_FILE_LOG_BLOCK_SIZE == 0);
1669 }
1670
1671 static inline size_t prepare_for_write_ahead(log_t &log,
1672 os_offset_t real_offset,
1673 size_t &write_size) {
1674 /* We need to perform write ahead during this write. */
1675
1676 const auto next_wa = compute_next_write_ahead_end(real_offset);
1677
1678 ut_a(real_offset + write_size <= next_wa);
1679
1680 size_t write_ahead =
1681 static_cast<size_t>(next_wa - (real_offset + write_size));
1682
1683 if (!current_file_has_space(log, real_offset, write_size + write_ahead)) {
1684 /* We must not write further than to the end
1685 of the current log file.
1686
1687 Note, that:log.m_current_file.m_size_in_bytes - LOG_FILE_HDR_SIZE
1688 does not have to be divisible by size of write ahead. For example:
1689 innodb_redo_log_capacity = 32M,
1690 innodb_log_write_ahead_size = 4KiB,
1691 LOG_FILE_HDR_SIZE is 2KiB. */
1692
1693 write_ahead = static_cast<size_t>(log.m_current_file.m_size_in_bytes -
1694 real_offset - write_size);
1695 }
1696
1697 ut_a(current_file_has_space(log, real_offset, write_size + write_ahead));
1698
1699 log_sync_point("log_writer_before_write_ahead");
1700
1701 std::memset(log.write_ahead_buf + write_size, 0x00, write_ahead);
1702
1703 write_size += write_ahead;
1704
1705 return write_ahead;
1706 }
1707
1708 static inline void update_current_write_ahead(log_t &log,
1709 os_offset_t real_offset,
1710 size_t write_size) {
1711 const auto end = real_offset + write_size;
1712
1713 if (end > log.write_ahead_end_offset) {
1714 log.write_ahead_end_offset =
1715 ut_uint64_align_down(end, srv_log_write_ahead_size);
1716 }
1717 }
1718
1719 } // namespace Log_files_write_impl
1720
1721 static dberr_t log_write_buffer(log_t &log, byte *buffer, size_t buffer_size,
1722 lsn_t start_lsn) {
1723 ut_ad(log_writer_mutex_own(log));
1724
1725 using namespace Log_files_write_impl;
1726
1727 validate_buffer(log, buffer, buffer_size);
1728
1729 validate_start_lsn(log, start_lsn, buffer_size);
1730
1731 const auto real_offset = log.m_current_file.offset(start_lsn);
1732
1733 bool write_from_log_buffer;
1734
1735 auto write_size = compute_how_much_to_write(log, real_offset, buffer_size,
1736 write_from_log_buffer);
1737
1738 if (write_size == 0) {
1739 return start_next_file(log, start_lsn);
1740 }
1741
1742 prepare_full_blocks(log, buffer, write_size, start_lsn);
1743
1744 byte *write_buf;
1745 os_offset_t written_ahead = 0;
1746 lsn_t lsn_advance = write_size;
1747
1748 if (write_from_log_buffer) {
1749 /* We have at least one completed log block to write.
1750 We write completed blocks from the log buffer. Note,
1751 that possibly we do not write all completed blocks,
1752 because of write-ahead strategy (described earlier). */
1753 DBUG_PRINT("ib_log",
1754 ("write from log buffer start_lsn=" LSN_PF " write_lsn=" LSN_PF
1755 " -> " LSN_PF,
1756 start_lsn, log.write_lsn.load(), start_lsn + lsn_advance));
1757
1758 write_buf = buffer;
1759
1760 log_sync_point("log_writer_before_write_from_log_buffer");
1761
1762 } else {
1763 DBUG_PRINT("ib_log",
1764 ("incomplete write start_lsn=" LSN_PF " write_lsn=" LSN_PF
1765 " -> " LSN_PF,
1766 start_lsn, log.write_lsn.load(), start_lsn + lsn_advance));
1767
1768 #ifdef UNIV_DEBUG
1769 if (start_lsn == log.write_lsn.load()) {
1770 log_sync_point("log_writer_before_write_new_incomplete_block");
1771 }
1772 /* Else: we are doing yet another incomplete block write within the
1773 same block as the one in which we did the previous write. */
1774 #endif /* UNIV_DEBUG */
1775
1776 write_buf = log.write_ahead_buf;
1777
1778 /* We write all the data directly from the write-ahead buffer,
1779 where we first need to copy the data. */
1780 copy_to_write_ahead_buffer(log, buffer, write_size, start_lsn);
1781
1782 if (!current_write_ahead_enough(log, real_offset, 1)) {
1783 written_ahead = prepare_for_write_ahead(log, real_offset, write_size);
1784 }
1785 }
1786
1787 srv_stats.os_log_pending_writes.inc();
1788
1789 /* Now, we know, that we are going to write completed
1790 blocks only (originally or copied and completed). */
1791 const dberr_t err = write_blocks(log, write_buf, write_size, real_offset);
1792 if (UNIV_UNLIKELY(err != DB_SUCCESS)) {
1793 return err;
1794 }
1795
1796 log_sync_point("log_writer_before_lsn_update");
1797
1798 const lsn_t old_write_lsn = log.write_lsn.load();
1799
1800 const lsn_t new_write_lsn = start_lsn + lsn_advance;
1801 ut_a(new_write_lsn > log.write_lsn.load());
1802
1803 log.write_lsn.store(new_write_lsn);
1804
1805 notify_about_advanced_write_lsn(log, old_write_lsn, new_write_lsn);
1806
1807 log_sync_point("log_writer_before_buf_limit_update");
1808
1809 log_update_buf_limit(log, new_write_lsn);
1810
1811 srv_stats.os_log_pending_writes.dec();
1812 srv_stats.log_writes.inc();
1813
1814 /* Write ahead is included in write_size. */
1815 ut_a(write_size >= written_ahead);
1816 srv_stats.os_log_written.add(write_size - written_ahead);
1817 MONITOR_INC_VALUE(MONITOR_LOG_PADDED, written_ahead);
1818
1819 int64_t free_space = log.m_capacity.soft_logical_capacity();
1820
1821 /* The free space may be negative (up to -extra_margin),
1822 in which case we are in the emergency mode, eating the
1823 extra margin and asking to pause next user threads. */
1824 free_space -= new_write_lsn - log.last_checkpoint_lsn.load();
1825
1826 MONITOR_SET(MONITOR_LOG_FREE_SPACE, free_space);
1827
1828 log.n_log_ios++;
1829
1830 update_current_write_ahead(log, real_offset, write_size);
1831
1832 return DB_SUCCESS;
1833 }
1834
1835 static void log_writer_enter_extra_margin(log_t &log) {
1836 ut_ad(log_writer_mutex_own(log));
1837 ut_ad(!log.m_writer_inside_extra_margin);
1838 log_limits_mutex_enter(log);
1839 log.m_writer_inside_extra_margin = true;
1840 ib::warn(ER_IB_MSG_LOG_WRITER_ENTERED_EXTRA_MARGIN);
1841 log_limits_mutex_exit(log);
1842 log_sync_point("log_writer_entered_extra_margin");
1843 }
1844
1845 static void log_writer_exit_extra_margin(log_t &log) {
1846 ut_ad(log_writer_mutex_own(log));
1847 ut_ad(log.m_writer_inside_extra_margin);
1848 log_limits_mutex_enter(log);
1849 log.m_writer_inside_extra_margin = false;
1850 ib::info(ER_IB_MSG_LOG_WRITER_EXITED_EXTRA_MARGIN);
1851 log_limits_mutex_exit(log);
1852 log_sync_point("log_writer_exited_extra_margin");
1853 }
1854
1855 static inline bool log_writer_extra_margin_check(log_t &log,
1856 lsn_t checkpoint_lsn,
1857 lsn_t next_write_lsn) {
1858 ut_ad(log_writer_mutex_own(log));
1859
1860 const lsn_t soft_limited_lsn =
1861 ut_uint64_align_down(checkpoint_lsn, OS_FILE_LOG_BLOCK_SIZE) +
1862 log.m_capacity.soft_logical_capacity();
1863
1864 if (next_write_lsn <= soft_limited_lsn) {
1865 if (log.m_writer_inside_extra_margin) {
1866 log_writer_exit_extra_margin(log);
1867 }
1868 return false;
1869 } else {
1870 if (!log.m_writer_inside_extra_margin) {
1871 log_writer_enter_extra_margin(log);
1872 }
1873 return true;
1874 }
1875 }
1876
1877 void log_writer_check_if_exited_extra_margin(log_t &log) {
1878 ut_ad(log_writer_mutex_own(log));
1879 ut_ad(log.m_writer_inside_extra_margin);
1880
1881 const lsn_t checkpoint_lsn = log_get_checkpoint_lsn(log);
1882
1883 /* Choose an option which minimizes the possibility that the current
1884 value of log.m_writer_inside_extra_margin changes. That's to avoid
1885 flipping when doing changes opposite to changes performed by the log
1886 writer thread, which knows what is the exact value of next_write_lsn
1887 in log_writer_wait_on_checkpoint (as opposed to log_checkpointer,
1888 which does not know when advancing checkpoint). This function exists
1889 and is exported, because the log_checkpointer thread needs to update
1890 the log.m_writer_inside_extra_margin when it advances checkpoint_lsn
1891 if the log_writer is idle (because has nothing more to write). */
1892
1893 log_writer_extra_margin_check(log, checkpoint_lsn, log_get_lsn(log));
1894 }
1895
1896 static inline std::pair<lsn_t, bool> log_writer_wait_on_checkpoint_optimistic(
1897 log_t &log, lsn_t last_write_lsn, lsn_t next_write_lsn) {
1898 ut_ad(log_writer_mutex_own(log));
1899
1900 const lsn_t checkpoint_lsn = log.last_checkpoint_lsn.load();
1901
1902 const lsn_t hard_limited_lsn =
1903 ut_uint64_align_down(checkpoint_lsn, OS_FILE_LOG_BLOCK_SIZE) +
1904 log.m_capacity.hard_logical_capacity();
1905
1906 ut_a(last_write_lsn <= hard_limited_lsn);
1907 ut_a(checkpoint_lsn < next_write_lsn);
1908
1909 return {hard_limited_lsn,
1910 !log_writer_extra_margin_check(log, checkpoint_lsn, next_write_lsn)};
1911 }
1912
1913 static lsn_t log_writer_wait_on_checkpoint_pessimistic(log_t &log,
1914 lsn_t last_write_lsn,
1915 lsn_t next_write_lsn) {
1916 ut_ad(log_writer_mutex_own(log));
1917
1918 auto missing_space_started = Log_clock::now();
1919
1920 while (true) {
1921 const int64_t next_checkpoint_sig_count =
1922 os_event_reset(log.next_checkpoint_event);
1923
1924 const lsn_t checkpoint_lsn = log.last_checkpoint_lsn.load();
1925
1926 auto [hard_limited_lsn, write_allowed] =
1927 log_writer_wait_on_checkpoint_optimistic(log, last_write_lsn,
1928 next_write_lsn);
1929
1930 if (write_allowed) {
1931 return hard_limited_lsn;
1932 }
1933
1934 os_event_set(log.checkpointer_event);
1935
1936 if (last_write_lsn + OS_FILE_LOG_BLOCK_SIZE <= hard_limited_lsn) {
1937 /* Write what we have - adjust the speed to speed of checkpoints
1938 going forward (to speed of page-cleaners). */
1939 return hard_limited_lsn;
1940 }
1941
1942 if (!log.writer_threads_paused.load(std::memory_order_acquire)) {
1943 log_advance_ready_for_write_lsn(log);
1944 }
1945
1946 if (Log_clock::now() - missing_space_started >= std::chrono::seconds(5)) {
1947 /* We could not reclaim even single redo block for 5sec */
1948 ib::error(ER_IB_MSG_LOG_WRITER_OUT_OF_SPACE, ulonglong{checkpoint_lsn});
1949 missing_space_started = Log_clock::now();
1950 log_sync_point("log_writer_ran_out_space");
1951 }
1952
1953 log_writer_mutex_exit(log);
1954
1955 if (!log.m_allow_checkpoints.load()) {
1956 if (srv_force_recovery < 4) {
1957 ib::fatal(UT_LOCATION_HERE,
1958 ER_IB_MSG_RECOVERY_NO_SPACE_IN_REDO_LOG__SKIP_IBUF_MERGES);
1959 } else {
1960 ib::fatal(UT_LOCATION_HERE,
1961 ER_IB_MSG_RECOVERY_NO_SPACE_IN_REDO_LOG__UNEXPECTED);
1962 }
1963 }
1964
1965 /* We don't want to ask for sync checkpoint, because it
1966 is possible, that the oldest dirty page is latched and
1967 user thread, which keeps the latch, is waiting for space
1968 in log buffer (for log_writer writing to disk). In such
1969 case it would be deadlock (we can't flush the latched
1970 page and advance the checkpoint). We only ask for the
1971 checkpoint, and wait for some time. */
1972 log_request_checkpoint(log, false);
1973
1974 os_event_wait_time_low(log.next_checkpoint_event,
1975 std::chrono::microseconds(100),
1976 next_checkpoint_sig_count);
1977
1978 MONITOR_INC(MONITOR_LOG_WRITER_ON_FREE_SPACE_WAITS);
1979
1980 log_writer_mutex_enter(log);
1981 }
1982 }
1983
1984 static lsn_t log_writer_wait_on_checkpoint(log_t &log, lsn_t last_write_lsn,
1985 lsn_t next_write_lsn) {
1986 auto [hard_limited_lsn, write_allowed] =
1987 log_writer_wait_on_checkpoint_optimistic(log, last_write_lsn,
1988 next_write_lsn);
1989 if (write_allowed) {
1990 return hard_limited_lsn;
1991 }
1992 return log_writer_wait_on_checkpoint_pessimistic(log, last_write_lsn,
1993 next_write_lsn);
1994 }
1995
1996 static void log_writer_wait_on_archiver(log_t &log, lsn_t next_write_lsn) {
1997 const int32_t SLEEP_BETWEEN_RETRIES_IN_US = 100; /* 100us */
1998
1999 const int32_t TIME_BETWEEN_WARNINGS_IN_US = 100000; /* 100ms */
2000
2001 const int32_t TIME_UNTIL_ERROR_IN_US = 1000000; /* 1s */
2002
2003 ut_ad(log_writer_mutex_own(log));
2004
2005 int32_t count = 0;
2006
2007 while (arch_log_sys != nullptr && arch_log_sys->is_active()) {
2008 lsn_t archiver_lsn = arch_log_sys->get_archived_lsn();
2009
2010 archiver_lsn = ut_uint64_align_down(archiver_lsn, OS_FILE_LOG_BLOCK_SIZE);
2011
2012 const lsn_t archiver_limited_lsn =
2013 archiver_lsn + log.m_capacity.hard_logical_capacity();
2014
2015 ut_a(next_write_lsn > archiver_lsn);
2016
2017 if (next_write_lsn <= archiver_limited_lsn) {
2018 /* Between archive_lsn and next_write_lsn there is less bytes than
2019 logical capacity provided by the redo log. There is no need to wait
2020 for the archiver. */
2021 break;
2022 }
2023
2024 if (!log.writer_threads_paused.load(std::memory_order_acquire)) {
2025 log_advance_ready_for_write_lsn(log);
2026 }
2027
2028 const int32_t ATTEMPTS_UNTIL_ERROR =
2029 TIME_UNTIL_ERROR_IN_US / SLEEP_BETWEEN_RETRIES_IN_US;
2030
2031 if (count >= ATTEMPTS_UNTIL_ERROR) {
2032 log_writer_mutex_exit(log);
2033
2034 arch_log_sys->force_abort();
2035
2036 const lsn_t lag = next_write_lsn - archiver_limited_lsn;
2037
2038 ib::error(ER_IB_MSG_LOG_WRITER_ABORTS_LOG_ARCHIVER, ulonglong{lag},
2039 ulonglong{archiver_lsn});
2040
2041 log_writer_mutex_enter(log);
2042 break;
2043 }
2044
2045 os_event_set(log_archiver_thread_event);
2046
2047 log_writer_mutex_exit(log);
2048
2049 const int32_t ATTEMPTS_BETWEEN_WARNINGS =
2050 TIME_BETWEEN_WARNINGS_IN_US / SLEEP_BETWEEN_RETRIES_IN_US;
2051
2052 if (count % ATTEMPTS_BETWEEN_WARNINGS == 0) {
2053 const lsn_t lag = next_write_lsn - archiver_limited_lsn;
2054
2055 ib::warn(ER_IB_MSG_LOG_WRITER_WAITING_FOR_ARCHIVER, ulonglong{lag},
2056 ulonglong{archiver_lsn});
2057 }
2058
2059 count++;
2060 std::this_thread::sleep_for(
2061 std::chrono::microseconds(SLEEP_BETWEEN_RETRIES_IN_US));
2062
2063 MONITOR_INC(MONITOR_LOG_WRITER_ON_ARCHIVER_WAITS);
2064
2065 log_writer_mutex_enter(log);
2066 }
2067 }
2068
2069 static void log_writer_wait_on_consumers(log_t &log, lsn_t next_write_lsn) {
2070 ut_ad(log_writer_mutex_own(log));
2071 constexpr auto SLEEP_BETWEEN_RETRIES = std::chrono::milliseconds(10);
2072 constexpr auto TIME_BETWEEN_WARNINGS = std::chrono::seconds(1);
2073 constexpr size_t ATTEMPTS_BETWEEN_WARNINGS =
2074 TIME_BETWEEN_WARNINGS / SLEEP_BETWEEN_RETRIES;
2075 size_t attempt = 0;
2076 while (log.m_oldest_need_lsn_lowerbound +
2077 log.m_capacity.hard_logical_capacity() <
2078 next_write_lsn) {
2079 log_files_mutex_enter(*log_sys);
2080 lsn_t oldest_needed_lsn;
2081 const auto consumer = log_consumer_get_oldest(log, oldest_needed_lsn);
2082 ut_ad(log.m_oldest_need_lsn_lowerbound <= oldest_needed_lsn);
2083 log.m_oldest_need_lsn_lowerbound = oldest_needed_lsn;
2084 if (next_write_lsn <=
2085 oldest_needed_lsn + log.m_capacity.hard_logical_capacity()) {
2086 log_files_mutex_exit(*log_sys);
2087 break;
2088 }
2089 const std::string name = consumer->get_name();
2090 log_files_mutex_exit(*log_sys);
2091 /* This should not be a checkpointer nor archiver, as we've used dedicated
2092 log_writer_wait_on_checkpoint() and log_writer_wait_on_archiver() to wait
2093 for them already */
2094 ut_ad(name == "MEB");
2095 log_writer_mutex_exit(log);
2096 if (attempt++ % ATTEMPTS_BETWEEN_WARNINGS == 0) {
2097 ib::log_warn(ER_IB_MSG_LOG_WRITER_WAIT_ON_CONSUMER, name.c_str(),
2098 ulonglong{oldest_needed_lsn});
2099 }
2100 std::this_thread::sleep_for(SLEEP_BETWEEN_RETRIES);
2101 log_writer_mutex_enter(log);
2102 }
2103 }
2104 static void log_writer_write_failed(log_t &log, dberr_t err) {
2105 ut_ad(log_writer_mutex_own(log));
2106 ut_ad(!log_files_mutex_own(log));
2107 const auto file_path =
2108 log_file_path(log.m_files_ctx, log.m_current_file.m_id);
2109 switch (err) {
2110 case DB_OUT_OF_DISK_SPACE: {
2111 ib::warn(ER_IB_MSG_LOG_WRITER_WAIT_ON_NEW_LOG_FILE_INFO,
2112 srv_redo_log_capacity, srv_redo_log_capacity_used);
2113 log_writer_mutex_exit(log);
2114 log_files_wait_for_next_file_available(log);
2115 log_writer_mutex_enter(log);
2116 break;
2117 }
2118 default:
2119 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_LOG_WRITER_WRITE_FAILED,
2120 static_cast<int>(err), file_path.c_str());
2121 }
2122 }
2123
2124 static void log_writer_write_buffer(log_t &log, lsn_t next_write_lsn) {
2125 ut_ad(log_writer_mutex_own(log));
2126
2127 log_sync_point("log_writer_write_begin");
2128
2129 const lsn_t last_write_lsn = log.write_lsn.load();
2130
2131 ut_a(log_is_data_lsn(last_write_lsn) ||
2132 last_write_lsn % OS_FILE_LOG_BLOCK_SIZE == 0);
2133
2134 ut_a(log_is_data_lsn(next_write_lsn) ||
2135 next_write_lsn % OS_FILE_LOG_BLOCK_SIZE == 0);
2136
2137 ut_a(next_write_lsn - last_write_lsn <= log.buf_size);
2138 ut_a(next_write_lsn > last_write_lsn);
2139
2140 size_t start_offset = last_write_lsn % log.buf_size;
2141 size_t end_offset = next_write_lsn % log.buf_size;
2142
2143 if (start_offset >= end_offset) {
2144 ut_a(next_write_lsn - last_write_lsn >= log.buf_size - start_offset);
2145
2146 end_offset = log.buf_size;
2147 next_write_lsn = last_write_lsn + (end_offset - start_offset);
2148 }
2149 ut_a(start_offset < end_offset);
2150
2151 ut_a(end_offset % OS_FILE_LOG_BLOCK_SIZE == 0 ||
2152 end_offset % OS_FILE_LOG_BLOCK_SIZE >= LOG_BLOCK_HDR_SIZE);
2153
2154 /* Wait until there is free space in log files.*/
2155
2156 const lsn_t checkpoint_limited_lsn =
2157 log_writer_wait_on_checkpoint(log, last_write_lsn, next_write_lsn);
2158
2159 ut_ad(log_writer_mutex_own(log));
2160 ut_a(checkpoint_limited_lsn > last_write_lsn);
2161
2162 log_sync_point("log_writer_after_checkpoint_check");
2163
2164 if (arch_log_sys != nullptr) {
2165 log_writer_wait_on_archiver(log, next_write_lsn);
2166 }
2167
2168 ut_ad(log_writer_mutex_own(log));
2169
2170 log_sync_point("log_writer_after_archiver_check");
2171
2172 const lsn_t limit_for_next_write_lsn = checkpoint_limited_lsn;
2173
2174 if (limit_for_next_write_lsn < next_write_lsn) {
2175 end_offset -= next_write_lsn - limit_for_next_write_lsn;
2176 next_write_lsn = limit_for_next_write_lsn;
2177
2178 ut_a(end_offset > start_offset);
2179 ut_a(end_offset % OS_FILE_LOG_BLOCK_SIZE == 0 ||
2180 end_offset % OS_FILE_LOG_BLOCK_SIZE >= LOG_BLOCK_HDR_SIZE);
2181
2182 ut_a(log_is_data_lsn(next_write_lsn) ||
2183 next_write_lsn % OS_FILE_LOG_BLOCK_SIZE == 0);
2184 }
2185
2186 log_writer_wait_on_consumers(log, next_write_lsn);
2187 ut_ad(log_writer_mutex_own(log));
2188 /* We do hold the log->writer_mutex now, but log_writer_wait_on_checkpoint(),
2189 log_writer_wait_on_archiver(), or log_writer_wait_on_consumers() could have
2190 released it for a moment. So, in case --innodb_log_writer_threads=OFF, another
2191 thread could have already performed a write to the redo log, in which case we
2192 should not even try to (over)write it again. In extreme case, the log buffer
2193 already contains a different range of lsns, we might have moved to another
2194 file, or even removed the old one, etc. If we detect that any write has
2195 happened, we let the caller retry.*/
2196 if (last_write_lsn != log.write_lsn.load()) {
2197 return;
2198 }
2199
2200 DBUG_PRINT("ib_log",
2201 ("write " LSN_PF " to " LSN_PF, last_write_lsn, next_write_lsn));
2202
2203 byte *buf_begin =
2204 log.buf + ut_uint64_align_down(start_offset, OS_FILE_LOG_BLOCK_SIZE);
2205
2206 byte *buf_end = log.buf + end_offset;
2207
2208 /* Do the write to the log files */
2209
2210 const dberr_t err = log_write_buffer(
2211 log, buf_begin, buf_end - buf_begin,
2212 ut_uint64_align_down(last_write_lsn, OS_FILE_LOG_BLOCK_SIZE));
2213
2214 if (UNIV_UNLIKELY(err != DB_SUCCESS)) {
2215 ut_a(log.write_lsn.load() == last_write_lsn);
2216 log_writer_write_failed(log, err);
2217 }
2218
2219 log_sync_point("log_writer_write_end");
2220 }
2221
2222 static bool log_writer_is_allowed_to_stop(log_t &log) {
2223 ut_ad(log_writer_mutex_own(log));
2224 log_writer_mutex_exit(log);
2225 log_files_dummy_records_disable(log);
2226 log_writer_mutex_enter(log);
2227
2228 /* When log threads are stopped, we must first
2229 ensure that all writes to log buffer have been
2230 finished and only then we are allowed to set
2231 the should_stop_threads to true. */
2232
2233 log_advance_ready_for_write_lsn(log);
2234
2235 return log.write_lsn.load() == log_buffer_ready_for_write_lsn(log);
2236 }
2237
2238 void log_writer(log_t *log_ptr) {
2239 ut_a(log_ptr != nullptr);
2240
2241 log_t &log = *log_ptr;
2242 lsn_t ready_lsn = 0;
2243
2244 ut_d(log.m_writer_thd = create_internal_thd());
2245
2246 log_writer_mutex_enter(log);
2247
2248 Log_thread_waiting waiting{log, log.writer_event, srv_log_writer_spin_delay,
2249 get_srv_log_writer_timeout()};
2250
2251 Log_write_to_file_requests_monitor write_to_file_requests_monitor{log};
2252
2253 for (uint64_t step = 0;; ++step) {
2254 bool released = false;
2255
2256 auto stop_condition = [&ready_lsn, &log, &released,
2257 &write_to_file_requests_monitor](bool wait) {
2258 if (released) {
2259 log_writer_mutex_enter(log);
2260 released = false;
2261 }
2262
2263 /* Advance lsn up to which data is ready in log buffer. */
2264 log_advance_ready_for_write_lsn(log);
2265
2266 ready_lsn = log_buffer_ready_for_write_lsn(log);
2267
2268 /* Wait until any of following conditions holds:
2269 1) There is some unwritten data in log buffer
2270 2) We should close threads. */
2271
2272 if (log.write_lsn.load() < ready_lsn || log.should_stop_threads.load()) {
2273 return true;
2274 }
2275
2276 if (UNIV_UNLIKELY(
2277 log.writer_threads_paused.load(std::memory_order_acquire))) {
2278 return true;
2279 }
2280
2281 if (wait) {
2282 write_to_file_requests_monitor.update();
2283 log_writer_mutex_exit(log);
2284 released = true;
2285 }
2286
2287 return false;
2288 };
2289
2290 const auto wait_stats = waiting.wait(stop_condition);
2291
2292 MONITOR_INC_WAIT_STATS(MONITOR_LOG_WRITER_, wait_stats);
2293
2294 if (UNIV_UNLIKELY(
2295 log.writer_threads_paused.load(std::memory_order_acquire) &&
2296 !log.should_stop_threads.load())) {
2297 log_writer_mutex_exit(log);
2298
2299 os_event_wait(log.writer_threads_resume_event);
2300
2301 log_writer_mutex_enter(log);
2302 ready_lsn = log_buffer_ready_for_write_lsn(log);
2303 }
2304
2305 /* Do the actual work. */
2306 if (log.write_lsn.load() < ready_lsn) {
2307 log_writer_write_buffer(log, ready_lsn);
2308
2309 if (step % 1024 == 0) {
2310 write_to_file_requests_monitor.update();
2311
2312 log_writer_mutex_exit(log);
2313
2314 std::this_thread::yield();
2315
2316 log_writer_mutex_enter(log);
2317 }
2318
2319 } else if (log.should_stop_threads.load() &&
2320 log_writer_is_allowed_to_stop(log)) {
2321 break;
2322 }
2323 }
2324
2325 log_writer_mutex_exit(log);
2326
2327 ut_d(destroy_internal_thd(log.m_writer_thd));
2328 }
2329
2330 /** @} */
2331
2332 /**************************************************/ /**
2333
2334 @name Log flusher thread
2335
2336 *******************************************************/
2337
2338 /** @{ */
2339
2340 static void log_flush_update_stats(log_t &log) {
2341 ut_ad(log_flusher_mutex_own(log));
2342
2343 /* Note that this code is inspired by similar logic in buf0flu.cc */
2344
2345 static uint64_t iterations = 0;
2346 static Log_clock_point prev_time{};
2347 static lsn_t prev_lsn;
2348 static lsn_t lsn_avg_rate = 0;
2349 static Log_clock::duration fsync_max_time;
2350 static Log_clock::duration fsync_total_time;
2351
2352 /* Calculate time of last fsync and update related counters. */
2353
2354 Log_clock::duration fsync_time;
2355
2356 fsync_time = log.last_flush_end_time - log.last_flush_start_time;
2357
2358 fsync_max_time = std::max(fsync_max_time, fsync_time);
2359
2360 if (fsync_time.count() > 0) {
2361 fsync_total_time += fsync_time;
2362
2363 MONITOR_INC_VALUE(
2364 MONITOR_LOG_FLUSH_TOTAL_TIME,
2365 std::chrono::duration_cast<std::chrono::milliseconds>(fsync_time)
2366 .count());
2367 }
2368
2369 /* Calculate time elapsed since start of last sample. */
2370
2371 if (prev_time == Log_clock_point{}) {
2372 prev_time = log.last_flush_start_time;
2373 prev_lsn = log.flushed_to_disk_lsn.load();
2374 }
2375
2376 const Log_clock_point curr_time = log.last_flush_end_time;
2377
2378 if (curr_time < prev_time) {
2379 /* Time was moved backward since we set prev_time.
2380 We cannot determine how much time passed since then. */
2381 prev_time = curr_time;
2382 }
2383
2384 auto time_elapsed =
2385 std::chrono::duration_cast<std::chrono::seconds>(curr_time - prev_time)
2386 .count();
2387
2388 ut_a(time_elapsed >= 0);
2389
2390 if (++iterations >= srv_flushing_avg_loops ||
2391 time_elapsed >= static_cast<double>(srv_flushing_avg_loops)) {
2392 if (time_elapsed < 1) {
2393 time_elapsed = 1;
2394 }
2395
2396 const lsn_t curr_lsn = log.flushed_to_disk_lsn.load();
2397
2398 const lsn_t lsn_rate = static_cast<lsn_t>(
2399 static_cast<double>(curr_lsn - prev_lsn) / time_elapsed);
2400
2401 lsn_avg_rate = (lsn_avg_rate + lsn_rate) / 2;
2402
2403 MONITOR_SET(MONITOR_LOG_FLUSH_LSN_AVG_RATE, lsn_avg_rate);
2404
2405 MONITOR_SET(
2406 MONITOR_LOG_FLUSH_MAX_TIME,
2407 std::chrono::duration_cast<std::chrono::microseconds>(fsync_max_time)
2408 .count());
2409
2410 log.flush_avg_time =
2411 std::chrono::duration_cast<std::chrono::microseconds>(fsync_total_time)
2412 .count() *
2413 1.0 / iterations;
2414
2415 MONITOR_SET(MONITOR_LOG_FLUSH_AVG_TIME, log.flush_avg_time);
2416
2417 fsync_max_time = Log_clock::duration{};
2418 fsync_total_time = Log_clock::duration{};
2419 iterations = 0;
2420 prev_time = curr_time;
2421 prev_lsn = curr_lsn;
2422 }
2423 }
2424
2425 uint64_t log_total_flushes() { return Log_file_handle::total_fsyncs(); }
2426
2427 uint64_t log_pending_flushes() { return Log_file_handle::fsyncs_in_progress(); }
2428
2429 static void log_flush_low(log_t &log) {
2430 ut_ad(log_flusher_mutex_own(log));
2431
2432 #ifndef _WIN32
2433 bool do_flush = srv_unix_file_flush_method != SRV_UNIX_O_DSYNC;
2434 #else
2435 bool do_flush = true;
2436 #endif
2437
2438 if (!log.writer_threads_paused.load(std::memory_order_acquire)) {
2439 os_event_reset(log.flusher_event);
2440 }
2441
2442 const lsn_t last_flush_lsn = log.flushed_to_disk_lsn.load();
2443
2444 const lsn_t flush_up_to_lsn = log.write_lsn.load();
2445
2446 if (flush_up_to_lsn == last_flush_lsn) {
2447 os_event_set(log.old_flush_event);
2448 return;
2449 }
2450
2451 log.last_flush_start_time = Log_clock::now();
2452
2453 ut_a(flush_up_to_lsn > last_flush_lsn);
2454
2455 if (do_flush) {
2456 log_sync_point("log_flush_before_fsync");
2457 log.m_current_file_handle.fsync();
2458 }
2459
2460 log.last_flush_end_time = Log_clock::now();
2461
2462 if (log.last_flush_end_time < log.last_flush_start_time) {
2463 /* Time was moved backward after we set start_time.
2464 Let assume that the fsync operation was instant.
2465
2466 We move start_time backward, because we don't want
2467 it to remain in the future. */
2468 log.last_flush_start_time = log.last_flush_end_time;
2469 }
2470
2471 log_sync_point("log_flush_before_flushed_to_disk_lsn");
2472
2473 log.flushed_to_disk_lsn.store(flush_up_to_lsn);
2474
2475 /* Notify other thread(s). */
2476
2477 DBUG_PRINT("ib_log", ("Flushed to disk up to " LSN_PF, flush_up_to_lsn));
2478
2479 if (!log.writer_threads_paused.load(std::memory_order_acquire)) {
2480 const auto first_slot =
2481 log_compute_flush_event_slot(log, last_flush_lsn + 1);
2482
2483 const auto last_slot = log_compute_flush_event_slot(log, flush_up_to_lsn);
2484
2485 if (first_slot == last_slot) {
2486 log_sync_point("log_flush_before_users_notify");
2487 os_event_set(log.flush_events[first_slot]);
2488 } else {
2489 log_sync_point("log_flush_before_notifier_notify");
2490 os_event_set(log.flush_notifier_event);
2491 }
2492 } else {
2493 log_sync_point("log_flush_before_users_notify");
2494 log_sync_point("log_flush_before_notifier_notify");
2495 os_event_set(log.old_flush_event);
2496 }
2497
2498 /* Update stats. */
2499
2500 log_flush_update_stats(log);
2501 }
2502
2503 void log_flusher(log_t *log_ptr) {
2504 ut_a(log_ptr != nullptr);
2505
2506 log_t &log = *log_ptr;
2507
2508 Log_thread_waiting waiting{log, log.flusher_event, srv_log_flusher_spin_delay,
2509 get_srv_log_flusher_timeout()};
2510
2511 log_flusher_mutex_enter(log);
2512
2513 for (uint64_t step = 0;; ++step) {
2514 if (log.should_stop_threads.load()) {
2515 if (!log_writer_is_active()) {
2516 /* If write_lsn > flushed_to_disk_lsn, we are going to execute
2517 one more fsync just after the for-loop and before this thread
2518 exits (inside log_flush_low at the very end of function def.). */
2519 break;
2520 }
2521 }
2522
2523 if (UNIV_UNLIKELY(
2524 log.writer_threads_paused.load(std::memory_order_acquire))) {
2525 log_flusher_mutex_exit(log);
2526
2527 os_event_wait(log.writer_threads_resume_event);
2528
2529 log_flusher_mutex_enter(log);
2530 }
2531
2532 bool released = false;
2533
2534 auto stop_condition = [&log, &released, step](bool wait) {
2535 if (released) {
2536 log_flusher_mutex_enter(log);
2537 released = false;
2538 }
2539
2540 log_sync_point("log_flusher_before_should_flush");
2541
2542 const lsn_t last_flush_lsn = log.flushed_to_disk_lsn.load();
2543
2544 ut_a(last_flush_lsn <= log.write_lsn.load());
2545
2546 if (last_flush_lsn < log.write_lsn.load()) {
2547 /* Flush and stop waiting. */
2548 log_flush_low(log);
2549
2550 if (step % 1024 == 0) {
2551 log_flusher_mutex_exit(log);
2552
2553 std::this_thread::yield();
2554
2555 log_flusher_mutex_enter(log);
2556 }
2557
2558 return true;
2559 }
2560
2561 /* Stop waiting if writer thread is dead. */
2562 if (log.should_stop_threads.load()) {
2563 if (!log_writer_is_active()) {
2564 return true;
2565 }
2566 }
2567
2568 if (UNIV_UNLIKELY(
2569 log.writer_threads_paused.load(std::memory_order_acquire))) {
2570 return true;
2571 }
2572
2573 if (wait) {
2574 log_flusher_mutex_exit(log);
2575 released = true;
2576 }
2577
2578 return false;
2579 };
2580
2581 if (srv_flush_log_at_trx_commit != 1) {
2582 const auto current_time = Log_clock::now();
2583
2584 ut_ad(log.last_flush_end_time >= log.last_flush_start_time);
2585
2586 if (current_time < log.last_flush_end_time) {
2587 /* Time was moved backward, possibly by a lot, so we need to
2588 adjust the last_flush times, because otherwise we could stop
2589 flushing every innodb_flush_log_at_timeout for a while. */
2590 log.last_flush_start_time = current_time;
2591 log.last_flush_end_time = current_time;
2592 }
2593
2594 const auto time_elapsed =
2595 std::chrono::duration_cast<std::chrono::milliseconds>(
2596 current_time - log.last_flush_start_time);
2597
2598 ut_a(time_elapsed >= std::chrono::seconds::zero());
2599
2600 const auto flush_every = get_srv_flush_log_at_timeout();
2601
2602 if (time_elapsed < flush_every) {
2603 log_flusher_mutex_exit(log);
2604
2605 /* When we are asked to stop threads, do not respect the limit
2606 for flushes per second. */
2607 if (!log.should_stop_threads.load()) {
2608 os_event_wait_time_low(log.flusher_event, flush_every - time_elapsed,
2609 0);
2610 }
2611
2612 log_flusher_mutex_enter(log);
2613 }
2614 }
2615
2616 const auto wait_stats = waiting.wait(stop_condition);
2617
2618 MONITOR_INC_WAIT_STATS(MONITOR_LOG_FLUSHER_, wait_stats);
2619 }
2620
2621 if (log.write_lsn.load() > log.flushed_to_disk_lsn.load()) {
2622 log_flush_low(log);
2623 }
2624
2625 ut_a(log.write_lsn.load() == log.flushed_to_disk_lsn.load());
2626
2627 log_flusher_mutex_exit(log);
2628 }
2629
2630 /** @} */
2631
2632 /**************************************************/ /**
2633
2634 @name Log write_notifier thread
2635
2636 *******************************************************/
2637
2638 /** @{ */
2639
2640 void log_write_notifier(log_t *log_ptr) {
2641 ut_a(log_ptr != nullptr);
2642
2643 log_t &log = *log_ptr;
2644 lsn_t lsn = log.write_lsn.load() + 1;
2645
2646 log_write_notifier_mutex_enter(log);
2647
2648 Log_thread_waiting waiting{log, log.write_notifier_event,
2649 srv_log_write_notifier_spin_delay,
2650 get_srv_log_write_notifier_timeout()};
2651
2652 for (uint64_t step = 0;; ++step) {
2653 if (log.should_stop_threads.load()) {
2654 if (!log_writer_is_active()) {
2655 if (lsn > log.write_lsn.load()) {
2656 ut_a(lsn == log.write_lsn.load() + 1);
2657 break;
2658 }
2659 }
2660 }
2661
2662 if (UNIV_UNLIKELY(
2663 log.writer_threads_paused.load(std::memory_order_acquire))) {
2664 ut_ad(log.write_notifier_resume_lsn.load(std::memory_order_acquire) == 0);
2665 log_write_notifier_mutex_exit(log);
2666
2667 /* set to acknowledge */
2668 log.write_notifier_resume_lsn.store(lsn, std::memory_order_release);
2669
2670 os_event_wait(log.writer_threads_resume_event);
2671 ut_ad(log.write_notifier_resume_lsn.load(std::memory_order_acquire) + 1 >=
2672 lsn);
2673 lsn = log.write_notifier_resume_lsn.load(std::memory_order_acquire) + 1;
2674 /* clears to acknowledge */
2675 log.write_notifier_resume_lsn.store(0, std::memory_order_release);
2676
2677 log_write_notifier_mutex_enter(log);
2678 }
2679
2680 log_sync_point("log_write_notifier_before_check");
2681
2682 bool released = false;
2683
2684 auto stop_condition = [&log, lsn, &released](bool wait) {
2685 log_sync_point("log_write_notifier_after_event_reset");
2686 if (released) {
2687 log_write_notifier_mutex_enter(log);
2688 released = false;
2689 }
2690
2691 log_sync_point("log_write_notifier_before_check");
2692
2693 if (log.write_lsn.load() >= lsn) {
2694 return true;
2695 }
2696
2697 if (log.should_stop_threads.load()) {
2698 if (!log_writer_is_active()) {
2699 return true;
2700 }
2701 }
2702
2703 if (UNIV_UNLIKELY(
2704 log.writer_threads_paused.load(std::memory_order_acquire))) {
2705 return true;
2706 }
2707
2708 if (wait) {
2709 log_write_notifier_mutex_exit(log);
2710 released = true;
2711 }
2712 log_sync_point("log_write_notifier_before_wait");
2713
2714 return false;
2715 };
2716
2717 const auto wait_stats = waiting.wait(stop_condition);
2718
2719 MONITOR_INC_WAIT_STATS(MONITOR_LOG_WRITE_NOTIFIER_, wait_stats);
2720
2721 log_sync_point("log_write_notifier_before_write_lsn");
2722
2723 const lsn_t write_lsn = log.write_lsn.load();
2724
2725 const lsn_t notified_up_to_lsn =
2726 ut_uint64_align_up(write_lsn, OS_FILE_LOG_BLOCK_SIZE);
2727
2728 while (lsn <= notified_up_to_lsn) {
2729 const auto slot = log_compute_write_event_slot(log, lsn);
2730
2731 lsn += OS_FILE_LOG_BLOCK_SIZE;
2732
2733 log_sync_point("log_write_notifier_before_notify");
2734
2735 os_event_set(log.write_events[slot]);
2736 }
2737
2738 lsn = write_lsn + 1;
2739
2740 if (step % 1024 == 0) {
2741 log_write_notifier_mutex_exit(log);
2742
2743 std::this_thread::yield();
2744
2745 log_write_notifier_mutex_enter(log);
2746 }
2747 }
2748
2749 log_write_notifier_mutex_exit(log);
2750 }
2751
2752 /** @} */
2753
2754 /**************************************************/ /**
2755
2756 @name Log flush_notifier thread
2757
2758 *******************************************************/
2759
2760 /** @{ */
2761
2762 void log_flush_notifier(log_t *log_ptr) {
2763 ut_a(log_ptr != nullptr);
2764
2765 log_t &log = *log_ptr;
2766 lsn_t lsn = log.flushed_to_disk_lsn.load() + 1;
2767
2768 log_flush_notifier_mutex_enter(log);
2769
2770 Log_thread_waiting waiting{log, log.flush_notifier_event,
2771 srv_log_flush_notifier_spin_delay,
2772 get_srv_log_flush_notifier_timeout()};
2773
2774 for (uint64_t step = 0;; ++step) {
2775 if (log.should_stop_threads.load()) {
2776 if (!log_flusher_is_active()) {
2777 if (lsn > log.flushed_to_disk_lsn.load()) {
2778 ut_a(lsn == log.flushed_to_disk_lsn.load() + 1);
2779 break;
2780 }
2781 }
2782 }
2783
2784 if (UNIV_UNLIKELY(
2785 log.writer_threads_paused.load(std::memory_order_acquire))) {
2786 ut_ad(log.flush_notifier_resume_lsn.load(std::memory_order_acquire) == 0);
2787 log_flush_notifier_mutex_exit(log);
2788
2789 /* set to acknowledge */
2790 log.flush_notifier_resume_lsn.store(lsn, std::memory_order_release);
2791
2792 os_event_wait(log.writer_threads_resume_event);
2793 ut_ad(log.flush_notifier_resume_lsn.load(std::memory_order_acquire) + 1 >=
2794 lsn);
2795 lsn = log.flush_notifier_resume_lsn.load(std::memory_order_acquire) + 1;
2796 /* clears to acknowledge */
2797 log.flush_notifier_resume_lsn.store(0, std::memory_order_release);
2798
2799 log_flush_notifier_mutex_enter(log);
2800 }
2801
2802 log_sync_point("log_flush_notifier_before_check");
2803
2804 bool released = false;
2805
2806 auto stop_condition = [&log, lsn, &released](bool wait) {
2807 log_sync_point("log_flush_notifier_after_event_reset");
2808 if (released) {
2809 log_flush_notifier_mutex_enter(log);
2810 released = false;
2811 }
2812
2813 log_sync_point("log_flush_notifier_before_check");
2814
2815 if (log.flushed_to_disk_lsn.load() >= lsn) {
2816 return true;
2817 }
2818
2819 if (log.should_stop_threads.load()) {
2820 if (!log_flusher_is_active()) {
2821 return true;
2822 }
2823 }
2824
2825 if (UNIV_UNLIKELY(
2826 log.writer_threads_paused.load(std::memory_order_acquire))) {
2827 return true;
2828 }
2829
2830 if (wait) {
2831 log_flush_notifier_mutex_exit(log);
2832 released = true;
2833 }
2834 log_sync_point("log_flush_notifier_before_wait");
2835
2836 return false;
2837 };
2838
2839 const auto wait_stats = waiting.wait(stop_condition);
2840
2841 MONITOR_INC_WAIT_STATS(MONITOR_LOG_FLUSH_NOTIFIER_, wait_stats);
2842
2843 log_sync_point("log_flush_notifier_before_flushed_to_disk_lsn");
2844
2845 const lsn_t flush_lsn = log.flushed_to_disk_lsn.load();
2846
2847 const lsn_t notified_up_to_lsn =
2848 ut_uint64_align_up(flush_lsn, OS_FILE_LOG_BLOCK_SIZE);
2849
2850 while (lsn <= notified_up_to_lsn) {
2851 const auto slot = log_compute_flush_event_slot(log, lsn);
2852
2853 lsn += OS_FILE_LOG_BLOCK_SIZE;
2854
2855 log_sync_point("log_flush_notifier_before_notify");
2856
2857 os_event_set(log.flush_events[slot]);
2858 }
2859
2860 lsn = flush_lsn + 1;
2861
2862 if (step % 1024 == 0) {
2863 log_flush_notifier_mutex_exit(log);
2864
2865 std::this_thread::yield();
2866
2867 log_flush_notifier_mutex_enter(log);
2868 }
2869 }
2870
2871 log_flush_notifier_mutex_exit(log);
2872 }
2873
2874 /** @} */
2875
2876 #endif /* !UNIV_HOTBACKUP */