Debian Codegraph @

storage/innobase/buf/buf0flu.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file buf/buf0flu.cc
29 The database buffer buf_pool flush algorithm
30
31 Created 11/11/1995 Heikki Tuuri
32 *******************************************************/
33
34 #include <math.h>
35 #include <my_dbug.h>
36 #include <mysql/service_thd_wait.h>
37 #include <sys/types.h>
38 #include <time.h>
39
40 #ifndef UNIV_HOTBACKUP
41 #include "buf0buf.h"
42 #include "buf0checksum.h"
43 #include "buf0flu.h"
44 #include "ha_prototypes.h"
45 #include "my_inttypes.h"
46 #include "sql_thd_internal_api.h"
47 #endif /* !UNIV_HOTBACKUP */
48 #include "page0zip.h"
49 #ifndef UNIV_HOTBACKUP
50 #include "arch0arch.h"
51 #include "buf0lru.h"
52 #include "buf0rea.h"
53 #include "fil0fil.h"
54 #include "fsp0sysspace.h"
55 #include "ibuf0ibuf.h"
56 #include "log0buf.h"
57 #include "log0chkp.h"
58 #include "log0write.h"
59 #include "my_compiler.h"
60 #include "os0file.h"
61 #include "os0thread-create.h"
62 #include "page0page.h"
63 #include "srv0mon.h"
64 #include "srv0srv.h"
65 #include "srv0start.h"
66 #include "trx0sys.h"
67 #include "ut0byte.h"
68 #include "ut0math.h"
69 #include "ut0stage.h"
70
71 #ifdef UNIV_LINUX
72 /* include defs for CPU time priority settings */
73 #include <sys/resource.h>
74 #include <sys/syscall.h>
75 #include <sys/time.h>
76 #include <unistd.h>
77
78 static const int buf_flush_page_cleaner_priority = -20;
79 #endif /* UNIV_LINUX */
80
81 /** Number of pages flushed through non flush_list flushes. */
82 static ulint buf_lru_flush_page_count = 0;
83
84 /** Factor for scan length to determine n_pages for intended oldest LSN
85 progress */
86 static uint buf_flush_lsn_scan_factor = 3;
87
88 /** Target oldest LSN for the requested flush_sync */
89 static lsn_t buf_flush_sync_lsn = 0;
90
91 #ifdef UNIV_DEBUG
92 /** Get the lsn up to which data pages are to be synchronously flushed.
93 @return target lsn for the requested flush_sync */
94 lsn_t get_flush_sync_lsn() noexcept { return buf_flush_sync_lsn; }
95 #endif /* UNIV_DEBUG */
96
97 #ifdef UNIV_PFS_THREAD
98 mysql_pfs_key_t page_flush_thread_key;
99 mysql_pfs_key_t page_flush_coordinator_thread_key;
100 #endif /* UNIV_PFS_THREAD */
101
102 /** Event to synchronise with the flushing. */
103 os_event_t buf_flush_event;
104
105 /** Event to wait for one flushing step */
106 os_event_t buf_flush_tick_event;
107
108 /** State for page cleaner array slot */
109 enum page_cleaner_state_t {
110 /** Not requested any yet.
111 Moved from FINISHED by the coordinator. */
112 PAGE_CLEANER_STATE_NONE = 0,
113 /** Requested but not started flushing.
114 Moved from NONE by the coordinator. */
115 PAGE_CLEANER_STATE_REQUESTED,
116 /** Flushing is on going.
117 Moved from REQUESTED by the worker. */
118 PAGE_CLEANER_STATE_FLUSHING,
119 /** Flushing was finished.
120 Moved from FLUSHING by the worker. */
121 PAGE_CLEANER_STATE_FINISHED
122 };
123
124 /** Page cleaner request state for each buffer pool instance */
125 struct page_cleaner_slot_t {
126 page_cleaner_state_t state; /*!< state of the request.
127 protected by page_cleaner_t::mutex
128 if the worker thread got the slot and
129 set to PAGE_CLEANER_STATE_FLUSHING,
130 n_flushed_lru and n_flushed_list can be
131 updated only by the worker thread */
132 /* This value is set during state==PAGE_CLEANER_STATE_NONE */
133 ulint n_pages_requested;
134 /*!< number of requested pages
135 for the slot */
136 /* These values are updated during state==PAGE_CLEANER_STATE_FLUSHING,
137 and committed with state==PAGE_CLEANER_STATE_FINISHED.
138 The consistency is protected by the 'state' */
139 ulint n_flushed_lru;
140 /*!< number of flushed pages
141 by LRU scan flushing */
142 ulint n_flushed_list;
143 /*!< number of flushed pages
144 by flush_list flushing */
145 bool succeeded_list;
146 /*!< true if flush_list flushing
147 succeeded. */
148 std::chrono::milliseconds flush_lru_time;
149 /*!< elapsed time for LRU flushing */
150 std::chrono::milliseconds flush_list_time;
151 /*!< elapsed time for flush_list
152 flushing */
153 ulint flush_lru_pass;
154 /*!< count to attempt LRU flushing */
155 ulint flush_list_pass;
156 /*!< count to attempt flush_list
157 flushing */
158 };
159
160 /** Page cleaner structure common for all threads */
161 struct page_cleaner_t {
162 ib_mutex_t mutex; /*!< mutex to protect whole of
163 page_cleaner_t struct and
164 page_cleaner_slot_t slots. */
165 os_event_t is_requested; /*!< event to activate worker
166 threads. */
167 os_event_t is_finished; /*!< event to signal that all
168 slots were finished. */
169 bool requested; /*!< true if requested pages
170 to flush */
171 lsn_t lsn_limit; /*!< upper limit of LSN to be
172 flushed */
173 ulint n_slots; /*!< total number of slots */
174 ulint n_slots_requested;
175 /*!< number of slots
176 in the state
177 PAGE_CLEANER_STATE_REQUESTED */
178 ulint n_slots_flushing;
179 /*!< number of slots
180 in the state
181 PAGE_CLEANER_STATE_FLUSHING */
182 ulint n_slots_finished;
183 /*!< number of slots
184 in the state
185 PAGE_CLEANER_STATE_FINISHED */
186 std::chrono::milliseconds flush_time; /*!< elapsed time to flush
187 requests for all slots */
188 ulint flush_pass; /*!< count to finish to flush
189 requests for all slots */
190 ut::unique_ptr<page_cleaner_slot_t[]> slots; /*!< pointer to the slots */
191 bool is_running; /*!< false if attempt
192 to shutdown */
193
194 #ifdef UNIV_DEBUG
195 ulint n_disabled_debug;
196 /*!< how many of pc threads
197 have been disabled */
198 #endif /* UNIV_DEBUG */
199 };
200
201 static ut::unique_ptr<page_cleaner_t> page_cleaner;
202
203 #ifdef UNIV_DEBUG
204 bool innodb_page_cleaner_disabled_debug;
205 #endif /* UNIV_DEBUG */
206
207 /** If LRU list of a buf_pool is less than this size then LRU eviction
208 should not happen. This is because when we do LRU flushing we also put
209 the blocks on free list. If LRU list is very small then we can end up
210 in thrashing. */
211 constexpr uint32_t BUF_LRU_MIN_LEN = 256;
212
213 /** Flush a batch of writes to the datafiles that have already been
214 written to the dblwr buffer on disk. */
215 static void buf_flush_sync_datafiles() {
216 /* Wake possible simulated AIO thread to actually post the
217 writes to the operating system */
218 os_aio_simulated_wake_handler_threads();
219
220 /* Wait that all async writes to tablespaces have been posted to
221 the OS */
222 os_aio_wait_until_no_pending_writes();
223
224 /* Now we flush the data to disk (for example, with fsync) */
225 fil_flush_file_spaces();
226 }
227
228 /** Thread tasked with flushing dirty pages from the buffer pools.
229 As of now we'll have only one coordinator. */
230 static void buf_flush_page_coordinator_thread();
231
232 /** Worker thread of page_cleaner. */
233 static void buf_flush_page_cleaner_thread();
234
235 /** Increases flush_list size in bytes with the page size in inline function */
236 static inline void incr_flush_list_size_in_bytes(
237 buf_block_t *block, /*!< in: control block */
238 buf_pool_t *buf_pool) /*!< in: buffer pool instance */
239 {
240 ut_ad(buf_flush_list_mutex_own(buf_pool));
241
242 buf_pool->stat.flush_list_bytes += block->page.size.physical();
243
244 ut_ad(buf_pool->stat.flush_list_bytes <= buf_pool->curr_pool_size);
245 }
246
247 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
248 /** Validate a buffer pool instance flush list.
249 @param[in] buf_pool Instance to validate
250 @return true on success. */
251 static bool buf_flush_validate_low(const buf_pool_t *buf_pool);
252
253 /** Validates the flush list some of the time.
254 @return true if ok or the check was skipped */
255 static bool buf_flush_validate_skip(
256 buf_pool_t *buf_pool) /*!< in: Buffer pool instance */
257 {
258 /** Try buf_flush_validate_low() every this many times */
259 constexpr uint32_t BUF_FLUSH_VALIDATE_SKIP = 23;
260
261 /** The buf_flush_validate_low() call skip counter.
262 Use a signed type because of the race condition below. */
263 static int buf_flush_validate_count = BUF_FLUSH_VALIDATE_SKIP;
264
265 DBUG_EXECUTE_IF("buf_flush_list_validate", buf_flush_validate_count = 1;);
266
267 /* There is a race condition below, but it does not matter,
268 because this call is only for heuristic purposes. We want to
269 reduce the call frequency of the costly buf_flush_validate_low()
270 check in debug builds. */
271 if (--buf_flush_validate_count > 0) {
272 return true;
273 }
274
275 buf_flush_validate_count = BUF_FLUSH_VALIDATE_SKIP;
276 return (buf_flush_validate_low(buf_pool));
277 }
278 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
279
280 /** Insert a block in the flush_rbt and returns a pointer to its
281 predecessor or NULL if no predecessor. The ordering is maintained
282 on the basis of the <oldest_modification, space, offset> key.
283 @return pointer to the predecessor or NULL if no predecessor. */
284 static buf_page_t *buf_flush_insert_in_flush_rbt(
285 buf_page_t *bpage) /*!< in: bpage to be inserted. */
286 {
287 const ib_rbt_node_t *c_node;
288 const ib_rbt_node_t *p_node;
289 buf_page_t *prev = nullptr;
290 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
291
292 ut_ad(buf_flush_list_mutex_own(buf_pool));
293
294 /* Insert this buffer into the rbt. */
295 c_node = rbt_insert(buf_pool->flush_rbt, &bpage, &bpage);
296 ut_a(c_node != nullptr);
297
298 /* Get the predecessor. */
299 p_node = rbt_prev(buf_pool->flush_rbt, c_node);
300
301 if (p_node != nullptr) {
302 buf_page_t **value;
303 value = rbt_value(buf_page_t *, p_node);
304 prev = *value;
305 ut_a(prev != nullptr);
306 }
307
308 return (prev);
309 }
310
311 /** Delete a bpage from the flush_rbt. */
312 static void buf_flush_delete_from_flush_rbt(
313 buf_page_t *bpage) /*!< in: bpage to be removed. */
314 {
315 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
316
317 ut_ad(buf_flush_list_mutex_own(buf_pool));
318
319 #ifdef UNIV_DEBUG
320 bool ret =
321 #endif /* UNIV_DEBUG */
322 rbt_delete(buf_pool->flush_rbt, &bpage);
323
324 ut_ad(ret);
325 }
326
327 /** Compare two modified blocks in the buffer pool. The key for comparison
328 is:
329 key = <oldest_modification, space, offset>
330 This comparison is used to maintian ordering of blocks in the
331 buf_pool->flush_rbt.
332 Note that for the purpose of flush_rbt, we only need to order blocks
333 on the oldest_modification. The other two fields are used to uniquely
334 identify the blocks.
335 @return < 0 if b2 < b1, 0 if b2 == b1, > 0 if b2 > b1 */
336 static int buf_flush_block_cmp(const void *p1, /*!< in: block1 */
337 const void *p2) /*!< in: block2 */
338 {
339 int ret;
340 const buf_page_t *b1 = *(const buf_page_t **)p1;
341 const buf_page_t *b2 = *(const buf_page_t **)p2;
342
343 ut_ad(b1 != nullptr);
344 ut_ad(b2 != nullptr);
345
346 #ifdef UNIV_DEBUG
347 buf_pool_t *buf_pool = buf_pool_from_bpage(b1);
348 #endif /* UNIV_DEBUG */
349
350 ut_ad(buf_flush_list_mutex_own(buf_pool));
351
352 ut_ad(b1->in_flush_list);
353 ut_ad(b2->in_flush_list);
354
355 if (b2->get_oldest_lsn() > b1->get_oldest_lsn()) {
356 return (1);
357 } else if (b2->get_oldest_lsn() < b1->get_oldest_lsn()) {
358 return (-1);
359 }
360
361 /* If oldest_modification is same then decide on the space. */
362 ret = (int)(b2->id.space() - b1->id.space());
363
364 /* Or else decide ordering on the page number. */
365 return (ret ? ret : (int)(b2->id.page_no() - b1->id.page_no()));
366 }
367
368 /** Initialize the red-black tree to speed up insertions into the flush_list
369 during recovery process. Should be called at the start of recovery
370 process before any page has been read/written. */
371 void buf_flush_init_flush_rbt(void) {
372 ulint i;
373
374 for (i = 0; i < srv_buf_pool_instances; i++) {
375 buf_pool_t *buf_pool;
376
377 buf_pool = buf_pool_from_array(i);
378
379 buf_flush_list_mutex_enter(buf_pool);
380
381 ut_ad(buf_pool->flush_rbt == nullptr);
382
383 /* Create red black tree for speedy insertions in flush list. */
384 buf_pool->flush_rbt = rbt_create(sizeof(buf_page_t *), buf_flush_block_cmp);
385
386 buf_flush_list_mutex_exit(buf_pool);
387 }
388 }
389
390 /** Frees up the red-black tree. */
391 void buf_flush_free_flush_rbt(void) {
392 ulint i;
393
394 for (i = 0; i < srv_buf_pool_instances; i++) {
395 buf_pool_t *buf_pool;
396
397 buf_pool = buf_pool_from_array(i);
398
399 buf_flush_list_mutex_enter(buf_pool);
400
401 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
402 ut_a(buf_flush_validate_low(buf_pool));
403 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
404
405 rbt_free(buf_pool->flush_rbt);
406 buf_pool->flush_rbt = nullptr;
407
408 buf_flush_list_mutex_exit(buf_pool);
409 }
410 }
411
412 bool buf_are_flush_lists_empty_validate(void) {
413 /* No mutex is acquired. It is used by single-thread
414 in assertions during startup. */
415
416 for (size_t i = 0; i < srv_buf_pool_instances; i++) {
417 auto buf_pool = buf_pool_from_array(i);
418
419 if (UT_LIST_GET_FIRST(buf_pool->flush_list) != nullptr) {
420 return false;
421 }
422 }
423
424 return true;
425 }
426
427 /** Checks that order of two consecutive pages in flush list would be valid,
428 according to their oldest_modification values.
429
430 @remarks
431 We have a relaxed order in flush list, but still we have guarantee,
432 that the earliest added page has oldest_modification not greater than
433 minimum oldest_midification of all dirty pages by more than number of
434 slots in the log recent closed buffer.
435
436 This is used by assertions only.
437
438 @param[in] earlier_added_lsn oldest_modification of page which was
439 added to flush list earlier
440 @param[in] new_added_lsn oldest_modification of page which is
441 being added to flush list
442 @retval true if the order is valid
443 */
444 MY_COMPILER_DIAGNOSTIC_PUSH()
445 MY_COMPILER_CLANG_WORKAROUND_REF_DOCBUG()
446 /**
447 @see @ref sect_redo_log_reclaim_space
448 @see @ref sect_redo_log_add_dirty_pages */
449 MY_COMPILER_DIAGNOSTIC_POP()
450
451 [[maybe_unused]] static inline bool buf_flush_list_order_validate(
452 lsn_t earlier_added_lsn, lsn_t new_added_lsn) {
453 return (earlier_added_lsn <=
454 new_added_lsn + log_buffer_flush_order_lag(*log_sys));
455 }
456
457 /** Borrows LSN from the recent added dirty page to the flush list.
458
459 This should be the lsn which we may use to mark pages dirtied without
460 underlying redo records, when we add them to the flush list.
461
462 The lsn should be chosen in a way which will guarantee that we will
463 not destroy checkpoint calculations if we inserted a new dirty page
464 with such lsn to the flush list. This is strictly related to the
465 limitations we put on the relaxed order in flush lists, which have
466 direct impact on computation of lsn available for next checkpoint.
467
468 Therefore when the flush list is empty, the lsn is chosen as the
469 maximum lsn up to which we know, that all dirty pages with smaller
470 oldest_modification were added to the flush list.
471
472 This guarantees that the limitations put on the relaxed order are
473 hold and lsn available for next checkpoint is not miscalculated.
474
475 @param[in] buf_pool buffer pool instance
476 @return the borrowed newest_modification of the page or lsn up
477 to which all dirty pages were added to the flush list
478 if the flush list is empty */
479 static inline lsn_t buf_flush_borrow_lsn(const buf_pool_t *buf_pool) {
480 ut_ad(buf_flush_list_mutex_own(buf_pool));
481
482 const auto page = UT_LIST_GET_FIRST(buf_pool->flush_list);
483
484 if (page == nullptr) {
485 /* Flush list is empty - use lsn up to which we know that all
486 dirty pages with smaller oldest_modification were added to
487 the flush list (they were flushed as the flush list is empty). */
488 const lsn_t lsn = log_buffer_dirty_pages_added_up_to_lsn(*log_sys);
489
490 if (lsn < LOG_START_LSN) {
491 ut_ad(srv_read_only_mode);
492 return LOG_START_LSN + LOG_BLOCK_HDR_SIZE;
493 }
494 return lsn;
495 }
496
497 ut_ad(page->is_dirty());
498 ut_ad(page->get_newest_lsn() >= page->get_oldest_lsn());
499
500 return page->get_oldest_lsn();
501 }
502
503 /** Inserts a modified block into the flush list. */
504 void buf_flush_insert_into_flush_list(
505 buf_pool_t *buf_pool, /*!< buffer pool instance */
506 buf_block_t *block, /*!< in/out: block which is modified */
507 lsn_t lsn) /*!< in: oldest modification */
508 {
509 ut_ad(mutex_own(buf_page_get_mutex(&block->page)));
510 ut_ad(log_sys != nullptr);
511
512 buf_flush_list_mutex_enter(buf_pool);
513
514 /* If we are in the recovery then we need to update the flush
515 red-black tree as well. */
516 if (buf_pool->flush_rbt != nullptr) {
517 ut_ad(lsn != 0);
518 ut_ad(block->page.get_newest_lsn() != 0);
519 buf_flush_list_mutex_exit(buf_pool);
520 buf_flush_insert_sorted_into_flush_list(buf_pool, block, lsn);
521 return;
522 }
523
524 ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
525 ut_ad(!block->page.in_flush_list);
526
527 ut_d(block->page.in_flush_list = true);
528
529 if (lsn == 0) {
530 /* This is no-redo dirtied page. Borrow the lsn. */
531 lsn = buf_flush_borrow_lsn(buf_pool);
532
533 ut_ad(log_is_data_lsn(lsn));
534
535 /* This page could already be no-redo dirtied before,
536 and flushed since then. Also the page from which we
537 borrowed lsn last time could be flushed by LRU and
538 we would end up borrowing smaller LSN.
539
540 Another risk is that this page was flushed earlier
541 and freed. We should not re-flush it to disk with
542 smaller FIL_PAGE_LSN.
543
544 The best way to go is to use flushed_to_disk_lsn,
545 unless we borrowed even higher value.
546
547 This way we are sure that no page has ever been
548 flushed with higher newest_modification - it would
549 first need to wait until redo is flushed up to
550 such point and it would ensure that by checking
551 the log_sys->flushed_to_disk_lsn's value too.
552
553 Because we keep the page latched, after we read
554 flushed_to_disk_lsn this page cannot be flushed
555 in background with higher lsn (hence we are safe
556 even if the flushed_to_disk_lsn advanced after
557 we read it). */
558
559 block->page.set_newest_lsn(
560 std::max(lsn, log_sys->flushed_to_disk_lsn.load()));
561 }
562
563 ut_ad(log_is_data_lsn(lsn));
564 ut_ad(!block->page.is_dirty());
565 ut_ad(block->page.get_newest_lsn() >= lsn);
566
567 ut_ad(UT_LIST_GET_FIRST(buf_pool->flush_list) == nullptr ||
568 buf_flush_list_order_validate(
569 UT_LIST_GET_FIRST(buf_pool->flush_list)->get_oldest_lsn(), lsn));
570
571 block->page.set_oldest_lsn(lsn);
572
573 UT_LIST_ADD_FIRST(buf_pool->flush_list, &block->page);
574
575 incr_flush_list_size_in_bytes(block, buf_pool);
576
577 #ifdef UNIV_DEBUG_VALGRIND
578 void *p;
579
580 if (block->page.size.is_compressed()) {
581 p = block->page.zip.data;
582 } else {
583 p = block->frame;
584 }
585
586 UNIV_MEM_ASSERT_RW(p, block->page.size.physical());
587 #endif /* UNIV_DEBUG_VALGRIND */
588
589 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
590 ut_a(buf_flush_validate_skip(buf_pool));
591 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
592
593 buf_flush_list_mutex_exit(buf_pool);
594 }
595
596 /** Inserts a modified block into the flush list in the right sorted position.
597 This function is used by recovery, because there the modifications do not
598 necessarily come in the order of lsn's. */
599 void buf_flush_insert_sorted_into_flush_list(
600 buf_pool_t *buf_pool, /*!< in: buffer pool instance */
601 buf_block_t *block, /*!< in/out: block which is modified */
602 lsn_t lsn) /*!< in: oldest modification */
603 {
604 buf_page_t *prev_b;
605 buf_page_t *b;
606
607 ut_ad(mutex_own(buf_page_get_mutex(&block->page)));
608 ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
609
610 buf_flush_list_mutex_enter(buf_pool);
611
612 /* While a block is in the flush list, it is dirty and cannot be discarded,
613 not from the page_hash. At most, the uncompressed page frame of a compressed
614 block may be discarded or created (copying the block->page to or from a
615 buf_page_t that is dynamically allocated from buf_buddy_alloc()). Because
616 those transitions hold block->mutex and the flush list mutex (via
617 buf_flush_relocate_on_flush_list()), there is no possibility
618 of a race condition in the assertions below. */
619 ut_ad(block->page.in_page_hash);
620 /* buf_buddy_block_register() will take a block in the
621 BUF_BLOCK_MEMORY state, not a file page. */
622 ut_ad(!block->page.in_zip_hash);
623
624 ut_ad(!block->page.in_flush_list);
625 ut_d(block->page.in_flush_list = true);
626 block->page.set_oldest_lsn(lsn);
627
628 #ifdef UNIV_DEBUG_VALGRIND
629 void *p;
630
631 if (block->page.size.is_compressed()) {
632 p = block->page.zip.data;
633 } else {
634 p = block->frame;
635 }
636
637 UNIV_MEM_ASSERT_RW(p, block->page.size.physical());
638 #endif /* UNIV_DEBUG_VALGRIND */
639
640 prev_b = nullptr;
641
642 /* For the most part when this function is called the flush_rbt
643 should not be NULL. In a very rare boundary case it is possible
644 that the flush_rbt has already been freed by the recovery thread
645 before the last page was hooked up in the flush_list by the
646 io-handler thread. In that case we'll just do a simple
647 linear search in the else block. */
648 if (buf_pool->flush_rbt != nullptr) {
649 prev_b = buf_flush_insert_in_flush_rbt(&block->page);
650
651 } else {
652 b = UT_LIST_GET_FIRST(buf_pool->flush_list);
653
654 while (b != nullptr && b->get_oldest_lsn() > block->page.get_oldest_lsn()) {
655 ut_ad(b->in_flush_list);
656 prev_b = b;
657 b = UT_LIST_GET_NEXT(list, b);
658 }
659 }
660
661 if (prev_b == nullptr) {
662 UT_LIST_ADD_FIRST(buf_pool->flush_list, &block->page);
663 } else {
664 UT_LIST_INSERT_AFTER(buf_pool->flush_list, prev_b, &block->page);
665 }
666
667 if (buf_pool->oldest_hp.get() != nullptr) {
668 /* clear oldest_hp */
669 buf_pool->oldest_hp.set(nullptr);
670 }
671
672 incr_flush_list_size_in_bytes(block, buf_pool);
673
674 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
675 ut_a(buf_flush_validate_low(buf_pool));
676 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
677
678 buf_flush_list_mutex_exit(buf_pool);
679 }
680
681 bool buf_flush_ready_for_replace(const buf_page_t *bpage) {
682 ut_d(auto buf_pool = buf_pool_from_bpage(bpage));
683 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
684 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
685 ut_ad(bpage->in_LRU_list);
686
687 if (!buf_page_in_file(bpage)) {
688 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_123)
689 << "Buffer block " << bpage << " state "
690 << static_cast<unsigned>(bpage->state) << " in the LRU list!";
691 }
692
693 /* We can't replace a page that is fixed in any way.*/
694 if (!buf_page_can_relocate(bpage)) {
695 return false;
696 }
697 /* We can replace it if it is stale, but only if the page is not fixed. */
698 if (bpage->was_stale()) {
699 return true;
700 }
701 return !bpage->is_dirty();
702 }
703
704 /** Check if the block was modified and was ready for flushing.
705 This is a common part of the logic of buf_flush_was_ready_for_flush() and
706 buf_flush_ready_for_flush() which differ by the tolerance for stale result.
707 @param[in] bpage buffer control block, must be buf_page_in_file()
708 @param[in] flush_type type of flush
709 @param[in] atomic false if the caller can tolerate stale data,
710 true if the caller needs accurate answer, which
711 requires the caller to hold buf_page_get_mutex.
712 @return true if page seems ready for flush */
713 static bool buf_flush_ready_for_flush_gen(buf_page_t *bpage,
714 buf_flush_t flush_type, bool atomic) {
715 #ifdef UNIV_DEBUG
716 auto buf_pool = buf_pool_from_bpage(bpage);
717
718 ut_a(buf_page_in_file(bpage) ||
719 (buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH &&
720 !mutex_own(&buf_pool->LRU_list_mutex)));
721 #else
722 ut_a(buf_page_in_file(bpage) ||
723 buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
724 #endif /* UNIV_DEBUG */
725
726 /*As buf_flush_insert_into_flush_list() acquires SYNC_BUF_BLOCK after
727 SYNC_BUF_FLUSH_LIST, the latch ordering prevents buf_do_flush_list_batch()
728 from acquiring SYNC_BUF_BLOCK after SYNC_BUF_FLUSH_LIST taken for iterating
729 over the flush_list. Thus for BUF_FLUSH_LIST we first perform a heuristic
730 check with atomic==false, and if it looks ready to flush, we relatch, and
731 recheck under proper mutex protection. In all other cases we already have
732 the block_mutex.
733 However, for BUF_LRU_LIST if we are called with atomic==false, then we will
734 have the block mutex which will allow us to provide exact answer, even if we
735 don't require it to be so (because atomic==false), and this is not required to
736 have flush_list mutex in such situation.*/
737 ut_ad(mutex_own(buf_page_get_mutex(bpage)) ||
738 (!atomic && flush_type == BUF_FLUSH_LIST &&
739 buf_flush_list_mutex_own(buf_pool)));
740
741 ut_ad(flush_type < BUF_FLUSH_N_TYPES);
742
743 if (!bpage->is_dirty() ||
744 (atomic ? bpage->get_io_fix() != BUF_IO_NONE : bpage->was_io_fixed())) {
745 return false;
746 }
747
748 ut_ad(bpage->in_flush_list);
749
750 switch (flush_type) {
751 case BUF_FLUSH_LIST:
752 return (buf_page_get_state(bpage) != BUF_BLOCK_REMOVE_HASH);
753 case BUF_FLUSH_LRU:
754 case BUF_FLUSH_SINGLE_PAGE:
755 return true;
756
757 case BUF_FLUSH_N_TYPES:
758 break;
759 }
760
761 ut_error;
762 }
763
764 /** Check if the block was modified and was ready for flushing at some point in
765 time during the call. Result might be obsolete.
766 @param[in] bpage buffer control block, must be buf_page_in_file()
767 @param[in] flush_type type of flush
768 @return true if can flush immediately */
769 static bool buf_flush_was_ready_for_flush(buf_page_t *bpage,
770 buf_flush_t flush_type) {
771 return buf_flush_ready_for_flush_gen(bpage, flush_type, false);
772 }
773
774 bool buf_flush_ready_for_flush(buf_page_t *bpage, buf_flush_t flush_type) {
775 return buf_flush_ready_for_flush_gen(bpage, flush_type, true);
776 }
777
778 /** Remove a block from the flush list of modified blocks.
779 @param[in] bpage pointer to the block in question */
780 void buf_flush_remove(buf_page_t *bpage) {
781 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
782
783 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
784 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
785 ut_ad(buf_page_get_state(bpage) != BUF_BLOCK_ZIP_DIRTY ||
786 mutex_own(&buf_pool->LRU_list_mutex));
787 #endif
788 ut_ad(bpage->in_flush_list);
789
790 buf_flush_list_mutex_enter(buf_pool);
791
792 /* Important that we adjust the hazard pointer before removing
793 the bpage from flush list. */
794 buf_pool->flush_hp.adjust(bpage);
795 buf_pool->oldest_hp.adjust(bpage);
796
797 switch (buf_page_get_state(bpage)) {
798 case BUF_BLOCK_POOL_WATCH:
799 case BUF_BLOCK_ZIP_PAGE:
800 /* Clean compressed pages should not be on the flush list */
801 case BUF_BLOCK_NOT_USED:
802 case BUF_BLOCK_READY_FOR_USE:
803 case BUF_BLOCK_MEMORY:
804 case BUF_BLOCK_REMOVE_HASH:
805 ut_error;
806 return;
807 case BUF_BLOCK_ZIP_DIRTY:
808 buf_page_set_state(bpage, BUF_BLOCK_ZIP_PAGE);
809 UT_LIST_REMOVE(buf_pool->flush_list, bpage);
810 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
811 buf_LRU_insert_zip_clean(bpage);
812 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
813 break;
814 case BUF_BLOCK_FILE_PAGE:
815 UT_LIST_REMOVE(buf_pool->flush_list, bpage);
816 break;
817 }
818
819 /* If the flush_rbt is active then delete from there as well. */
820 if (buf_pool->flush_rbt != nullptr) {
821 buf_flush_delete_from_flush_rbt(bpage);
822 }
823
824 /* Must be done after we have removed it from the flush_rbt
825 because we assert on in_flush_list in comparison function. */
826 ut_d(bpage->in_flush_list = false);
827
828 buf_pool->stat.flush_list_bytes -= bpage->size.physical();
829
830 bpage->set_clean();
831
832 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
833 ut_a(buf_flush_validate_skip(buf_pool));
834 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
835
836 /* If there is an observer that want to know if the asynchronous
837 flushing was done then notify it. */
838 if (bpage->get_flush_observer() != nullptr) {
839 bpage->get_flush_observer()->notify_remove(buf_pool, bpage);
840
841 bpage->reset_flush_observer();
842 }
843
844 buf_flush_list_mutex_exit(buf_pool);
845 }
846
847 /** Relocates a buffer control block on the flush_list.
848 Note that it is assumed that the contents of bpage have already been
849 copied to dpage.
850 IMPORTANT: When this function is called bpage and dpage are not
851 exact copies of each other. For example, they both will have different
852 "::state". Also the "::list" pointers in dpage may be stale. We need to
853 use the current list node (bpage) to do the list manipulation because
854 the list pointers could have changed between the time that we copied
855 the contents of bpage to the dpage and the flush list manipulation
856 below. */
857 void buf_flush_relocate_on_flush_list(
858 buf_page_t *bpage, /*!< in/out: control block being moved */
859 buf_page_t *dpage) /*!< in/out: destination block */
860 {
861 buf_page_t *prev;
862 buf_page_t *prev_b = nullptr;
863 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
864
865 /* Must reside in the same buffer pool. */
866 ut_ad(buf_pool == buf_pool_from_bpage(dpage));
867
868 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
869
870 buf_flush_list_mutex_enter(buf_pool);
871
872 ut_ad(bpage->in_flush_list);
873 ut_ad(dpage->in_flush_list);
874
875 /* If recovery is active we must swap the control blocks in
876 the flush_rbt as well. */
877 if (buf_pool->flush_rbt != nullptr) {
878 buf_flush_delete_from_flush_rbt(bpage);
879 prev_b = buf_flush_insert_in_flush_rbt(dpage);
880 }
881
882 /* Important that we adjust the hazard pointer before removing
883 the bpage from the flush list. */
884 buf_pool->flush_hp.move(bpage, dpage);
885 buf_pool->oldest_hp.move(bpage, dpage);
886
887 /* Must be done after we have removed it from the flush_rbt
888 because we assert on in_flush_list in comparison function. */
889 ut_d(bpage->in_flush_list = false);
890
891 prev = UT_LIST_GET_PREV(list, bpage);
892 UT_LIST_REMOVE(buf_pool->flush_list, bpage);
893
894 if (prev) {
895 ut_ad(prev->in_flush_list);
896 UT_LIST_INSERT_AFTER(buf_pool->flush_list, prev, dpage);
897 } else {
898 UT_LIST_ADD_FIRST(buf_pool->flush_list, dpage);
899 }
900
901 /* Just an extra check. Previous in flush_list
902 should be the same control block as in flush_rbt. */
903 ut_a(buf_pool->flush_rbt == nullptr || prev_b == prev);
904
905 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
906 ut_a(buf_flush_validate_low(buf_pool));
907 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
908
909 buf_flush_list_mutex_exit(buf_pool);
910 }
911
912 /** Updates the flush system data structures when a write is completed.
913 @param[in] bpage pointer to the block in question */
914 void buf_flush_write_complete(buf_page_t *bpage) {
915 auto buf_pool = buf_pool_from_bpage(bpage);
916
917 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
918
919 ut_ad(buf_page_get_state(bpage) != BUF_BLOCK_ZIP_DIRTY ||
920 mutex_own(&buf_pool->LRU_list_mutex));
921
922 const buf_flush_t flush_type = buf_page_get_flush_type(bpage);
923
924 mutex_enter(&buf_pool->flush_state_mutex);
925
926 buf_flush_remove(bpage);
927
928 buf_page_set_io_fix(bpage, BUF_IO_NONE);
929
930 buf_pool->n_flush[flush_type]--;
931
932 if (buf_pool->n_flush[flush_type] == 0 &&
933 buf_pool->init_flush[flush_type] == false) {
934 /* The running flush batch has ended */
935
936 os_event_set(buf_pool->no_flush[flush_type]);
937 }
938
939 mutex_exit(&buf_pool->flush_state_mutex);
940
941 if (!fsp_is_system_temporary(bpage->id.space()) && dblwr::is_enabled()) {
942 dblwr::write_complete(bpage, flush_type);
943 }
944 }
945 #endif /* !UNIV_HOTBACKUP */
946
947 /** Calculate the checksum of a page from compressed table and update
948 the page.
949 @param[in,out] page page to update
950 @param[in] size compressed page size
951 @param[in] lsn LSN to stamp on the page
952 @param[in] skip_lsn_check true to skip check for lsn (in DEBUG) */
953 void buf_flush_update_zip_checksum(buf_frame_t *page, ulint size, lsn_t lsn,
954 bool skip_lsn_check) {
955 ut_a(size > 0);
956
957 BlockReporter reporter = BlockReporter(false, nullptr, univ_page_size, false);
958
959 const uint32_t checksum = reporter.calc_zip_checksum(
960 page, size,
961 static_cast<srv_checksum_algorithm_t>(srv_checksum_algorithm));
962
963 ut_ad(skip_lsn_check || mach_read_from_8(page + FIL_PAGE_LSN) <= lsn);
964
965 mach_write_to_8(page + FIL_PAGE_LSN, lsn);
966 mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM, checksum);
967 }
968
969 bool page_is_uncompressed_type(const byte *page) {
970 switch (fil_page_get_type(page)) {
971 case FIL_PAGE_TYPE_ALLOCATED:
972 case FIL_PAGE_INODE:
973 case FIL_PAGE_IBUF_BITMAP:
974 case FIL_PAGE_TYPE_FSP_HDR:
975 case FIL_PAGE_TYPE_XDES:
976 case FIL_PAGE_TYPE_ZLOB_FIRST:
977 case FIL_PAGE_TYPE_ZLOB_DATA:
978 case FIL_PAGE_TYPE_ZLOB_INDEX:
979 case FIL_PAGE_TYPE_ZLOB_FRAG:
980 case FIL_PAGE_TYPE_ZLOB_FRAG_ENTRY:
981 return (true);
982 }
983 return (false);
984 }
985
986 /** Initialize a page for writing to the tablespace.
987 @param[in] block buffer block; NULL if bypassing the buffer pool
988 @param[in,out] page page frame
989 @param[in,out] page_zip_ compressed page, or NULL if uncompressed
990 @param[in] newest_lsn newest modification LSN to the page
991 @param[in] skip_checksum whether to disable the page checksum
992 @param[in] skip_lsn_check true to skip check for LSN (in DEBUG) */
993 void buf_flush_init_for_writing(const buf_block_t *block, byte *page,
994 void *page_zip_, lsn_t newest_lsn,
995 bool skip_checksum, bool skip_lsn_check) {
996 uint32_t checksum = BUF_NO_CHECKSUM_MAGIC;
997
998 ut_ad(block == nullptr || block->frame == page);
999 ut_ad(block == nullptr || page_zip_ == nullptr ||
1000 &block->page.zip == page_zip_);
1001 ut_ad(page);
1002
1003 if (page_zip_) {
1004 page_zip_des_t *page_zip;
1005 ulint size;
1006
1007 page_zip = static_cast<page_zip_des_t *>(page_zip_);
1008 size = page_zip_get_size(page_zip);
1009
1010 ut_ad(size);
1011 ut_ad(ut_is_2pow(size));
1012 ut_ad(size <= UNIV_ZIP_SIZE_MAX);
1013
1014 switch (fil_page_get_type(page)) {
1015 case FIL_PAGE_TYPE_ALLOCATED:
1016 case FIL_PAGE_INODE:
1017 case FIL_PAGE_IBUF_BITMAP:
1018 case FIL_PAGE_TYPE_FSP_HDR:
1019 case FIL_PAGE_TYPE_XDES:
1020 case FIL_PAGE_TYPE_ZLOB_FIRST:
1021 case FIL_PAGE_TYPE_ZLOB_DATA:
1022 case FIL_PAGE_TYPE_ZLOB_INDEX:
1023 case FIL_PAGE_TYPE_ZLOB_FRAG:
1024 case FIL_PAGE_TYPE_ZLOB_FRAG_ENTRY:
1025 /* These are essentially uncompressed pages. */
1026 ut_ad(page_is_uncompressed_type(page));
1027 /* Skip copy if they points to same memory: clone page copy. */
1028 if (page_zip->data != page) {
1029 memcpy(page_zip->data, page, size);
1030 }
1031 [[fallthrough]];
1032 case FIL_PAGE_TYPE_ZBLOB:
1033 case FIL_PAGE_TYPE_ZBLOB2:
1034 case FIL_PAGE_SDI_ZBLOB:
1035 case FIL_PAGE_INDEX:
1036 case FIL_PAGE_SDI:
1037 case FIL_PAGE_RTREE:
1038
1039 buf_flush_update_zip_checksum(page_zip->data, size, newest_lsn,
1040 skip_lsn_check);
1041
1042 return;
1043 }
1044
1045 ib::error(ER_IB_MSG_124) << "The compressed page to be written"
1046 " seems corrupt:";
1047 ut_print_buf(stderr, page, size);
1048 fputs("\nInnoDB: Possibly older version of the page:", stderr);
1049 ut_print_buf(stderr, page_zip->data, size);
1050 putc('\n', stderr);
1051 ut_error;
1052 }
1053
1054 /* Write the newest modification lsn to the page header and trailer */
1055 ut_ad(skip_lsn_check || mach_read_from_8(page + FIL_PAGE_LSN) <= newest_lsn);
1056
1057 mach_write_to_8(page + FIL_PAGE_LSN, newest_lsn);
1058
1059 mach_write_to_8(page + UNIV_PAGE_SIZE - FIL_PAGE_END_LSN_OLD_CHKSUM,
1060 newest_lsn);
1061
1062 if (skip_checksum) {
1063 mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM, checksum);
1064 } else {
1065 if (block != nullptr && UNIV_PAGE_SIZE == 16384) {
1066 /* The page type could be garbage in old files
1067 created before MySQL 5.5. Such files always
1068 had a page size of 16 kilobytes. */
1069 ulint page_type = fil_page_get_type(page);
1070 ulint reset_type = page_type;
1071
1072 switch (block->page.id.page_no() % 16384) {
1073 case 0:
1074 reset_type = block->page.id.page_no() == 0 ? FIL_PAGE_TYPE_FSP_HDR
1075 : FIL_PAGE_TYPE_XDES;
1076 break;
1077 case 1:
1078 reset_type = FIL_PAGE_IBUF_BITMAP;
1079 break;
1080 default:
1081 switch (page_type) {
1082 case FIL_PAGE_INDEX:
1083 case FIL_PAGE_RTREE:
1084 case FIL_PAGE_SDI:
1085 case FIL_PAGE_UNDO_LOG:
1086 case FIL_PAGE_INODE:
1087 case FIL_PAGE_IBUF_FREE_LIST:
1088 case FIL_PAGE_TYPE_ALLOCATED:
1089 case FIL_PAGE_TYPE_SYS:
1090 case FIL_PAGE_TYPE_TRX_SYS:
1091 case FIL_PAGE_TYPE_BLOB:
1092 case FIL_PAGE_TYPE_ZBLOB:
1093 case FIL_PAGE_TYPE_ZBLOB2:
1094 case FIL_PAGE_SDI_BLOB:
1095 case FIL_PAGE_SDI_ZBLOB:
1096 case FIL_PAGE_TYPE_LOB_INDEX:
1097 case FIL_PAGE_TYPE_LOB_DATA:
1098 case FIL_PAGE_TYPE_LOB_FIRST:
1099 case FIL_PAGE_TYPE_ZLOB_FIRST:
1100 case FIL_PAGE_TYPE_ZLOB_DATA:
1101 case FIL_PAGE_TYPE_ZLOB_INDEX:
1102 case FIL_PAGE_TYPE_ZLOB_FRAG:
1103 case FIL_PAGE_TYPE_ZLOB_FRAG_ENTRY:
1104 case FIL_PAGE_TYPE_RSEG_ARRAY:
1105 break;
1106 case FIL_PAGE_TYPE_FSP_HDR:
1107 case FIL_PAGE_TYPE_XDES:
1108 case FIL_PAGE_IBUF_BITMAP:
1109 /* These pages should have
1110 predetermined page numbers
1111 (see above). */
1112 default:
1113 reset_type = FIL_PAGE_TYPE_UNKNOWN;
1114 break;
1115 }
1116 }
1117
1118 if (UNIV_UNLIKELY(page_type != reset_type)) {
1119 ib::info(ER_IB_MSG_125)
1120 << "Resetting invalid page " << block->page.id << " type "
1121 << page_type << " to " << reset_type << " when flushing.";
1122 fil_page_set_type(page, reset_type);
1123 }
1124 }
1125
1126 switch ((srv_checksum_algorithm_t)srv_checksum_algorithm) {
1127 case SRV_CHECKSUM_ALGORITHM_CRC32:
1128 case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
1129 checksum = buf_calc_page_crc32(page);
1130 mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM, checksum);
1131 break;
1132 case SRV_CHECKSUM_ALGORITHM_INNODB:
1133 case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
1134 checksum = (uint32_t)buf_calc_page_new_checksum(page);
1135 mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM, checksum);
1136 checksum = (uint32_t)buf_calc_page_old_checksum(page);
1137 break;
1138 case SRV_CHECKSUM_ALGORITHM_NONE:
1139 case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
1140 mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM, checksum);
1141 break;
1142 /* no default so the compiler will emit a warning if
1143 new enum is added and not handled here */
1144 }
1145 }
1146
1147 /* With the InnoDB checksum, we overwrite the first 4 bytes of
1148 the end lsn field to store the old formula checksum. Since it
1149 depends also on the field FIL_PAGE_SPACE_OR_CHKSUM, it has to
1150 be calculated after storing the new formula checksum.
1151
1152 In other cases we write the same value to both fields.
1153 If CRC32 is used then it is faster to use that checksum
1154 (calculated above) instead of calculating another one.
1155 We can afford to store something other than
1156 buf_calc_page_old_checksum() or BUF_NO_CHECKSUM_MAGIC in
1157 this field because the file will not be readable by old
1158 versions of MySQL/InnoDB anyway (older than MySQL 5.6.3) */
1159
1160 mach_write_to_4(page + UNIV_PAGE_SIZE - FIL_PAGE_END_LSN_OLD_CHKSUM,
1161 checksum);
1162 }
1163
1164 #ifndef UNIV_HOTBACKUP
1165 /** Does an asynchronous write of a buffer page.
1166 @param[in] bpage buffer block to write
1167 @param[in] flush_type type of flush
1168 @param[in] sync true if sync IO request */
1169 static void buf_flush_write_block_low(buf_page_t *bpage, buf_flush_t flush_type,
1170 bool sync) {
1171 page_t *frame = nullptr;
1172
1173 #ifdef UNIV_DEBUG
1174 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
1175 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
1176 #endif /* UNIV_DEBUG */
1177
1178 DBUG_PRINT("ib_buf", ("flush %s %u page " UINT32PF ":" UINT32PF,
1179 sync ? "sync" : "async", (unsigned)flush_type,
1180 bpage->id.space(), bpage->id.page_no()));
1181
1182 ut_ad(buf_page_in_file(bpage));
1183
1184 /* We are not holding block_mutex here. Nevertheless, it is safe to
1185 access bpage, because it is io_fixed and oldest_modification != 0.
1186 Thus, it cannot be relocated in the buffer pool or removed from
1187 flush_list or LRU_list. */
1188 ut_ad(!buf_flush_list_mutex_own(buf_pool));
1189 ut_ad(!buf_page_get_mutex(bpage)->is_owned());
1190 ut_ad(bpage->is_io_fix_write());
1191 ut_ad(bpage->is_dirty());
1192
1193 #ifdef UNIV_IBUF_COUNT_DEBUG
1194 ut_a(ibuf_count_get(bpage->id) == 0);
1195 #endif /* UNIV_IBUF_COUNT_DEBUG */
1196
1197 ut_ad(recv_recovery_is_on() || bpage->get_newest_lsn() != 0);
1198
1199 /* Force the log to the disk before writing the modified block */
1200 if (!srv_read_only_mode) {
1201 const lsn_t flush_to_lsn = bpage->get_newest_lsn();
1202
1203 /* Do the check before calling log_write_up_to() because in most
1204 cases it would allow to avoid call, and because of that we don't
1205 want those calls because they would have bad impact on the counter
1206 of calls, which is monitored to save CPU on spinning in log threads. */
1207
1208 if (log_sys->flushed_to_disk_lsn.load() < flush_to_lsn) {
1209 Wait_stats wait_stats;
1210
1211 wait_stats = log_write_up_to(*log_sys, flush_to_lsn, true);
1212
1213 MONITOR_INC_WAIT_STATS_EX(MONITOR_ON_LOG_, _PAGE_WRITTEN, wait_stats);
1214 }
1215 }
1216
1217 switch (buf_page_get_state(bpage)) {
1218 case BUF_BLOCK_POOL_WATCH:
1219 case BUF_BLOCK_ZIP_PAGE: /* The page should be dirty. */
1220 case BUF_BLOCK_NOT_USED:
1221 case BUF_BLOCK_READY_FOR_USE:
1222 case BUF_BLOCK_MEMORY:
1223 case BUF_BLOCK_REMOVE_HASH:
1224 ut_error;
1225 break;
1226 case BUF_BLOCK_ZIP_DIRTY: {
1227 frame = bpage->zip.data;
1228 BlockReporter reporter =
1229 BlockReporter(false, frame, bpage->size,
1230 fsp_is_checksum_disabled(bpage->id.space()));
1231
1232 mach_write_to_8(frame + FIL_PAGE_LSN, bpage->get_newest_lsn());
1233
1234 ut_a(reporter.verify_zip_checksum());
1235 break;
1236 }
1237 case BUF_BLOCK_FILE_PAGE:
1238 frame = bpage->zip.data;
1239 if (!frame) {
1240 frame = ((buf_block_t *)bpage)->frame;
1241 }
1242
1243 buf_flush_init_for_writing(
1244 reinterpret_cast<const buf_block_t *>(bpage),
1245 reinterpret_cast<const buf_block_t *>(bpage)->frame,
1246 bpage->zip.data ? &bpage->zip : nullptr, bpage->get_newest_lsn(),
1247 fsp_is_checksum_disabled(bpage->id.space()),
1248 false /* do not skip lsn check */);
1249 break;
1250 }
1251
1252 dberr_t err = dblwr::write(flush_type, bpage, sync);
1253
1254 ut_a(err == DB_SUCCESS || err == DB_TABLESPACE_DELETED);
1255
1256 /* Increment the counter of I/O operations used
1257 for selecting LRU policy. */
1258 buf_LRU_stat_inc_io();
1259 }
1260
1261 /** Writes a flushable page asynchronously from the buffer pool to a file.
1262 NOTE: 1. in simulated aio we must call os_aio_simulated_wake_handler_threads
1263 after we have posted a batch of writes! 2. buf_page_get_mutex(bpage) must be
1264 held upon entering this function. The LRU list mutex must be held if flush_type
1265 == BUF_FLUSH_SINGLE_PAGE. Both mutexes will be released by this function if it
1266 returns true.
1267 @param[in] buf_pool buffer pool instance
1268 @param[in] bpage buffer control block
1269 @param[in] flush_type type of flush
1270 @param[in] sync true if sync IO request
1271 @return true if page was flushed */
1272 bool buf_flush_page(buf_pool_t *buf_pool, buf_page_t *bpage,
1273 buf_flush_t flush_type, bool sync) {
1274 BPageMutex *block_mutex;
1275
1276 ut_ad(flush_type < BUF_FLUSH_N_TYPES);
1277 /* Hold the LRU list mutex iff called for a single page LRU
1278 flush. A single page LRU flush is already non-performant, and holding
1279 the LRU list mutex allows us to avoid having to store the previous LRU
1280 list page or to restart the LRU scan in
1281 buf_flush_single_page_from_LRU(). */
1282 ut_ad(flush_type == BUF_FLUSH_SINGLE_PAGE ||
1283 !mutex_own(&buf_pool->LRU_list_mutex));
1284 ut_ad(flush_type != BUF_FLUSH_SINGLE_PAGE ||
1285 mutex_own(&buf_pool->LRU_list_mutex));
1286 ut_ad(buf_page_in_file(bpage));
1287 ut_ad(!sync || flush_type == BUF_FLUSH_SINGLE_PAGE);
1288
1289 block_mutex = buf_page_get_mutex(bpage);
1290 ut_ad(mutex_own(block_mutex));
1291
1292 ut_ad(buf_flush_ready_for_flush(bpage, flush_type));
1293
1294 bool is_uncompressed;
1295
1296 is_uncompressed = (buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE);
1297 ut_ad(is_uncompressed == (block_mutex != &buf_pool->zip_mutex));
1298
1299 bool flush;
1300 rw_lock_t *rw_lock = nullptr;
1301 bool no_fix_count = bpage->buf_fix_count == 0;
1302
1303 if (!is_uncompressed) {
1304 flush = true;
1305 rw_lock = nullptr;
1306 } else if (!(no_fix_count || flush_type == BUF_FLUSH_LIST) ||
1307 (!no_fix_count &&
1308 srv_shutdown_state.load() < SRV_SHUTDOWN_FLUSH_PHASE &&
1309 fsp_is_system_temporary(bpage->id.space()))) {
1310 /* This is a heuristic, to avoid expensive SX attempts. */
1311 /* For table residing in temporary tablespace sync is done
1312 using IO_FIX and so before scheduling for flush ensure that
1313 page is not fixed. */
1314 flush = false;
1315 } else {
1316 rw_lock = &reinterpret_cast<buf_block_t *>(bpage)->lock;
1317 if (flush_type != BUF_FLUSH_LIST) {
1318 flush = rw_lock_sx_lock_nowait(rw_lock, BUF_IO_WRITE, UT_LOCATION_HERE);
1319 } else {
1320 /* Will SX lock later */
1321 flush = true;
1322 }
1323 }
1324
1325 if (flush) {
1326 /* We are committed to flushing by the time we get here */
1327
1328 mutex_enter(&buf_pool->flush_state_mutex);
1329
1330 buf_page_set_io_fix(bpage, BUF_IO_WRITE);
1331
1332 buf_page_set_flush_type(bpage, flush_type);
1333
1334 if (buf_pool->n_flush[flush_type] == 0) {
1335 os_event_reset(buf_pool->no_flush[flush_type]);
1336 }
1337
1338 ++buf_pool->n_flush[flush_type];
1339
1340 if (bpage->get_oldest_lsn() > buf_pool->max_lsn_io) {
1341 buf_pool->max_lsn_io = bpage->get_oldest_lsn();
1342 }
1343
1344 if (!fsp_is_system_temporary(bpage->id.space()) &&
1345 buf_pool->track_page_lsn != LSN_MAX) {
1346 auto frame = bpage->zip.data;
1347
1348 if (frame == nullptr) {
1349 frame = ((buf_block_t *)bpage)->frame;
1350 }
1351 lsn_t frame_lsn = mach_read_from_8(frame + FIL_PAGE_LSN);
1352
1353 arch_page_sys->track_page(bpage, buf_pool->track_page_lsn, frame_lsn,
1354 false);
1355 }
1356
1357 mutex_exit(&buf_pool->flush_state_mutex);
1358
1359 mutex_exit(block_mutex);
1360
1361 if (flush_type == BUF_FLUSH_SINGLE_PAGE) {
1362 mutex_exit(&buf_pool->LRU_list_mutex);
1363 }
1364
1365 if (flush_type == BUF_FLUSH_LIST && is_uncompressed &&
1366 !rw_lock_sx_lock_nowait(rw_lock, BUF_IO_WRITE, UT_LOCATION_HERE)) {
1367 if (!fsp_is_system_temporary(bpage->id.space()) && dblwr::is_enabled()) {
1368 dblwr::force_flush(flush_type, buf_pool_index(buf_pool));
1369 } else {
1370 buf_flush_sync_datafiles();
1371 }
1372
1373 rw_lock_sx_lock_gen(rw_lock, BUF_IO_WRITE, UT_LOCATION_HERE);
1374 }
1375
1376 /* If there is an observer that wants to know if the
1377 asynchronous flushing was sent then notify it.
1378 Note: we set flush observer to a page with x-latch, so we can
1379 guarantee that notify_flush and notify_remove are called in pair
1380 with s-latch on a uncompressed page. */
1381 if (bpage->get_flush_observer() != nullptr) {
1382 bpage->get_flush_observer()->notify_flush(buf_pool, bpage);
1383 }
1384
1385 /* Even though bpage is not protected by any mutex at this
1386 point, it is safe to access bpage, because it is io_fixed and
1387 oldest_modification != 0. Thus, it cannot be relocated in the
1388 buffer pool or removed from flush_list or LRU_list. */
1389
1390 buf_flush_write_block_low(bpage, flush_type, sync);
1391 }
1392
1393 return flush;
1394 }
1395
1396 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
1397 /** Writes a flushable page asynchronously from the buffer pool to a file.
1398 NOTE: block and LRU list mutexes must be held upon entering this function, and
1399 they will be released by this function after flushing. This is loosely based on
1400 buf_flush_batch() and buf_flush_page().
1401 @param[in,out] buf_pool buffer pool instance
1402 @param[in,out] block buffer control block
1403 @return true if the page was flushed and the mutex released */
1404 bool buf_flush_page_try(buf_pool_t *buf_pool, buf_block_t *block) {
1405 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1406 ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
1407 ut_ad(mutex_own(buf_page_get_mutex(&block->page)));
1408
1409 if (!buf_flush_ready_for_flush(&block->page, BUF_FLUSH_SINGLE_PAGE)) {
1410 return false;
1411 }
1412
1413 /* The following call will release the LRU list and block mutexes. */
1414 return (buf_flush_page(buf_pool, &block->page, BUF_FLUSH_SINGLE_PAGE, true));
1415 }
1416 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
1417
1418 /** Check if the page is in buffer pool and can be flushed.
1419 @param[in] page_id page id
1420 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST
1421 @return true if the page can be flushed. */
1422 static bool buf_flush_check_neighbor(const page_id_t &page_id,
1423 buf_flush_t flush_type) {
1424 buf_page_t *bpage;
1425 buf_pool_t *buf_pool = buf_pool_get(page_id);
1426 bool ret;
1427 rw_lock_t *hash_lock;
1428 BPageMutex *block_mutex;
1429
1430 ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST);
1431
1432 /* We only want to flush pages from this buffer pool. */
1433 bpage = buf_page_hash_get_s_locked(buf_pool, page_id, &hash_lock);
1434
1435 if (!bpage) {
1436 return (false);
1437 }
1438
1439 block_mutex = buf_page_get_mutex(bpage);
1440
1441 mutex_enter(block_mutex);
1442
1443 rw_lock_s_unlock(hash_lock);
1444
1445 ut_a(buf_page_in_file(bpage));
1446
1447 /* We avoid flushing 'non-old' blocks in an LRU flush,
1448 because the flushed blocks are soon freed */
1449
1450 ret = false;
1451 if (flush_type != BUF_FLUSH_LRU || buf_page_is_old(bpage)) {
1452 if (buf_flush_ready_for_flush(bpage, flush_type)) {
1453 ret = true;
1454 }
1455 }
1456
1457 mutex_exit(block_mutex);
1458
1459 return (ret);
1460 }
1461
1462 /** Flushes to disk all flushable pages within the flush area.
1463 @param[in] page_id page id
1464 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST
1465 @param[in] n_flushed number of pages flushed so far in this batch
1466 @param[in] n_to_flush maximum number of pages we are allowed to flush
1467 @return number of pages flushed */
1468 static ulint buf_flush_try_neighbors(const page_id_t &page_id,
1469 buf_flush_t flush_type, ulint n_flushed,
1470 ulint n_to_flush) {
1471 page_no_t i;
1472 page_no_t low;
1473 page_no_t high;
1474 ulint count = 0;
1475 buf_pool_t *buf_pool = buf_pool_get(page_id);
1476
1477 ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST);
1478 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
1479 ut_ad(!buf_flush_list_mutex_own(buf_pool));
1480
1481 if (UT_LIST_GET_LEN(buf_pool->LRU) < BUF_LRU_OLD_MIN_LEN ||
1482 srv_flush_neighbors == 0) {
1483 /* If there is little space or neighbor flushing is
1484 not enabled then just flush the victim. */
1485 low = page_id.page_no();
1486 high = page_id.page_no() + 1;
1487 } else {
1488 /* When flushed, dirty blocks are searched in
1489 neighborhoods of this size, and flushed along with the
1490 original page. */
1491
1492 page_no_t buf_flush_area;
1493
1494 buf_flush_area = std::min(buf_pool->read_ahead_area,
1495 static_cast<page_no_t>(buf_pool->curr_size / 16));
1496
1497 low = (page_id.page_no() / buf_flush_area) * buf_flush_area;
1498 high = (page_id.page_no() / buf_flush_area + 1) * buf_flush_area;
1499
1500 if (srv_flush_neighbors == 1) {
1501 /* adjust 'low' and 'high' to limit
1502 for contiguous dirty area */
1503 if (page_id.page_no() > low) {
1504 for (i = page_id.page_no() - 1; i >= low; i--) {
1505 if (!buf_flush_check_neighbor(page_id_t(page_id.space(), i),
1506 flush_type)) {
1507 break;
1508 }
1509
1510 if (i == low) {
1511 /* Avoid overwrap when low == 0
1512 and calling
1513 buf_flush_check_neighbor() with
1514 i == (ulint) -1 */
1515 i--;
1516 break;
1517 }
1518 }
1519 low = i + 1;
1520 }
1521
1522 for (i = page_id.page_no() + 1;
1523 i < high &&
1524 buf_flush_check_neighbor(page_id_t(page_id.space(), i), flush_type);
1525 i++) {
1526 /* do nothing */
1527 }
1528 high = i;
1529 }
1530 }
1531
1532 DBUG_PRINT("ib_buf", ("flush " UINT32PF ":%u..%u", page_id.space(),
1533 (unsigned)low, (unsigned)high));
1534
1535 for (i = low; i < high; i++) {
1536 if ((count + n_flushed) >= n_to_flush) {
1537 /* We have already flushed enough pages and
1538 should call it a day. There is, however, one
1539 exception. If the page whose neighbors we
1540 are flushing has not been flushed yet then
1541 we'll try to flush the victim that we
1542 selected originally. */
1543 if (i <= page_id.page_no()) {
1544 i = page_id.page_no();
1545 } else {
1546 break;
1547 }
1548 }
1549
1550 const page_id_t cur_page_id(page_id.space(), i);
1551
1552 auto buf_pool = buf_pool_get(cur_page_id);
1553
1554 rw_lock_t *hash_lock;
1555
1556 /* We only want to flush pages from this buffer pool. */
1557 auto bpage = buf_page_hash_get_s_locked(buf_pool, cur_page_id, &hash_lock);
1558
1559 if (bpage == nullptr) {
1560 continue;
1561 }
1562
1563 auto block_mutex = buf_page_get_mutex(bpage);
1564
1565 mutex_enter(block_mutex);
1566
1567 if (flush_type == BUF_FLUSH_LIST &&
1568 buf_flush_ready_for_flush(bpage, flush_type) &&
1569 bpage->buf_fix_count == 0 && bpage->was_stale()) {
1570 mutex_exit(block_mutex);
1571 buf_page_free_stale(buf_pool, bpage, hash_lock);
1572 continue;
1573 }
1574
1575 rw_lock_s_unlock(hash_lock);
1576
1577 ut_a(buf_page_in_file(bpage));
1578
1579 /* We avoid flushing 'non-old' blocks in an LRU flush,
1580 because the flushed blocks are soon freed */
1581
1582 if (flush_type != BUF_FLUSH_LRU || i == page_id.page_no() ||
1583 buf_page_is_old(bpage)) {
1584 if (buf_flush_ready_for_flush(bpage, flush_type) &&
1585 (i == page_id.page_no() || bpage->buf_fix_count == 0)) {
1586 /* We also try to flush those
1587 neighbors != offset */
1588
1589 if (buf_flush_page(buf_pool, bpage, flush_type, false)) {
1590 ++count;
1591 } else {
1592 mutex_exit(block_mutex);
1593 }
1594
1595 continue;
1596 }
1597 }
1598
1599 mutex_exit(block_mutex);
1600 }
1601
1602 if (count > 1) {
1603 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_NEIGHBOR_TOTAL_PAGE,
1604 MONITOR_FLUSH_NEIGHBOR_COUNT,
1605 MONITOR_FLUSH_NEIGHBOR_PAGES, (count - 1));
1606 }
1607
1608 return (count);
1609 }
1610
1611 /** Check if the block is modified and ready for flushing.
1612 If ready to flush then flush the page and try o flush its neighbors. The caller
1613 must hold the buffer pool list mutex corresponding to the type of flush.
1614 @param[in] bpage buffer control block,
1615 must be buf_page_in_file(bpage)
1616 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST
1617 @param[in] n_to_flush number of pages to flush
1618 @param[in,out] count number of pages flushed
1619 @return true if the list mutex was released during this function. This does
1620 not guarantee that some pages were written as well. */
1621 static bool buf_flush_page_and_try_neighbors(buf_page_t *bpage,
1622 buf_flush_t flush_type,
1623 ulint n_to_flush, ulint *count) {
1624 #ifdef UNIV_DEBUG
1625 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
1626 #endif /* UNIV_DEBUG */
1627
1628 bool flushed;
1629 BPageMutex *block_mutex = nullptr;
1630
1631 ut_ad(flush_type != BUF_FLUSH_SINGLE_PAGE);
1632
1633 ut_ad((flush_type == BUF_FLUSH_LRU && mutex_own(&buf_pool->LRU_list_mutex)) ||
1634 (flush_type == BUF_FLUSH_LIST && buf_flush_list_mutex_own(buf_pool)));
1635
1636 if (flush_type == BUF_FLUSH_LRU) {
1637 block_mutex = buf_page_get_mutex(bpage);
1638 mutex_enter(block_mutex);
1639 }
1640
1641 #ifdef UNIV_DEBUG
1642 if (!buf_page_in_file(bpage)) {
1643 ut_ad(buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
1644 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
1645 }
1646 #else
1647 ut_a(buf_page_in_file(bpage) ||
1648 buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
1649 #endif /* UNIV_DEBUG */
1650
1651 /* This is just a heuristic check, perhaps without block mutex latch, so we
1652 will repeat the check with block mutexes in buf_flush_try_neighbors. */
1653 if (buf_flush_was_ready_for_flush(bpage, flush_type)) {
1654 buf_pool_t *buf_pool;
1655
1656 buf_pool = buf_pool_from_bpage(bpage);
1657
1658 if (flush_type == BUF_FLUSH_LRU) {
1659 mutex_exit(&buf_pool->LRU_list_mutex);
1660 }
1661
1662 const page_id_t page_id = bpage->id;
1663
1664 if (flush_type == BUF_FLUSH_LRU) {
1665 mutex_exit(block_mutex);
1666 } else {
1667 buf_flush_list_mutex_exit(buf_pool);
1668 }
1669
1670 /* Try to flush also all the neighbors */
1671 *count += buf_flush_try_neighbors(page_id, flush_type, *count, n_to_flush);
1672
1673 if (flush_type == BUF_FLUSH_LRU) {
1674 mutex_enter(&buf_pool->LRU_list_mutex);
1675 } else {
1676 buf_flush_list_mutex_enter(buf_pool);
1677 }
1678 flushed = true;
1679
1680 } else if (flush_type == BUF_FLUSH_LRU) {
1681 mutex_exit(block_mutex);
1682
1683 flushed = false;
1684 } else {
1685 flushed = false;
1686 }
1687
1688 ut_ad((flush_type == BUF_FLUSH_LRU && mutex_own(&buf_pool->LRU_list_mutex)) ||
1689 (flush_type == BUF_FLUSH_LIST && buf_flush_list_mutex_own(buf_pool)));
1690
1691 return (flushed);
1692 }
1693
1694 /** This utility moves the uncompressed frames of pages to the free list.
1695 Note that this function does not actually flush any data to disk. It
1696 just detaches the uncompressed frames from the compressed pages at the
1697 tail of the unzip_LRU and puts those freed frames in the free list.
1698 Note that it is a best effort attempt and it is not guaranteed that
1699 after a call to this function there will be 'max' blocks in the free
1700 list. The caller must hold the LRU list mutex.
1701 @param[in] buf_pool buffer pool instance
1702 @param[in] max desired number of blocks in the free_list
1703 @return number of blocks moved to the free list. */
1704 static ulint buf_free_from_unzip_LRU_list_batch(buf_pool_t *buf_pool,
1705 ulint max) {
1706 ulint scanned = 0;
1707 ulint count = 0;
1708 ulint free_len = UT_LIST_GET_LEN(buf_pool->free);
1709 ulint lru_len = UT_LIST_GET_LEN(buf_pool->unzip_LRU);
1710
1711 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1712
1713 buf_block_t *block = UT_LIST_GET_LAST(buf_pool->unzip_LRU);
1714
1715 while (block != nullptr && count < max && free_len < srv_LRU_scan_depth &&
1716 lru_len > UT_LIST_GET_LEN(buf_pool->LRU) / 10) {
1717 BPageMutex *block_mutex = buf_page_get_mutex(&block->page);
1718
1719 ++scanned;
1720
1721 mutex_enter(block_mutex);
1722
1723 if (buf_LRU_free_page(&block->page, false)) {
1724 /* Block was freed, all mutexes released */
1725 ++count;
1726 mutex_enter(&buf_pool->LRU_list_mutex);
1727 block = UT_LIST_GET_LAST(buf_pool->unzip_LRU);
1728
1729 } else {
1730 mutex_exit(block_mutex);
1731 block = UT_LIST_GET_PREV(unzip_LRU, block);
1732 }
1733
1734 free_len = UT_LIST_GET_LEN(buf_pool->free);
1735 lru_len = UT_LIST_GET_LEN(buf_pool->unzip_LRU);
1736 }
1737
1738 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1739
1740 if (scanned) {
1741 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_BATCH_SCANNED,
1742 MONITOR_LRU_BATCH_SCANNED_NUM_CALL,
1743 MONITOR_LRU_BATCH_SCANNED_PER_CALL, scanned);
1744 }
1745
1746 return (count);
1747 }
1748
1749 /** This utility flushes dirty blocks from the end of the LRU list.
1750 The calling thread is not allowed to own any latches on pages!
1751 It attempts to make 'max' blocks available in the free list. Note that
1752 it is a best effort attempt and it is not guaranteed that after a call
1753 to this function there will be 'max' blocks in the free list.
1754 @param[in] buf_pool buffer pool instance
1755 @param[in] max desired number for blocks in the free_list
1756 @return number of blocks for which the write request was queued. */
1757 static ulint buf_flush_LRU_list_batch(buf_pool_t *buf_pool, ulint max) {
1758 buf_page_t *bpage;
1759 ulint scanned = 0;
1760 ulint evict_count = 0;
1761 ulint count = 0;
1762 ulint free_len = UT_LIST_GET_LEN(buf_pool->free);
1763 ulint lru_len = UT_LIST_GET_LEN(buf_pool->LRU);
1764 ulint withdraw_depth;
1765
1766 withdraw_depth = buf_get_withdraw_depth(buf_pool);
1767
1768 for (bpage = UT_LIST_GET_LAST(buf_pool->LRU);
1769 bpage != nullptr && count + evict_count < max &&
1770 free_len < srv_LRU_scan_depth + withdraw_depth &&
1771 lru_len > BUF_LRU_MIN_LEN;
1772 ++scanned, bpage = buf_pool->lru_hp.get()) {
1773 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1774
1775 auto prev = UT_LIST_GET_PREV(LRU, bpage);
1776 buf_pool->lru_hp.set(prev);
1777
1778 auto block_mutex = buf_page_get_mutex(bpage);
1779
1780 if (bpage->was_stale()) {
1781 if (buf_page_free_stale(buf_pool, bpage)) {
1782 ++evict_count;
1783 mutex_enter(&buf_pool->LRU_list_mutex);
1784 }
1785 } else {
1786 auto acquired = mutex_enter_nowait(block_mutex) == 0;
1787
1788 if (acquired && buf_flush_ready_for_replace(bpage)) {
1789 /* block is ready for eviction i.e., it is
1790 clean and is not IO-fixed or buffer fixed. */
1791 if (buf_LRU_free_page(bpage, true)) {
1792 ++evict_count;
1793 mutex_enter(&buf_pool->LRU_list_mutex);
1794 } else {
1795 mutex_exit(block_mutex);
1796 }
1797 } else if (acquired && buf_flush_ready_for_flush(bpage, BUF_FLUSH_LRU)) {
1798 /* Block is ready for flush. Dispatch an IO request. The IO helper
1799 thread will put it on the free list in the IO completion routine. */
1800 mutex_exit(block_mutex);
1801 buf_flush_page_and_try_neighbors(bpage, BUF_FLUSH_LRU, max, &count);
1802 } else if (!acquired) {
1803 ut_ad(buf_pool->lru_hp.is_hp(prev));
1804 } else {
1805 /* Can't evict or dispatch this block. Go to previous. */
1806 mutex_exit(block_mutex);
1807 ut_ad(buf_pool->lru_hp.is_hp(prev));
1808 }
1809 }
1810
1811 ut_ad(!mutex_own(block_mutex));
1812 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1813
1814 free_len = UT_LIST_GET_LEN(buf_pool->free);
1815 lru_len = UT_LIST_GET_LEN(buf_pool->LRU);
1816 withdraw_depth = buf_get_withdraw_depth(buf_pool);
1817 }
1818
1819 buf_pool->lru_hp.set(nullptr);
1820
1821 /* We keep track of all flushes happening as part of LRU
1822 flush. When estimating the desired rate at which flush_list
1823 should be flushed, we factor in this value. */
1824 buf_lru_flush_page_count += count;
1825
1826 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1827
1828 if (evict_count) {
1829 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_BATCH_EVICT_TOTAL_PAGE,
1830 MONITOR_LRU_BATCH_EVICT_COUNT,
1831 MONITOR_LRU_BATCH_EVICT_PAGES, evict_count);
1832 }
1833
1834 if (scanned) {
1835 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_BATCH_SCANNED,
1836 MONITOR_LRU_BATCH_SCANNED_NUM_CALL,
1837 MONITOR_LRU_BATCH_SCANNED_PER_CALL, scanned);
1838 }
1839
1840 return (count);
1841 }
1842
1843 /** Flush and move pages from LRU or unzip_LRU list to the free list.
1844 Whether LRU or unzip_LRU is used depends on the state of the system.
1845 @param[in] buf_pool buffer pool instance
1846 @param[in] max desired number of blocks in the free_list
1847 @return number of blocks for which either the write request was queued
1848 or in case of unzip_LRU the number of blocks actually moved to the
1849 free list */
1850 static ulint buf_do_LRU_batch(buf_pool_t *buf_pool, ulint max) {
1851 ulint count = 0;
1852
1853 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1854
1855 if (buf_LRU_evict_from_unzip_LRU(buf_pool)) {
1856 count += buf_free_from_unzip_LRU_list_batch(buf_pool, max);
1857 }
1858
1859 if (max > count) {
1860 count += buf_flush_LRU_list_batch(buf_pool, max - count);
1861 }
1862
1863 return (count);
1864 }
1865
1866 /** This utility flushes dirty blocks from the end of the flush_list.
1867 The calling thread is not allowed to own any latches on pages!
1868 @param[in] buf_pool buffer pool instance
1869 @param[in] min_n wished minimum number of blocks flushed (it is
1870 not guaranteed that the actual number is that big, though)
1871 @param[in] lsn_limit all blocks whose oldest_modification is smaller
1872 than this should be flushed (if their number does not exceed min_n)
1873 @return number of blocks for which the write request was queued;
1874 ULINT_UNDEFINED if there was a flush of the same type already
1875 running */
1876 static ulint buf_do_flush_list_batch(buf_pool_t *buf_pool, ulint min_n,
1877 lsn_t lsn_limit) {
1878 ulint count = 0;
1879 ulint scanned = 0;
1880
1881 /* Start from the end of the list looking for a suitable
1882 block to be flushed. */
1883 buf_flush_list_mutex_enter(buf_pool);
1884 ulint len = UT_LIST_GET_LEN(buf_pool->flush_list);
1885
1886 /* In order not to degenerate this scan to O(n*n) we attempt
1887 to preserve pointer of previous block in the flush list. To do
1888 so we declare it a hazard pointer. Any thread working on the
1889 flush list must check the hazard pointer and if it is removing
1890 the same block then it must reset it. */
1891 for (buf_page_t *bpage = UT_LIST_GET_LAST(buf_pool->flush_list);
1892 count < min_n && bpage != nullptr && len > 0 &&
1893 bpage->get_oldest_lsn() < lsn_limit;
1894 bpage = buf_pool->flush_hp.get(), ++scanned) {
1895 buf_page_t *prev;
1896
1897 ut_a(bpage->is_dirty());
1898 ut_ad(bpage->in_flush_list);
1899
1900 prev = UT_LIST_GET_PREV(list, bpage);
1901 buf_pool->flush_hp.set(prev);
1902
1903 #ifdef UNIV_DEBUG
1904 bool flushed =
1905 #endif /* UNIV_DEBUG */
1906 buf_flush_page_and_try_neighbors(bpage, BUF_FLUSH_LIST, min_n, &count);
1907
1908 ut_ad(flushed || buf_pool->flush_hp.is_hp(prev));
1909
1910 --len;
1911 }
1912
1913 buf_pool->flush_hp.set(nullptr);
1914 buf_flush_list_mutex_exit(buf_pool);
1915
1916 if (scanned) {
1917 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_BATCH_SCANNED,
1918 MONITOR_FLUSH_BATCH_SCANNED_NUM_CALL,
1919 MONITOR_FLUSH_BATCH_SCANNED_PER_CALL, scanned);
1920 }
1921
1922 if (count) {
1923 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_BATCH_TOTAL_PAGE,
1924 MONITOR_FLUSH_BATCH_COUNT,
1925 MONITOR_FLUSH_BATCH_PAGES, count);
1926 }
1927
1928 return (count);
1929 }
1930
1931 /** This utility flushes dirty blocks from the end of the LRU list or
1932 flush_list.
1933 NOTE 1: in the case of an LRU flush the calling thread may own latches to
1934 pages: to avoid deadlocks, this function must be written so that it cannot
1935 end up waiting for these latches! NOTE 2: in the case of a flush list flush,
1936 the calling thread is not allowed to own any latches on pages!
1937 @param[in] buf_pool buffer pool instance
1938 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST; if
1939 BUF_FLUSH_LIST, then the caller must not own any latches on pages
1940 @param[in] min_n wished minimum number of blocks flushed (it is
1941 not guaranteed that the actual number is that big, though)
1942 @param[in] lsn_limit in the case of BUF_FLUSH_LIST all blocks whose
1943 oldest_modification is smaller than this should be flushed (if their number
1944 does not exceed min_n), otherwise ignored
1945 @return number of blocks for which the write request was queued */
1946 static ulint buf_flush_batch(buf_pool_t *buf_pool, buf_flush_t flush_type,
1947 ulint min_n, lsn_t lsn_limit) {
1948 ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST);
1949
1950 #ifdef UNIV_DEBUG
1951 {
1952 dict_sync_check check(true);
1953
1954 ut_ad(flush_type != BUF_FLUSH_LIST || !sync_check_iterate(check));
1955 }
1956 #endif /* UNIV_DEBUG */
1957
1958 ulint count = 0;
1959
1960 /* Note: The buffer pool mutexes is released and reacquired within
1961 the flush functions. */
1962 switch (flush_type) {
1963 case BUF_FLUSH_LRU:
1964 mutex_enter(&buf_pool->LRU_list_mutex);
1965 count = buf_do_LRU_batch(buf_pool, min_n);
1966 mutex_exit(&buf_pool->LRU_list_mutex);
1967 break;
1968 case BUF_FLUSH_LIST:
1969 count = buf_do_flush_list_batch(buf_pool, min_n, lsn_limit);
1970 break;
1971 default:
1972 ut_error;
1973 }
1974
1975 DBUG_PRINT("ib_buf", ("flush %u completed, %u pages", unsigned(flush_type),
1976 unsigned(count)));
1977
1978 return (count);
1979 }
1980
1981 /** Gather the aggregated stats for both flush list and LRU list flushing.
1982 @param page_count_flush number of pages flushed from the end of the
1983 flush_list
1984 @param page_count_LRU number of pages flushed from the end of the LRU list
1985 */
1986 static void buf_flush_stats(ulint page_count_flush, ulint page_count_LRU) {
1987 DBUG_PRINT("ib_buf", ("flush completed, from flush_list %u pages, "
1988 "from LRU_list %u pages",
1989 unsigned(page_count_flush), unsigned(page_count_LRU)));
1990
1991 srv_stats.buf_pool_flushed.add(page_count_flush + page_count_LRU);
1992 }
1993
1994 /** Start a buffer flush batch for LRU or flush list
1995 @param[in] buf_pool buffer pool instance
1996 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST */
1997 static bool buf_flush_start(buf_pool_t *buf_pool, buf_flush_t flush_type) {
1998 ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST);
1999
2000 mutex_enter(&buf_pool->flush_state_mutex);
2001
2002 if (buf_pool->n_flush[flush_type] > 0 ||
2003 buf_pool->init_flush[flush_type] == true) {
2004 /* There is already a flush batch of the same type running */
2005
2006 mutex_exit(&buf_pool->flush_state_mutex);
2007
2008 return false;
2009 }
2010
2011 buf_pool->init_flush[flush_type] = true;
2012
2013 os_event_reset(buf_pool->no_flush[flush_type]);
2014
2015 mutex_exit(&buf_pool->flush_state_mutex);
2016
2017 return true;
2018 }
2019
2020 /** End a buffer flush batch for LRU or flush list
2021 @param[in] buf_pool buffer pool instance
2022 @param[in] flush_type BUF_FLUSH_LRU or BUF_FLUSH_LIST */
2023 static void buf_flush_end(buf_pool_t *buf_pool, buf_flush_t flush_type) {
2024 mutex_enter(&buf_pool->flush_state_mutex);
2025
2026 buf_pool->init_flush[flush_type] = false;
2027
2028 buf_pool->try_LRU_scan = true;
2029
2030 if (buf_pool->n_flush[flush_type] == 0) {
2031 /* The running flush batch has ended */
2032
2033 os_event_set(buf_pool->no_flush[flush_type]);
2034 }
2035
2036 mutex_exit(&buf_pool->flush_state_mutex);
2037
2038 if (!srv_read_only_mode) {
2039 if (dblwr::is_enabled()) {
2040 dblwr::force_flush(flush_type, buf_pool_index(buf_pool));
2041 } else {
2042 buf_flush_sync_datafiles();
2043 }
2044 } else {
2045 os_aio_simulated_wake_handler_threads();
2046 }
2047 }
2048
2049 void buf_flush_wait_batch_end(buf_pool_t *buf_pool, buf_flush_t flush_type) {
2050 ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST);
2051
2052 if (buf_pool == nullptr) {
2053 ulint i;
2054
2055 for (i = 0; i < srv_buf_pool_instances; ++i) {
2056 auto buf_pool = buf_pool_from_array(i);
2057
2058 thd_wait_begin(nullptr, THD_WAIT_DISKIO);
2059 os_event_wait(buf_pool->no_flush[flush_type]);
2060 thd_wait_end(nullptr);
2061 }
2062 } else {
2063 thd_wait_begin(nullptr, THD_WAIT_DISKIO);
2064 os_event_wait(buf_pool->no_flush[flush_type]);
2065 thd_wait_end(nullptr);
2066 }
2067 }
2068
2069 bool buf_flush_do_batch(buf_pool_t *buf_pool, buf_flush_t type, ulint min_n,
2070 lsn_t lsn_limit, ulint *n_processed) {
2071 ut_ad(type == BUF_FLUSH_LRU || type == BUF_FLUSH_LIST);
2072
2073 if (n_processed != nullptr) {
2074 *n_processed = 0;
2075 }
2076
2077 if (!buf_flush_start(buf_pool, type)) {
2078 return (false);
2079 }
2080
2081 ulint page_count = buf_flush_batch(buf_pool, type, min_n, lsn_limit);
2082
2083 buf_flush_end(buf_pool, type);
2084
2085 if (n_processed != nullptr) {
2086 *n_processed = page_count;
2087 }
2088
2089 return (true);
2090 }
2091
2092 bool buf_flush_lists(ulint min_n, lsn_t lsn_limit, ulint *n_processed) {
2093 ulint n_flushed = 0;
2094 bool success = true;
2095
2096 if (n_processed) {
2097 *n_processed = 0;
2098 }
2099
2100 if (min_n != ULINT_MAX) {
2101 /* Ensure that flushing is spread evenly amongst the
2102 buffer pool instances. When min_n is ULINT_MAX
2103 we need to flush everything up to the lsn limit
2104 so no limit here. */
2105 min_n = ut::div_ceil(min_n, ulint{srv_buf_pool_instances});
2106 }
2107
2108 /* Flush to lsn_limit in all buffer pool instances */
2109 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2110 buf_pool_t *buf_pool;
2111 ulint page_count = 0;
2112
2113 buf_pool = buf_pool_from_array(i);
2114
2115 if (!buf_flush_do_batch(buf_pool, BUF_FLUSH_LIST, min_n, lsn_limit,
2116 &page_count)) {
2117 /* We have two choices here. If lsn_limit was
2118 specified then skipping an instance of buffer
2119 pool means we cannot guarantee that all pages
2120 up to lsn_limit has been flushed. We can
2121 return right now with failure or we can try
2122 to flush remaining buffer pools up to the
2123 lsn_limit. We attempt to flush other buffer
2124 pools based on the assumption that it will
2125 help in the retry which will follow the
2126 failure. */
2127 success = false;
2128
2129 continue;
2130 }
2131
2132 n_flushed += page_count;
2133 }
2134
2135 if (n_flushed) {
2136 buf_flush_stats(n_flushed, 0);
2137 }
2138
2139 if (n_processed) {
2140 *n_processed = n_flushed;
2141 }
2142
2143 return (success);
2144 }
2145
2146 /** This function picks up a single page from the tail of the LRU
2147 list, flushes it (if it is dirty), removes it from page_hash and LRU
2148 list and puts it on the free list. It is called from user threads when
2149 they are unable to find a replaceable page at the tail of the LRU
2150 list i.e.: when the background LRU flushing in the page_cleaner thread
2151 is not fast enough to keep pace with the workload.
2152 @param[in,out] buf_pool buffer pool instance
2153 @return true if success. */
2154 bool buf_flush_single_page_from_LRU(buf_pool_t *buf_pool) {
2155 bool freed;
2156 ulint scanned;
2157 buf_page_t *bpage;
2158
2159 mutex_enter(&buf_pool->LRU_list_mutex);
2160
2161 for (bpage = buf_pool->single_scan_itr.start(), scanned = 0, freed = false;
2162 bpage != nullptr; ++scanned, bpage = buf_pool->single_scan_itr.get()) {
2163 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
2164
2165 auto prev = UT_LIST_GET_PREV(LRU, bpage);
2166
2167 buf_pool->single_scan_itr.set(prev);
2168
2169 if (bpage->was_stale()) {
2170 freed = buf_page_free_stale(buf_pool, bpage);
2171 if (freed) {
2172 break;
2173 }
2174 } else {
2175 auto block_mutex = buf_page_get_mutex(bpage);
2176
2177 mutex_enter(block_mutex);
2178
2179 if (buf_flush_ready_for_replace(bpage)) {
2180 /* block is ready for eviction i.e., it is
2181 clean and is not IO-fixed or buffer fixed. */
2182
2183 if (buf_LRU_free_page(bpage, true)) {
2184 freed = true;
2185 break;
2186 }
2187
2188 mutex_exit(block_mutex);
2189
2190 } else if (buf_flush_ready_for_flush(bpage, BUF_FLUSH_SINGLE_PAGE)) {
2191 /* Block is ready for flush. Try and dispatch an IO
2192 request. We'll put it on free list in IO completion
2193 routine if it is not buffer fixed. The following call
2194 will release the buffer pool and block mutex.
2195
2196 Note: There is no guarantee that this page has actually
2197 been freed, only that it has been flushed to disk */
2198
2199 freed = buf_flush_page(buf_pool, bpage, BUF_FLUSH_SINGLE_PAGE, true);
2200
2201 if (freed) {
2202 break;
2203 }
2204
2205 mutex_exit(block_mutex);
2206 } else {
2207 mutex_exit(block_mutex);
2208 }
2209 ut_ad(!mutex_own(block_mutex));
2210 }
2211 }
2212
2213 if (!freed) {
2214 /* Can't find a single flushable page. */
2215 ut_ad(bpage == nullptr);
2216 mutex_exit(&buf_pool->LRU_list_mutex);
2217 }
2218
2219 if (scanned) {
2220 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_SINGLE_FLUSH_SCANNED,
2221 MONITOR_LRU_SINGLE_FLUSH_SCANNED_NUM_CALL,
2222 MONITOR_LRU_SINGLE_FLUSH_SCANNED_PER_CALL,
2223 scanned);
2224 }
2225
2226 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
2227
2228 return freed;
2229 }
2230
2231 /**
2232 Clears up tail of the LRU list of a given buffer pool instance:
2233 * Put replaceable pages at the tail of LRU to the free list
2234 * Flush dirty pages at the tail of LRU to the disk
2235 The depth to which we scan each buffer pool is controlled by dynamic
2236 config parameter innodb_LRU_scan_depth.
2237 @param buf_pool buffer pool instance
2238 @return total pages flushed */
2239 static ulint buf_flush_LRU_list(buf_pool_t *buf_pool) {
2240 ulint scan_depth, withdraw_depth;
2241 ulint n_flushed = 0;
2242
2243 ut_ad(buf_pool);
2244
2245 /* srv_LRU_scan_depth can be arbitrarily large value.
2246 We cap it with current LRU size. */
2247 scan_depth = UT_LIST_GET_LEN(buf_pool->LRU);
2248 withdraw_depth = buf_get_withdraw_depth(buf_pool);
2249
2250 if (withdraw_depth > srv_LRU_scan_depth) {
2251 scan_depth = std::min(withdraw_depth, scan_depth);
2252 } else {
2253 scan_depth = std::min(static_cast<ulint>(srv_LRU_scan_depth), scan_depth);
2254 }
2255
2256 /* Currently one of page_cleaners is the only thread
2257 that can trigger an LRU flush at the same time.
2258 So, it is not possible that a batch triggered during
2259 last iteration is still running, */
2260 buf_flush_do_batch(buf_pool, BUF_FLUSH_LRU, scan_depth, 0, &n_flushed);
2261
2262 return (n_flushed);
2263 }
2264
2265 /** Wait for any possible LRU flushes that are in progress to end. */
2266 void buf_flush_wait_LRU_batch_end(void) {
2267 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2268 buf_pool_t *buf_pool;
2269
2270 buf_pool = buf_pool_from_array(i);
2271
2272 mutex_enter(&buf_pool->flush_state_mutex);
2273
2274 if (buf_pool->n_flush[BUF_FLUSH_LRU] > 0 ||
2275 buf_pool->init_flush[BUF_FLUSH_LRU]) {
2276 mutex_exit(&buf_pool->flush_state_mutex);
2277 buf_flush_wait_batch_end(buf_pool, BUF_FLUSH_LRU);
2278 } else {
2279 mutex_exit(&buf_pool->flush_state_mutex);
2280 }
2281 }
2282 }
2283
2284 namespace Adaptive_flush {
2285
2286 /** Time stamp of current iteration. */
2287 std::chrono::steady_clock::time_point cur_iter_time;
2288
2289 /** LSN at current iteration. */
2290 lsn_t cur_iter_lsn = 0;
2291
2292 /** Number of dirty pages in flush list in current iteration. */
2293 ulint cur_iter_pages_dirty = 0;
2294
2295 /** Dirty page percentage in buffer pool. */
2296 ulint cur_iter_dirty_pct = 0;
2297
2298 /** Time stamp of previous iteration. */
2299 std::chrono::steady_clock::time_point prev_iter_time;
2300
2301 /** Number of dirty pages in flush list at previous iteration. */
2302 ulint prev_iter_pages_dirty = 0;
2303
2304 /** Actual number of pages flushed by last iteration. */
2305 ulint prev_iter_pages_flushed = 0;
2306
2307 /** Average redo generation rate */
2308 lsn_t lsn_avg_rate = 0;
2309
2310 /** Average page flush rate */
2311 ulint page_avg_rate = 0;
2312
2313 /** LSN when last average rates are computed. */
2314 lsn_t prev_lsn = 0;
2315
2316 /** Time stamp when last average rates are computed. */
2317 std::chrono::steady_clock::time_point prev_time;
2318
2319 /** Number of iteration till average rates are computed. */
2320 ulint n_iterations = 0;
2321
2322 /** Pages flushed till last average rates are computed.*/
2323 ulint sum_pages = 0;
2324
2325 /** Initialize flush parameters for current iteration.
2326 @param[in] n_pages_last number of pages flushed in last iteration
2327 @return true if current iteration should be skipped. */
2328 bool initialize(ulint n_pages_last) {
2329 lsn_t curr_lsn = log_buffer_dirty_pages_added_up_to_lsn(*log_sys);
2330 const auto curr_time = std::chrono::steady_clock::now();
2331
2332 if (prev_lsn == 0) {
2333 /* First time initialization for next average computation. */
2334 prev_lsn = curr_lsn;
2335 prev_time = curr_time;
2336 prev_iter_time = curr_time;
2337
2338 return (true);
2339 }
2340
2341 prev_iter_pages_flushed = n_pages_last;
2342
2343 cur_iter_lsn = curr_lsn;
2344 cur_iter_time = curr_time;
2345 cur_iter_pages_dirty = 0;
2346
2347 return (false);
2348 }
2349
2350 /** Set average LSN and page flush speed across multiple iterations. */
2351 void set_average() {
2352 ++n_iterations;
2353 sum_pages += prev_iter_pages_flushed;
2354 auto time_elapsed = cur_iter_time - prev_time;
2355
2356 if (time_elapsed < std::chrono::seconds{1}) {
2357 time_elapsed = std::chrono::seconds{1};
2358 }
2359
2360 auto avg_loops = srv_flushing_avg_loops;
2361
2362 /* Adjust flushing loop when redo log flush is disabled. */
2363 if (mtr_t::s_logging.is_disabled()) {
2364 auto nolog_loop = mtr_t::s_logging.get_nolog_flush_loop();
2365 if (nolog_loop < avg_loops) {
2366 avg_loops = nolog_loop;
2367 }
2368 }
2369
2370 /* We update our variables every srv_flushing_avg_loops iterations to smooth
2371 out transition in workload. */
2372 if (n_iterations < avg_loops &&
2373 time_elapsed < std::chrono::seconds{avg_loops}) {
2374 return;
2375 }
2376
2377 const auto time_elapsed_sec =
2378 std::chrono::duration_cast<std::chrono::duration<double>>(time_elapsed)
2379 .count();
2380
2381 page_avg_rate =
2382 static_cast<ulint>(((sum_pages / time_elapsed_sec) + page_avg_rate) / 2);
2383
2384 /* How much LSN we have generated since last call. */
2385 auto lsn_rate =
2386 static_cast<lsn_t>((cur_iter_lsn - prev_lsn) / time_elapsed_sec);
2387
2388 lsn_avg_rate = (lsn_avg_rate + lsn_rate) / 2;
2389
2390 MONITOR_SET(MONITOR_FLUSH_AVG_PAGE_RATE, page_avg_rate);
2391 MONITOR_SET(MONITOR_FLUSH_LSN_AVG_RATE, lsn_avg_rate);
2392
2393 /* aggregate stats of all slots */
2394 mutex_enter(&page_cleaner->mutex);
2395
2396 auto flush_tm = page_cleaner->flush_time.count();
2397 ulint flush_pass = page_cleaner->flush_pass;
2398
2399 page_cleaner->flush_time = std::chrono::seconds::zero();
2400 page_cleaner->flush_pass = 0;
2401
2402 uint64_t lru_tm = 0;
2403 uint64_t list_tm = 0;
2404 ulint lru_pass = 0;
2405 ulint list_pass = 0;
2406
2407 for (ulint i = 0; i < page_cleaner->n_slots; i++) {
2408 page_cleaner_slot_t *slot;
2409
2410 slot = &page_cleaner->slots[i];
2411
2412 lru_tm += slot->flush_lru_time.count();
2413 lru_pass += slot->flush_lru_pass;
2414 list_tm += slot->flush_list_time.count();
2415 list_pass += slot->flush_list_pass;
2416
2417 slot->flush_lru_time = std::chrono::seconds::zero();
2418 slot->flush_lru_pass = 0;
2419 slot->flush_list_time = std::chrono::seconds::zero();
2420 slot->flush_list_pass = 0;
2421 }
2422
2423 mutex_exit(&page_cleaner->mutex);
2424
2425 /* minimum values are 1, to avoid dividing by zero. */
2426 if (lru_tm < 1) {
2427 lru_tm = 1;
2428 }
2429 if (list_tm < 1) {
2430 list_tm = 1;
2431 }
2432 if (flush_tm < 1) {
2433 flush_tm = 1;
2434 }
2435
2436 if (lru_pass < 1) {
2437 lru_pass = 1;
2438 }
2439 if (list_pass < 1) {
2440 list_pass = 1;
2441 }
2442 if (flush_pass < 1) {
2443 flush_pass = 1;
2444 }
2445
2446 MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_SLOT, list_tm / list_pass);
2447 MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_SLOT, lru_tm / lru_pass);
2448
2449 MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_THREAD,
2450 list_tm / (srv_n_page_cleaners * flush_pass));
2451 MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_THREAD,
2452 lru_tm / (srv_n_page_cleaners * flush_pass));
2453 MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_EST,
2454 flush_tm * list_tm / flush_pass / (list_tm + lru_tm));
2455 MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_EST,
2456 flush_tm * lru_tm / flush_pass / (list_tm + lru_tm));
2457 MONITOR_SET(MONITOR_FLUSH_AVG_TIME, flush_tm / flush_pass);
2458
2459 MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_PASS,
2460 list_pass / page_cleaner->n_slots);
2461 MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_PASS,
2462 lru_pass / page_cleaner->n_slots);
2463 MONITOR_SET(MONITOR_FLUSH_AVG_PASS, flush_pass);
2464
2465 prev_lsn = cur_iter_lsn;
2466 prev_time = cur_iter_time;
2467
2468 n_iterations = 0;
2469 sum_pages = 0;
2470 }
2471
2472 /** Calculates if flushing is required based on number of dirty pages in
2473 the buffer pool.
2474 @return percent of io_capacity to flush to manage dirty page ratio */
2475 ulint get_pct_for_dirty() {
2476 double dirty_pct = buf_get_modified_ratio_pct();
2477
2478 if (dirty_pct == 0.0) {
2479 /* No pages modified */
2480 return (0);
2481 }
2482
2483 ut_a(srv_max_dirty_pages_pct_lwm <= srv_max_buf_pool_modified_pct);
2484
2485 if (srv_max_dirty_pages_pct_lwm == 0) {
2486 /* The user has not set the option to preflush dirty
2487 pages as we approach the high water mark. */
2488 if (dirty_pct >= srv_max_buf_pool_modified_pct) {
2489 /* We have crossed the high water mark of dirty
2490 pages In this case we start flushing at 100% of
2491 innodb_io_capacity. */
2492 return (100);
2493 }
2494 } else if (dirty_pct >= srv_max_dirty_pages_pct_lwm) {
2495 /* We should start flushing pages gradually. */
2496 return (static_cast<ulint>((dirty_pct * 100) /
2497 (srv_max_buf_pool_modified_pct + 1)));
2498 }
2499
2500 return (0);
2501 }
2502
2503 /** Calculates if flushing is required based on redo generation rate.
2504 @return percent of io_capacity to flush to manage redo space */
2505 ulint get_pct_for_lsn(lsn_t age) /*!< in: current age of LSN. */
2506 {
2507 ut_a(log_sys != nullptr);
2508 log_t &log = *log_sys;
2509
2510 lsn_t limit_for_free_check;
2511 lsn_t limit_for_dirty_page_age;
2512
2513 log_files_capacity_get_limits(log, limit_for_free_check,
2514 limit_for_dirty_page_age);
2515
2516 double lsn_age_factor;
2517 lsn_t af_lwm = (srv_adaptive_flushing_lwm * limit_for_free_check) / 100;
2518
2519 if (age < af_lwm) {
2520 /* No adaptive flushing. */
2521 return (0);
2522 }
2523
2524 if (age < limit_for_dirty_page_age && !srv_adaptive_flushing) {
2525 /* We have still not reached the max_async point and
2526 the user has disabled adaptive flushing. */
2527 return (0);
2528 }
2529
2530 /* If we are here then we know that either:
2531 1) User has enabled adaptive flushing
2532 2) User may have disabled adaptive flushing but we have reached
2533 limit_for_dirty_page_age. */
2534 lsn_age_factor = (age * 100.0) / limit_for_dirty_page_age;
2535
2536 ut_ad(srv_max_io_capacity >= srv_io_capacity);
2537
2538 return (static_cast<ulint>(((srv_max_io_capacity / srv_io_capacity) *
2539 (lsn_age_factor * sqrt(lsn_age_factor))) /
2540 7.5));
2541 }
2542
2543 /** Set page flush target based on LSN change and checkpoint age.
2544 @param[in] sync_flush true iff this is sync flush mode
2545 @param[in] sync_flush_limit_lsn low limit for oldest_modification
2546 if sync_flush is true
2547 @return number of pages requested to flush */
2548 ulint set_flush_target_by_lsn(bool sync_flush, lsn_t sync_flush_limit_lsn) {
2549 lsn_t oldest_lsn = buf_pool_get_oldest_modification_approx();
2550 ut_ad(oldest_lsn <= log_get_lsn(*log_sys));
2551
2552 lsn_t age = cur_iter_lsn > oldest_lsn ? cur_iter_lsn - oldest_lsn : 0;
2553
2554 ulint pct_for_dirty = get_pct_for_dirty();
2555 ulint pct_for_lsn = get_pct_for_lsn(age);
2556 ulint pct_total = std::max(pct_for_dirty, pct_for_lsn);
2557
2558 /* Estimate pages to be flushed for the lsn progress */
2559 ulint sum_pages_for_lsn = 0;
2560
2561 lsn_t target_lsn;
2562 uint scan_factor;
2563
2564 if (sync_flush) {
2565 target_lsn = sync_flush_limit_lsn;
2566 ut_a(target_lsn < LSN_MAX);
2567 scan_factor = 1;
2568 buf_flush_sync_lsn = target_lsn;
2569 } else {
2570 target_lsn = oldest_lsn + lsn_avg_rate * buf_flush_lsn_scan_factor;
2571 scan_factor = buf_flush_lsn_scan_factor;
2572 buf_flush_sync_lsn = 0;
2573 }
2574
2575 /* Cap the maximum IO capacity that we are going to use by
2576 max_io_capacity. Limit the value to avoid too quick increase */
2577 const ulint sum_pages_max = srv_max_io_capacity * 2;
2578
2579 /* Limit individual BP scan based on overall capacity. */
2580 const ulint pages_for_lsn_max =
2581 (sum_pages_max / srv_buf_pool_instances) * scan_factor * 2;
2582
2583 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2584 buf_pool_t *buf_pool = buf_pool_from_array(i);
2585 ulint pages_for_lsn = 0;
2586
2587 buf_flush_list_mutex_enter(buf_pool);
2588 for (buf_page_t *b = UT_LIST_GET_LAST(buf_pool->flush_list); b != nullptr;
2589 b = UT_LIST_GET_PREV(list, b)) {
2590 if (b->get_oldest_lsn() > target_lsn) {
2591 break;
2592 }
2593 ++pages_for_lsn;
2594 if (pages_for_lsn >= pages_for_lsn_max) {
2595 break;
2596 }
2597 }
2598 buf_flush_list_mutex_exit(buf_pool);
2599
2600 sum_pages_for_lsn += pages_for_lsn;
2601
2602 mutex_enter(&page_cleaner->mutex);
2603 ut_ad(page_cleaner->slots[i].state == PAGE_CLEANER_STATE_NONE);
2604 page_cleaner->slots[i].n_pages_requested = pages_for_lsn / scan_factor + 1;
2605 mutex_exit(&page_cleaner->mutex);
2606 }
2607
2608 sum_pages_for_lsn /= scan_factor;
2609 if (sum_pages_for_lsn < 1) {
2610 sum_pages_for_lsn = 1;
2611 }
2612
2613 /* Cap the maximum IO capacity that we are going to use by
2614 max_io_capacity. Limit the value to avoid too quick increase */
2615 ulint pages_for_lsn = std::min<ulint>(sum_pages_for_lsn, sum_pages_max);
2616
2617 /* Estimate based on LSN and dirty pages. */
2618 ulint n_pages;
2619 if (sync_flush) {
2620 n_pages = pages_for_lsn;
2621 /* For sync flush, make sure we flush at least at io capacity rate. This
2622 lower bound works as a safeguard against any miscalculation leading to
2623 too less flushing while we are in urgent flushing mode. Specifically, for
2624 small target, if the target is evaluated to zero the flush could be stuck
2625 in sync flush mode indefinitely, flushing nothing. */
2626 if (n_pages < srv_io_capacity) {
2627 n_pages = srv_io_capacity;
2628 }
2629 } else {
2630 n_pages = (PCT_IO(pct_total) + page_avg_rate + pages_for_lsn) / 3;
2631 if (n_pages > srv_max_io_capacity) {
2632 n_pages = srv_max_io_capacity;
2633 }
2634 }
2635
2636 /* Normalize request for each instance */
2637 mutex_enter(&page_cleaner->mutex);
2638 ut_ad(page_cleaner->n_slots_requested == 0);
2639 ut_ad(page_cleaner->n_slots_flushing == 0);
2640 ut_ad(page_cleaner->n_slots_finished == 0);
2641
2642 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2643 /* if REDO has enough of free space,
2644 don't care about age distribution of pages */
2645 page_cleaner->slots[i].n_pages_requested =
2646 pct_for_lsn > 30 ? page_cleaner->slots[i].n_pages_requested * n_pages /
2647 sum_pages_for_lsn +
2648 1
2649 : n_pages / srv_buf_pool_instances + 1;
2650 }
2651 mutex_exit(&page_cleaner->mutex);
2652
2653 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_AGE, sum_pages_for_lsn);
2654 MONITOR_SET(MONITOR_FLUSH_PCT_FOR_DIRTY, pct_for_dirty);
2655 MONITOR_SET(MONITOR_FLUSH_PCT_FOR_LSN, pct_for_lsn);
2656
2657 return (n_pages);
2658 }
2659
2660 /** Set page flush target based on dirty pages in buffer pool. Set only if
2661 the target are is found to be higher than the target evaluated based on LSN.
2662 @param[in] n_pages_lsn number of pages estimated and set based on LSN
2663 @return page flush target. */
2664 ulint set_flush_target_by_page(ulint n_pages_lsn) {
2665 ulint lru_len = 0;
2666 ulint free_len = 0;
2667 ulint flush_list_len = 0;
2668
2669 buf_get_total_list_len(&lru_len, &free_len, &flush_list_len);
2670
2671 cur_iter_pages_dirty = flush_list_len;
2672
2673 cur_iter_dirty_pct = get_pct_for_dirty();
2674 MONITOR_SET(MONITOR_FLUSH_PCT_FOR_DIRTY, cur_iter_dirty_pct);
2675
2676 /* Enable page based target only when redo logging is disabled. */
2677 if (mtr_t::s_logging.is_enabled()) {
2678 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_DIRTY_PAGE, 0);
2679 return (n_pages_lsn);
2680 }
2681
2682 /* No dirty pages to flush. */
2683 if (cur_iter_dirty_pct == 0) {
2684 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_DIRTY_PAGE, 0);
2685 return (n_pages_lsn);
2686 }
2687
2688 ut_ad(cur_iter_time >= prev_iter_time);
2689
2690 auto delta_time_s = 1.0;
2691 if (cur_iter_time > prev_iter_time) {
2692 delta_time_s = std::chrono::duration_cast<std::chrono::duration<double>>(
2693 cur_iter_time - prev_iter_time)
2694 .count();
2695 }
2696
2697 /* Number of pages flushed per second in last iteration. */
2698 double prev_page_rate_sec = prev_iter_pages_flushed / delta_time_s;
2699
2700 auto delta_dirty_pages = static_cast<double>(cur_iter_pages_dirty) -
2701 static_cast<double>(prev_iter_pages_dirty);
2702
2703 /* Change in number of dirty pages per second. It could be negative. */
2704 double dirty_page_change_sec = delta_dirty_pages / delta_time_s;
2705
2706 /* Next iteration we would like to adapt the flush rate based on changes in
2707 dirty page rate. */
2708 auto estimate = prev_page_rate_sec + dirty_page_change_sec;
2709
2710 ulint n_pages = 0;
2711
2712 if (estimate <= 0) {
2713 n_pages = 0;
2714 } else {
2715 n_pages = static_cast<ulint>(estimate);
2716 }
2717
2718 /* We use radical function of current dirty page percentage to boost
2719 the flush rate when dirty page percentage goes higher. The boost factor
2720 monotonically increases from 0.10(1%) - 1.05 (100%) with a value 1 at 90%. */
2721 double boost_factor = sqrt(static_cast<double>(cur_iter_dirty_pct) / 90.0);
2722
2723 n_pages = static_cast<ulint>(boost_factor * n_pages);
2724
2725 /* We moderate the effect of spikes by including average page rate across
2726 multiple iterations. */
2727 n_pages = (page_avg_rate + n_pages) / 2;
2728
2729 if (n_pages > srv_max_io_capacity) {
2730 n_pages = srv_max_io_capacity;
2731 }
2732
2733 if (n_pages <= n_pages_lsn) {
2734 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_DIRTY_PAGE, n_pages);
2735 return (n_pages_lsn);
2736 }
2737
2738 /* Set new targets for each instance */
2739 mutex_enter(&page_cleaner->mutex);
2740 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2741 page_cleaner->slots[i].n_pages_requested = n_pages / srv_buf_pool_instances;
2742 }
2743 mutex_exit(&page_cleaner->mutex);
2744
2745 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_DIRTY_PAGE, n_pages);
2746 return (n_pages);
2747 }
2748
2749 /** This function is called approximately once every second by the
2750 page_cleaner thread, unless it is sync flushing mode, in which case
2751 it is called every small round. Based on various factors it decides
2752 if there is a need to do flushing.
2753 @param last_pages_in the number of pages flushed by the last
2754 flush_list flushing
2755 @param is_sync_flush true iff this is sync flush mode
2756 @param sync_flush_limit_lsn low limit for oldest_modification
2757 if is_sync_flush is true
2758 @return number of pages recommended to be flushed */
2759 ulint page_recommendation(ulint last_pages_in, bool is_sync_flush,
2760 lsn_t sync_flush_limit_lsn) {
2761 if (initialize(last_pages_in)) {
2762 /* First time around. */
2763 return (0);
2764 }
2765
2766 /* No LSN based estimate if system LSN has not moved and not sync flush. */
2767 bool skip_lsn = (prev_lsn == cur_iter_lsn && !is_sync_flush);
2768
2769 /* Compute and set average rates across multiple iterations,
2770 if limit is reached. */
2771 set_average();
2772
2773 /* Set page flush target based on LSN. */
2774 auto n_pages =
2775 skip_lsn ? 0
2776 : set_flush_target_by_lsn(is_sync_flush, sync_flush_limit_lsn);
2777
2778 /* Estimate based on only dirty pages. We don't want to flush at lesser rate
2779 as LSN based estimate may not represent the right picture for modifications
2780 without redo logging - temp tables, bulk load and global redo off. */
2781 n_pages = set_flush_target_by_page(n_pages);
2782
2783 prev_iter_time = cur_iter_time;
2784 prev_iter_pages_dirty = cur_iter_pages_dirty;
2785
2786 MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_REQUESTED, n_pages);
2787 return (n_pages);
2788 }
2789 } // namespace Adaptive_flush
2790
2791 /** Puts the page_cleaner thread to sleep if it has finished work in less
2792 than a second
2793 @retval 0 wake up by event set,
2794 @retval OS_SYNC_TIME_EXCEEDED if timeout was exceeded
2795 @param next_loop_time time when next loop iteration should start
2796 @param sig_count zero or the value returned by previous call of
2797 os_event_reset() */
2798 static ulint pc_sleep_if_needed(
2799 std::chrono::steady_clock::time_point next_loop_time, int64_t sig_count) {
2800 const auto cur_time = std::chrono::steady_clock::now();
2801
2802 if (next_loop_time > cur_time) {
2803 auto sleep_time = next_loop_time - cur_time;
2804 if (sleep_time > std::chrono::seconds{1}) {
2805 sleep_time = std::chrono::seconds{1};
2806 }
2807
2808 ut_a(sleep_time.count() > 0);
2809
2810 return (os_event_wait_time_low(
2811 buf_flush_event,
2812 std::chrono::duration_cast<std::chrono::microseconds>(sleep_time),
2813 sig_count));
2814 }
2815
2816 return (OS_SYNC_TIME_EXCEEDED);
2817 }
2818
2819 /** Checks if page cleaners are active. */
2820 bool buf_flush_page_cleaner_is_active() {
2821 return (srv_thread_is_active(srv_threads.m_page_cleaner_coordinator));
2822 }
2823
2824 void buf_flush_page_cleaner_init() {
2825 ut_ad(page_cleaner == nullptr);
2826
2827 page_cleaner = ut::make_unique<page_cleaner_t>(UT_NEW_THIS_FILE_PSI_KEY);
2828
2829 mutex_create(LATCH_ID_PAGE_CLEANER, &page_cleaner->mutex);
2830
2831 page_cleaner->is_requested = os_event_create();
2832 page_cleaner->is_finished = os_event_create();
2833
2834 page_cleaner->n_slots = static_cast<ulint>(srv_buf_pool_instances);
2835
2836 page_cleaner->slots = ut::make_unique<page_cleaner_slot_t[]>(
2837 UT_NEW_THIS_FILE_PSI_KEY, page_cleaner->n_slots);
2838
2839 ut_d(page_cleaner->n_disabled_debug = 0);
2840
2841 page_cleaner->is_running = true;
2842
2843 srv_threads.m_page_cleaner_coordinator = os_thread_create(
2844 page_flush_coordinator_thread_key, 0, buf_flush_page_coordinator_thread);
2845
2846 srv_threads.m_page_cleaner_workers[0] =
2847 srv_threads.m_page_cleaner_coordinator;
2848
2849 srv_threads.m_page_cleaner_coordinator.start();
2850
2851 /* Make sure page cleaner is active. */
2852 ut_a(buf_flush_page_cleaner_is_active());
2853 }
2854
2855 /**
2856 Close page_cleaner. */
2857 static void buf_flush_page_cleaner_close(void) {
2858 /* Waiting for all worker threads to exit, note that worker 0 is actually
2859 the page cleaner coordinator itself which is calling the function which
2860 we are inside. */
2861 for (size_t i = 1; i < srv_threads.m_page_cleaner_workers_n; ++i) {
2862 srv_threads.m_page_cleaner_workers[i].wait();
2863 }
2864
2865 mutex_destroy(&page_cleaner->mutex);
2866
2867 os_event_destroy(page_cleaner->is_finished);
2868 os_event_destroy(page_cleaner->is_requested);
2869
2870 page_cleaner.reset();
2871 }
2872
2873 /**
2874 Requests for all slots to flush all buffer pool instances.
2875 @param min_n wished minimum number of blocks flushed
2876 (it is not guaranteed that the actual number is that big)
2877 @param lsn_limit in the case BUF_FLUSH_LIST all blocks whose
2878 oldest_modification is smaller than this should be flushed
2879 (if their number does not exceed min_n), otherwise ignored
2880 */
2881 static void pc_request(ulint min_n, lsn_t lsn_limit) {
2882 if (min_n != ULINT_MAX) {
2883 /* Ensure that flushing is spread evenly amongst the
2884 buffer pool instances. When min_n is ULINT_MAX
2885 we need to flush everything up to the lsn limit
2886 so no limit here. */
2887 min_n = ut::div_ceil(min_n, ulint{srv_buf_pool_instances});
2888 }
2889
2890 mutex_enter(&page_cleaner->mutex);
2891
2892 ut_ad(page_cleaner->n_slots_requested == 0);
2893 ut_ad(page_cleaner->n_slots_flushing == 0);
2894 ut_ad(page_cleaner->n_slots_finished == 0);
2895
2896 page_cleaner->requested = (min_n > 0);
2897 page_cleaner->lsn_limit = lsn_limit;
2898
2899 for (ulint i = 0; i < page_cleaner->n_slots; i++) {
2900 page_cleaner_slot_t *slot = &page_cleaner->slots[i];
2901
2902 ut_ad(slot->state == PAGE_CLEANER_STATE_NONE);
2903
2904 if (min_n == ULINT_MAX) {
2905 slot->n_pages_requested = ULINT_MAX;
2906 } else if (min_n == 0) {
2907 slot->n_pages_requested = 0;
2908 }
2909
2910 /* slot->n_pages_requested was already set by
2911 Adaptive_flush::page_recommendation() */
2912
2913 slot->state = PAGE_CLEANER_STATE_REQUESTED;
2914 }
2915
2916 page_cleaner->n_slots_requested = page_cleaner->n_slots;
2917 page_cleaner->n_slots_flushing = 0;
2918 page_cleaner->n_slots_finished = 0;
2919
2920 os_event_set(page_cleaner->is_requested);
2921
2922 mutex_exit(&page_cleaner->mutex);
2923 }
2924
2925 /**
2926 Do flush for one slot.
2927 @return the number of the slots which has not been treated yet. */
2928 static ulint pc_flush_slot(void) {
2929 std::chrono::steady_clock::duration lru_time;
2930 std::chrono::steady_clock::duration flush_list_time{};
2931 int lru_pass = 0;
2932 int list_pass = 0;
2933
2934 mutex_enter(&page_cleaner->mutex);
2935
2936 if (page_cleaner->n_slots_requested > 0) {
2937 page_cleaner_slot_t *slot = nullptr;
2938 ulint i;
2939
2940 for (i = 0; i < page_cleaner->n_slots; i++) {
2941 slot = &page_cleaner->slots[i];
2942
2943 if (slot->state == PAGE_CLEANER_STATE_REQUESTED) {
2944 break;
2945 }
2946 }
2947
2948 /* slot should be found because
2949 page_cleaner->n_slots_requested > 0 */
2950 ut_a(i < page_cleaner->n_slots);
2951
2952 buf_pool_t *buf_pool = buf_pool_from_array(i);
2953
2954 page_cleaner->n_slots_requested--;
2955 page_cleaner->n_slots_flushing++;
2956 slot->state = PAGE_CLEANER_STATE_FLUSHING;
2957
2958 if (page_cleaner->n_slots_requested == 0) {
2959 os_event_reset(page_cleaner->is_requested);
2960 }
2961
2962 if (!page_cleaner->is_running) {
2963 slot->n_flushed_lru = 0;
2964 slot->n_flushed_list = 0;
2965 } else {
2966 mutex_exit(&page_cleaner->mutex);
2967
2968 const auto lru_start = std::chrono::steady_clock::now();
2969
2970 /* Flush pages from end of LRU if required */
2971 slot->n_flushed_lru = buf_flush_LRU_list(buf_pool);
2972
2973 lru_time = std::chrono::steady_clock::now() - lru_start;
2974 lru_pass = 1;
2975
2976 if (!page_cleaner->is_running) {
2977 slot->n_flushed_list = 0;
2978 } else {
2979 /* Flush pages from flush_list if required */
2980 if (page_cleaner->requested) {
2981 const auto flush_list_start = std::chrono::steady_clock::now();
2982
2983 slot->succeeded_list = buf_flush_do_batch(
2984 buf_pool, BUF_FLUSH_LIST, slot->n_pages_requested,
2985 page_cleaner->lsn_limit, &slot->n_flushed_list);
2986
2987 flush_list_time = std::chrono::steady_clock::now() - flush_list_start;
2988 list_pass = 1;
2989 } else {
2990 slot->n_flushed_list = 0;
2991 slot->succeeded_list = true;
2992 }
2993 }
2994 mutex_enter(&page_cleaner->mutex);
2995 }
2996 page_cleaner->n_slots_flushing--;
2997 page_cleaner->n_slots_finished++;
2998 slot->state = PAGE_CLEANER_STATE_FINISHED;
2999
3000 slot->flush_lru_time +=
3001 std::chrono::duration_cast<std::chrono::milliseconds>(lru_time);
3002 slot->flush_list_time +=
3003 std::chrono::duration_cast<std::chrono::milliseconds>(flush_list_time);
3004 slot->flush_lru_pass += lru_pass;
3005 slot->flush_list_pass += list_pass;
3006
3007 if (page_cleaner->n_slots_requested == 0 &&
3008 page_cleaner->n_slots_flushing == 0) {
3009 os_event_set(page_cleaner->is_finished);
3010 }
3011 }
3012
3013 ulint ret = page_cleaner->n_slots_requested;
3014
3015 mutex_exit(&page_cleaner->mutex);
3016
3017 return (ret);
3018 }
3019
3020 /**
3021 Wait until all flush requests are finished.
3022 @param n_flushed_lru number of pages flushed from the end of the LRU list.
3023 @param n_flushed_list number of pages flushed from the end of the
3024 flush_list.
3025 @return true if all flush_list flushing batch were success. */
3026 static bool pc_wait_finished(ulint *n_flushed_lru, ulint *n_flushed_list) {
3027 bool all_succeeded = true;
3028
3029 *n_flushed_lru = 0;
3030 *n_flushed_list = 0;
3031
3032 os_event_wait(page_cleaner->is_finished);
3033
3034 mutex_enter(&page_cleaner->mutex);
3035
3036 ut_ad(page_cleaner->n_slots_requested == 0);
3037 ut_ad(page_cleaner->n_slots_flushing == 0);
3038 ut_ad(page_cleaner->n_slots_finished == page_cleaner->n_slots);
3039
3040 for (ulint i = 0; i < page_cleaner->n_slots; i++) {
3041 page_cleaner_slot_t *slot = &page_cleaner->slots[i];
3042
3043 ut_ad(slot->state == PAGE_CLEANER_STATE_FINISHED);
3044
3045 *n_flushed_lru += slot->n_flushed_lru;
3046 *n_flushed_list += slot->n_flushed_list;
3047 all_succeeded &= slot->succeeded_list;
3048
3049 slot->state = PAGE_CLEANER_STATE_NONE;
3050
3051 slot->n_pages_requested = 0;
3052 }
3053
3054 page_cleaner->n_slots_finished = 0;
3055
3056 os_event_reset(page_cleaner->is_finished);
3057
3058 mutex_exit(&page_cleaner->mutex);
3059
3060 os_event_set(buf_flush_tick_event);
3061
3062 return (all_succeeded);
3063 }
3064
3065 #ifdef UNIV_LINUX
3066 /**
3067 Set priority for page_cleaner threads.
3068 @param[in] priority priority intended to set
3069 @return true if set as intended */
3070 static bool buf_flush_page_cleaner_set_priority(int priority) {
3071 setpriority(PRIO_PROCESS, (pid_t)syscall(SYS_gettid), priority);
3072 return (getpriority(PRIO_PROCESS, (pid_t)syscall(SYS_gettid)) == priority);
3073 }
3074 #endif /* UNIV_LINUX */
3075
3076 #ifdef UNIV_DEBUG
3077 /** Loop used to disable page cleaner threads. */
3078 static void buf_flush_page_cleaner_disabled_loop(void) {
3079 ut_ad(page_cleaner != nullptr);
3080
3081 if (!innodb_page_cleaner_disabled_debug) {
3082 /* We return to avoid entering and exiting mutex. */
3083 return;
3084 }
3085
3086 mutex_enter(&page_cleaner->mutex);
3087 page_cleaner->n_disabled_debug++;
3088 mutex_exit(&page_cleaner->mutex);
3089
3090 while (innodb_page_cleaner_disabled_debug &&
3091 srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP &&
3092 page_cleaner->is_running) {
3093 std::this_thread::sleep_for(std::chrono::milliseconds(100)); /* [A] */
3094 }
3095
3096 /* We need to wait for threads exiting here, otherwise we would
3097 encounter problem when we quickly perform following steps:
3098 1) SET GLOBAL innodb_page_cleaner_disabled_debug = 1;
3099 2) SET GLOBAL innodb_page_cleaner_disabled_debug = 0;
3100 3) SET GLOBAL innodb_page_cleaner_disabled_debug = 1;
3101 That's because after step 1 this thread could still be sleeping
3102 inside the loop above at [A] and steps 2, 3 could happen before
3103 this thread wakes up from [A]. In such case this thread would
3104 not re-increment n_disabled_debug and we would be waiting for
3105 him forever in buf_flush_page_cleaner_disabled_debug_update(...).
3106
3107 Therefore we are waiting in step 2 for this thread exiting here. */
3108
3109 mutex_enter(&page_cleaner->mutex);
3110 page_cleaner->n_disabled_debug--;
3111 mutex_exit(&page_cleaner->mutex);
3112 }
3113
3114 void buf_flush_page_cleaner_disabled_debug_update(THD *, SYS_VAR *, void *,
3115 const void *save) {
3116 if (page_cleaner == nullptr) {
3117 return;
3118 }
3119
3120 if (!*static_cast<const bool *>(save)) {
3121 if (!innodb_page_cleaner_disabled_debug) {
3122 return;
3123 }
3124
3125 innodb_page_cleaner_disabled_debug = false;
3126
3127 /* Enable page cleaner threads. */
3128 while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
3129 mutex_enter(&page_cleaner->mutex);
3130 const ulint n = page_cleaner->n_disabled_debug;
3131 mutex_exit(&page_cleaner->mutex);
3132 /* Check if all threads have been enabled, to avoid
3133 problem when we decide to re-disable them soon. */
3134 if (n == 0) {
3135 break;
3136 }
3137 }
3138 return;
3139 }
3140
3141 if (innodb_page_cleaner_disabled_debug) {
3142 return;
3143 }
3144
3145 innodb_page_cleaner_disabled_debug = true;
3146
3147 while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
3148 /* Workers are possibly sleeping on is_requested.
3149
3150 We have to wake them, otherwise they could possibly
3151 have never noticed, that they should be disabled,
3152 and we would wait for them here forever.
3153
3154 That's why we have sleep-loop instead of simply
3155 waiting on some disabled_debug_event. */
3156 os_event_set(page_cleaner->is_requested);
3157
3158 mutex_enter(&page_cleaner->mutex);
3159
3160 ut_ad(page_cleaner->n_disabled_debug <= srv_n_page_cleaners);
3161
3162 if (page_cleaner->n_disabled_debug == srv_n_page_cleaners) {
3163 mutex_exit(&page_cleaner->mutex);
3164 break;
3165 }
3166
3167 mutex_exit(&page_cleaner->mutex);
3168
3169 std::this_thread::sleep_for(std::chrono::milliseconds(100));
3170 }
3171 }
3172 #endif /* UNIV_DEBUG */
3173
3174 /** Thread tasked with flushing dirty pages from the buffer pools.
3175 As of now we'll have only one coordinator.
3176 @param[in] n_page_cleaners Number of page cleaner threads to create */
3177 static void buf_flush_page_coordinator_thread() {
3178 auto loop_start_time = std::chrono::steady_clock::now();
3179 ulint n_flushed = 0;
3180 ulint last_activity = srv_get_activity_count();
3181 ulint last_pages = 0;
3182
3183 THD *thd = create_internal_thd();
3184
3185 #ifdef UNIV_LINUX
3186 /* linux might be able to set different setting for each thread.
3187 worth to try to set high priority for page cleaner threads */
3188 if (buf_flush_page_cleaner_set_priority(buf_flush_page_cleaner_priority)) {
3189 ib::info(ER_IB_MSG_126) << "page_cleaner coordinator priority: "
3190 << buf_flush_page_cleaner_priority;
3191 } else {
3192 ib::info(ER_IB_MSG_127) << "If the mysqld execution user is authorized,"
3193 " page cleaner thread priority can be changed."
3194 " See the man page of setpriority().";
3195 }
3196 #endif /* UNIV_LINUX */
3197
3198 /* We start from 1 because the coordinator thread is part of the
3199 same set */
3200 for (size_t i = 1; i < srv_threads.m_page_cleaner_workers_n; ++i) {
3201 srv_threads.m_page_cleaner_workers[i] = os_thread_create(
3202 page_flush_thread_key, i, buf_flush_page_cleaner_thread);
3203
3204 srv_threads.m_page_cleaner_workers[i].start();
3205 }
3206
3207 while (!srv_read_only_mode &&
3208 srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP &&
3209 recv_sys->spaces != nullptr) {
3210 /* treat flushing requests during recovery. */
3211 ulint n_flushed_lru = 0;
3212 ulint n_flushed_list = 0;
3213
3214 os_event_wait(recv_sys->flush_start);
3215
3216 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP ||
3217 recv_sys->spaces == nullptr) {
3218 break;
3219 }
3220
3221 switch (recv_sys->flush_type) {
3222 case BUF_FLUSH_LRU:
3223 /* Flush pages from end of LRU if required */
3224 pc_request(0, LSN_MAX);
3225 while (pc_flush_slot() > 0) {
3226 }
3227 pc_wait_finished(&n_flushed_lru, &n_flushed_list);
3228 break;
3229
3230 case BUF_FLUSH_LIST:
3231 /* Flush all pages */
3232 do {
3233 pc_request(ULINT_MAX, LSN_MAX);
3234 while (pc_flush_slot() > 0) {
3235 }
3236 } while (!pc_wait_finished(&n_flushed_lru, &n_flushed_list));
3237 break;
3238
3239 default:
3240 ut_d(ut_error);
3241 }
3242
3243 os_event_reset(recv_sys->flush_start);
3244 os_event_set(recv_sys->flush_end);
3245 }
3246
3247 os_event_wait(buf_flush_event);
3248
3249 ulint ret_sleep = 0;
3250 ulint n_evicted = 0;
3251 ulint n_flushed_last = 0;
3252 ulint warn_interval = 1;
3253 ulint warn_count = 0;
3254 bool is_sync_flush = false;
3255 bool was_server_active = true;
3256 int64_t sig_count = os_event_reset(buf_flush_event);
3257
3258 while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
3259 /* We consider server active if either we have just discovered a first
3260 activity after a period of inactive server, or we are after the period
3261 of active server in which case, it could be just the beginning of the
3262 next period, so there is no reason to consider it idle yet.
3263 The withdrawing blocks process when shrinking the buffer pool always
3264 needs the page_cleaner activity. So, we consider server is active
3265 during the withdrawing blocks process also. */
3266
3267 bool is_withdrawing = false;
3268 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
3269 buf_pool_t *buf_pool = buf_pool_from_array(i);
3270 if (buf_get_withdraw_depth(buf_pool) > 0) {
3271 is_withdrawing = true;
3272 break;
3273 }
3274 }
3275
3276 const bool is_server_active = is_withdrawing || was_server_active ||
3277 srv_check_activity(last_activity);
3278
3279 /* The page_cleaner skips sleep if the server is
3280 idle and there are no pending IOs in the buffer pool
3281 and there is work to do. */
3282 if ((is_server_active || buf_get_n_pending_read_ios() || n_flushed == 0) &&
3283 !is_sync_flush) {
3284 ret_sleep = pc_sleep_if_needed(loop_start_time + std::chrono::seconds{1},
3285 sig_count);
3286
3287 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP) {
3288 break;
3289 }
3290 } else if (std::chrono::steady_clock::now() >
3291 loop_start_time + std::chrono::seconds{1}) {
3292 ret_sleep = OS_SYNC_TIME_EXCEEDED;
3293 } else {
3294 ret_sleep = 0;
3295 }
3296
3297 sig_count = os_event_reset(buf_flush_event);
3298
3299 if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
3300 const auto curr_time = std::chrono::steady_clock::now();
3301
3302 if (curr_time > loop_start_time + std::chrono::seconds{4}) {
3303 if (warn_count == 0) {
3304 auto diff_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
3305 curr_time - loop_start_time);
3306
3307 ib::info(ER_IB_MSG_128)
3308 << "Page cleaner took " << diff_ms.count() << "ms to flush "
3309 << n_flushed_last << " and evict " << n_evicted << " pages";
3310
3311 if (warn_interval > 300) {
3312 warn_interval = 600;
3313 } else {
3314 warn_interval *= 2;
3315 }
3316
3317 warn_count = warn_interval;
3318 } else {
3319 --warn_count;
3320 }
3321 } else {
3322 /* reset counter */
3323 warn_interval = 1;
3324 warn_count = 0;
3325 }
3326
3327 loop_start_time = curr_time;
3328 n_flushed_last = n_evicted = 0;
3329
3330 was_server_active = srv_check_activity(last_activity);
3331 last_activity = srv_get_activity_count();
3332 }
3333
3334 lsn_t lsn_limit;
3335 if (srv_flush_sync && !srv_read_only_mode) {
3336 /* lsn_limit!=0 means there are requests. needs to check the lsn. */
3337 lsn_limit = log_sync_flush_lsn(*log_sys);
3338 if (lsn_limit != 0) {
3339 /* Avoid aggressive sync flush beyond limit when redo is disabled. */
3340 if (mtr_t::s_logging.is_enabled()) {
3341 lsn_limit += Adaptive_flush::lsn_avg_rate * buf_flush_lsn_scan_factor;
3342 }
3343 is_sync_flush = true;
3344 } else {
3345 /* Stop the sync flush. */
3346 is_sync_flush = false;
3347 }
3348 } else {
3349 is_sync_flush = false;
3350 lsn_limit = LSN_MAX;
3351 }
3352
3353 if (!srv_read_only_mode && mtr_t::s_logging.is_enabled() &&
3354 ret_sleep == OS_SYNC_TIME_EXCEEDED) {
3355 /* For smooth page flushing along with WAL,
3356 flushes log as much as possible. */
3357 log_sys->recent_written.advance_tail();
3358 auto wait_stats = log_write_up_to(
3359 *log_sys, log_buffer_ready_for_write_lsn(*log_sys), true);
3360 MONITOR_INC_WAIT_STATS_EX(MONITOR_ON_LOG_, _PAGE_WRITTEN, wait_stats);
3361 }
3362
3363 if (is_sync_flush || is_server_active) {
3364 ulint n_to_flush;
3365
3366 /* Estimate pages from flush_list to be flushed */
3367 if (is_sync_flush) {
3368 ut_a(lsn_limit > 0);
3369 ut_a(lsn_limit < LSN_MAX);
3370 n_to_flush =
3371 Adaptive_flush::page_recommendation(last_pages, true, lsn_limit);
3372 last_pages = 0;
3373 /* Flush n_to_flush pages or stop if you reach lsn_limit earlier.
3374 This is because in sync-flush mode we want finer granularity of
3375 flushes through all BP instances. */
3376 } else if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
3377 n_to_flush =
3378 Adaptive_flush::page_recommendation(last_pages, false, LSN_MAX);
3379 lsn_limit = LSN_MAX;
3380 last_pages = 0;
3381 } else {
3382 n_to_flush = 0;
3383 lsn_limit = 0;
3384 }
3385
3386 /* Request flushing for threads */
3387 pc_request(n_to_flush, lsn_limit);
3388
3389 const auto flush_start = std::chrono::steady_clock::now();
3390
3391 /* Coordinator also treats requests */
3392 while (pc_flush_slot() > 0) {
3393 /* No op */
3394 }
3395
3396 /* only coordinator is using these counters,
3397 so no need to protect by lock. */
3398 page_cleaner->flush_time +=
3399 std::chrono::duration_cast<std::chrono::milliseconds>(
3400 std::chrono::steady_clock::now() - flush_start);
3401 page_cleaner->flush_pass++;
3402
3403 /* Wait for all slots to be finished */
3404 ulint n_flushed_lru = 0;
3405 ulint n_flushed_list = 0;
3406
3407 pc_wait_finished(&n_flushed_lru, &n_flushed_list);
3408
3409 if (n_flushed_list > 0 || n_flushed_lru > 0) {
3410 buf_flush_stats(n_flushed_list, n_flushed_lru);
3411 }
3412
3413 if (n_to_flush != 0) {
3414 last_pages = n_flushed_list;
3415 }
3416
3417 n_evicted += n_flushed_lru;
3418 n_flushed_last += n_flushed_list;
3419
3420 n_flushed = n_flushed_lru + n_flushed_list;
3421
3422 if (is_sync_flush) {
3423 MONITOR_INC_VALUE_CUMULATIVE(
3424 MONITOR_FLUSH_SYNC_TOTAL_PAGE, MONITOR_FLUSH_SYNC_COUNT,
3425 MONITOR_FLUSH_SYNC_PAGES, n_flushed_lru + n_flushed_list);
3426 } else {
3427 if (n_flushed_lru) {
3428 MONITOR_INC_VALUE_CUMULATIVE(
3429 MONITOR_LRU_BATCH_FLUSH_TOTAL_PAGE, MONITOR_LRU_BATCH_FLUSH_COUNT,
3430 MONITOR_LRU_BATCH_FLUSH_PAGES, n_flushed_lru);
3431 }
3432 if (n_flushed_list) {
3433 MONITOR_INC_VALUE_CUMULATIVE(
3434 MONITOR_FLUSH_ADAPTIVE_TOTAL_PAGE, MONITOR_FLUSH_ADAPTIVE_COUNT,
3435 MONITOR_FLUSH_ADAPTIVE_PAGES, n_flushed_list);
3436 }
3437 }
3438
3439 } else if (ret_sleep == OS_SYNC_TIME_EXCEEDED && srv_idle_flush_pct) {
3440 /* no activity, slept enough */
3441 buf_flush_lists(PCT_IO(srv_idle_flush_pct), LSN_MAX, &n_flushed);
3442
3443 n_flushed_last += n_flushed;
3444
3445 if (n_flushed) {
3446 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_BACKGROUND_TOTAL_PAGE,
3447 MONITOR_FLUSH_BACKGROUND_COUNT,
3448 MONITOR_FLUSH_BACKGROUND_PAGES, n_flushed);
3449 }
3450
3451 } else {
3452 /* no activity, but woken up by event */
3453 n_flushed = 0;
3454 }
3455
3456 ut_d(buf_flush_page_cleaner_disabled_loop());
3457 }
3458
3459 /* This is just for test scenarios. */
3460 srv_thread_delay_cleanup_if_needed(thd);
3461
3462 ut_ad(srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP);
3463
3464 if (srv_fast_shutdown == 2 ||
3465 srv_shutdown_state.load() == SRV_SHUTDOWN_EXIT_THREADS) {
3466 /* In very fast shutdown or when innodb failed to start, we
3467 simulate a crash of the buffer pool. We are not required to do
3468 any flushing. */
3469 goto thread_exit;
3470 }
3471
3472 /* In case of normal and slow shutdown the page_cleaner thread
3473 must wait for all other activity in the server to die down.
3474 Note that we can start flushing the buffer pool as soon as the
3475 server enters shutdown phase but we must stay alive long enough
3476 to ensure that any work done by the master or purge threads is
3477 also flushed.
3478 During shutdown we pass through three stages. In the first stage,
3479 when SRV_SHUTDOWN_CLEANUP is set other threads like the master
3480 and the purge threads may be working as well. We start flushing
3481 the buffer pool but can't be sure that no new pages are being
3482 dirtied until we enter SRV_SHUTDOWN_FLUSH_PHASE phase which is
3483 the last phase (meanwhile we visit SRV_SHUTDOWN_MASTER_STOP).
3484
3485 Note, that if we are handling fatal error, we set the state
3486 directly to EXIT_THREADS in which case we also might exit the loop
3487 below, but still some new dirty pages could be arriving...
3488 In such case we just want to stop and don't care about the new pages.
3489 However we need to be careful not to crash (e.g. in assertions). */
3490
3491 do {
3492 pc_request(ULINT_MAX, LSN_MAX);
3493
3494 while (pc_flush_slot() > 0) {
3495 }
3496
3497 ulint n_flushed_lru = 0;
3498 ulint n_flushed_list = 0;
3499 pc_wait_finished(&n_flushed_lru, &n_flushed_list);
3500
3501 n_flushed = n_flushed_lru + n_flushed_list;
3502
3503 /* We sleep only if there are no pages to flush */
3504 if (n_flushed == 0) {
3505 std::this_thread::sleep_for(std::chrono::milliseconds(100));
3506 }
3507 } while (srv_shutdown_state.load() < SRV_SHUTDOWN_FLUSH_PHASE);
3508
3509 /* At this point all threads including the master and the purge
3510 thread must have been closed, unless we are handling some error
3511 during initialization of InnoDB (srv_init_abort). In such case
3512 we could have SRV_SHUTDOWN_EXIT_THREADS set directly from the
3513 srv_shutdown_exit_threads(). */
3514 if (srv_shutdown_state.load() != SRV_SHUTDOWN_EXIT_THREADS) {
3515 /* We could have srv_shutdown_state.load() >= FLUSH_PHASE only
3516 when either: shutdown started or init is being aborted. In the
3517 first case we would have FLUSH_PHASE and keep waiting until
3518 this thread is alive before we switch to LAST_PHASE.
3519
3520 In the second case, we would jump to EXIT_THREADS from NONE,
3521 so we would not enter here. */
3522 ut_a(!srv_is_being_started);
3523 ut_a(srv_shutdown_state.load() == SRV_SHUTDOWN_FLUSH_PHASE);
3524
3525 ut_a(!srv_master_thread_is_active());
3526 if (!srv_read_only_mode) {
3527 ut_a(!srv_purge_threads_active());
3528 ut_a(!srv_thread_is_active(srv_threads.m_dict_stats));
3529 ut_a(!srv_thread_is_active(srv_threads.m_ts_alter_encrypt));
3530 }
3531 }
3532
3533 /* We can now make a final sweep on flushing the buffer pool
3534 and exit after we have cleaned the whole buffer pool.
3535 It is important that we wait for any running batch that has
3536 been triggered by us to finish. Otherwise we can end up
3537 considering end of that batch as a finish of our final
3538 sweep and we'll come out of the loop leaving behind dirty pages
3539 in the flush_list */
3540 buf_flush_wait_batch_end(nullptr, BUF_FLUSH_LIST);
3541 buf_flush_wait_LRU_batch_end();
3542
3543 bool success;
3544 bool are_any_read_ios_still_underway;
3545
3546 do {
3547 /* If there are any read operations pending, they can result in the ibuf
3548 merges and a dirtying page after the read is completed. If there are any
3549 IO reads running before we run the flush loop, we risk having some dirty
3550 pages after flushing reports n_flushed == 0. The ibuf change merging on
3551 page results in dirtying the page and is followed by decreasing the
3552 n_pend_reads counter, thus it's safe to check it before flush loop and
3553 have guarantees if it was seen with value of 0. These reads could be issued
3554 in the previous stage(s), the srv_master thread on shutdown tasks clear the
3555 ibuf unless it's the fast shutdown. */
3556 are_any_read_ios_still_underway = buf_get_n_pending_read_ios() > 0;
3557 pc_request(ULINT_MAX, LSN_MAX);
3558
3559 while (pc_flush_slot() > 0) {
3560 }
3561
3562 ulint n_flushed_lru = 0;
3563 ulint n_flushed_list = 0;
3564 success = pc_wait_finished(&n_flushed_lru, &n_flushed_list);
3565
3566 n_flushed = n_flushed_lru + n_flushed_list;
3567
3568 buf_flush_wait_batch_end(nullptr, BUF_FLUSH_LIST);
3569 buf_flush_wait_LRU_batch_end();
3570
3571 } while (!success || n_flushed > 0 || are_any_read_ios_still_underway);
3572
3573 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
3574 buf_pool_t *buf_pool = buf_pool_from_array(i);
3575 ut_a(UT_LIST_GET_LEN(buf_pool->flush_list) == 0);
3576 }
3577
3578 /* Mark that it is safe to recover as we have already flushed all dirty
3579 pages in buffer pools. */
3580 if (mtr_t::s_logging.is_disabled() && !srv_read_only_mode) {
3581 log_persist_crash_safe(*log_sys);
3582 }
3583 log_crash_safe_validate(*log_sys);
3584
3585 /* We have lived our life. Time to die. */
3586
3587 thread_exit:
3588 /* All worker threads are waiting for the event here,
3589 and no more access to page_cleaner structure by them.
3590 Wakes worker threads up just to make them exit. */
3591 page_cleaner->is_running = false;
3592 os_event_set(page_cleaner->is_requested);
3593
3594 buf_flush_page_cleaner_close();
3595
3596 destroy_internal_thd(thd);
3597 }
3598
3599 /** Worker thread of page_cleaner. */
3600 static void buf_flush_page_cleaner_thread() {
3601 #ifdef UNIV_LINUX
3602 /* linux might be able to set different setting for each thread
3603 worth to try to set high priority for page cleaner threads */
3604 if (buf_flush_page_cleaner_set_priority(buf_flush_page_cleaner_priority)) {
3605 ib::info(ER_IB_MSG_129)
3606 << "page_cleaner worker priority: " << buf_flush_page_cleaner_priority;
3607 }
3608 #endif /* UNIV_LINUX */
3609
3610 for (;;) {
3611 os_event_wait(page_cleaner->is_requested);
3612
3613 ut_d(buf_flush_page_cleaner_disabled_loop());
3614
3615 if (!page_cleaner->is_running) {
3616 break;
3617 }
3618
3619 pc_flush_slot();
3620 }
3621 }
3622
3623 void buf_flush_fsync() {
3624 #ifdef _WIN32
3625 switch (srv_win_file_flush_method) {
3626 case SRV_WIN_IO_UNBUFFERED:
3627 break;
3628 case SRV_WIN_IO_NORMAL:
3629 fil_flush_file_spaces();
3630 break;
3631 }
3632 #else /* !_WIN32 */
3633 switch (srv_unix_file_flush_method) {
3634 case SRV_UNIX_NOSYNC:
3635 break;
3636 case SRV_UNIX_O_DSYNC:
3637 /* O_SYNC is respected only for redo files and we need to
3638 flush data files here. For details look inside os0file.cc. */
3639 case SRV_UNIX_FSYNC:
3640 case SRV_UNIX_LITTLESYNC:
3641 case SRV_UNIX_O_DIRECT:
3642 case SRV_UNIX_O_DIRECT_NO_FSYNC:
3643 fil_flush_file_spaces();
3644 }
3645 #endif /* _WIN32 */
3646 }
3647
3648 /** Synchronously flush dirty blocks from the end of the flush list of all
3649 buffer pool instances. NOTE: The calling thread is not allowed to own any
3650 latches on pages! */
3651 void buf_flush_sync_all_buf_pools() {
3652 bool success;
3653 ulint n_pages;
3654 do {
3655 n_pages = 0;
3656 success = buf_flush_lists(ULINT_MAX, LSN_MAX, &n_pages);
3657 buf_flush_wait_batch_end(nullptr, BUF_FLUSH_LIST);
3658
3659 if (!success) {
3660 MONITOR_INC(MONITOR_FLUSH_SYNC_WAITS);
3661 }
3662
3663 MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_SYNC_TOTAL_PAGE,
3664 MONITOR_FLUSH_SYNC_COUNT,
3665 MONITOR_FLUSH_SYNC_PAGES, n_pages);
3666 } while (!success);
3667
3668 ut_a(success);
3669
3670 /* All pages have been written to disk, but we need to make fsync for files
3671 to which the writes have been made. */
3672 buf_flush_fsync();
3673 }
3674
3675 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3676
3677 /** Functor to validate the flush list. */
3678 struct Check {
3679 void operator()(const buf_page_t *elem) { ut_a(elem->in_flush_list); }
3680 };
3681
3682 static bool buf_flush_validate_low(const buf_pool_t *buf_pool) {
3683 buf_page_t *bpage;
3684 const ib_rbt_node_t *rnode = nullptr;
3685 Check check;
3686
3687 ut_ad(buf_flush_list_mutex_own(buf_pool));
3688
3689 ut_list_validate(buf_pool->flush_list, check);
3690
3691 bpage = UT_LIST_GET_FIRST(buf_pool->flush_list);
3692
3693 /* If we are in recovery mode i.e.: flush_rbt != NULL
3694 then each block in the flush_list must also be present
3695 in the flush_rbt. */
3696 if (buf_pool->flush_rbt != nullptr) {
3697 rnode = rbt_first(buf_pool->flush_rbt);
3698 }
3699
3700 while (bpage != nullptr) {
3701 const lsn_t om = bpage->get_oldest_lsn();
3702
3703 ut_ad(buf_pool_from_bpage(bpage) == buf_pool);
3704
3705 ut_ad(bpage->in_flush_list);
3706
3707 /* A page in buf_pool->flush_list can be in
3708 BUF_BLOCK_REMOVE_HASH state. This happens when a page
3709 is in the middle of being relocated. In that case the
3710 original descriptor can have this state and still be
3711 in the flush list waiting to acquire the
3712 buf_pool->flush_list_mutex to complete the relocation. */
3713 ut_a(buf_page_in_file(bpage) ||
3714 buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
3715 ut_a(om > 0);
3716
3717 if (buf_pool->flush_rbt != nullptr) {
3718 buf_page_t **prpage;
3719
3720 ut_a(rnode != nullptr);
3721 prpage = rbt_value(buf_page_t *, rnode);
3722
3723 ut_a(*prpage != nullptr);
3724 ut_a(*prpage == bpage);
3725 rnode = rbt_next(buf_pool->flush_rbt, rnode);
3726 }
3727
3728 bpage = UT_LIST_GET_NEXT(list, bpage);
3729
3730 ut_a(bpage == nullptr ||
3731 buf_flush_list_order_validate(bpage->get_oldest_lsn(), om));
3732 }
3733
3734 /* By this time we must have exhausted the traversal of
3735 flush_rbt (if active) as well. */
3736 ut_a(rnode == nullptr);
3737
3738 return true;
3739 }
3740
3741 bool buf_flush_validate(buf_pool_t *buf_pool) {
3742 buf_flush_list_mutex_enter(buf_pool);
3743
3744 auto ret = buf_flush_validate_low(buf_pool);
3745
3746 buf_flush_list_mutex_exit(buf_pool);
3747
3748 return (ret);
3749 }
3750 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3751
3752 /** Check if there are any dirty pages that belong to a space id in the flush
3753 list in a particular buffer pool.
3754 @return number of dirty pages present in a single buffer pool */
3755 ulint buf_pool_get_dirty_pages_count(
3756 buf_pool_t *buf_pool, /*!< in: buffer pool */
3757 space_id_t id, /*!< in: space id to check */
3758 Flush_observer *observer) /*!< in: flush observer to check */
3759
3760 {
3761 ulint count = 0;
3762
3763 buf_flush_list_mutex_enter(buf_pool);
3764
3765 for (auto bpage : buf_pool->flush_list) {
3766 ut_ad(buf_page_in_file(bpage) ||
3767 buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
3768 ut_ad(bpage->in_flush_list);
3769 ut_ad(bpage->is_dirty());
3770
3771 if ((observer != nullptr && observer == bpage->get_flush_observer()) ||
3772 (observer == nullptr && id == bpage->id.space())) {
3773 ++count;
3774 }
3775 }
3776
3777 buf_flush_list_mutex_exit(buf_pool);
3778
3779 return (count);
3780 }
3781
3782 /** Check if there are any dirty pages that belong to a space id in the flush
3783 list.
3784 @return number of dirty pages present in all the buffer pools */
3785 static ulint buf_flush_get_dirty_pages_count(
3786 space_id_t id, /*!< in: space id to check */
3787 Flush_observer *observer) /*!< in: flush observer to check */
3788 {
3789 ulint count = 0;
3790
3791 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
3792 buf_pool_t *buf_pool;
3793
3794 buf_pool = buf_pool_from_array(i);
3795
3796 count += buf_pool_get_dirty_pages_count(buf_pool, id, observer);
3797 }
3798
3799 return (count);
3800 }
3801
3802 Flush_observer::Flush_observer(space_id_t space_id, trx_t *trx,
3803 Alter_stage *stage) noexcept
3804 : m_space_id(space_id),
3805 m_trx(trx),
3806 m_stage(stage),
3807 m_flushed(srv_buf_pool_instances),
3808 m_removed(srv_buf_pool_instances) {
3809 #ifdef FLUSH_LIST_OBSERVER_DEBUG
3810 ib::info(ER_IB_MSG_130) << "Flush_observer : ID= " << m_id
3811 << ", space_id=" << space_id << ", trx_id="
3812 << (m_trx == nullptr ? TRX_ID_MAX : trx->id);
3813 #endif /* FLUSH_LIST_OBSERVER_DEBUG */
3814 }
3815
3816 Flush_observer::~Flush_observer() noexcept {
3817 ut_a(m_n_ref_count.fetch_add(0, std::memory_order_relaxed) == 0);
3818 ut_ad(buf_flush_get_dirty_pages_count(m_space_id, this) == 0);
3819
3820 #ifdef FLUSH_LIST_OBSERVER_DEBUG
3821 ib::info(ER_IB_MSG_131) << "~Flush_observer : ID= " << m_id
3822 << ", space_id=" << space_id << ", trx_id="
3823 << (m_trx == nullptr ? TRX_ID_MAX : trx->id);
3824 #endif /* FLUSH_LIST_OBSERVER_DEBUG */
3825 }
3826
3827 bool Flush_observer::check_interrupted() {
3828 if (m_trx != nullptr && trx_is_interrupted(m_trx)) {
3829 interrupted();
3830
3831 return true;
3832 }
3833
3834 return false;
3835 }
3836
3837 void Flush_observer::notify_flush(buf_pool_t *buf_pool, buf_page_t *) {
3838 m_flushed.at(buf_pool->instance_no).fetch_add(1, std::memory_order_relaxed);
3839
3840 if (m_stage != nullptr) {
3841 m_stage->inc(1);
3842 }
3843 }
3844
3845 void Flush_observer::notify_remove(buf_pool_t *buf_pool, buf_page_t *) {
3846 m_removed.at(buf_pool->instance_no).fetch_add(1, std::memory_order_relaxed);
3847 }
3848
3849 void Flush_observer::flush() {
3850 buf_remove_t buf_remove;
3851
3852 if (m_interrupted) {
3853 buf_remove = BUF_REMOVE_FLUSH_NO_WRITE;
3854 } else {
3855 buf_remove = BUF_REMOVE_FLUSH_WRITE;
3856
3857 if (m_stage != nullptr) {
3858 auto pages_to_flush = buf_flush_get_dirty_pages_count(m_space_id, this);
3859 m_stage->begin_phase_flush(pages_to_flush);
3860 }
3861 }
3862
3863 /* Flush or remove dirty pages. */
3864 buf_LRU_flush_or_remove_pages(m_space_id, buf_remove, m_trx);
3865
3866 /* Wait for all dirty pages were flushed. */
3867 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
3868 while (!is_complete(i)) {
3869 std::this_thread::sleep_for(std::chrono::milliseconds(2));
3870 }
3871 }
3872 }
3873 #else
3874
3875 bool buf_flush_page_cleaner_is_active() { return (false); }
3876
3877 #endif /* UNIV_HOTBACKUP */