Debian Codegraph @

storage/innobase/buf/buf0buf.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4 Copyright (c) 2008, Google Inc.
5
6 Portions of this file contain modifications contributed and copyrighted by
7 Google, Inc. Those modifications are gratefully acknowledged and are described
8 briefly in the InnoDB documentation. The contributions by Google are
9 incorporated with their permission, and subject to the conditions contained in
10 the file COPYING.Google.
11
12 This program is free software; you can redistribute it and/or modify it under
13 the terms of the GNU General Public License, version 2.0, as published by the
14 Free Software Foundation.
15
16 This program is designed to work with certain software (including
17 but not limited to OpenSSL) that is licensed under separate terms,
18 as designated in a particular file or component or in included license
19 documentation. The authors of MySQL hereby grant you an additional
20 permission to link the program and your derivative works with the
21 separately licensed software that they have either included with
22 the program or referenced in the documentation.
23
24 This program is distributed in the hope that it will be useful, but WITHOUT
25 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
26 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
27 for more details.
28
29 You should have received a copy of the GNU General Public License along with
30 this program; if not, write to the Free Software Foundation, Inc.,
31 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
32
33 *****************************************************************************/
34
35 /** @file buf/buf0buf.cc
36 The database buffer buf_pool
37
38 Created 11/5/1995 Heikki Tuuri
39 *******************************************************/
40
41 #include "my_config.h"
42
43 #include "btr0btr.h"
44 #include "buf0buf.h"
45 #include "fil0fil.h"
46 #include "fsp0sysspace.h"
47 #include "ha_prototypes.h"
48 #include "mem0mem.h"
49 #include "my_dbug.h"
50 #include "page0size.h"
51 #ifndef UNIV_HOTBACKUP
52 #include "btr0sea.h"
53 #include "buf0buddy.h"
54 #include "buf0stats.h"
55 #include "dict0stats_bg.h"
56 #include "ibuf0ibuf.h"
57 #include "lock0lock.h"
58 #include "log0buf.h"
59 #include "log0chkp.h"
60 #include "sync0rw.h"
61 #include "trx0purge.h"
62 #include "trx0undo.h"
63
64 #include <errno.h>
65 #include <stdarg.h>
66 #include <sys/types.h>
67 #include <time.h>
68 #include <map>
69 #include <new>
70 #include <sstream>
71 #include <string_view>
72 #include <unordered_map>
73
74 #include "buf0checksum.h"
75 #include "buf0dump.h"
76 #include "dict0dict.h"
77 #include "log0recv.h"
78 #include "os0thread-create.h"
79 #include "page0zip.h"
80 #include "srv0mon.h"
81 #include "srv0srv.h"
82 #include "srv0start.h"
83 #include "sync0sync.h"
84 #include "ut0new.h"
85
86 #include "scope_guard.h"
87
88 #endif /* !UNIV_HOTBACKUP */
89
90 #ifdef UNIV_DEBUG
91 #include "ut0stateful_latching_rules.h"
92 #endif /* UNIV_DEBUG */
93
94 #ifdef HAVE_LIBNUMA
95 #include <numa.h>
96 #include <numaif.h>
97
98 struct set_numa_interleave_t {
99 set_numa_interleave_t() {
100 if (srv_numa_interleave) {
101 ib::info(ER_IB_MSG_47) << "Setting NUMA memory policy to"
102 " MPOL_INTERLEAVE";
103 struct bitmask *numa_nodes = numa_get_mems_allowed();
104 if (set_mempolicy(MPOL_INTERLEAVE, numa_nodes->maskp, numa_nodes->size) !=
105 0) {
106 ib::warn(ER_IB_MSG_48) << "Failed to set NUMA memory"
107 " policy to MPOL_INTERLEAVE: "
108 << strerror(errno);
109 }
110 numa_bitmask_free(numa_nodes);
111 }
112 }
113
114 ~set_numa_interleave_t() {
115 if (srv_numa_interleave) {
116 ib::info(ER_IB_MSG_49) << "Setting NUMA memory policy to"
117 " MPOL_DEFAULT";
118 if (set_mempolicy(MPOL_DEFAULT, nullptr, 0) != 0) {
119 ib::warn(ER_IB_MSG_50) << "Failed to set NUMA memory"
120 " policy to MPOL_DEFAULT: "
121 << strerror(errno);
122 }
123 }
124 }
125 };
126
127 #define NUMA_MEMPOLICY_INTERLEAVE_IN_SCOPE set_numa_interleave_t scoped_numa
128 #else
129 #define NUMA_MEMPOLICY_INTERLEAVE_IN_SCOPE
130 #endif /* HAVE_LIBNUMA */
131
132 /*
133 IMPLEMENTATION OF THE BUFFER POOL
134 =================================
135
136 Buffer frames and blocks
137 ------------------------
138 Following the terminology of Gray and Reuter, we call the memory
139 blocks where file pages are loaded buffer frames. For each buffer
140 frame there is a control block, or shortly, a block, in the buffer
141 control array. The control info which does not need to be stored
142 in the file along with the file page, resides in the control block.
143
144 Buffer pool struct
145 ------------------
146 The buffer buf_pool contains several mutexes which protect all the
147 control data structures of the buf_pool. The content of a buffer frame is
148 protected by a separate read-write lock in its control block, though.
149
150 buf_pool->chunks_mutex protects the chunks, n_chunks during resize;
151 it also protects buf_pool_should_madvise:
152 - readers of buf_pool_should_madvise hold any buf_pool's chunks_mutex
153 - writers hold all buf_pools' chunk_mutex-es;
154 it is useful to think that it also protects the status of madvice() flags set
155 for chunks in this pool, even though these flags are handled by OS, as we only
156 modify them why holding this latch;
157 buf_pool->LRU_list_mutex protects the LRU_list;
158 buf_pool->free_list_mutex protects the free_list and withdraw list;
159 buf_pool->flush_state_mutex protects the flush state related data structures;
160 buf_pool->zip_free mutex protects the zip_free arrays;
161 buf_pool->zip_hash mutex protects the zip_hash hash and in_zip_hash flag.
162
163 Control blocks
164 --------------
165
166 The control block contains, for instance, the bufferfix count
167 which is incremented when a thread wants a file page to be fixed
168 in a buffer frame. The bufferfix operation does not lock the
169 contents of the frame, however. For this purpose, the control
170 block contains a read-write lock.
171
172 The buffer frames have to be aligned so that the start memory
173 address of a frame is divisible by the universal page size, which
174 is a power of two.
175
176 The control blocks containing file pages are put to a hash table
177 according to the file address of the page.
178 We could speed up the access to an individual page by using
179 "pointer swizzling": we could replace the page references on
180 non-leaf index pages by direct pointers to the page, if it exists
181 in the buf_pool. We could make a separate hash table where we could
182 chain all the page references in non-leaf pages residing in the buf_pool,
183 using the page reference as the hash key,
184 and at the time of reading of a page update the pointers accordingly.
185 Drawbacks of this solution are added complexity and,
186 possibly, extra space required on non-leaf pages for memory pointers.
187 A simpler solution is just to speed up the hash table mechanism
188 in the database, using tables whose size is a power of 2.
189
190 Lists of blocks
191 ---------------
192
193 There are several lists of control blocks.
194
195 The free list (buf_pool->free) contains blocks which are currently not
196 used.
197
198 The common LRU list contains all the blocks holding a file page
199 except those for which the bufferfix count is non-zero.
200 The pages are in the LRU list roughly in the order of the last
201 access to the page, so that the oldest pages are at the end of the
202 list. We also keep a pointer to near the end of the LRU list,
203 which we can use when we want to artificially age a page in the
204 buf_pool. This is used if we know that some page is not needed
205 again for some time: we insert the block right after the pointer,
206 causing it to be replaced sooner than would normally be the case.
207 Currently this aging mechanism is used for read-ahead mechanism
208 of pages, and it can also be used when there is a scan of a full
209 table which cannot fit in the memory. Putting the pages near the
210 end of the LRU list, we make sure that most of the buf_pool stays
211 in the main memory, undisturbed.
212
213 The unzip_LRU list contains a subset of the common LRU list. The
214 blocks on the unzip_LRU list hold a compressed file page and the
215 corresponding uncompressed page frame. A block is in unzip_LRU if and
216 only if the predicate buf_page_belongs_to_unzip_LRU(&block->page)
217 holds. The blocks in unzip_LRU will be in same order as they are in
218 the common LRU list. That is, each manipulation of the common LRU
219 list will result in the same manipulation of the unzip_LRU list.
220
221 The chain of modified blocks (buf_pool->flush_list) contains the blocks
222 holding file pages that have been modified in the memory
223 but not written to disk yet. The block with the oldest modification
224 which has not yet been written to disk is at the end of the chain.
225 The access to this list is protected by buf_pool->flush_list_mutex.
226
227 The chain of unmodified compressed blocks (buf_pool->zip_clean)
228 contains the control blocks (buf_page_t) of those compressed pages
229 that are not in buf_pool->flush_list and for which no uncompressed
230 page has been allocated in the buffer pool. The control blocks for
231 uncompressed pages are accessible via buf_block_t objects that are
232 reachable via buf_pool->chunks[].
233
234 The chains of free memory blocks (buf_pool->zip_free[]) are used by
235 the buddy allocator (buf0buddy.cc) to keep track of currently unused
236 memory blocks of size sizeof(buf_page_t)..UNIV_PAGE_SIZE / 2. These
237 blocks are inside the UNIV_PAGE_SIZE-sized memory blocks of type
238 BUF_BLOCK_MEMORY that the buddy allocator requests from the buffer
239 pool. The buddy allocator is solely used for allocating control
240 blocks for compressed pages (buf_page_t) and compressed page frames.
241
242 Loading a file page
243 -------------------
244
245 First, a victim block for replacement has to be found in the
246 buf_pool. It is taken from the free list or searched for from the
247 end of the LRU-list. An exclusive lock is reserved for the frame,
248 the io_fix field is set in the block fixing the block in buf_pool,
249 and the io-operation for loading the page is queued. The io-handler thread
250 releases the X-lock on the frame and resets the io_fix field
251 when the io operation completes.
252
253 A thread may request the above operation using the function
254 buf_page_get(). It may then continue to request a lock on the frame.
255 The lock is granted when the io-handler releases the x-lock.
256
257 Read-ahead
258 ----------
259
260 The read-ahead mechanism is intended to be intelligent and
261 isolated from the semantically higher levels of the database
262 index management. From the higher level we only need the
263 information if a file page has a natural successor or
264 predecessor page. On the leaf level of a B-tree index,
265 these are the next and previous pages in the natural
266 order of the pages.
267
268 Let us first explain the read-ahead mechanism when the leafs
269 of a B-tree are scanned in an ascending or descending order.
270 When a read page is the first time referenced in the buf_pool,
271 the buffer manager checks if it is at the border of a so-called
272 linear read-ahead area. The tablespace is divided into these
273 areas of size 64 blocks, for example. So if the page is at the
274 border of such an area, the read-ahead mechanism checks if
275 all the other blocks in the area have been accessed in an
276 ascending or descending order. If this is the case, the system
277 looks at the natural successor or predecessor of the page,
278 checks if that is at the border of another area, and in this case
279 issues read-requests for all the pages in that area. Maybe
280 we could relax the condition that all the pages in the area
281 have to be accessed: if data is deleted from a table, there may
282 appear holes of unused pages in the area.
283
284 A different read-ahead mechanism is used when there appears
285 to be a random access pattern to a file.
286 If a new page is referenced in the buf_pool, and several pages
287 of its random access area (for instance, 32 consecutive pages
288 in a tablespace) have recently been referenced, we may predict
289 that the whole area may be needed in the near future, and issue
290 the read requests for the whole area.
291 */
292
293 #ifndef UNIV_HOTBACKUP
294 constexpr std::chrono::microseconds WAIT_FOR_READ{100};
295 constexpr std::chrono::microseconds WAIT_FOR_WRITE{100};
296 /** Number of attempts made to read in a page in the buffer pool */
297 static const ulint BUF_PAGE_READ_MAX_RETRIES = 100;
298 /** Number of pages to read ahead */
299 static const ulint BUF_READ_AHEAD_PAGES = 64;
300 /** The maximum portion of the buffer pool that can be used for the
301 read-ahead buffer. (Divide buf_pool size by this amount) */
302 static const ulint BUF_READ_AHEAD_PORTION = 32;
303
304 /** The buffer pools of the database */
305 buf_pool_t *buf_pool_ptr;
306
307 /** true when resizing buffer pool is in the critical path. */
308 volatile bool buf_pool_resizing;
309
310 /** Atomic variables to track resize status code and progress */
311 std::atomic_uint32_t buf_pool_resize_status_code = {0};
312 std::atomic_uint32_t buf_pool_resize_status_progress = {0};
313
314 /** Map of buffer pool chunks by its first frame address
315 This is newly made by initialization of buffer pool and buf_resize_thread.
316 Note: mutex protection is required when creating multiple buffer pools
317 in parallel. We don't use a mutex during resize because that is still single
318 threaded. */
319 typedef std::map<const byte *, buf_chunk_t *, std::less<const byte *>,
320 ut::allocator<std::pair<const byte *const, buf_chunk_t *>>>
321 buf_pool_chunk_map_t;
322
323 static buf_pool_chunk_map_t *buf_chunk_map_reg;
324
325 /** Container for how many pages from each index are contained in the buffer
326 pool(s). */
327 buf_stat_per_index_t *buf_stat_per_index;
328
329 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
330 /** This is used to insert validation operations in execution
331 in the debug version */
332 static ulint buf_dbg_counter = 0;
333 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
334
335 #ifdef UNIV_DEBUG
336 /** This is used to enable multiple buffer pool instances
337 with small buffer pool size. */
338 bool srv_buf_pool_debug;
339 #endif /* UNIV_DEBUG */
340
341 namespace {
342 #ifndef UNIV_HOTBACKUP
343 const std::unordered_map<buf_io_fix, std::string_view> buf_io_fix_str{
344 {BUF_IO_NONE, "BUF_IO_NONE"},
345 {BUF_IO_READ, "BUF_IO_READ"},
346 {BUF_IO_WRITE, "BUF_IO_WRITE"},
347 {BUF_IO_PIN, "BUF_IO_PIN"},
348 };
349
350 const std::unordered_map<buf_flush_t, std::string_view> buf_flush_str{
351 {BUF_FLUSH_LRU, "BUF_FLUSH_LRU"},
352 {BUF_FLUSH_LIST, "BUF_FLUSH_LIST"},
353 {BUF_FLUSH_SINGLE_PAGE, "BUF_FLUSH_SINGLE_PAGE"},
354 {BUF_FLUSH_N_TYPES, "BUF_FLUSH_N_TYPES"}};
355
356 /** Helper iostream operator presenting the io_fix value as human-readable
357 name of the enum. Used in error messages of Buf_io_fix_latching_rules.
358 @param[in,out] outs the output stream to which to print
359 @param[in] io_fix the value to be printed
360 @return always equals the stream passed as the outs argument
361 */
362 static std::ostream &operator<<(std::ostream &outs, const buf_io_fix io_fix) {
363 ut_a(buf_page_t::is_correct_io_fix_value(io_fix));
364 return outs << buf_io_fix_str.at(io_fix);
365 }
366
367 /** Helper ostream operator to print buf_page_state in human-readable name of
368 the enum.
369 @param[in,out] outs the output stream
370 @param[in] state the page state to be printed
371 @return same output stream passed as input */
372 std::ostream &operator<<(std::ostream &outs, const buf_page_state &state) {
373 const std::string_view state_str = buf_page_state_str.at(state);
374 if (state_str.length() < 2) {
375 /* Compression pages states: invalid for buffer block pages */
376 if (state == BUF_BLOCK_POOL_WATCH) {
377 return outs << "POOL_WATCH";
378 } else if (state == BUF_BLOCK_ZIP_PAGE) {
379 return outs << "ZIP_PAGE";
380 } else if (state == BUF_BLOCK_ZIP_DIRTY) {
381 return outs << "ZIP_DIRTY";
382 } else {
383 ut_error;
384 }
385 }
386 return outs << state_str;
387 }
388
389 /** Helper ostream operator to print buf_flush_t in human-readable name of the
390 enum.
391 @param[in,out] outs the output stream
392 @param[in] flush_type the flush_type to be printed
393 @return same output stream passed as input */
394 std::ostream &operator<<(std::ostream &outs, const buf_flush_t &flush_type) {
395 return outs << buf_flush_str.at(flush_type);
396 }
397 #endif /* !UNIV_HOTBACKUP */
398 } // namespace
399
400 #if defined UNIV_PFS_MUTEX || defined UNIV_PFS_RWLOCK
401 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
402
403 /* Buffer block mutexes and rwlocks can be registered
404 in one group rather than individually. If PFS_GROUP_BUFFER_SYNC
405 is defined, register buffer block mutex and rwlock
406 in one group after their initialization. */
407 #define PFS_GROUP_BUFFER_SYNC
408
409 /* This define caps the number of mutexes/rwlocks can
410 be registered with performance schema. Developers can
411 modify this define if necessary. Please note, this would
412 be effective only if PFS_GROUP_BUFFER_SYNC is defined. */
413 #define PFS_MAX_BUFFER_MUTEX_LOCK_REGISTER ULINT_MAX
414
415 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
416 #endif /* UNIV_PFS_MUTEX || UNIV_PFS_RWLOCK */
417
418 /** Macro to determine whether the read of write counter is used depending
419 on the io_type */
420 #define MONITOR_RW_COUNTER(io_type, counter) \
421 ((io_type == BUF_IO_READ) ? (counter##_READ) : (counter##_WRITTEN))
422
423 /** Registers a chunk to buf_pool_chunk_map
424 @param[in] chunk chunk of buffers */
425 static void buf_pool_register_chunk(buf_chunk_t *chunk) {
426 buf_chunk_map_reg->insert(
427 buf_pool_chunk_map_t::value_type(chunk->blocks->frame, chunk));
428 }
429
430 lsn_t buf_pool_get_oldest_modification_approx(void) {
431 lsn_t lsn = 0;
432 lsn_t oldest_lsn = 0;
433
434 /* When we traverse all the flush lists we don't care if previous
435 flush lists changed. We do not require consistent result. */
436
437 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
438 buf_pool_t *buf_pool;
439
440 buf_pool = buf_pool_from_array(i);
441
442 buf_flush_list_mutex_enter(buf_pool);
443
444 buf_page_t *bpage;
445
446 /* We don't let log-checkpoint halt because pages from system
447 temporary are not yet flushed to the disk. Anyway, object
448 residing in system temporary doesn't generate REDO logging. */
449 bpage = buf_pool->oldest_hp.get();
450 if (bpage != nullptr) {
451 ut_ad(bpage->in_flush_list);
452 } else {
453 bpage = UT_LIST_GET_LAST(buf_pool->flush_list);
454 }
455
456 for (; bpage != nullptr && fsp_is_system_temporary(bpage->id.space());
457 bpage = UT_LIST_GET_PREV(list, bpage)) {
458 /* Do nothing. */
459 }
460
461 if (bpage != nullptr) {
462 ut_ad(bpage->in_flush_list);
463 lsn = bpage->get_oldest_lsn();
464 buf_pool->oldest_hp.set(bpage);
465 } else {
466 /* The last scanned page as entry point, or nullptr. */
467 buf_pool->oldest_hp.set(UT_LIST_GET_FIRST(buf_pool->flush_list));
468 }
469
470 buf_flush_list_mutex_exit(buf_pool);
471
472 if (!oldest_lsn || oldest_lsn > lsn) {
473 oldest_lsn = lsn;
474 }
475 }
476
477 /* The returned answer may be out of date: the flush_list can
478 change after the mutex has been released. */
479
480 return (oldest_lsn);
481 }
482
483 lsn_t buf_pool_get_oldest_modification_lwm(void) {
484 const lsn_t lsn = buf_pool_get_oldest_modification_approx();
485
486 if (lsn == 0) {
487 return (0);
488 }
489
490 ut_a(lsn % OS_FILE_LOG_BLOCK_SIZE >= LOG_BLOCK_HDR_SIZE);
491
492 const log_t &log = *log_sys;
493
494 const lsn_t lag = log_buffer_flush_order_lag(log);
495
496 ut_a(lag % OS_FILE_LOG_BLOCK_SIZE == 0);
497
498 const lsn_t checkpoint_lsn = log_get_checkpoint_lsn(log);
499
500 ut_a(checkpoint_lsn != 0);
501
502 if (lsn > lag) {
503 return (std::max(checkpoint_lsn, lsn - lag));
504
505 } else {
506 return (checkpoint_lsn);
507 }
508 }
509
510 /** Get total buffer pool statistics.
511 @param[out] LRU_len Length of all lru lists
512 @param[out] free_len Length of all free lists
513 @param[out] flush_list_len Length of all flush lists */
514 void buf_get_total_list_len(ulint *LRU_len, ulint *free_len,
515 ulint *flush_list_len) {
516 ulint i;
517
518 *LRU_len = 0;
519 *free_len = 0;
520 *flush_list_len = 0;
521
522 for (i = 0; i < srv_buf_pool_instances; i++) {
523 buf_pool_t *buf_pool;
524
525 buf_pool = buf_pool_from_array(i);
526
527 *LRU_len += UT_LIST_GET_LEN(buf_pool->LRU);
528 *free_len += UT_LIST_GET_LEN(buf_pool->free);
529 *flush_list_len += UT_LIST_GET_LEN(buf_pool->flush_list);
530 }
531 }
532
533 /** Get total list size in bytes from all buffer pools. */
534 void buf_get_total_list_size_in_bytes(
535 buf_pools_list_size_t *buf_pools_list_size) /*!< out: list sizes
536 in all buffer pools */
537 {
538 ut_ad(buf_pools_list_size);
539 memset(buf_pools_list_size, 0, sizeof(*buf_pools_list_size));
540
541 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
542 buf_pool_t *buf_pool;
543
544 buf_pool = buf_pool_from_array(i);
545 /* We don't need mutex protection since this is
546 for statistics purpose */
547 buf_pools_list_size->LRU_bytes += buf_pool->stat.LRU_bytes;
548 buf_pools_list_size->unzip_LRU_bytes +=
549 UT_LIST_GET_LEN(buf_pool->unzip_LRU) * UNIV_PAGE_SIZE;
550 buf_pools_list_size->flush_list_bytes += buf_pool->stat.flush_list_bytes;
551 }
552 }
553
554 /** Get total buffer pool statistics. */
555 void buf_get_total_stat(
556 buf_pool_stat_t *tot_stat) /*!< out: buffer pool stats */
557 {
558 ulint i;
559
560 tot_stat->reset();
561
562 for (i = 0; i < srv_buf_pool_instances; i++) {
563 buf_pool_t *buf_pool = buf_pool_from_array(i);
564 buf_pool_stat_t *buf_stat = &buf_pool->stat;
565
566 Counter::add(tot_stat->m_n_page_gets, buf_stat->m_n_page_gets);
567 tot_stat->n_pages_read += buf_stat->n_pages_read;
568 tot_stat->n_pages_written += buf_stat->n_pages_written;
569 tot_stat->n_pages_created += buf_stat->n_pages_created;
570 tot_stat->n_ra_pages_read_rnd += buf_stat->n_ra_pages_read_rnd;
571 tot_stat->n_ra_pages_read += buf_stat->n_ra_pages_read;
572 tot_stat->n_ra_pages_evicted += buf_stat->n_ra_pages_evicted;
573 tot_stat->n_pages_made_young += buf_stat->n_pages_made_young;
574
575 tot_stat->n_pages_not_made_young += buf_stat->n_pages_not_made_young;
576 }
577 }
578
579 /** Allocates a buffer block.
580 @return own: the allocated block, in state BUF_BLOCK_MEMORY */
581 buf_block_t *buf_block_alloc(
582 buf_pool_t *buf_pool) /*!< in/out: buffer pool instance,
583 or NULL for round-robin selection
584 of the buffer pool */
585 {
586 buf_block_t *block;
587 ulint index;
588 static ulint buf_pool_index;
589
590 if (buf_pool == nullptr) {
591 /* We are allocating memory from any buffer pool, ensure
592 we spread the grace on all buffer pool instances. */
593 index = buf_pool_index++ % srv_buf_pool_instances;
594 buf_pool = buf_pool_from_array(index);
595 }
596
597 block = buf_LRU_get_free_block(buf_pool);
598
599 buf_block_set_state(block, BUF_BLOCK_MEMORY);
600
601 return (block);
602 }
603 #endif /* !UNIV_HOTBACKUP */
604
605 /** Prints a page to stderr.
606 @param[in] read_buf a database page
607 @param[in] page_size page size
608 @param[in] flags 0 or BUF_PAGE_PRINT_NO_CRASH or
609 BUF_PAGE_PRINT_NO_FULL */
610 void buf_page_print(const byte *read_buf, const page_size_t &page_size,
611 ulint flags) {
612 if (!(flags & BUF_PAGE_PRINT_NO_FULL)) {
613 ib::info(ER_IB_MSG_51) << "Page dump in ascii and hex ("
614 << page_size.physical() << " bytes):";
615
616 ut_print_buf(stderr, read_buf, page_size.physical());
617 fputs("\nInnoDB: End of page dump\n", stderr);
618 }
619
620 if (page_size.is_compressed()) {
621 BlockReporter compressed = BlockReporter(false, read_buf, page_size, false);
622
623 /* Print compressed page. */
624 ib::info(ER_IB_MSG_52)
625 << "Compressed page type (" << fil_page_get_type(read_buf)
626 << "); stored checksum in field1 "
627 << mach_read_from_4(read_buf + FIL_PAGE_SPACE_OR_CHKSUM)
628 << "; calculated checksums for field1: "
629 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_CRC32) << " "
630 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_CRC32) << ", "
631 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_INNODB) << " "
632 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_INNODB) << ", "
633 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_NONE) << " "
634 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_NONE)
635 << "; page LSN " << mach_read_from_8(read_buf + FIL_PAGE_LSN)
636 << "; page number (if stored to page"
637 << " already) " << mach_read_from_4(read_buf + FIL_PAGE_OFFSET)
638 << "; space id (if stored to page already) "
639 << mach_read_from_4(read_buf + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
640
641 } else {
642 const uint32_t crc32 = buf_calc_page_crc32(read_buf);
643
644 const uint32_t crc32_legacy = buf_calc_page_crc32(read_buf, true);
645
646 ib::info(ER_IB_MSG_53)
647 << "Uncompressed page, stored checksum in field1 "
648 << mach_read_from_4(read_buf + FIL_PAGE_SPACE_OR_CHKSUM)
649 << ", calculated checksums for field1: "
650 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_CRC32) << " "
651 << crc32 << "/" << crc32_legacy << ", "
652 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_INNODB) << " "
653 << buf_calc_page_new_checksum(read_buf) << ", "
654 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_NONE) << " "
655 << BUF_NO_CHECKSUM_MAGIC << ", stored checksum in field2 "
656 << mach_read_from_4(read_buf + page_size.logical() -
657 FIL_PAGE_END_LSN_OLD_CHKSUM)
658 << ", calculated checksums for field2: "
659 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_CRC32) << " "
660 << crc32 << "/" << crc32_legacy << ", "
661 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_INNODB) << " "
662 << buf_calc_page_old_checksum(read_buf) << ", "
663 << buf_checksum_algorithm_name(SRV_CHECKSUM_ALGORITHM_NONE) << " "
664 << BUF_NO_CHECKSUM_MAGIC << ", page LSN "
665 << mach_read_from_4(read_buf + FIL_PAGE_LSN) << " "
666 << mach_read_from_4(read_buf + FIL_PAGE_LSN + 4)
667 << ", low 4 bytes of LSN at page end "
668 << mach_read_from_4(read_buf + page_size.logical() -
669 FIL_PAGE_END_LSN_OLD_CHKSUM + 4)
670 << ", page number (if stored to page already) "
671 << mach_read_from_4(read_buf + FIL_PAGE_OFFSET)
672 << ", space id (if created with >= MySQL-4.1.1"
673 " and stored already) "
674 << mach_read_from_4(read_buf + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
675 }
676
677 #ifndef UNIV_HOTBACKUP
678 if (mach_read_from_2(read_buf + TRX_UNDO_PAGE_HDR + TRX_UNDO_PAGE_TYPE) ==
679 TRX_UNDO_INSERT) {
680 fprintf(stderr, "InnoDB: Page may be an insert undo log page\n");
681 } else if (mach_read_from_2(read_buf + TRX_UNDO_PAGE_HDR +
682 TRX_UNDO_PAGE_TYPE) == TRX_UNDO_UPDATE) {
683 fprintf(stderr, "InnoDB: Page may be an update undo log page\n");
684 }
685 #endif /* !UNIV_HOTBACKUP */
686
687 switch (fil_page_get_type(read_buf)) {
688 space_index_t index_id;
689 case FIL_PAGE_INDEX:
690 case FIL_PAGE_RTREE:
691 index_id = btr_page_get_index_id(read_buf);
692 fprintf(stderr,
693 "InnoDB: Page may be an index page where"
694 " index id is " IB_ID_FMT "\n",
695 index_id);
696 break;
697 case FIL_PAGE_INODE:
698 fputs("InnoDB: Page may be an 'inode' page\n", stderr);
699 break;
700 case FIL_PAGE_IBUF_FREE_LIST:
701 fputs("InnoDB: Page may be an insert buffer free list page\n", stderr);
702 break;
703 case FIL_PAGE_TYPE_ALLOCATED:
704 fputs("InnoDB: Page may be a freshly allocated page\n", stderr);
705 break;
706 case FIL_PAGE_IBUF_BITMAP:
707 fputs("InnoDB: Page may be an insert buffer bitmap page\n", stderr);
708 break;
709 case FIL_PAGE_TYPE_SYS:
710 fputs("InnoDB: Page may be a system page\n", stderr);
711 break;
712 case FIL_PAGE_TYPE_TRX_SYS:
713 fputs("InnoDB: Page may be a transaction system page\n", stderr);
714 break;
715 case FIL_PAGE_TYPE_FSP_HDR:
716 fputs("InnoDB: Page may be a file space header page\n", stderr);
717 break;
718 case FIL_PAGE_TYPE_XDES:
719 fputs("InnoDB: Page may be an extent descriptor page\n", stderr);
720 break;
721 case FIL_PAGE_TYPE_BLOB:
722 fputs("InnoDB: Page may be a BLOB page\n", stderr);
723 break;
724 case FIL_PAGE_SDI_BLOB:
725 fputs("InnoDB: Page may be a SDI BLOB page\n", stderr);
726 break;
727 case FIL_PAGE_TYPE_ZBLOB:
728 case FIL_PAGE_TYPE_ZBLOB2:
729 fputs("InnoDB: Page may be a compressed BLOB page\n", stderr);
730 break;
731 case FIL_PAGE_SDI_ZBLOB:
732 fputs("InnoDB: Page may be a compressed SDI BLOB page\n", stderr);
733 break;
734 case FIL_PAGE_TYPE_RSEG_ARRAY:
735 fputs("InnoDB: Page may be a Rollback Segment Array page\n", stderr);
736 break;
737 }
738
739 ut_ad(flags & BUF_PAGE_PRINT_NO_CRASH);
740 }
741
742 #ifndef UNIV_HOTBACKUP
743
744 #ifdef PFS_GROUP_BUFFER_SYNC
745
746 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
747 extern mysql_pfs_key_t buffer_block_mutex_key;
748 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
749
750 /** This function registers mutexes and rwlocks in buffer blocks with
751 performance schema. If PFS_MAX_BUFFER_MUTEX_LOCK_REGISTER is
752 defined to be a value less than chunk->size, then only mutexes
753 and rwlocks in the first PFS_MAX_BUFFER_MUTEX_LOCK_REGISTER
754 blocks are registered. */
755 static void pfs_register_buffer_block(
756 buf_chunk_t *chunk) /*!< in/out: chunk of buffers */
757 {
758 buf_block_t *block;
759 ulint num_to_register;
760
761 block = chunk->blocks;
762
763 num_to_register = std::min(chunk->size, PFS_MAX_BUFFER_MUTEX_LOCK_REGISTER);
764
765 for (ulint i = 0; i < num_to_register; i++) {
766 #ifdef UNIV_PFS_MUTEX
767 BPageMutex *mutex;
768
769 mutex = &block->mutex;
770
771 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
772 mutex->pfs_add(buffer_block_mutex_key);
773 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
774
775 #endif /* UNIV_PFS_MUTEX */
776
777 rw_lock_t *rwlock;
778
779 #ifdef UNIV_PFS_RWLOCK
780 rwlock = &block->lock;
781 ut_a(!rwlock->pfs_psi);
782
783 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
784 rwlock->pfs_psi = (PSI_server)
785 ? PSI_server->init_rwlock(buf_block_lock_key, rwlock)
786 : NULL;
787 #else
788 rwlock->pfs_psi =
789 (PSI_server) ? PSI_server->init_rwlock(PFS_NOT_INSTRUMENTED, rwlock)
790 : NULL;
791 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
792
793 #ifdef UNIV_DEBUG
794 rwlock = &block->debug_latch;
795 ut_a(!rwlock->pfs_psi);
796 rwlock->pfs_psi = (PSI_server) ? PSI_server->init_rwlock(
797 buf_block_debug_latch_key, rwlock)
798 : NULL;
799 #endif /* UNIV_DEBUG */
800
801 #endif /* UNIV_PFS_RWLOCK */
802 block++;
803 }
804 }
805 #endif /* PFS_GROUP_BUFFER_SYNC */
806
807 /** Initializes a buffer control block when the buf_pool is created. */
808 static void buf_block_init(
809 buf_pool_t *buf_pool, /*!< in: buffer pool instance */
810 buf_block_t *block, /*!< in: pointer to control block */
811 byte *frame) /*!< in: pointer to buffer frame */
812 {
813 UNIV_MEM_DESC(frame, UNIV_PAGE_SIZE);
814
815 /* This function should only be executed at database startup or by
816 buf_pool_resize(). Either way, adaptive hash index must not exist. */
817 block->ahi.assert_empty_on_init();
818
819 block->frame = frame;
820
821 block->page.buf_pool_index = buf_pool_index(buf_pool);
822 block->page.state = BUF_BLOCK_NOT_USED;
823 block->page.buf_fix_count.store(0);
824 block->page.init_io_fix();
825 block->page.reset_flush_observer();
826 block->page.m_space = nullptr;
827 block->page.m_version = 0;
828
829 block->modify_clock = 0;
830
831 ut_d(block->page.file_page_was_freed = false);
832
833 block->ahi.index = nullptr;
834 block->made_dirty_with_no_latch = false;
835
836 ut_d(block->page.in_page_hash = false);
837 ut_d(block->page.in_zip_hash = false);
838 ut_d(block->page.in_flush_list = false);
839 ut_d(block->page.in_free_list = false);
840 ut_d(block->page.in_LRU_list = false);
841 ut_d(block->in_unzip_LRU_list = false);
842 ut_d(block->in_withdraw_list = false);
843
844 page_zip_des_init(&block->page.zip);
845
846 mutex_create(LATCH_ID_BUF_BLOCK_MUTEX, &block->mutex);
847
848 #if defined PFS_SKIP_BUFFER_MUTEX_RWLOCK || defined PFS_GROUP_BUFFER_SYNC
849 /* If PFS_SKIP_BUFFER_MUTEX_RWLOCK is defined, skip registration
850 of buffer block rwlock with performance schema.
851
852 If PFS_GROUP_BUFFER_SYNC is defined, skip the registration
853 since buffer block rwlock will be registered later in
854 pfs_register_buffer_block(). */
855
856 rw_lock_create(PFS_NOT_INSTRUMENTED, &block->lock, LATCH_ID_BUF_BLOCK_LOCK);
857
858 ut_d(rw_lock_create(PFS_NOT_INSTRUMENTED, &block->debug_latch,
859 LATCH_ID_BUF_BLOCK_DEBUG));
860
861 #else /* PFS_SKIP_BUFFER_MUTEX_RWLOCK || PFS_GROUP_BUFFER_SYNC */
862
863 rw_lock_create(buf_block_lock_key, &block->lock, LATCH_ID_BUF_BLOCK_LOCK);
864
865 ut_d(rw_lock_create(buf_block_debug_latch_key, &block->debug_latch,
866 LATCH_ID_BUF_BLOCK_DEBUG));
867
868 #endif /* PFS_SKIP_BUFFER_MUTEX_RWLOCK || PFS_GROUP_BUFFER_SYNC */
869
870 block->lock.is_block_lock = true;
871
872 ut_ad(rw_lock_validate(&(block->lock)));
873 }
874 /* We maintain our private view of innobase_should_madvise_buf_pool() which we
875 initialize at the beginning of buf_pool_init() and then update when the
876 @@global.innodb_buffer_pool_in_core_file changes.
877 Changes to buf_pool_should_madvise are protected by holding chunk_mutex for all
878 buf_pool_t instances.
879 This way, even if @@global.innodb_buffer_pool_in_core_file changes during
880 execution of buf_pool_init() (unlikely) or during buf_pool_resize(), we will use
881 a single consistent value for all (de)allocated chunks.
882 The function buf_pool_update_madvise() handles updating buf_pool_should_madvise
883 in reaction to changes to @@global.innodb_buffer_pool_in_core_file and makes
884 sure before releasing chunk_mutex-es that all chunks are properly madvised
885 according to new value.
886 It is important that initial value of this variable is `false` and not `true`,
887 as on some platforms which do not support madvise() or MADV_DONT_DUMP we need to
888 avoid taking any actions which might trigger a warning or disabling @@core_file.
889 */
890 static bool buf_pool_should_madvise = false;
891
892 // Doxygen gets confused by buf_chunk_t somehow.
893
894 //! @cond
895
896 /* Implementation of buf_chunk_t's methods */
897
898 /** Advices the OS that this chunk should be dumped to a core file.
899 Emits a warning to the log if could not succeed.
900 @return true iff succeeded, false if no OS support or failed */
901 bool buf_chunk_t::madvise_dump() {
902 #ifdef HAVE_MADV_DONTDUMP
903 const auto low_level_info =
904 ut::large_page_low_level_info(this->mem, ut::fallback_to_normal_page_t{});
905 if (madvise(low_level_info.base_ptr, low_level_info.allocation_size,
906 MADV_DODUMP)) {
907 ib::warn(ER_IB_MSG_MADVISE_FAILED, low_level_info.base_ptr,
908 low_level_info.allocation_size, "MADV_DODUMP", strerror(errno));
909 return false;
910 }
911 return true;
912 #else /* HAVE_MADV_DONTDUMP */
913 ib::warn(ER_IB_MSG_MADV_DONTDUMP_UNSUPPORTED);
914 return false;
915 #endif /* HAVE_MADV_DONTDUMP */
916 }
917
918 /** Advices the OS that this chunk should not be dumped to a core file.
919 Emits a warning to the log if could not succeed.
920 @return true iff succeeded, false if no OS support or failed */
921 bool buf_chunk_t::madvise_dont_dump() {
922 #ifdef HAVE_MADV_DONTDUMP
923 const auto low_level_info =
924 ut::large_page_low_level_info(this->mem, ut::fallback_to_normal_page_t{});
925 if (madvise(low_level_info.base_ptr, low_level_info.allocation_size,
926 MADV_DONTDUMP)) {
927 ib::warn(ER_IB_MSG_MADVISE_FAILED, low_level_info.base_ptr,
928 low_level_info.allocation_size, "MADV_DONTDUMP", strerror(errno));
929 return false;
930 }
931 return true;
932 #else /* HAVE_MADV_DONTDUMP */
933 ib::warn(ER_IB_MSG_MADV_DONTDUMP_UNSUPPORTED);
934 return false;
935 #endif /* HAVE_MADV_DONTDUMP */
936 }
937
938 /* End of implementation of buf_chunk_t's methods */
939
940 //! @endcond
941
942 /* Implementation of buf_pool_t's methods */
943
944 bool buf_pool_t::allocate_chunk(ulonglong mem_size, buf_chunk_t *chunk) {
945 ut_ad(mutex_own(&chunks_mutex));
946 chunk->mem = static_cast<uint8_t *>(ut::malloc_large_page_withkey(
947 ut::make_psi_memory_key(mem_key_buf_buf_pool), mem_size,
948 ut::fallback_to_normal_page_t{}));
949 if (chunk->mem == nullptr) {
950 return false;
951 }
952 /* Dump core without large memory buffers */
953 if (buf_pool_should_madvise) {
954 if (!chunk->madvise_dont_dump()) {
955 innobase_disable_core_dump();
956 }
957 }
958 #ifdef HAVE_LIBNUMA
959 if (srv_numa_interleave) {
960 const auto low_level_info = ut::large_page_low_level_info(
961 chunk->mem, ut::fallback_to_normal_page_t{});
962 struct bitmask *numa_nodes = numa_get_mems_allowed();
963 int st = mbind(low_level_info.base_ptr, low_level_info.allocation_size,
964 MPOL_INTERLEAVE, numa_nodes->maskp, numa_nodes->size,
965 MPOL_MF_MOVE);
966 if (st != 0) {
967 ib::warn(ER_IB_MSG_54, low_level_info.base_ptr,
968 low_level_info.allocation_size, "MPOL_INTERLEAVE",
969 "MPOL_MF_MOVE", strerror(errno));
970 }
971 numa_bitmask_free(numa_nodes);
972 }
973 #endif /* HAVE_LIBNUMA */
974
975 return true;
976 }
977
978 void buf_pool_t::deallocate_chunk(buf_chunk_t *chunk) {
979 ut_ad(mutex_own(&chunks_mutex));
980 /* Undo the effect of the earlier MADV_DONTDUMP */
981 if (buf_pool_should_madvise) {
982 if (!chunk->madvise_dump()) {
983 innobase_disable_core_dump();
984 }
985 }
986 ut::free_large_page(chunk->mem, ut::fallback_to_normal_page_t{});
987 }
988
989 bool buf_pool_t::madvise_dump() {
990 ut_ad(mutex_own(&chunks_mutex));
991 for (buf_chunk_t *chunk = chunks; chunk < chunks + n_chunks; chunk++) {
992 if (!chunk->madvise_dump()) {
993 return false;
994 }
995 }
996 return true;
997 }
998
999 bool buf_pool_t::madvise_dont_dump() {
1000 ut_ad(mutex_own(&chunks_mutex));
1001 for (buf_chunk_t *chunk = chunks; chunk < chunks + n_chunks; chunk++) {
1002 if (!chunk->madvise_dont_dump()) {
1003 return false;
1004 }
1005 }
1006 return true;
1007 }
1008
1009 /* End of implementation of buf_pool_t's methods */
1010
1011 /** Checks if innobase_should_madvise_buf_pool() value has changed since we've
1012 last check and if so, then updates buf_pool_should_madvise and calls madvise
1013 for all chunks in all srv_buf_pool_instances.
1014 @see buf_pool_should_madvise comment for a longer explanation. */
1015 void buf_pool_update_madvise() {
1016 /* We need to make sure that buf_pool_should_madvise value change does not
1017 occur in parallel with allocation or deallocation of chunks in some buf_pool
1018 as this could lead to inconsistency - we would call madvise for some but not
1019 all chunks, perhaps with a wrong MADV_DO(NT)_DUMP flag.
1020 Moreover, we are about to iterate over chunks, which requires the bounds of
1021 for loop to be fixed.
1022 To solve both problems we first latch all buf_pool_t::chunks_mutex-es, and
1023 only then update the buf_pool_should_madvise, and perform iteration over
1024 buf_pool-s and their chunks.*/
1025 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
1026 mutex_enter(&buf_pool_from_array(i)->chunks_mutex);
1027 }
1028
1029 auto should_madvise = innobase_should_madvise_buf_pool();
1030 /* This `if` is here not for performance, but for correctness: on platforms
1031 which do not support madvise MADV_DONT_DUMP we prefer to not call madvice to
1032 avoid warnings and disabling @@global.core_file in cases where the user did
1033 not really intend to change anything */
1034 if (should_madvise != buf_pool_should_madvise) {
1035 buf_pool_should_madvise = should_madvise;
1036 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
1037 buf_pool_t *buf_pool = buf_pool_from_array(i);
1038 bool success = buf_pool_should_madvise ? buf_pool->madvise_dont_dump()
1039 : buf_pool->madvise_dump();
1040 if (!success) {
1041 innobase_disable_core_dump();
1042 break;
1043 }
1044 }
1045 }
1046 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
1047 mutex_exit(&buf_pool_from_array(i)->chunks_mutex);
1048 }
1049 }
1050
1051 /** Allocates a chunk of buffer frames. If called for an existing buf_pool, its
1052 free_list_mutex must be locked.
1053 @return chunk, or NULL on failure */
1054 static buf_chunk_t *buf_chunk_init(
1055 buf_pool_t *buf_pool, /*!< in: buffer pool instance */
1056 buf_chunk_t *chunk, /*!< out: chunk of buffers */
1057 ulonglong mem_size, /*!< in: requested size in bytes */
1058 std::mutex *mutex) /*!< in,out: Mutex protecting chunk map. */
1059 {
1060 buf_block_t *block;
1061 byte *frame;
1062 ulint i;
1063
1064 mutex_own(&buf_pool->chunks_mutex);
1065
1066 /* Round down to a multiple of page size,
1067 although it already should be. */
1068 mem_size = ut_2pow_round(mem_size, UNIV_PAGE_SIZE);
1069 /* Reserve space for the block descriptors. */
1070 mem_size += ut_2pow_round(
1071 (mem_size / UNIV_PAGE_SIZE) * (sizeof *block) + (UNIV_PAGE_SIZE - 1),
1072 UNIV_PAGE_SIZE);
1073
1074 DBUG_EXECUTE_IF("ib_buf_chunk_init_fails", return (nullptr););
1075
1076 if (!buf_pool->allocate_chunk(mem_size, chunk)) {
1077 return (nullptr);
1078 }
1079
1080 /* Allocate the block descriptors from
1081 the start of the memory block. */
1082 chunk->blocks = (buf_block_t *)chunk->mem;
1083
1084 /* Align a pointer to the first frame. Note that when
1085 os_large_page_size is smaller than UNIV_PAGE_SIZE,
1086 we may allocate one fewer block than requested. When
1087 it is bigger, we may allocate more blocks than requested. */
1088
1089 frame = (byte *)ut_align(chunk->mem, UNIV_PAGE_SIZE);
1090 chunk->size = ut::large_page_allocation_size(
1091 chunk->mem, ut::fallback_to_normal_page_t{}) /
1092 UNIV_PAGE_SIZE -
1093 (frame != chunk->mem);
1094
1095 /* Subtract the space needed for block descriptors. */
1096 {
1097 ulint size = chunk->size;
1098
1099 while (frame < (byte *)(chunk->blocks + size)) {
1100 frame += UNIV_PAGE_SIZE;
1101 size--;
1102 }
1103
1104 chunk->size = size;
1105 }
1106
1107 /* Init block structs and assign frames for them. Then we
1108 assign the frames to the first blocks (we already mapped the
1109 memory above). */
1110
1111 block = chunk->blocks;
1112
1113 for (i = chunk->size; i--;) {
1114 buf_block_init(buf_pool, block, frame);
1115 UNIV_MEM_INVALID(block->frame, UNIV_PAGE_SIZE);
1116
1117 /* Add the block to the free list */
1118 UT_LIST_ADD_LAST(buf_pool->free, &block->page);
1119
1120 ut_d(block->page.in_free_list = true);
1121 ut_ad(!block->page.someone_has_io_responsibility());
1122 ut_ad(buf_pool_from_block(block) == buf_pool);
1123
1124 block++;
1125 frame += UNIV_PAGE_SIZE;
1126 }
1127
1128 if (mutex != nullptr) {
1129 mutex->lock();
1130 }
1131
1132 buf_pool_register_chunk(chunk);
1133
1134 if (mutex != nullptr) {
1135 mutex->unlock();
1136 }
1137
1138 #ifdef PFS_GROUP_BUFFER_SYNC
1139 pfs_register_buffer_block(chunk);
1140 #endif /* PFS_GROUP_BUFFER_SYNC */
1141 return (chunk);
1142 }
1143
1144 #ifdef UNIV_DEBUG
1145 /** Finds a block in the given buffer chunk that points to a
1146 given compressed page.
1147 @return buffer block pointing to the compressed page, or NULL */
1148 static buf_block_t *buf_chunk_contains_zip(
1149 buf_chunk_t *chunk, /*!< in: chunk being checked */
1150 const void *data) /*!< in: pointer to compressed page */
1151 {
1152 buf_block_t *block;
1153 ulint i;
1154
1155 block = chunk->blocks;
1156
1157 for (i = chunk->size; i--; block++) {
1158 if (block->page.zip.data == data) {
1159 return (block);
1160 }
1161 }
1162
1163 return (nullptr);
1164 }
1165
1166 /** Finds a block in the buffer pool that points to a
1167 given compressed page. Used only to confirm that buffer pool does not contain a
1168 given pointer, thus protected by zip_free_mutex.
1169 @param[in] buf_pool buffer pool instance
1170 @param[in] data pointer to compressed page
1171 @return buffer block pointing to the compressed page, or NULL */
1172 buf_block_t *buf_pool_contains_zip(buf_pool_t *buf_pool, const void *data) {
1173 ulint n;
1174 buf_chunk_t *chunk = buf_pool->chunks;
1175
1176 ut_ad(buf_pool);
1177 ut_ad(mutex_own(&buf_pool->zip_free_mutex));
1178 for (n = buf_pool->n_chunks; n--; chunk++) {
1179 buf_block_t *block = buf_chunk_contains_zip(chunk, data);
1180
1181 if (block) {
1182 return (block);
1183 }
1184 }
1185
1186 return (nullptr);
1187 }
1188 #endif /* UNIV_DEBUG */
1189
1190 /** Checks that all file pages in the buffer chunk are in a replaceable state.
1191 @param[in] chunk The chunk to be checked */
1192 static void buf_assert_all_are_replaceable(buf_chunk_t *chunk) {
1193 buf_block_t *block = chunk->blocks;
1194
1195 for (auto i = chunk->size; i--; block++) {
1196 switch (buf_block_get_state(block)) {
1197 case BUF_BLOCK_POOL_WATCH:
1198 case BUF_BLOCK_ZIP_PAGE:
1199 case BUF_BLOCK_ZIP_DIRTY:
1200 /* The uncompressed buffer pool should never
1201 contain compressed block descriptors. */
1202 ut_error;
1203 break;
1204 case BUF_BLOCK_NOT_USED:
1205 case BUF_BLOCK_READY_FOR_USE:
1206 case BUF_BLOCK_MEMORY:
1207 case BUF_BLOCK_REMOVE_HASH:
1208 /* Skip blocks that are not being used for
1209 file pages. */
1210 break;
1211 case BUF_BLOCK_FILE_PAGE:
1212 buf_page_mutex_enter(block);
1213 const auto &bpage = block->page;
1214 if (!buf_flush_ready_for_replace(&bpage) ||
1215 DBUG_EVALUATE_IF("simulate_dirty_page_at_shutdown", true, false)) {
1216 ib::fatal(UT_LOCATION_HERE, ER_IB_ERR_PAGE_DIRTY_AT_SHUTDOWN)
1217 << *block;
1218 }
1219 buf_page_mutex_exit(block);
1220 break;
1221 }
1222 }
1223 }
1224
1225 /** Set buffer pool size variables
1226 Note: It's safe without mutex protection because of startup only. */
1227 static void buf_pool_set_sizes(void) {
1228 ulint i;
1229 ulint curr_size = 0;
1230
1231 for (i = 0; i < srv_buf_pool_instances; i++) {
1232 buf_pool_t *buf_pool;
1233
1234 buf_pool = buf_pool_from_array(i);
1235 curr_size += buf_pool->curr_pool_size;
1236 }
1237 if (srv_buf_pool_curr_size == 0) {
1238 srv_buf_pool_curr_size = curr_size;
1239 } else {
1240 srv_buf_pool_curr_size = srv_buf_pool_size;
1241 }
1242 srv_buf_pool_old_size = srv_buf_pool_size;
1243 srv_buf_pool_base_size = srv_buf_pool_size;
1244 os_wmb;
1245 }
1246
1247 /** Initialize a buffer pool instance.
1248 @param[in] buf_pool buffer pool instance
1249 @param[in] buf_pool_size size in bytes
1250 @param[in] instance_no id of the instance
1251 @param[in,out] mutex Mutex to protect common data structures
1252 @param[out] err DB_SUCCESS if all goes well */
1253 static void buf_pool_create(buf_pool_t *buf_pool, ulint buf_pool_size,
1254 ulint instance_no, std::mutex *mutex,
1255 dberr_t &err) {
1256 ulint i;
1257 ulint chunk_size;
1258 buf_chunk_t *chunk;
1259
1260 #ifdef UNIV_LINUX
1261 cpu_set_t cpuset;
1262
1263 CPU_ZERO(&cpuset);
1264
1265 const long n_cores = sysconf(_SC_NPROCESSORS_ONLN);
1266
1267 CPU_SET(instance_no % n_cores, &cpuset);
1268
1269 buf_pool->stat.reset();
1270
1271 if (pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset) == -1) {
1272 ib::error(ER_IB_ERR_SCHED_SETAFFNINITY_FAILED)
1273 << "sched_setaffinity() failed!";
1274 }
1275 /* Linux might be able to set different setting for each thread
1276 worth to try to set high priority for this thread. */
1277 setpriority(PRIO_PROCESS, (pid_t)syscall(SYS_gettid), -20);
1278 #endif /* UNIV_LINUX */
1279
1280 ut_ad(buf_pool_size % srv_buf_pool_chunk_unit == 0);
1281
1282 /* 1. Initialize general fields
1283 ------------------------------- */
1284 mutex_create(LATCH_ID_BUF_POOL_CHUNKS, &buf_pool->chunks_mutex);
1285 mutex_create(LATCH_ID_BUF_POOL_LRU_LIST, &buf_pool->LRU_list_mutex);
1286 mutex_create(LATCH_ID_BUF_POOL_FREE_LIST, &buf_pool->free_list_mutex);
1287 mutex_create(LATCH_ID_BUF_POOL_ZIP_FREE, &buf_pool->zip_free_mutex);
1288 mutex_create(LATCH_ID_BUF_POOL_ZIP_HASH, &buf_pool->zip_hash_mutex);
1289 mutex_create(LATCH_ID_BUF_POOL_ZIP, &buf_pool->zip_mutex);
1290 mutex_create(LATCH_ID_BUF_POOL_FLUSH_STATE, &buf_pool->flush_state_mutex);
1291
1292 if (buf_pool_size > 0) {
1293 mutex_enter(&buf_pool->chunks_mutex);
1294 buf_pool->n_chunks = buf_pool_size / srv_buf_pool_chunk_unit;
1295 chunk_size = srv_buf_pool_chunk_unit;
1296
1297 buf_pool->chunks = reinterpret_cast<buf_chunk_t *>(ut::zalloc_withkey(
1298 UT_NEW_THIS_FILE_PSI_KEY, buf_pool->n_chunks * sizeof(*chunk)));
1299
1300 if (buf_pool->chunks == nullptr) {
1301 ib::error(ER_IB_MSG_64) << "buffer pool " << instance_no
1302 << " : failed to allocate"
1303 " the chunk array.";
1304 err = DB_ERROR;
1305 mutex_exit(&buf_pool->chunks_mutex);
1306 return;
1307 }
1308
1309 buf_pool->chunks_old = nullptr;
1310
1311 UT_LIST_INIT(buf_pool->LRU);
1312 UT_LIST_INIT(buf_pool->free);
1313 UT_LIST_INIT(buf_pool->withdraw);
1314 buf_pool->withdraw_target = 0;
1315 UT_LIST_INIT(buf_pool->flush_list);
1316 UT_LIST_INIT(buf_pool->unzip_LRU);
1317
1318 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
1319 UT_LIST_INIT(buf_pool->zip_clean);
1320 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
1321
1322 for (i = 0; i < UT_ARR_SIZE(buf_pool->zip_free); ++i) {
1323 UT_LIST_INIT(buf_pool->zip_free[i]);
1324 }
1325
1326 buf_pool->curr_size = 0;
1327 chunk = buf_pool->chunks;
1328
1329 do {
1330 if (!buf_chunk_init(buf_pool, chunk, chunk_size, mutex)) {
1331 while (--chunk >= buf_pool->chunks) {
1332 buf_block_t *block = chunk->blocks;
1333
1334 for (i = chunk->size; i--; block++) {
1335 mutex_free(&block->mutex);
1336 rw_lock_free(&block->lock);
1337
1338 ut_d(rw_lock_free(&block->debug_latch));
1339 }
1340 buf_pool->deallocate_chunk(chunk);
1341 }
1342 ut::free(buf_pool->chunks);
1343 buf_pool->chunks = nullptr;
1344
1345 err = DB_ERROR;
1346 mutex_exit(&buf_pool->chunks_mutex);
1347 return;
1348 }
1349
1350 buf_pool->curr_size += chunk->size;
1351 } while (++chunk < buf_pool->chunks + buf_pool->n_chunks);
1352 mutex_exit(&buf_pool->chunks_mutex);
1353
1354 buf_pool->instance_no = instance_no;
1355 buf_pool->read_ahead_area = static_cast<page_no_t>(
1356 std::min(BUF_READ_AHEAD_PAGES,
1357 ut_2_power_up(buf_pool->curr_size / BUF_READ_AHEAD_PORTION)));
1358 buf_pool->curr_pool_size = buf_pool->curr_size * UNIV_PAGE_SIZE;
1359
1360 buf_pool->old_size = buf_pool->curr_size;
1361 buf_pool->n_chunks_new = buf_pool->n_chunks;
1362
1363 /* Number of locks protecting page_hash must be a
1364 power of two */
1365 srv_n_page_hash_locks =
1366 static_cast<ulong>(ut_2_power_up(srv_n_page_hash_locks));
1367 ut_a(srv_n_page_hash_locks != 0);
1368 ut_a(srv_n_page_hash_locks <= MAX_PAGE_HASH_LOCKS);
1369
1370 buf_pool->page_hash =
1371 ib_create(2 * buf_pool->curr_size, LATCH_ID_HASH_TABLE_RW_LOCK,
1372 srv_n_page_hash_locks, MEM_HEAP_FOR_PAGE_HASH);
1373
1374 buf_pool->zip_hash = ut::new_<hash_table_t>(2 * buf_pool->curr_size);
1375
1376 buf_pool->last_printout_time = std::chrono::steady_clock::now();
1377 }
1378 /* 2. Initialize flushing fields
1379 -------------------------------- */
1380
1381 mutex_create(LATCH_ID_FLUSH_LIST, &buf_pool->flush_list_mutex);
1382
1383 for (i = BUF_FLUSH_LRU; i < BUF_FLUSH_N_TYPES; i++) {
1384 buf_pool->no_flush[i] = os_event_create();
1385 }
1386
1387 buf_pool->watch = (buf_page_t *)ut::zalloc_withkey(
1388 UT_NEW_THIS_FILE_PSI_KEY, sizeof(*buf_pool->watch) * BUF_POOL_WATCH_SIZE);
1389 for (i = 0; i < BUF_POOL_WATCH_SIZE; i++) {
1390 buf_pool->watch[i].buf_pool_index = buf_pool->instance_no;
1391 }
1392
1393 /* All fields are initialized by ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY).
1394 */
1395
1396 buf_pool->try_LRU_scan = true;
1397
1398 /* Dirty Page Tracking is disabled by default. */
1399 buf_pool->track_page_lsn = LSN_MAX;
1400
1401 buf_pool->max_lsn_io = 0;
1402
1403 /* Initialize the hazard pointer for flush_list batches */
1404 new (&buf_pool->flush_hp) FlushHp(buf_pool, &buf_pool->flush_list_mutex);
1405
1406 /* Initialize the hazard pointer for the oldest page scan */
1407 new (&buf_pool->oldest_hp) FlushHp(buf_pool, &buf_pool->flush_list_mutex);
1408
1409 /* Initialize the hazard pointer for LRU batches */
1410 new (&buf_pool->lru_hp) LRUHp(buf_pool, &buf_pool->LRU_list_mutex);
1411
1412 /* Initialize the iterator for LRU scan search */
1413 new (&buf_pool->lru_scan_itr) LRUItr(buf_pool, &buf_pool->LRU_list_mutex);
1414
1415 /* Initialize the iterator for single page scan search */
1416 new (&buf_pool->single_scan_itr) LRUItr(buf_pool, &buf_pool->LRU_list_mutex);
1417
1418 err = DB_SUCCESS;
1419 }
1420
1421 void buf_page_free_descriptor(buf_page_t *bpage) {
1422 bpage->reset_page_id();
1423
1424 ut::free(bpage);
1425 }
1426
1427 /** Free one buffer pool instance
1428 @param[in] buf_pool buffer pool instance to free */
1429 static void buf_pool_free_instance(buf_pool_t *buf_pool) {
1430 buf_chunk_t *chunk;
1431 buf_chunk_t *chunks;
1432 buf_page_t *bpage;
1433 buf_page_t *prev_bpage = nullptr;
1434
1435 mutex_free(&buf_pool->LRU_list_mutex);
1436 mutex_free(&buf_pool->free_list_mutex);
1437 mutex_free(&buf_pool->zip_free_mutex);
1438 mutex_free(&buf_pool->zip_hash_mutex);
1439 mutex_free(&buf_pool->flush_state_mutex);
1440 mutex_free(&buf_pool->zip_mutex);
1441 mutex_free(&buf_pool->flush_list_mutex);
1442
1443 for (bpage = UT_LIST_GET_LAST(buf_pool->LRU); bpage != nullptr;
1444 bpage = prev_bpage) {
1445 prev_bpage = UT_LIST_GET_PREV(LRU, bpage);
1446 buf_page_state state = buf_page_get_state(bpage);
1447
1448 ut_ad(buf_page_in_file(bpage));
1449 ut_ad(bpage->in_LRU_list);
1450
1451 if (state != BUF_BLOCK_FILE_PAGE) {
1452 /* We must not have any dirty block except
1453 when doing a fast shutdown. */
1454 ut_ad(state == BUF_BLOCK_ZIP_PAGE || srv_fast_shutdown == 2);
1455 buf_page_free_descriptor(bpage);
1456 }
1457 }
1458
1459 ut::free(buf_pool->watch);
1460 buf_pool->watch = nullptr;
1461 mutex_enter(&buf_pool->chunks_mutex);
1462 chunks = buf_pool->chunks;
1463 chunk = chunks + buf_pool->n_chunks;
1464
1465 while (--chunk >= chunks) {
1466 buf_block_t *block = chunk->blocks;
1467
1468 for (ulint i = chunk->size; i--; block++) {
1469 mutex_free(&block->mutex);
1470 rw_lock_free(&block->lock);
1471
1472 ut_d(rw_lock_free(&block->debug_latch));
1473 }
1474
1475 buf_pool->deallocate_chunk(chunk);
1476 }
1477
1478 for (ulint i = BUF_FLUSH_LRU; i < BUF_FLUSH_N_TYPES; ++i) {
1479 os_event_destroy(buf_pool->no_flush[i]);
1480 }
1481
1482 ut::free(buf_pool->chunks);
1483 mutex_exit(&buf_pool->chunks_mutex);
1484 mutex_free(&buf_pool->chunks_mutex);
1485 ha_clear(buf_pool->page_hash);
1486 ut::delete_(buf_pool->page_hash);
1487 ut::delete_(buf_pool->zip_hash);
1488 }
1489
1490 /** Frees the buffer pool global data structures. */
1491 static void buf_pool_free() {
1492 ut::delete_(buf_stat_per_index);
1493
1494 ut::delete_(buf_chunk_map_reg);
1495 buf_chunk_map_reg = nullptr;
1496
1497 ut::free(buf_pool_ptr);
1498 buf_pool_ptr = nullptr;
1499 }
1500
1501 /** Creates the buffer pool.
1502 @param[in] total_size Size of the total pool in bytes.
1503 @param[in] n_instances Number of buffer pool instances to create.
1504 @return DB_SUCCESS if success, DB_ERROR if not enough memory or error */
1505 dberr_t buf_pool_init(ulint total_size, ulint n_instances) {
1506 ulint i;
1507 const ulint size = total_size / n_instances;
1508
1509 ut_ad(n_instances > 0);
1510 ut_ad(n_instances <= MAX_BUFFER_POOLS);
1511 ut_ad(n_instances == srv_buf_pool_instances);
1512
1513 NUMA_MEMPOLICY_INTERLEAVE_IN_SCOPE;
1514
1515 /* Usually buf_pool_should_madvise is protected by buf_pool_t::chunk_mutex-es,
1516 but at this point in time there is no buf_pool_t instances yet, and no risk of
1517 race condition with sys_var modifications or buffer pool resizing because we
1518 have just started initializing the buffer pool.*/
1519 buf_pool_should_madvise = innobase_should_madvise_buf_pool();
1520
1521 buf_pool_resizing = false;
1522
1523 buf_pool_ptr = (buf_pool_t *)ut::zalloc_withkey(
1524 UT_NEW_THIS_FILE_PSI_KEY, n_instances * sizeof *buf_pool_ptr);
1525
1526 buf_chunk_map_reg =
1527 ut::new_withkey<buf_pool_chunk_map_t>(UT_NEW_THIS_FILE_PSI_KEY);
1528
1529 std::vector<dberr_t> errs;
1530
1531 errs.assign(n_instances, DB_SUCCESS);
1532
1533 #ifdef UNIV_LINUX
1534 ulint n_cores = sysconf(_SC_NPROCESSORS_ONLN);
1535
1536 /* Magic number 8 is from empirical testing on a
1537 4 socket x 10 Cores x 2 HT host. 128G / 16 instances
1538 takes about 4 secs, compared to 10 secs without this
1539 optimisation.. */
1540
1541 if (n_cores > 8) {
1542 n_cores = 8;
1543 }
1544 #else
1545 ulint n_cores = 4;
1546 #endif /* UNIV_LINUX */
1547
1548 dberr_t err = DB_SUCCESS;
1549
1550 for (i = 0; i < n_instances; /* no op */) {
1551 ulint n = i + n_cores;
1552
1553 if (n > n_instances) {
1554 n = n_instances;
1555 }
1556
1557 std::vector<IB_thread> threads;
1558
1559 std::mutex m;
1560
1561 for (ulint id = i; id < n; ++id) {
1562 threads.emplace_back(os_thread_create(buf_pool_create_thread_key, 0,
1563 buf_pool_create, &buf_pool_ptr[id],
1564 size, id, &m, std::ref(errs[id])));
1565 threads[id - i].start();
1566 }
1567
1568 for (ulint id = i; id < n; ++id) {
1569 threads[id - i].join();
1570
1571 if (errs[id] != DB_SUCCESS) {
1572 err = errs[id];
1573 }
1574 }
1575
1576 if (err != DB_SUCCESS) {
1577 for (size_t id = 0; id < n; ++id) {
1578 if (buf_pool_ptr[id].chunks != nullptr) {
1579 buf_pool_free_instance(&buf_pool_ptr[id]);
1580 }
1581 }
1582
1583 buf_pool_free();
1584
1585 return (err);
1586 }
1587
1588 /* Do the next block of instances */
1589 i = n;
1590 }
1591
1592 buf_pool_set_sizes();
1593 buf_LRU_old_ratio_update(100 * 3 / 8, false);
1594
1595 btr_search_sys_create(buf_pool_get_curr_size() / sizeof(void *) / 64);
1596
1597 buf_stat_per_index = ut::new_withkey<buf_stat_per_index_t>(
1598 ut::make_psi_memory_key(mem_key_buf_stat_per_index_t));
1599
1600 return (DB_SUCCESS);
1601 }
1602
1603 /** Reallocate a control block.
1604 @param[in] buf_pool buffer pool instance
1605 @param[in] block pointer to control block
1606 @retval true if succeeded or if failed because the block was fixed
1607 @retval false if failed because of no free blocks. */
1608 static bool buf_page_realloc(buf_pool_t *buf_pool, buf_block_t *block) {
1609 buf_block_t *new_block;
1610
1611 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
1612
1613 /* Try allocating from the buf_pool->free list if it is not empty. This
1614 method is executed during withdrawing phase of BufferPool resize only. It is
1615 better to not block other user threads as much as possible. So, the main
1616 strategy is to passively reserve and use blocks that are already on the free
1617 list. Otherwise, if we were to call `buf_LRU_get_free_block` instead of
1618 `buf_LRU_get_free_only`, we would have to release the LRU mutex before the
1619 call and this would cause a need to break the reallocation loop in
1620 `buf_pool_withdraw_blocks`, which would render withdrawing even more
1621 inefficient. */
1622 new_block = buf_LRU_get_free_only(buf_pool);
1623
1624 if (new_block == nullptr) {
1625 return (false); /* free_list was not enough */
1626 }
1627
1628 rw_lock_t *hash_lock = buf_page_hash_lock_get(buf_pool, block->page.id);
1629
1630 rw_lock_x_lock(hash_lock, UT_LOCATION_HERE);
1631 mutex_enter(&block->mutex);
1632
1633 if (buf_page_can_relocate(&block->page)) {
1634 mutex_enter(&new_block->mutex);
1635
1636 memcpy(new_block->frame, block->frame, UNIV_PAGE_SIZE);
1637 new (&new_block->page) buf_page_t(block->page);
1638
1639 /* relocate LRU list */
1640 ut_ad(block->page.in_LRU_list);
1641 ut_ad(!block->page.in_zip_hash);
1642 ut_d(block->page.in_LRU_list = false);
1643
1644 buf_LRU_adjust_hp(buf_pool, &block->page);
1645
1646 auto prev_b = UT_LIST_GET_PREV(LRU, &block->page);
1647 UT_LIST_REMOVE(buf_pool->LRU, &block->page);
1648
1649 if (prev_b != nullptr) {
1650 UT_LIST_INSERT_AFTER(buf_pool->LRU, prev_b, &new_block->page);
1651 } else {
1652 UT_LIST_ADD_FIRST(buf_pool->LRU, &new_block->page);
1653 }
1654
1655 if (buf_pool->LRU_old == &block->page) {
1656 buf_pool->LRU_old = &new_block->page;
1657 }
1658
1659 ut_ad(new_block->page.in_LRU_list);
1660
1661 /* relocate unzip_LRU list */
1662 if (block->page.zip.data != nullptr) {
1663 ut_ad(block->in_unzip_LRU_list);
1664 ut_d(new_block->in_unzip_LRU_list = true);
1665 UNIV_MEM_DESC(&new_block->page.zip.data,
1666 page_zip_get_size(&new_block->page.zip));
1667
1668 auto prev_block = UT_LIST_GET_PREV(unzip_LRU, block);
1669 UT_LIST_REMOVE(buf_pool->unzip_LRU, block);
1670
1671 ut_d(block->in_unzip_LRU_list = false);
1672 block->page.zip.data = nullptr;
1673 page_zip_set_size(&block->page.zip, 0);
1674
1675 if (prev_block != nullptr) {
1676 UT_LIST_INSERT_AFTER(buf_pool->unzip_LRU, prev_block, new_block);
1677 } else {
1678 UT_LIST_ADD_FIRST(buf_pool->unzip_LRU, new_block);
1679 }
1680 } else {
1681 ut_ad(!block->in_unzip_LRU_list);
1682 ut_d(new_block->in_unzip_LRU_list = false);
1683 }
1684
1685 /* relocate buf_pool->page_hash */
1686 ut_ad(block->page.in_page_hash);
1687 ut_ad(&block->page == buf_page_hash_get_low(buf_pool, block->page.id));
1688 ut_d(block->page.in_page_hash = false);
1689 const auto hash_value = block->page.id.hash();
1690 ut_ad(hash_value == new_block->page.id.hash());
1691 HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, hash_value,
1692 (&block->page));
1693 HASH_INSERT(buf_page_t, hash, buf_pool->page_hash, hash_value,
1694 (&new_block->page));
1695
1696 ut_ad(new_block->page.in_page_hash);
1697
1698 buf_block_modify_clock_inc(block);
1699 memset(block->frame + FIL_PAGE_OFFSET, 0xff, 4);
1700 memset(block->frame + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, 0xff, 4);
1701 UNIV_MEM_INVALID(block->frame, UNIV_PAGE_SIZE);
1702 buf_block_set_state(block, BUF_BLOCK_REMOVE_HASH);
1703
1704 /* Relocate buf_pool->flush_list. */
1705 if (block->page.is_dirty()) {
1706 buf_flush_relocate_on_flush_list(&block->page, &new_block->page);
1707 }
1708
1709 /* Set other flags of buf_block_t */
1710
1711 /* This code should only be executed by buf_pool_resize(),
1712 while the adaptive hash index is disabled. */
1713 block->ahi.assert_empty();
1714 new_block->ahi.assert_empty_on_init();
1715 ut_ad(!block->ahi.index);
1716 new_block->ahi.index = nullptr;
1717 new_block->n_hash_helps = 0;
1718 new_block->ahi.recommended_prefix_info = {0, 1, true};
1719
1720 rw_lock_x_unlock(hash_lock);
1721 mutex_exit(&block->mutex);
1722 mutex_exit(&new_block->mutex);
1723
1724 /* Free block */
1725 buf_block_set_state(block, BUF_BLOCK_MEMORY);
1726 buf_LRU_block_free_non_file_page(block);
1727 } else {
1728 rw_lock_x_unlock(hash_lock);
1729 mutex_exit(&block->mutex);
1730
1731 /* Free new_block */
1732 buf_LRU_block_free_non_file_page(new_block);
1733 }
1734
1735 return (true); /* free_list was enough */
1736 }
1737
1738 static void buf_resize_status(buf_pool_resize_status_code_t status,
1739 const char *fmt, ...)
1740 MY_ATTRIBUTE((format(printf, 2, 3)));
1741
1742 static void buf_resize_status_progress_reset();
1743
1744 static void buf_resize_status_progress_update(uint current_step,
1745 uint total_steps);
1746
1747 /** Sets the global variable that feeds MySQL's innodb_buffer_pool_resize_status
1748 to the specified string. The format and the following parameters are the
1749 same as the ones used for printf(3).
1750 @param[in] status status code
1751 @param[in] fmt format
1752 @param[in] ... extra parameters according to fmt */
1753 static void buf_resize_status(buf_pool_resize_status_code_t status,
1754 const char *fmt, ...) {
1755 buf_pool_resize_status_code.store(status);
1756
1757 va_list ap;
1758
1759 va_start(ap, fmt);
1760
1761 ut_vsnprintf(export_vars.innodb_buffer_pool_resize_status,
1762 sizeof(export_vars.innodb_buffer_pool_resize_status), fmt, ap);
1763
1764 va_end(ap);
1765
1766 ib::info(ER_IB_MSG_BUF_POOL_RESIZE_CODE_STATUS,
1767 uint{buf_pool_resize_status_code.load()},
1768 export_vars.innodb_buffer_pool_resize_status);
1769 }
1770
1771 #ifdef UNIV_DEBUG
1772 void buf_pool_resize_wait_for_test() {
1773 bool should_wait_for_test = true;
1774 while (should_wait_for_test) {
1775 should_wait_for_test = false;
1776 switch (buf_pool_resize_status_code.load()) {
1777 case BUF_POOL_RESIZE_COMPLETE:
1778 DBUG_EXECUTE_IF(
1779 "ib_buf_pool_resize_complete_status_code",
1780 should_wait_for_test = true;
1781 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1782 break;
1783 case BUF_POOL_RESIZE_START:
1784 DBUG_EXECUTE_IF(
1785 "ib_buf_pool_resize_start_status_code", should_wait_for_test = true;
1786 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1787 break;
1788 case BUF_POOL_RESIZE_DISABLE_AHI:
1789 DBUG_EXECUTE_IF(
1790 "ib_buf_pool_resize_disable_ahi_status_code",
1791 should_wait_for_test = true;
1792 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1793 break;
1794 case BUF_POOL_RESIZE_WITHDRAW_BLOCKS:
1795 DBUG_EXECUTE_IF(
1796 "ib_buf_pool_resize_withdraw_blocks_status_code",
1797 should_wait_for_test = true;
1798 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1799 break;
1800 case BUF_POOL_RESIZE_GLOBAL_LOCK:
1801 DBUG_EXECUTE_IF(
1802 "ib_buf_pool_resize_global_lock_status_code",
1803 should_wait_for_test = true;
1804 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1805 break;
1806 case BUF_POOL_RESIZE_IN_PROGRESS:
1807 DBUG_EXECUTE_IF(
1808 "ib_buf_pool_resize_in_progress_status_code",
1809 should_wait_for_test = true;
1810 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1811 break;
1812 case BUF_POOL_RESIZE_HASH:
1813 DBUG_EXECUTE_IF(
1814 "ib_buf_pool_resize_hash_status_code", should_wait_for_test = true;
1815 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1816 break;
1817 case BUF_POOL_RESIZE_FAILED:
1818 DBUG_EXECUTE_IF(
1819 "ib_buf_pool_resize_failed_status_code",
1820 should_wait_for_test = true;
1821 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
1822 break;
1823 }
1824 }
1825 }
1826 #endif
1827
1828 /** Reset progress in current status code. This indicates beginning of a new
1829 status code */
1830 static void buf_resize_status_progress_reset() {
1831 // Ensure that pervious status code is completed (100) or skipped (0)
1832 ut_ad(buf_pool_resize_status_progress.load() == 100 ||
1833 buf_pool_resize_status_progress.load() == 0);
1834 #ifdef UNIV_DEBUG
1835 buf_pool_resize_wait_for_test();
1836 #endif
1837 buf_pool_resize_status_progress.store(0);
1838
1839 ib::info(ER_IB_MSG_BUF_POOL_RESIZE_COMPLETE_CUR_CODE,
1840 uint{buf_pool_resize_status_code.load()});
1841 }
1842
1843 /** Update progress in current status code.
1844 @param[in] current_step current step that is complete.
1845 @param[in] total_steps steps to complete before moving to next status
1846 code */
1847 static void buf_resize_status_progress_update(uint current_step,
1848 uint total_steps) {
1849 ut_ad(current_step <= total_steps);
1850
1851 buf_pool_resize_status_progress.store((current_step * 100 / total_steps));
1852 ib::info(ER_IB_MSG_BUF_POOL_RESIZE_PROGRESS_UPDATE,
1853 uint{buf_pool_resize_status_code.load()},
1854 uint{buf_pool_resize_status_progress.load()});
1855 }
1856
1857 /** Determines if a block is intended to be withdrawn. The caller must ensure
1858 that there was a sufficient memory barrier to read curr_size and old_size.
1859 @param[in] buf_pool buffer pool instance
1860 @param[in] block pointer to control block
1861 @retval true if will be withdrawn */
1862 bool buf_block_will_withdrawn(buf_pool_t *buf_pool, const buf_block_t *block) {
1863 ut_ad(buf_pool->curr_size < buf_pool->old_size);
1864
1865 const buf_chunk_t *chunk = buf_pool->chunks + buf_pool->n_chunks_new;
1866 const buf_chunk_t *echunk = buf_pool->chunks + buf_pool->n_chunks;
1867
1868 while (chunk < echunk) {
1869 if (block >= chunk->blocks && block < chunk->blocks + chunk->size) {
1870 return (true);
1871 }
1872 ++chunk;
1873 }
1874
1875 return (false);
1876 }
1877
1878 /** Determines if a frame is intended to be withdrawn. The caller must ensure
1879 that there was a sufficient memory barrier to read curr_size and old_size.
1880 @param[in] buf_pool buffer pool instance
1881 @param[in] ptr pointer to a frame
1882 @retval true if will be withdrawn */
1883 bool buf_frame_will_withdrawn(buf_pool_t *buf_pool, const byte *ptr) {
1884 ut_ad(buf_pool->curr_size < buf_pool->old_size);
1885
1886 const buf_chunk_t *chunk = buf_pool->chunks + buf_pool->n_chunks_new;
1887 const buf_chunk_t *echunk = buf_pool->chunks + buf_pool->n_chunks;
1888
1889 while (chunk < echunk) {
1890 if (ptr >= chunk->blocks->frame &&
1891 ptr < (chunk->blocks + chunk->size - 1)->frame + UNIV_PAGE_SIZE) {
1892 return (true);
1893 }
1894 ++chunk;
1895 }
1896
1897 return (false);
1898 }
1899
1900 /** Withdraw the buffer pool blocks from end of the buffer pool instance
1901 until withdrawn by buf_pool->withdraw_target.
1902 @param[in] buf_pool buffer pool instance
1903 @retval true if retry is needed */
1904 static bool buf_pool_withdraw_blocks(buf_pool_t *buf_pool) {
1905 buf_block_t *block;
1906 ulint loop_count = 0;
1907 ulint i = buf_pool_index(buf_pool);
1908
1909 ib::info(ER_IB_MSG_56) << "buffer pool " << i
1910 << " : start to withdraw the last "
1911 << buf_pool->withdraw_target << " blocks.";
1912
1913 /* Minimize buf_pool->zip_free[i] lists */
1914 buf_buddy_condense_free(buf_pool);
1915
1916 mutex_enter(&buf_pool->free_list_mutex);
1917 while (UT_LIST_GET_LEN(buf_pool->withdraw) < buf_pool->withdraw_target) {
1918 /* try to withdraw from free_list */
1919 ulint count1 = 0;
1920
1921 block = reinterpret_cast<buf_block_t *>(UT_LIST_GET_FIRST(buf_pool->free));
1922 while (block != nullptr &&
1923 UT_LIST_GET_LEN(buf_pool->withdraw) < buf_pool->withdraw_target) {
1924 ut_ad(block->page.in_free_list);
1925 ut_ad(!block->page.in_flush_list);
1926 ut_ad(!block->page.in_LRU_list);
1927 ut_a(!buf_page_in_file(&block->page));
1928
1929 buf_block_t *next_block;
1930 next_block =
1931 reinterpret_cast<buf_block_t *>(UT_LIST_GET_NEXT(list, &block->page));
1932
1933 if (buf_block_will_withdrawn(buf_pool, block)) {
1934 /* This should be withdrawn */
1935 UT_LIST_REMOVE(buf_pool->free, &block->page);
1936 UT_LIST_ADD_LAST(buf_pool->withdraw, &block->page);
1937 ut_d(block->in_withdraw_list = true);
1938 count1++;
1939 }
1940
1941 block = next_block;
1942 }
1943 mutex_exit(&buf_pool->free_list_mutex);
1944
1945 /* relocate blocks/buddies in withdrawn area */
1946 ulint count2 = 0;
1947 auto loop_start_time = std::chrono::steady_clock::now();
1948 uint32_t remove_loop_count = 0;
1949
1950 mutex_enter(&buf_pool->LRU_list_mutex);
1951 for (auto bpage : buf_pool->LRU.removable()) {
1952 BPageMutex *block_mutex;
1953
1954 block_mutex = buf_page_get_mutex(bpage);
1955 mutex_enter(block_mutex);
1956
1957 if (bpage->zip.data != nullptr &&
1958 buf_frame_will_withdrawn(buf_pool,
1959 static_cast<byte *>(bpage->zip.data))) {
1960 if (buf_page_can_relocate(bpage)) {
1961 mutex_exit(block_mutex);
1962 if (!buf_buddy_realloc(buf_pool, bpage->zip.data,
1963 page_zip_get_size(&bpage->zip))) {
1964 /* failed to allocate block */
1965 break;
1966 }
1967 mutex_enter(block_mutex);
1968 count2++;
1969 }
1970 /* NOTE: if the page is in use,
1971 not reallocated yet */
1972 }
1973
1974 if (buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE &&
1975 buf_block_will_withdrawn(buf_pool,
1976 reinterpret_cast<buf_block_t *>(bpage))) {
1977 if (buf_page_can_relocate(bpage)) {
1978 mutex_exit(block_mutex);
1979 if (!buf_page_realloc(buf_pool,
1980 reinterpret_cast<buf_block_t *>(bpage))) {
1981 /* failed to allocate block */
1982 break;
1983 }
1984 count2++;
1985 } else {
1986 mutex_exit(block_mutex);
1987 }
1988 /* NOTE: if the page is in use,
1989 not reallocated yet */
1990 } else {
1991 mutex_exit(block_mutex);
1992 }
1993
1994 if ((remove_loop_count++) % 1000 == 0) {
1995 const auto timeout = get_srv_fatal_semaphore_wait_threshold() / 2;
1996 const auto time_diff =
1997 std::chrono::steady_clock::now() - loop_start_time;
1998 if (time_diff > timeout) {
1999 /* avoids crash at srv_fatal_semaphore_wait_threshold */
2000 break;
2001 }
2002 }
2003 }
2004
2005 mutex_exit(&buf_pool->LRU_list_mutex);
2006
2007 mutex_enter(&buf_pool->free_list_mutex);
2008
2009 buf_resize_status(
2010 BUF_POOL_RESIZE_WITHDRAW_BLOCKS,
2011 "buffer pool " ULINTPF " : withdrawing blocks. (%zu/" ULINTPF ")", i,
2012 UT_LIST_GET_LEN(buf_pool->withdraw), buf_pool->withdraw_target);
2013
2014 ib::info(ER_IB_MSG_57) << "buffer pool " << i << " : withdrew " << count1
2015 << " blocks from free list."
2016 << " Tried to relocate " << count2 << " pages ("
2017 << UT_LIST_GET_LEN(buf_pool->withdraw) << "/"
2018 << buf_pool->withdraw_target << ").";
2019
2020 if (++loop_count >= 10) {
2021 /* give up for now.
2022 retried after user threads paused. */
2023
2024 mutex_exit(&buf_pool->free_list_mutex);
2025
2026 ib::info(ER_IB_MSG_58)
2027 << "buffer pool " << i << " : will retry to withdraw later.";
2028
2029 /* need retry later */
2030 return (true);
2031 }
2032 }
2033 mutex_exit(&buf_pool->free_list_mutex);
2034
2035 /* confirm withdrawn enough */
2036 const buf_chunk_t *chunk = buf_pool->chunks + buf_pool->n_chunks_new;
2037 const buf_chunk_t *echunk = buf_pool->chunks + buf_pool->n_chunks;
2038
2039 while (chunk < echunk) {
2040 block = chunk->blocks;
2041 for (ulint j = chunk->size; j--; block++) {
2042 /* If !=BUF_BLOCK_NOT_USED block in the
2043 withdrawn area, it means corruption
2044 something */
2045 ut_a(buf_block_get_state(block) == BUF_BLOCK_NOT_USED);
2046 ut_ad(block->in_withdraw_list);
2047 }
2048 ++chunk;
2049 }
2050
2051 ib::info(ER_IB_MSG_59) << "buffer pool " << i << " : withdrawn target "
2052 << UT_LIST_GET_LEN(buf_pool->withdraw) << " blocks.";
2053
2054 /* retry is not needed */
2055 os_wmb;
2056
2057 return (false);
2058 }
2059
2060 /** resize page_hash and zip_hash for a buffer pool instance.
2061 @param[in] buf_pool buffer pool instance */
2062 static void buf_pool_resize_hash(buf_pool_t *buf_pool) {
2063 hash_table_t *new_hash_table;
2064
2065 ut_ad(mutex_own(&buf_pool->zip_hash_mutex));
2066
2067 /* create a temporary hash_table with twice larger cells[] */
2068 new_hash_table = ut::new_<hash_table_t>(2 * buf_pool->curr_size);
2069 /* Only the current thread will use this temporary hash table, so no need for
2070 latching */
2071 ut_ad(new_hash_table->type == HASH_TABLE_SYNC_NONE);
2072 ut_ad(0 == new_hash_table->n_sync_obj);
2073 ut_ad(nullptr == new_hash_table->rw_locks);
2074 /* move the data to the temporary hash table */
2075 for (ulint i = 0; i < hash_get_n_cells(buf_pool->page_hash); i++) {
2076 buf_page_t *bpage;
2077
2078 bpage = static_cast<buf_page_t *>(hash_get_first(buf_pool->page_hash, i));
2079
2080 while (bpage) {
2081 buf_page_t *prev_bpage = bpage;
2082
2083 bpage = static_cast<buf_page_t *>(HASH_GET_NEXT(hash, prev_bpage));
2084
2085 const auto hash_value = prev_bpage->id.hash();
2086
2087 HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, hash_value,
2088 prev_bpage);
2089
2090 HASH_INSERT(buf_page_t, hash, new_hash_table, hash_value, prev_bpage);
2091 }
2092 }
2093 /* Concurrent threads may be accessing buf_pool->page_hash->n_cells,
2094 n_sync_obj and try to latch rw_locks[i] while we are resizing. Therefore we
2095 never deallocate page_hash, instead we overwrite its n_cells and cells with
2096 the new values "stolen" from the temporary new_hash_table. We also move the
2097 old n_cells and cells to the new_hash_table, so they get freed with it. It's
2098 important that neither new nor old hash table use `heap`, as otherwise hash
2099 chains would got inconsistent after the swap. */
2100 ut_ad(buf_pool->page_hash->adaptive == new_hash_table->adaptive);
2101 ut_ad(buf_pool->page_hash->heap == nullptr &&
2102 new_hash_table->heap == nullptr);
2103 std::swap(buf_pool->page_hash->cells, new_hash_table->cells);
2104 /* swap(buf_pool->page_hash->n_cells, new_hash_table->n_cells): */
2105 {
2106 const auto new_n_cells = new_hash_table->get_n_cells();
2107 new_hash_table->set_n_cells(buf_pool->page_hash->get_n_cells());
2108 buf_pool->page_hash->set_n_cells(new_n_cells);
2109 }
2110 ut::delete_(new_hash_table);
2111
2112 /* recreate zip_hash */
2113 new_hash_table = ut::new_<hash_table_t>(2 * buf_pool->curr_size);
2114
2115 for (ulint i = 0; i < hash_get_n_cells(buf_pool->zip_hash); i++) {
2116 buf_page_t *bpage;
2117
2118 bpage = static_cast<buf_page_t *>(hash_get_first(buf_pool->zip_hash, i));
2119
2120 while (bpage) {
2121 buf_page_t *prev_bpage = bpage;
2122
2123 bpage = static_cast<buf_page_t *>(HASH_GET_NEXT(hash, prev_bpage));
2124
2125 const auto hash_value =
2126 buf_pool_hash_zip(reinterpret_cast<buf_block_t *>(prev_bpage));
2127
2128 HASH_DELETE(buf_page_t, hash, buf_pool->zip_hash, hash_value, prev_bpage);
2129
2130 HASH_INSERT(buf_page_t, hash, new_hash_table, hash_value, prev_bpage);
2131 }
2132 }
2133
2134 ut::delete_(buf_pool->zip_hash);
2135 buf_pool->zip_hash = new_hash_table;
2136 }
2137
2138 #ifdef UNIV_DEBUG
2139 /** This is a debug routine to inject an memory allocation failure error. */
2140 static void buf_pool_resize_chunk_make_null(buf_chunk_t **new_chunks) {
2141 static int count = 0;
2142
2143 if (count == 1) {
2144 ut::free(*new_chunks);
2145 *new_chunks = nullptr;
2146 }
2147
2148 count++;
2149 }
2150 #endif /* UNIV_DEBUG */
2151
2152 ulonglong buf_pool_adjust_chunk_unit(ulonglong size) {
2153 /* Size unit of buffer pool is larger than srv_buf_pool_size.
2154 adjust srv_buf_pool_chunk_unit for srv_buf_pool_size. */
2155 if (size * srv_buf_pool_instances > srv_buf_pool_size) {
2156 size = (srv_buf_pool_size + srv_buf_pool_instances - 1) /
2157 srv_buf_pool_instances;
2158 }
2159
2160 /* Make sure that srv_buf_pool_chunk_unit is divisible by blk_sz */
2161 if (size % srv_buf_pool_chunk_unit_blk_sz != 0) {
2162 size += srv_buf_pool_chunk_unit_blk_sz -
2163 (size % srv_buf_pool_chunk_unit_blk_sz);
2164 }
2165
2166 /* Make sure that srv_buf_pool_chunk_unit is not larger than max, and don't
2167 forget that it also has to be divisible by blk_sz */
2168 const auto CHUNK_UNIT_ALIGNED_MAX =
2169 srv_buf_pool_chunk_unit_max -
2170 (srv_buf_pool_chunk_unit_max % srv_buf_pool_chunk_unit_blk_sz);
2171 if (size > CHUNK_UNIT_ALIGNED_MAX) {
2172 size = CHUNK_UNIT_ALIGNED_MAX;
2173 }
2174
2175 /* Make sure that srv_buf_pool_chunk_unit is not smaller than min */
2176 ut_ad(srv_buf_pool_chunk_unit_min % srv_buf_pool_chunk_unit_blk_sz == 0);
2177 if (size < srv_buf_pool_chunk_unit_min) {
2178 size = srv_buf_pool_chunk_unit_min;
2179 }
2180
2181 ut_ad(size >= srv_buf_pool_chunk_unit_min);
2182 ut_ad(size <= srv_buf_pool_chunk_unit_max);
2183 ut_ad(size % srv_buf_pool_chunk_unit_blk_sz == 0);
2184 ut_ad(size % UNIV_PAGE_SIZE == 0);
2185
2186 return size;
2187 }
2188
2189 /** Resize the buffer pool based on srv_buf_pool_size from
2190 srv_buf_pool_old_size. */
2191 static void buf_pool_resize() {
2192 buf_pool_t *buf_pool;
2193 ulint new_instance_size;
2194 bool warning = false;
2195
2196 NUMA_MEMPOLICY_INTERLEAVE_IN_SCOPE;
2197
2198 ut_ad(!buf_pool_resizing);
2199 ut_ad(srv_buf_pool_chunk_unit > 0);
2200
2201 /* Assumes that buf_resize_thread has already issued the necessary
2202 memory barrier to read srv_buf_pool_size and srv_buf_pool_old_size */
2203 new_instance_size = srv_buf_pool_size / srv_buf_pool_instances;
2204 new_instance_size /= UNIV_PAGE_SIZE;
2205
2206 buf_resize_status(
2207 BUF_POOL_RESIZE_START,
2208 "Resizing buffer pool from " ULINTPF " to " ULINTPF " (unit=%llu).",
2209 srv_buf_pool_old_size, srv_buf_pool_size, srv_buf_pool_chunk_unit);
2210
2211 /* set new limit for all buffer pool for resizing */
2212 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2213 buf_pool = buf_pool_from_array(i);
2214
2215 // No locking needed to read, same thread updated those
2216 ut_ad(buf_pool->curr_size == buf_pool->old_size);
2217 ut_ad(buf_pool->n_chunks_new == buf_pool->n_chunks);
2218 #ifdef UNIV_DEBUG
2219 ut_ad(UT_LIST_GET_LEN(buf_pool->withdraw) == 0);
2220
2221 buf_flush_list_mutex_enter(buf_pool);
2222 ut_ad(buf_pool->flush_rbt == nullptr);
2223 buf_flush_list_mutex_exit(buf_pool);
2224 #endif
2225
2226 buf_pool->curr_size = new_instance_size;
2227
2228 ut_ad(srv_buf_pool_chunk_unit % UNIV_PAGE_SIZE == 0);
2229 buf_pool->n_chunks_new =
2230 new_instance_size * UNIV_PAGE_SIZE / srv_buf_pool_chunk_unit;
2231 buf_resize_status_progress_update(i + 1, srv_buf_pool_instances);
2232
2233 os_wmb;
2234 }
2235
2236 buf_resize_status_progress_reset();
2237 buf_resize_status(BUF_POOL_RESIZE_DISABLE_AHI,
2238 "Disabling adaptive hash index.");
2239
2240 /* disable AHI if needed */
2241 const bool btr_search_was_enabled = btr_search_disable();
2242
2243 if (btr_search_was_enabled) {
2244 ib::info(ER_IB_MSG_60) << "disabled adaptive hash index.";
2245 }
2246
2247 /* set withdraw target */
2248 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2249 buf_pool = buf_pool_from_array(i);
2250 if (buf_pool->curr_size < buf_pool->old_size) {
2251 ulint withdraw_target = 0;
2252
2253 const buf_chunk_t *chunk = buf_pool->chunks + buf_pool->n_chunks_new;
2254 const buf_chunk_t *echunk = buf_pool->chunks + buf_pool->n_chunks;
2255
2256 while (chunk < echunk) {
2257 withdraw_target += chunk->size;
2258 ++chunk;
2259 }
2260
2261 ut_ad(buf_pool->withdraw_target == 0);
2262 buf_pool->withdraw_target = withdraw_target;
2263 }
2264 buf_resize_status_progress_update(i + 1, srv_buf_pool_instances);
2265 }
2266
2267 buf_resize_status_progress_reset();
2268 buf_resize_status(BUF_POOL_RESIZE_WITHDRAW_BLOCKS,
2269 "Withdrawing blocks to be shrunken.");
2270
2271 auto withdraw_start_time = std::chrono::system_clock::now();
2272 std::chrono::minutes message_interval{1};
2273 ulint retry_interval = 1;
2274
2275 withdraw_retry:
2276 bool should_retry_withdraw = false;
2277
2278 /* wait for the number of blocks fit to the new size (if needed)*/
2279 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2280 buf_pool = buf_pool_from_array(i);
2281 if (buf_pool->curr_size < buf_pool->old_size) {
2282 should_retry_withdraw |= buf_pool_withdraw_blocks(buf_pool);
2283 }
2284 if (!should_retry_withdraw) {
2285 buf_resize_status_progress_update(i + 1, srv_buf_pool_instances);
2286 }
2287 }
2288
2289 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP) {
2290 /* abort to resize for shutdown. */
2291 return;
2292 }
2293
2294 /* abort buffer pool load */
2295 buf_load_abort();
2296
2297 if (should_retry_withdraw &&
2298 std::chrono::system_clock::now() - withdraw_start_time >=
2299 message_interval) {
2300 if (message_interval > std::chrono::minutes{15}) {
2301 message_interval = std::chrono::minutes{30};
2302 } else {
2303 message_interval *= 2;
2304 }
2305
2306 {
2307 /* lock_trx_print_wait_and_mvcc_state() requires exclusive global latch */
2308 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
2309 trx_sys_mutex_enter();
2310 bool found = false;
2311 for (auto trx : trx_sys->mysql_trx_list) {
2312 /* Note that trx->state might be changed from TRX_STATE_NOT_STARTED to
2313 TRX_STATE_ACTIVE without usage of trx_sys->mutex when the transaction
2314 is read-only (look inside trx_start_low() for details).
2315
2316 These loads below might be inconsistent for read-only transactions,
2317 because state and start_time for such transactions are saved using
2318 the std::memory_order_relaxed, not to risk performance regression
2319 on ARM (and this code here is the only victim of the issue, so seems
2320 it is a minor issue with potentially incorrect warning message).
2321
2322 TODO: check performance gain from this micro-optimization */
2323 const auto trx_state = trx->state.load(std::memory_order_relaxed);
2324 const auto trx_start = trx->start_time.load(std::memory_order_relaxed);
2325 if (trx_state != TRX_STATE_NOT_STARTED && trx->mysql_thd != nullptr &&
2326 trx_start != std::chrono::system_clock::time_point{} &&
2327 withdraw_start_time > trx_start) {
2328 if (!found) {
2329 ib::warn(ER_IB_MSG_61)
2330 << "The following trx might hold the blocks in buffer pool to "
2331 "be withdrawn. Buffer pool resizing can complete only after "
2332 "all the transactions below release the blocks.";
2333 found = true;
2334 }
2335
2336 lock_trx_print_wait_and_mvcc_state(stderr, trx);
2337 }
2338 }
2339 trx_sys_mutex_exit();
2340 }
2341
2342 withdraw_start_time = std::chrono::system_clock::now();
2343 }
2344
2345 if (should_retry_withdraw) {
2346 ib::info(ER_IB_MSG_62) << "Will retry to withdraw " << retry_interval
2347 << " seconds later.";
2348 std::this_thread::sleep_for(std::chrono::seconds(retry_interval));
2349
2350 if (retry_interval > 5) {
2351 retry_interval = 10;
2352 } else {
2353 retry_interval *= 2;
2354 }
2355
2356 goto withdraw_retry;
2357 }
2358
2359 buf_resize_status_progress_reset();
2360 buf_resize_status(BUF_POOL_RESIZE_GLOBAL_LOCK,
2361 "Latching whole of buffer pool.");
2362
2363 #ifdef UNIV_DEBUG
2364 {
2365 bool should_wait = true;
2366
2367 while (should_wait) {
2368 should_wait = false;
2369 DBUG_EXECUTE_IF(
2370 "ib_buf_pool_resize_wait_before_resize", should_wait = true;
2371 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
2372 }
2373 }
2374 #endif /* UNIV_DEBUG */
2375
2376 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP) {
2377 return;
2378 }
2379
2380 /* Indicate critical path */
2381 buf_pool_resizing = true;
2382
2383 /* Acquire all buffer pool mutexes and hash table locks */
2384 /* TODO: while we certainly lock a lot here, it does not necessarily
2385 buy us enough correctness. Exploits the fact that freed pages must
2386 have no pointers to them from the buffer pool nor from any other thread
2387 except for the freeing one to remove redundant locking. The same applies
2388 to freshly allocated pages before any pointers to them are published.*/
2389 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2390 mutex_enter(&(buf_pool_from_array(i)->chunks_mutex));
2391 }
2392 buf_resize_status_progress_update(1, 7);
2393
2394 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2395 mutex_enter(&(buf_pool_from_array(i)->LRU_list_mutex));
2396 }
2397 buf_resize_status_progress_update(2, 7);
2398
2399 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2400 hash_lock_x_all(buf_pool_from_array(i)->page_hash);
2401 }
2402 buf_resize_status_progress_update(3, 7);
2403
2404 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2405 mutex_enter(&(buf_pool_from_array(i)->zip_free_mutex));
2406 }
2407 buf_resize_status_progress_update(4, 7);
2408
2409 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2410 mutex_enter(&(buf_pool_from_array(i)->free_list_mutex));
2411 }
2412 buf_resize_status_progress_update(5, 7);
2413
2414 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2415 mutex_enter(&(buf_pool_from_array(i)->zip_hash_mutex));
2416 }
2417 buf_resize_status_progress_update(6, 7);
2418
2419 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2420 mutex_enter(&(buf_pool_from_array(i)->flush_state_mutex));
2421 }
2422 buf_resize_status_progress_update(7, 7);
2423
2424 ut::delete_(buf_chunk_map_reg);
2425 buf_chunk_map_reg =
2426 ut::new_withkey<buf_pool_chunk_map_t>(UT_NEW_THIS_FILE_PSI_KEY);
2427
2428 buf_resize_status_progress_reset();
2429 buf_resize_status(BUF_POOL_RESIZE_IN_PROGRESS, "Starting pool resize");
2430 /* add/delete chunks */
2431 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2432 buf_pool_t *buf_pool = buf_pool_from_array(i);
2433 buf_chunk_t *chunk;
2434 buf_chunk_t *echunk;
2435
2436 buf_resize_status(BUF_POOL_RESIZE_IN_PROGRESS,
2437 "buffer pool " ULINTPF
2438 " :"
2439 " resizing with chunks " ULINTPF " to " ULINTPF ".",
2440 i, buf_pool->n_chunks, buf_pool->n_chunks_new);
2441
2442 if (buf_pool->n_chunks_new < buf_pool->n_chunks) {
2443 /* delete chunks */
2444 chunk = buf_pool->chunks + buf_pool->n_chunks_new;
2445 echunk = buf_pool->chunks + buf_pool->n_chunks;
2446
2447 ulint sum_freed = 0;
2448
2449 while (chunk < echunk) {
2450 buf_block_t *block = chunk->blocks;
2451
2452 for (ulint j = chunk->size; j--; block++) {
2453 mutex_free(&block->mutex);
2454 rw_lock_free(&block->lock);
2455
2456 ut_d(rw_lock_free(&block->debug_latch));
2457 }
2458
2459 buf_pool->deallocate_chunk(chunk);
2460
2461 sum_freed += chunk->size;
2462
2463 ++chunk;
2464 }
2465
2466 /* discard withdraw list */
2467 buf_pool->withdraw.clear();
2468 buf_pool->withdraw_target = 0;
2469
2470 ib::info(ER_IB_MSG_63)
2471 << "buffer pool " << i << " : "
2472 << buf_pool->n_chunks - buf_pool->n_chunks_new << " chunks ("
2473 << sum_freed << " blocks) were freed.";
2474
2475 buf_pool->n_chunks = buf_pool->n_chunks_new;
2476 }
2477
2478 {
2479 /* reallocate buf_pool->chunks */
2480 const ulint new_chunks_size = buf_pool->n_chunks_new * sizeof(*chunk);
2481
2482 buf_chunk_t *new_chunks = reinterpret_cast<buf_chunk_t *>(
2483 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, new_chunks_size));
2484
2485 DBUG_EXECUTE_IF("buf_pool_resize_chunk_null",
2486 buf_pool_resize_chunk_make_null(&new_chunks););
2487
2488 if (new_chunks == nullptr) {
2489 ib::error(ER_IB_MSG_64) << "buffer pool " << i
2490 << " : failed to allocate"
2491 " the chunk array.";
2492 buf_pool->n_chunks_new = buf_pool->n_chunks;
2493 warning = true;
2494 buf_pool->chunks_old = nullptr;
2495 for (ulint j = 0; j < buf_pool->n_chunks_new; j++) {
2496 buf_pool_register_chunk(&buf_pool->chunks[j]);
2497 }
2498 goto calc_buf_pool_size;
2499 }
2500
2501 ulint n_chunks_copy =
2502 std::min(buf_pool->n_chunks_new, buf_pool->n_chunks);
2503
2504 memcpy(new_chunks, buf_pool->chunks, n_chunks_copy * sizeof(*chunk));
2505
2506 for (ulint j = 0; j < n_chunks_copy; j++) {
2507 buf_pool_register_chunk(&new_chunks[j]);
2508 }
2509
2510 buf_pool->chunks_old = buf_pool->chunks;
2511 buf_pool->chunks = new_chunks;
2512 }
2513
2514 if (buf_pool->n_chunks_new > buf_pool->n_chunks) {
2515 /* add chunks */
2516 chunk = buf_pool->chunks + buf_pool->n_chunks;
2517 echunk = buf_pool->chunks + buf_pool->n_chunks_new;
2518
2519 ulint sum_added = 0;
2520 ulint n_chunks = buf_pool->n_chunks;
2521
2522 while (chunk < echunk) {
2523 ulonglong unit = srv_buf_pool_chunk_unit;
2524
2525 if (!buf_chunk_init(buf_pool, chunk, unit, nullptr)) {
2526 ib::error(ER_IB_MSG_65) << "buffer pool " << i
2527 << " : failed to allocate"
2528 " new memory.";
2529
2530 warning = true;
2531
2532 buf_pool->n_chunks_new = n_chunks;
2533
2534 break;
2535 }
2536
2537 sum_added += chunk->size;
2538
2539 ++n_chunks;
2540 ++chunk;
2541 }
2542
2543 ib::info(ER_IB_MSG_66)
2544 << "buffer pool " << i << " : "
2545 << buf_pool->n_chunks_new - buf_pool->n_chunks << " chunks ("
2546 << sum_added << " blocks) were added.";
2547
2548 buf_pool->n_chunks = n_chunks;
2549 }
2550 calc_buf_pool_size:
2551
2552 /* recalc buf_pool->curr_size */
2553 ulint new_size = 0;
2554
2555 chunk = buf_pool->chunks;
2556 do {
2557 new_size += chunk->size;
2558 } while (++chunk < buf_pool->chunks + buf_pool->n_chunks);
2559
2560 buf_pool->curr_size = new_size;
2561 buf_pool->n_chunks_new = buf_pool->n_chunks;
2562
2563 if (buf_pool->chunks_old) {
2564 ut::free(buf_pool->chunks_old);
2565 buf_pool->chunks_old = nullptr;
2566 }
2567 buf_resize_status_progress_update(i + 1, srv_buf_pool_instances);
2568 }
2569
2570 /* set instance sizes */
2571 {
2572 ulint curr_size = 0;
2573
2574 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
2575 buf_pool = buf_pool_from_array(i);
2576
2577 ut_ad(UT_LIST_GET_LEN(buf_pool->withdraw) == 0);
2578
2579 buf_pool->read_ahead_area = static_cast<page_no_t>(std::min(
2580 BUF_READ_AHEAD_PAGES,
2581 ut_2_power_up(buf_pool->curr_size / BUF_READ_AHEAD_PORTION)));
2582 buf_pool->curr_pool_size = buf_pool->curr_size * UNIV_PAGE_SIZE;
2583 curr_size += buf_pool->curr_pool_size;
2584 buf_pool->old_size = buf_pool->curr_size;
2585 }
2586 srv_buf_pool_curr_size = curr_size;
2587 innodb_set_buf_pool_size(buf_pool_size_align(curr_size));
2588 }
2589
2590 const bool new_size_too_diff =
2591 srv_buf_pool_base_size > srv_buf_pool_size * 2 ||
2592 srv_buf_pool_base_size * 2 < srv_buf_pool_size;
2593
2594 /* Normalize page_hash and zip_hash,
2595 if the new size is too different */
2596 if (!warning && new_size_too_diff) {
2597 buf_resize_status_progress_reset();
2598 buf_resize_status(BUF_POOL_RESIZE_HASH, "Resizing hash tables.");
2599
2600 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2601 buf_pool_t *buf_pool = buf_pool_from_array(i);
2602
2603 buf_pool_resize_hash(buf_pool);
2604
2605 ib::info(ER_IB_MSG_67)
2606 << "buffer pool " << i << " : hash tables were resized.";
2607 buf_resize_status_progress_update(i + 1, srv_buf_pool_instances);
2608 }
2609 }
2610
2611 /* Release all buf_pool_mutex/page_hash */
2612 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
2613 buf_pool_t *buf_pool = buf_pool_from_array(i);
2614
2615 mutex_exit(&buf_pool->chunks_mutex);
2616 mutex_exit(&buf_pool->flush_state_mutex);
2617 mutex_exit(&buf_pool->zip_hash_mutex);
2618 mutex_exit(&buf_pool->free_list_mutex);
2619 mutex_exit(&buf_pool->zip_free_mutex);
2620 hash_unlock_x_all(buf_pool->page_hash);
2621 mutex_exit(&buf_pool->LRU_list_mutex);
2622 }
2623 buf_pool_resizing = false;
2624
2625 /* Normalize other components, if the new size is too different */
2626 if (!warning && new_size_too_diff) {
2627 srv_buf_pool_base_size = srv_buf_pool_size;
2628
2629 buf_resize_status(BUF_POOL_RESIZE_HASH, "Resizing also other hash tables.");
2630
2631 /* normalize lock_sys */
2632 srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
2633 lock_sys_resize(srv_lock_table_size);
2634
2635 /* normalize btr_search_sys */
2636 btr_search_sys_resize(buf_pool_get_curr_size() / sizeof(void *) / 64);
2637
2638 /* normalize dict_sys */
2639 dict_resize();
2640
2641 ib::info(ER_IB_MSG_68) << "Resized hash tables at lock_sys,"
2642 " adaptive hash index, dictionary.";
2643 }
2644
2645 /* normalize ibuf->max_size */
2646 ibuf_max_size_update(srv_change_buffer_max_size);
2647
2648 if (srv_buf_pool_old_size != srv_buf_pool_size) {
2649 ib::info(ER_IB_MSG_69) << "Completed to resize buffer pool from "
2650 << srv_buf_pool_old_size << " to "
2651 << srv_buf_pool_size << ".";
2652 srv_buf_pool_old_size = srv_buf_pool_size;
2653 os_wmb;
2654 }
2655
2656 /* enable AHI if needed */
2657 if (btr_search_was_enabled) {
2658 btr_search_enable();
2659 ib::info(ER_IB_MSG_70) << "Re-enabled adaptive hash index.";
2660 }
2661
2662 char now[32];
2663
2664 ut_sprintf_timestamp(now);
2665 if (!warning) {
2666 buf_resize_status_progress_reset();
2667 buf_resize_status(BUF_POOL_RESIZE_COMPLETE,
2668 "Completed resizing buffer pool at %s.", now);
2669 buf_resize_status_progress_update(1, 1);
2670 } else {
2671 buf_resize_status_progress_reset();
2672 buf_resize_status(BUF_POOL_RESIZE_FAILED,
2673 "Resizing buffer pool failed,"
2674 " finished resizing at %s.",
2675 now);
2676 buf_resize_status_progress_update(1, 1);
2677 }
2678
2679 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
2680 ut_a(buf_validate());
2681 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
2682
2683 return;
2684 }
2685
2686 /** This is the thread for resizing buffer pool. It waits for an event and
2687 when waked up either performs a resizing and sleeps again. */
2688 void buf_resize_thread() {
2689 while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
2690 os_event_wait(srv_buf_resize_event);
2691 os_event_reset(srv_buf_resize_event);
2692
2693 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_CLEANUP) {
2694 break;
2695 }
2696
2697 os_rmb;
2698 if (srv_buf_pool_old_size == srv_buf_pool_size) {
2699 std::ostringstream sout;
2700 sout << "Size did not change (old size = new size = " << srv_buf_pool_size
2701 << ". Nothing to do.";
2702 buf_resize_status_progress_update(1, 1);
2703 buf_resize_status_progress_reset();
2704 buf_resize_status(BUF_POOL_RESIZE_COMPLETE, "%s", sout.str().c_str());
2705
2706 /* nothing to do */
2707 continue;
2708 }
2709
2710 buf_pool_resize();
2711 }
2712 }
2713
2714 /** Clears the adaptive hash index on all pages in the buffer pool. */
2715 void buf_pool_clear_hash_index(void) {
2716 ut_ad(!buf_pool_resizing);
2717 ut_ad(!btr_search_enabled);
2718
2719 DEBUG_SYNC_C("purge_wait_for_btr_search_latch");
2720
2721 bool pause_before_processing = DBUG_EVALUATE_IF(
2722 "buf_pool_clear_hash_index_check_other_blocks", true, false);
2723
2724 for (ulong p = 0; p < srv_buf_pool_instances; p++) {
2725 buf_pool_t *const buf_pool = buf_pool_from_array(p);
2726 buf_chunk_t *const chunks = buf_pool->chunks;
2727 buf_chunk_t *chunk = chunks + buf_pool->n_chunks;
2728
2729 while (--chunk >= chunks) {
2730 buf_block_t *block = chunk->blocks;
2731 ulint i = chunk->size;
2732
2733 for (; i--; block++) {
2734 block->ahi.validate();
2735
2736 /* As AHI is disabled, blocks can't be added to AHI, but can only be
2737 removed from it, so once block->ahi.index becomes nullptr, it can't
2738 become non-null again. */
2739 if (block->ahi.index.load() == nullptr) {
2740 /* The block is already not in AHI, and it can't be added before the
2741 AHI is re-enabled, so there's nothing to be done here. */
2742 continue;
2743 }
2744
2745 /* Identify target block and sync with test */
2746 if (pause_before_processing && block->page.old &&
2747 !block->page.is_dirty()) {
2748 DEBUG_SYNC_C("buf_pool_clear_hash_index_will_process_block");
2749 pause_before_processing = false;
2750 }
2751
2752 /* This latch will prevent block state transitions. It is important for
2753 us to not change blocks that are kept in private in
2754 BUF_BLOCK_REMOVE_HASH state by some concurrently executed
2755 buf_LRU_free_page(). */
2756 mutex_enter(&block->mutex);
2757 auto block_mutex_guard =
2758 create_scope_guard([block]() { mutex_exit(&block->mutex); });
2759
2760 block->ahi.validate();
2761
2762 switch (buf_block_get_state(block)) {
2763 case BUF_BLOCK_FILE_PAGE:
2764 /* When the page is in the Buffer Pool, it can't be removed from AHI
2765 (by the btr_search_drop_page_hash_index()) while AHI is disabled,
2766 unless it is called from buf_LRU_free_page(). If it was freed using
2767 buf_LRU_free_page(), then the state would not be
2768 BUF_BLOCK_FILE_PAGE, but it could have already been re-assigned to
2769 some different page (ABA problem on state). The index would be
2770 nullptr then and only then. */
2771 if (block->ahi.index.load() == nullptr) {
2772 continue;
2773 }
2774 break;
2775 case BUF_BLOCK_REMOVE_HASH:
2776 /* It is possible that a parallel thread might have set this state.
2777 It means AHI for this block is being removed. We will wait for this
2778 block to be removed from AHI by waiting for the index's AHI
2779 reference counter to drop to zero. */
2780 continue;
2781 default:
2782 /* No other state should have AHI */
2783 ut_ad(block->ahi.index == nullptr);
2784 ut_ad(block->ahi.n_pointers == 0);
2785 /* Go to next block as AHI is already nullptr */
2786 continue;
2787 }
2788
2789 #if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG
2790 block->ahi.n_pointers = 0;
2791 #endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */
2792 /* It is important to have the index reset to nullptr after the
2793 n_pointers is set to 0, so it synchronizes correctly with check in
2794 buf_block_t::ahi_t::validate(). */
2795 btr_search_set_block_not_cached(block);
2796 }
2797 }
2798 }
2799
2800 /* Main intent was to identify target block. Due to rare race conditions, such
2801 block is not found. To prevent timeout, unblock in case target block is not
2802 found */
2803 if (pause_before_processing) {
2804 DEBUG_SYNC_C("buf_pool_clear_hash_index_will_process_block");
2805 }
2806 }
2807
2808 /** Relocate a buffer control block. Relocates the block on the LRU list
2809 and in buf_pool->page_hash. Does not relocate bpage->list.
2810 The caller must take care of relocating bpage->list.
2811 @param[in,out] bpage control block being relocated, buf_page_get_state()
2812 must be BUF_BLOCK_ZIP_DIRTY or BUF_BLOCK_ZIP_PAGE
2813 @param[in,out] dpage destination control block */
2814 static void buf_relocate(buf_page_t *bpage, buf_page_t *dpage) {
2815 buf_page_t *b;
2816 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
2817
2818 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
2819 ut_ad(buf_page_hash_lock_held_x(buf_pool, bpage));
2820 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
2821 ut_a(buf_page_get_io_fix(bpage) == BUF_IO_NONE);
2822 ut_a(bpage->buf_fix_count == 0);
2823 ut_ad(bpage->in_LRU_list);
2824 ut_ad(!bpage->in_zip_hash);
2825 ut_ad(bpage->in_page_hash);
2826 ut_ad(bpage == buf_page_hash_get_low(buf_pool, bpage->id));
2827
2828 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, bpage));
2829 #ifdef UNIV_DEBUG
2830 switch (buf_page_get_state(bpage)) {
2831 case BUF_BLOCK_POOL_WATCH:
2832 case BUF_BLOCK_NOT_USED:
2833 case BUF_BLOCK_READY_FOR_USE:
2834 case BUF_BLOCK_FILE_PAGE:
2835 case BUF_BLOCK_MEMORY:
2836 case BUF_BLOCK_REMOVE_HASH:
2837 ut_error;
2838 case BUF_BLOCK_ZIP_DIRTY:
2839 case BUF_BLOCK_ZIP_PAGE:
2840 break;
2841 }
2842 #endif /* UNIV_DEBUG */
2843
2844 new (dpage) buf_page_t(*bpage);
2845
2846 /* Important that we adjust the hazard pointer before
2847 removing bpage from LRU list. */
2848 buf_LRU_adjust_hp(buf_pool, bpage);
2849
2850 ut_d(bpage->in_LRU_list = false);
2851 ut_d(bpage->in_page_hash = false);
2852
2853 /* relocate buf_pool->LRU */
2854 b = UT_LIST_GET_PREV(LRU, bpage);
2855 UT_LIST_REMOVE(buf_pool->LRU, bpage);
2856
2857 if (b != nullptr) {
2858 UT_LIST_INSERT_AFTER(buf_pool->LRU, b, dpage);
2859 } else {
2860 UT_LIST_ADD_FIRST(buf_pool->LRU, dpage);
2861 }
2862
2863 if (buf_pool->LRU_old == bpage) {
2864 buf_pool->LRU_old = dpage;
2865 #ifdef UNIV_LRU_DEBUG
2866 /* buf_pool->LRU_old must be the first item in the LRU list
2867 whose "old" flag is set. */
2868 ut_a(buf_pool->LRU_old->old);
2869 ut_a(!UT_LIST_GET_PREV(LRU, buf_pool->LRU_old) ||
2870 !UT_LIST_GET_PREV(LRU, buf_pool->LRU_old)->old);
2871 ut_a(!UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old) ||
2872 UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old)->old);
2873 } else {
2874 /* Check that the "old" flag is consistent in
2875 the block and its neighbours. */
2876 buf_page_set_old(dpage, buf_page_is_old(dpage));
2877 #endif /* UNIV_LRU_DEBUG */
2878 }
2879
2880 ut_d(CheckInLRUList::validate(buf_pool));
2881
2882 /* relocate buf_pool->page_hash */
2883 const auto hash_value = bpage->id.hash();
2884 ut_ad(hash_value == dpage->id.hash());
2885 HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, hash_value, bpage);
2886 HASH_INSERT(buf_page_t, hash, buf_pool->page_hash, hash_value, dpage);
2887 }
2888
2889 /* Hazard Pointer implementation. */
2890
2891 /** Set current value
2892 @param bpage buffer block to be set as hp */
2893 void HazardPointer::set(buf_page_t *bpage) {
2894 ut_ad(mutex_own(m_mutex));
2895 ut_ad(!bpage || buf_pool_from_bpage(bpage) == m_buf_pool);
2896 ut_ad(!bpage || buf_page_in_file(bpage) ||
2897 buf_page_get_state(bpage) == BUF_BLOCK_REMOVE_HASH);
2898
2899 m_hp = bpage;
2900 }
2901
2902 /** Checks if a bpage is the hp
2903 @param bpage buffer block to be compared
2904 @return true if it is hp */
2905
2906 bool HazardPointer::is_hp(const buf_page_t *bpage) {
2907 ut_ad(mutex_own(m_mutex));
2908 ut_ad(!m_hp || buf_pool_from_bpage(m_hp) == m_buf_pool);
2909 ut_ad(!bpage || buf_pool_from_bpage(bpage) == m_buf_pool);
2910
2911 return (bpage == m_hp);
2912 }
2913
2914 /** Adjust the value of hp for moving. This happens when some other thread
2915 working on the same list attempts to relocate the hp of the page.
2916 @param bpage buffer block to be compared
2917 @param dpage buffer block to be moved to */
2918 void HazardPointer::move(const buf_page_t *bpage, buf_page_t *dpage) {
2919 ut_ad(bpage != nullptr);
2920 ut_ad(dpage != nullptr);
2921
2922 if (is_hp(bpage)) {
2923 m_hp = dpage;
2924 }
2925 }
2926
2927 /** Adjust the value of hp. This happens when some other thread working
2928 on the same list attempts to remove the hp from the list.
2929 @param bpage buffer block to be compared */
2930
2931 void FlushHp::adjust(const buf_page_t *bpage) {
2932 ut_ad(bpage != nullptr);
2933
2934 /** We only support reverse traversal for now. */
2935 if (is_hp(bpage)) {
2936 m_hp = UT_LIST_GET_PREV(list, m_hp);
2937 }
2938
2939 ut_ad(!m_hp || m_hp->in_flush_list);
2940 }
2941
2942 /** Adjust the value of hp. This happens when some other thread working
2943 on the same list attempts to remove the hp from the list.
2944 @param bpage buffer block to be compared */
2945
2946 void LRUHp::adjust(const buf_page_t *bpage) {
2947 ut_ad(bpage);
2948
2949 /** We only support reverse traversal for now. */
2950 if (is_hp(bpage)) {
2951 m_hp = UT_LIST_GET_PREV(LRU, m_hp);
2952 }
2953
2954 ut_ad(!m_hp || m_hp->in_LRU_list);
2955 }
2956
2957 /** Selects from where to start a scan. If we have scanned too deep into
2958 the LRU list it resets the value to the tail of the LRU list.
2959 @return buf_page_t from where to start scan. */
2960
2961 buf_page_t *LRUItr::start() {
2962 ut_ad(mutex_own(m_mutex));
2963
2964 if (!m_hp || m_hp->old) {
2965 m_hp = UT_LIST_GET_LAST(m_buf_pool->LRU);
2966 }
2967
2968 return (m_hp);
2969 }
2970
2971 bool buf_pool_watch_is_sentinel(const buf_pool_t *buf_pool,
2972 const buf_page_t *bpage) {
2973 /* We must own the appropriate hash lock. */
2974 ut_ad(buf_page_hash_lock_held_s_or_x(buf_pool, bpage));
2975 ut_ad(buf_page_in_file(bpage));
2976
2977 if (bpage < &buf_pool->watch[0] ||
2978 bpage >= &buf_pool->watch[BUF_POOL_WATCH_SIZE]) {
2979 ut_ad(buf_page_get_state(bpage) != BUF_BLOCK_ZIP_PAGE ||
2980 bpage->zip.data != nullptr);
2981
2982 return false;
2983 }
2984
2985 ut_ad(buf_page_get_state(bpage) == BUF_BLOCK_ZIP_PAGE);
2986 ut_ad(!bpage->in_zip_hash);
2987 ut_ad(bpage->in_page_hash);
2988 ut_ad(bpage->zip.data == nullptr);
2989 return true;
2990 }
2991
2992 /** Add watch for the given page to be read in. Caller must have
2993 appropriate hash_lock for the bpage and hold the LRU list mutex to avoid a race
2994 condition with buf_LRU_free_page inserting the same page into the page hash.
2995 This function may release the hash_lock and reacquire it.
2996 @param[in] page_id page id
2997 @param[in,out] hash_lock hash_lock currently latched
2998 @return NULL if watch set, block if the page is in the buffer pool */
2999 static buf_page_t *buf_pool_watch_set(const page_id_t &page_id,
3000 rw_lock_t **hash_lock) {
3001 buf_page_t *bpage;
3002 ulint i;
3003 buf_pool_t *buf_pool = buf_pool_get(page_id);
3004
3005 ut_ad(*hash_lock == buf_page_hash_lock_get(buf_pool, page_id));
3006
3007 ut_ad(rw_lock_own(*hash_lock, RW_LOCK_X));
3008
3009 bpage = buf_page_hash_get_low(buf_pool, page_id);
3010
3011 if (bpage != nullptr) {
3012 page_found:
3013 if (!buf_pool_watch_is_sentinel(buf_pool, bpage)) {
3014 /* The page was loaded meanwhile. */
3015 return (bpage);
3016 }
3017
3018 /* Add to an existing watch. */
3019 buf_block_fix(bpage);
3020 return (nullptr);
3021 }
3022
3023 /* From this point this function becomes fairly heavy in terms
3024 of latching. We acquire all the hash_locks. They are needed
3025 because we don't want to read any stale information in
3026 buf_pool->watch[]. However, it is not in the critical code path
3027 as this function will be called only by the purge thread. */
3028
3029 /* To obey latching order first release the hash_lock. */
3030 rw_lock_x_unlock(*hash_lock);
3031
3032 mutex_enter(&buf_pool->LRU_list_mutex);
3033 hash_lock_x_all(buf_pool->page_hash);
3034
3035 /* If not own LRU_list_mutex, page_hash can be changed. */
3036 *hash_lock = buf_page_hash_lock_get(buf_pool, page_id);
3037
3038 /* We have to recheck that the page
3039 was not loaded or a watch set by some other
3040 purge thread. This is because of the small
3041 time window between when we release the
3042 hash_lock to lock all the hash_locks. */
3043
3044 bpage = buf_page_hash_get_low(buf_pool, page_id);
3045 if (bpage) {
3046 mutex_exit(&buf_pool->LRU_list_mutex);
3047 hash_unlock_x_all_but(buf_pool->page_hash, *hash_lock);
3048 goto page_found;
3049 }
3050
3051 /* The maximum number of purge threads should never exceed
3052 BUF_POOL_WATCH_SIZE. So there is no way for purge thread
3053 instance to hold a watch when setting another watch. */
3054 for (i = 0; i < BUF_POOL_WATCH_SIZE; i++) {
3055 bpage = &buf_pool->watch[i];
3056
3057 ut_ad(bpage->access_time == std::chrono::steady_clock::time_point{});
3058 ut_ad(bpage->get_newest_lsn() == 0);
3059 ut_ad(!bpage->is_dirty());
3060 ut_ad(bpage->zip.data == nullptr);
3061 ut_ad(!bpage->in_zip_hash);
3062
3063 switch (bpage->state) {
3064 case BUF_BLOCK_POOL_WATCH:
3065 ut_ad(!bpage->in_page_hash);
3066 ut_ad(bpage->buf_fix_count == 0);
3067
3068 bpage->state = BUF_BLOCK_ZIP_PAGE;
3069 bpage->reset_page_id(page_id);
3070 bpage->buf_fix_count.store(1);
3071 bpage->buf_pool_index = buf_pool_index(buf_pool);
3072
3073 ut_d(bpage->in_page_hash = true);
3074 HASH_INSERT(buf_page_t, hash, buf_pool->page_hash, page_id.hash(),
3075 bpage);
3076
3077 mutex_exit(&buf_pool->LRU_list_mutex);
3078
3079 /* Once the sentinel is in the page_hash we can
3080 safely release all locks except just the
3081 relevant hash_lock */
3082 hash_unlock_x_all_but(buf_pool->page_hash, *hash_lock);
3083
3084 return (nullptr);
3085 case BUF_BLOCK_ZIP_PAGE:
3086 ut_ad(bpage->in_page_hash);
3087 ut_ad(bpage->buf_fix_count > 0);
3088 break;
3089 default:
3090 ut_error;
3091 }
3092 }
3093
3094 /* Allocation failed. Either the maximum number of purge
3095 threads should never exceed BUF_POOL_WATCH_SIZE, or this code
3096 should be modified to return a special non-NULL value and the
3097 caller should purge the record directly. */
3098 ut_error;
3099 }
3100
3101 /** Remove the sentinel block for the watch before replacing it with a
3102 real block. buf_page_watch_unset() or buf_page_watch_occurred() will notice
3103 that the block has been replaced with the real block.
3104 @param[in,out] buf_pool buffer pool instance
3105 @param[in,out] watch sentinel for watch
3106 */
3107 static void buf_pool_watch_remove(buf_pool_t *buf_pool, buf_page_t *watch) {
3108 #ifdef UNIV_DEBUG
3109 /* We must also own the appropriate hash cell's mutex. */
3110 rw_lock_t *hash_lock = buf_page_hash_lock_get(buf_pool, watch->id);
3111 ut_ad(rw_lock_own(hash_lock, RW_LOCK_X));
3112 #endif /* UNIV_DEBUG */
3113
3114 ut_ad(buf_page_get_state(watch) == BUF_BLOCK_ZIP_PAGE);
3115
3116 HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, watch->id.hash(), watch);
3117 ut_d(watch->in_page_hash = false);
3118 watch->buf_fix_count.store(0);
3119 watch->state = BUF_BLOCK_POOL_WATCH;
3120 watch->reset_page_id();
3121 }
3122
3123 /** Stop watching if the page has been read in.
3124 buf_pool_watch_set(same_page_id) must have returned NULL before.
3125 @param[in] page_id page id */
3126 void buf_pool_watch_unset(const page_id_t &page_id) {
3127 buf_page_t *bpage;
3128 buf_pool_t *buf_pool = buf_pool_get(page_id);
3129
3130 rw_lock_t *hash_lock = buf_page_hash_lock_get(buf_pool, page_id);
3131 rw_lock_x_lock(hash_lock, UT_LOCATION_HERE);
3132
3133 /* page_hash can be changed. */
3134 hash_lock = buf_page_hash_lock_x_confirm(hash_lock, buf_pool, page_id);
3135
3136 /* The page must exist because buf_pool_watch_set()
3137 increments buf_fix_count. */
3138 bpage = buf_page_hash_get_low(buf_pool, page_id);
3139
3140 if (buf_block_unfix(bpage) == 0 &&
3141 buf_pool_watch_is_sentinel(buf_pool, bpage)) {
3142 buf_pool_watch_remove(buf_pool, bpage);
3143 }
3144
3145 rw_lock_x_unlock(hash_lock);
3146 }
3147
3148 /** Check if the page has been read in.
3149 This may only be called after buf_pool_watch_set(same_page_id)
3150 has returned NULL and before invoking buf_pool_watch_unset(same_page_id).
3151 @param[in] page_id page id
3152 @return false if the given page was not read in, true if it was */
3153 bool buf_pool_watch_occurred(const page_id_t &page_id) {
3154 buf_page_t *bpage;
3155 buf_pool_t *buf_pool = buf_pool_get(page_id);
3156 rw_lock_t *hash_lock = buf_page_hash_lock_get(buf_pool, page_id);
3157
3158 rw_lock_s_lock(hash_lock, UT_LOCATION_HERE);
3159
3160 /* If not own buf_pool_mutex, page_hash can be changed. */
3161 hash_lock = buf_page_hash_lock_s_confirm(hash_lock, buf_pool, page_id);
3162
3163 /* The page must exist because buf_pool_watch_set()
3164 increments buf_fix_count. */
3165 bpage = buf_page_hash_get_low(buf_pool, page_id);
3166
3167 auto ret = !buf_pool_watch_is_sentinel(buf_pool, bpage);
3168 rw_lock_s_unlock(hash_lock);
3169
3170 return ret;
3171 }
3172
3173 /** Moves a page to the start of the buffer pool LRU list. This high-level
3174 function can be used to prevent an important page from slipping out of
3175 the buffer pool.
3176 @param[in,out] bpage buffer block of a file page */
3177 void buf_page_make_young(buf_page_t *bpage) {
3178 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
3179
3180 mutex_enter(&buf_pool->LRU_list_mutex);
3181
3182 ut_a(buf_page_in_file(bpage));
3183
3184 buf_LRU_make_block_young(bpage);
3185
3186 mutex_exit(&buf_pool->LRU_list_mutex);
3187 }
3188
3189 void buf_page_make_old(buf_page_t *bpage) {
3190 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
3191
3192 mutex_enter(&buf_pool->LRU_list_mutex);
3193
3194 ut_a(buf_page_in_file(bpage));
3195
3196 buf_LRU_make_block_old(bpage);
3197
3198 mutex_exit(&buf_pool->LRU_list_mutex);
3199 }
3200
3201 /** Moves a page to the start of the buffer pool LRU list if it is too old.
3202 This high-level function can be used to prevent an important page from
3203 slipping out of the buffer pool. The page must be fixed to the buffer pool.
3204 @param[in,out] bpage buffer block of a file page */
3205 static void buf_page_make_young_if_needed(buf_page_t *bpage) {
3206 ut_ad(!mutex_own(&buf_pool_from_bpage(bpage)->LRU_list_mutex));
3207 ut_ad(bpage->buf_fix_count > 0);
3208 ut_a(buf_page_in_file(bpage));
3209
3210 if (buf_page_peek_if_too_old(bpage)) {
3211 buf_page_make_young(bpage);
3212 }
3213 }
3214
3215 #ifdef UNIV_DEBUG
3216
3217 /** Sets file_page_was_freed true if the page is found in the buffer pool.
3218 This function should be called when we free a file page and want the
3219 debug version to check that it is not accessed any more unless
3220 reallocated.
3221 @param[in] page_id page id
3222 @return control block if found in page hash table, otherwise NULL */
3223 buf_page_t *buf_page_set_file_page_was_freed(const page_id_t &page_id) {
3224 buf_page_t *bpage;
3225 buf_pool_t *buf_pool = buf_pool_get(page_id);
3226 rw_lock_t *hash_lock;
3227
3228 bpage = buf_page_hash_get_s_locked(buf_pool, page_id, &hash_lock);
3229
3230 if (bpage) {
3231 BPageMutex *block_mutex = buf_page_get_mutex(bpage);
3232 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, bpage));
3233 mutex_enter(block_mutex);
3234 rw_lock_s_unlock(hash_lock);
3235
3236 bpage->file_page_was_freed = true;
3237 mutex_exit(block_mutex);
3238 }
3239
3240 return (bpage);
3241 }
3242
3243 /** Sets file_page_was_freed false if the page is found in the buffer pool.
3244 This function should be called when we free a file page and want the
3245 debug version to check that it is not accessed any more unless
3246 reallocated.
3247 @param[in] page_id page id
3248 @return control block if found in page hash table, otherwise NULL */
3249 buf_page_t *buf_page_reset_file_page_was_freed(const page_id_t &page_id) {
3250 buf_page_t *bpage;
3251 buf_pool_t *buf_pool = buf_pool_get(page_id);
3252 rw_lock_t *hash_lock;
3253
3254 bpage = buf_page_hash_get_s_locked(buf_pool, page_id, &hash_lock);
3255 if (bpage) {
3256 BPageMutex *block_mutex = buf_page_get_mutex(bpage);
3257 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, bpage));
3258 mutex_enter(block_mutex);
3259 rw_lock_s_unlock(hash_lock);
3260 bpage->file_page_was_freed = false;
3261 mutex_exit(block_mutex);
3262 }
3263
3264 return (bpage);
3265 }
3266 #endif /* UNIV_DEBUG */
3267
3268 /** Attempts to discard the uncompressed frame of a compressed page.
3269 The caller should not be holding any mutexes when this function is called.
3270 @param[in] page_id page id
3271 */
3272 static void buf_block_try_discard_uncompressed(const page_id_t &page_id) {
3273 buf_page_t *bpage;
3274 buf_pool_t *buf_pool = buf_pool_get(page_id);
3275
3276 /* Since we need to acquire buf_pool->LRU_list_mutex to discard
3277 the uncompressed frame and because page_hash mutex resides below
3278 buf_pool->LRU_list_mutex in sync ordering therefore we must first
3279 release the page_hash mutex. This means that the block in question
3280 can move out of page_hash. Therefore we need to check again if the
3281 block is still in page_hash. */
3282 mutex_enter(&buf_pool->LRU_list_mutex);
3283
3284 bpage = buf_page_hash_get(buf_pool, page_id);
3285
3286 if (bpage) {
3287 BPageMutex *block_mutex = buf_page_get_mutex(bpage);
3288
3289 mutex_enter(block_mutex);
3290
3291 if (buf_LRU_free_page(bpage, false)) {
3292 return;
3293 }
3294 mutex_exit(block_mutex);
3295 }
3296
3297 mutex_exit(&buf_pool->LRU_list_mutex);
3298 }
3299
3300 /** Get read access to a compressed page (usually of type
3301 FIL_PAGE_TYPE_ZBLOB or FIL_PAGE_TYPE_ZBLOB2).
3302 The page must be released with buf_page_release_zip().
3303 NOTE: the page is not protected by any latch. Mutual exclusion has to
3304 be implemented at a higher level. In other words, all possible
3305 accesses to a given page through this function must be protected by
3306 the same set of mutexes or latches.
3307 @param[in] page_id page id
3308 @param[in] page_size page size
3309 @return pointer to the block */
3310 buf_page_t *buf_page_get_zip(const page_id_t &page_id,
3311 const page_size_t &page_size) {
3312 buf_page_t *bpage;
3313 BPageMutex *block_mutex;
3314 rw_lock_t *hash_lock;
3315 bool discard_attempted = false;
3316 buf_pool_t *buf_pool = buf_pool_get(page_id);
3317
3318 Counter::inc(buf_pool->stat.m_n_page_gets, page_id.page_no());
3319
3320 for (;;) {
3321 lookup:
3322
3323 /* The following call will also grab the page_hash
3324 mutex if the page is found. */
3325 bpage = buf_page_hash_get_s_locked(buf_pool, page_id, &hash_lock);
3326 if (bpage) {
3327 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, bpage));
3328 ut_ad(!bpage->was_stale());
3329 break;
3330 }
3331
3332 /* Page not in buf_pool: needs to be read from file */
3333
3334 ut_ad(!hash_lock);
3335 buf_read_page(page_id, page_size);
3336
3337 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3338 ut_a(++buf_dbg_counter % 5771 || buf_validate());
3339 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3340 }
3341
3342 ut_ad(buf_page_hash_lock_held_s(buf_pool, bpage));
3343
3344 if (bpage->zip.data == nullptr) {
3345 /* There is no compressed page. */
3346 err_exit:
3347 rw_lock_s_unlock(hash_lock);
3348
3349 return (nullptr);
3350 }
3351
3352 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, bpage));
3353
3354 switch (buf_page_get_state(bpage)) {
3355 case BUF_BLOCK_POOL_WATCH:
3356 case BUF_BLOCK_NOT_USED:
3357 case BUF_BLOCK_READY_FOR_USE:
3358 case BUF_BLOCK_MEMORY:
3359 case BUF_BLOCK_REMOVE_HASH:
3360 ut_error;
3361
3362 case BUF_BLOCK_ZIP_PAGE:
3363 case BUF_BLOCK_ZIP_DIRTY:
3364 buf_block_fix(bpage);
3365 block_mutex = &buf_pool->zip_mutex;
3366 mutex_enter(block_mutex);
3367 goto got_block;
3368 case BUF_BLOCK_FILE_PAGE:
3369 /* Discard the uncompressed page frame if possible. */
3370 if (!discard_attempted) {
3371 rw_lock_s_unlock(hash_lock);
3372 buf_block_try_discard_uncompressed(page_id);
3373 discard_attempted = true;
3374 goto lookup;
3375 }
3376
3377 block_mutex = &((buf_block_t *)bpage)->mutex;
3378
3379 mutex_enter(block_mutex);
3380
3381 buf_block_buf_fix_inc((buf_block_t *)bpage, UT_LOCATION_HERE);
3382
3383 goto got_block;
3384 }
3385
3386 ut_error;
3387 goto err_exit;
3388
3389 got_block:
3390 auto must_read = buf_page_get_io_fix(bpage) == BUF_IO_READ;
3391
3392 rw_lock_s_unlock(hash_lock);
3393
3394 ut_ad(!bpage->file_page_was_freed);
3395
3396 buf_page_set_accessed(bpage);
3397
3398 mutex_exit(block_mutex);
3399
3400 buf_page_make_young_if_needed(bpage);
3401
3402 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3403 ut_a(++buf_dbg_counter % 5771 || buf_validate());
3404 ut_a(bpage->buf_fix_count > 0);
3405 ut_a(buf_page_in_file(bpage));
3406 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3407
3408 if (must_read) {
3409 /* Let us wait until the read operation
3410 completes */
3411
3412 for (;;) {
3413 enum buf_io_fix io_fix;
3414
3415 mutex_enter(block_mutex);
3416 io_fix = buf_page_get_io_fix(bpage);
3417 mutex_exit(block_mutex);
3418
3419 if (io_fix == BUF_IO_READ) {
3420 std::this_thread::sleep_for(WAIT_FOR_READ);
3421 } else {
3422 break;
3423 }
3424 }
3425 }
3426
3427 #ifdef UNIV_IBUF_COUNT_DEBUG
3428 ut_a(ibuf_count_get(page_id) == 0);
3429 #endif /* UNIV_IBUF_COUNT_DEBUG */
3430
3431 return (bpage);
3432 }
3433
3434 /** Initialize some fields of a control block. */
3435 static inline void buf_block_init_low(
3436 buf_block_t *block) /*!< in: block to init */
3437 {
3438 /* No adaptive hash index entries may point to a previously
3439 unused (and now freshly allocated) block. */
3440 block->ahi.assert_empty_on_init();
3441 block->ahi.index = nullptr;
3442 block->made_dirty_with_no_latch = false;
3443
3444 block->n_hash_helps = 0;
3445 block->ahi.recommended_prefix_info = {0, 1, true};
3446 ut_a(block->page.get_space() != nullptr);
3447 }
3448 #endif /* !UNIV_HOTBACKUP */
3449
3450 /** Decompress a block.
3451 @return true if successful */
3452 bool buf_zip_decompress(buf_block_t *block, /*!< in/out: block */
3453 bool check) /*!< in: true=verify the page checksum */
3454 {
3455 const byte *frame = block->page.zip.data;
3456
3457 ut_ad(block->page.size.is_compressed());
3458 ut_a(block->page.id.space() != 0);
3459
3460 BlockReporter compressed =
3461 BlockReporter(false, frame, block->page.size, false);
3462
3463 if (check && !compressed.verify_zip_checksum()) {
3464 ib::error(ER_IB_MSG_71)
3465 << "Compressed page checksum mismatch " << block->page.id
3466 << "): stored: " << mach_read_from_4(frame + FIL_PAGE_SPACE_OR_CHKSUM)
3467 << ", crc32: "
3468 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_CRC32)
3469 << " innodb: "
3470 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_INNODB)
3471 << ", none: "
3472 << compressed.calc_zip_checksum(SRV_CHECKSUM_ALGORITHM_NONE);
3473
3474 return false;
3475 }
3476
3477 switch (fil_page_get_type(frame)) {
3478 case FIL_PAGE_INDEX:
3479 case FIL_PAGE_SDI:
3480 case FIL_PAGE_RTREE:
3481 if (page_zip_decompress(&block->page.zip, block->frame, true)) {
3482 return true;
3483 }
3484
3485 ib::error(ER_IB_MSG_72)
3486 << "Unable to decompress space " << block->page.id.space() << " page "
3487 << block->page.id.page_no();
3488
3489 return false;
3490
3491 case FIL_PAGE_TYPE_ALLOCATED:
3492 case FIL_PAGE_INODE:
3493 case FIL_PAGE_IBUF_BITMAP:
3494 case FIL_PAGE_TYPE_FSP_HDR:
3495 case FIL_PAGE_TYPE_XDES:
3496 case FIL_PAGE_TYPE_ZBLOB:
3497 case FIL_PAGE_TYPE_ZBLOB2:
3498 case FIL_PAGE_SDI_ZBLOB:
3499 case FIL_PAGE_TYPE_ZLOB_FIRST:
3500 case FIL_PAGE_TYPE_ZLOB_DATA:
3501 case FIL_PAGE_TYPE_ZLOB_INDEX:
3502 case FIL_PAGE_TYPE_ZLOB_FRAG:
3503 case FIL_PAGE_TYPE_ZLOB_FRAG_ENTRY:
3504 /* Copy to uncompressed storage. */
3505 memcpy(block->frame, frame, block->page.size.physical());
3506 return true;
3507 }
3508
3509 ib::error(ER_IB_MSG_73) << "Unknown compressed page type "
3510 << fil_page_get_type(frame);
3511
3512 return false;
3513 }
3514
3515 #ifndef UNIV_HOTBACKUP
3516 /** Get a buffer block from an adaptive hash index pointer.
3517 This function does not return if the block is not identified.
3518 @param[in] ptr pointer to within a page frame
3519 @return pointer to block, never NULL */
3520 buf_block_t *buf_block_from_ahi(const byte *ptr) {
3521 buf_pool_chunk_map_t::iterator it;
3522
3523 buf_pool_chunk_map_t *chunk_map = buf_chunk_map_reg;
3524 ut_ad(!buf_pool_resizing);
3525
3526 buf_chunk_t *chunk;
3527 it = chunk_map->upper_bound(ptr);
3528
3529 ut_a(it != chunk_map->begin());
3530
3531 if (it == chunk_map->end()) {
3532 chunk = chunk_map->rbegin()->second;
3533 } else {
3534 chunk = (--it)->second;
3535 }
3536
3537 ulint offs = ptr - chunk->blocks->frame;
3538
3539 offs >>= UNIV_PAGE_SIZE_SHIFT;
3540
3541 ut_a(offs < chunk->size);
3542
3543 buf_block_t *block = &chunk->blocks[offs];
3544
3545 /* The function buf_chunk_init() invokes buf_block_init() so that
3546 block[n].frame == block->frame + n * UNIV_PAGE_SIZE. Check it. */
3547 ut_ad(block->frame == page_align(ptr));
3548 /* Read the state of the block without holding a mutex.
3549 A state transition from BUF_BLOCK_FILE_PAGE to
3550 BUF_BLOCK_REMOVE_HASH is possible during this execution. */
3551 ut_d(const buf_page_state state = buf_block_get_state(block));
3552 ut_ad(state == BUF_BLOCK_FILE_PAGE || state == BUF_BLOCK_REMOVE_HASH);
3553 return (block);
3554 }
3555
3556 bool buf_is_block_in_instance(const buf_pool_t *buf_pool,
3557 const buf_block_t *ptr) {
3558 const size_t n_chunks = std::min(buf_pool->n_chunks, buf_pool->n_chunks_new);
3559 for (size_t i = 0; i < n_chunks; ++i) {
3560 if (buf_pool->chunks[i].contains(ptr)) {
3561 return true;
3562 }
3563 }
3564
3565 return false;
3566 }
3567
3568 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
3569 /** Return true if probe is enabled.
3570 @return true if probe enabled. */
3571 static bool buf_debug_execute_is_force_flush() {
3572 DBUG_EXECUTE_IF("ib_buf_force_flush", return (true););
3573
3574 /* This is used during quiesce testing, we want to ensure maximum
3575 buffering by the change buffer. */
3576
3577 if (srv_ibuf_disable_background_merge) {
3578 return (true);
3579 }
3580
3581 return (false);
3582 }
3583 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
3584
3585 /** Wait for the block to be read in.
3586 @param[in] block The block to check */
3587 static void buf_wait_for_read(buf_block_t *block) {
3588 /* Note:
3589 This unlocked read of IO fix is safe as we have the block buf-fixed. The page
3590 can only transition away from the IO_READ state, and once this is done, it
3591 will not be IO_READ again as long as we have it buf-fixed.
3592
3593 The repeated reads of io_fix will not be optimized out because it's an atomic
3594 variable.*/
3595 while (block->page.was_io_fix_read()) {
3596 /* Page is X-latched on block->lock until the read is completed.
3597 Let's just wait for S-lock on block->lock, it will be granted as soon as the
3598 read completes. */
3599 rw_lock_s_lock(&block->lock, UT_LOCATION_HERE);
3600 rw_lock_s_unlock(&block->lock);
3601 }
3602 }
3603
3604 /** This class implements the rules for fetching the pages from the buffer
3605 pool depending on the context. It will set the page latches as requested,
3606 detect and handle stale reads and initiate read requests if required. */
3607 template <typename T>
3608 struct Buf_fetch {
3609 public:
3610 /** Constructor.
3611 @param[in] page_id ID of page to fetch.
3612 @param[in] page_size Size of page on disk. */
3613 Buf_fetch(const page_id_t &page_id, const page_size_t &page_size) noexcept
3614 : m_page_id(page_id),
3615 m_page_size(page_size),
3616 m_is_temp_space(fsp_is_system_temporary(page_id.space())),
3617 m_buf_pool(buf_pool_get(m_page_id)) {}
3618
3619 /** For fetching a single page.
3620 @return block from pool on success or nullptr on failure. */
3621 buf_block_t *single_page();
3622
3623 private:
3624 /** Lookup page in the hash table.
3625 @return block if found or nullptr if not found. */
3626 buf_block_t *lookup();
3627
3628 /** Get page if it's in the buffer pool or set a watch on it.
3629 @return block that is being watched or nullptr. */
3630 buf_block_t *is_on_watch();
3631
3632 /** Initiate a read request from persistent store. */
3633 void read_page();
3634
3635 dberr_t zip_page_handler(buf_block_t *&fix_block);
3636
3637 /** Check block state.
3638 @return DB_SUCCESS or error code. */
3639 dberr_t check_state(buf_block_t *&block);
3640
3641 /** Temporary table pages have different latching rules because they are
3642 not redo logged.
3643 @param[in,out] block Temporary tablespace to fetch. */
3644 void temp_space_page_handler(buf_block_t *block);
3645
3646 /** Add the page to the mini-transaction along with latching context.
3647 @param[in,out] block Block for which to add the latching context. */
3648 void mtr_add_page(buf_block_t *block);
3649
3650 /** Check if fetch mode is an optimistic fetch.
3651 @return true if it's an optimistic fetch. */
3652 bool is_optimistic() const;
3653
3654 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
3655 dberr_t debug_check(buf_block_t *fix_block);
3656 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
3657
3658 public:
3659 /** ID of page to lookup. */
3660 const page_id_t &m_page_id;
3661 /** Size of page on disk. */
3662 const page_size_t &m_page_size;
3663 /** true if page belongs to a temporary tablespace. */
3664 const bool m_is_temp_space{};
3665 /** Latch mode required on the page. */
3666 ulint m_rw_latch;
3667 /** Hint about page to fetch. */
3668 buf_block_t *m_guess{};
3669 /** Fetch mode. */
3670 Page_fetch m_mode;
3671 /** File from where called. */
3672 const char *m_file{};
3673 /** Line number in file from where called. */
3674 ulint m_line{};
3675 /** Mini-transaction covering the fetch. */
3676 mtr_t *m_mtr{};
3677 /** Mark page as dirty even if page is being pinned without any latch. */
3678 bool m_dirty_with_no_latch{};
3679 /** Number of retries before giving up. */
3680 size_t m_retries{};
3681 /** Buffer pool to fetch from. */
3682 buf_pool_t *m_buf_pool{};
3683 /** Hash table lock. */
3684 rw_lock_t *m_hash_lock{};
3685
3686 friend T;
3687 };
3688
3689 struct Buf_fetch_normal : public Buf_fetch<Buf_fetch_normal> {
3690 /** Constructor.
3691 @param[in] page_id Page ID of page to fetch.
3692 @param[in] page_size Size of page on disk. */
3693 Buf_fetch_normal(const page_id_t &page_id, const page_size_t &page_size)
3694 : Buf_fetch(page_id, page_size) {}
3695
3696 /** Fetch a block from the hash table or read from disk if necessary.
3697 @param[out] block Block to fetch.
3698 @return DB_SUCCESS or error code. */
3699 dberr_t get(buf_block_t *&block) noexcept;
3700 };
3701
3702 dberr_t Buf_fetch_normal::get(buf_block_t *&block) noexcept {
3703 /* Keep this path as simple as possible. */
3704 for (;;) {
3705 /* Lookup the page in the page hash. If it doesn't exist in the
3706 buffer pool then try and read it in from disk. */
3707
3708 ut_ad(
3709 !rw_lock_own(buf_page_hash_lock_get(m_buf_pool, m_page_id), RW_LOCK_S));
3710
3711 block = lookup();
3712
3713 if (block != nullptr) {
3714 if (block->page.was_stale()) {
3715 if (!buf_page_free_stale(m_buf_pool, &block->page, m_hash_lock)) {
3716 /* The page is during IO and can't be released. We wait some to not go
3717 into loop that would consume CPU. This is not something that will be
3718 hit frequently. */
3719 std::this_thread::sleep_for(std::chrono::microseconds(100));
3720 }
3721 /* The hash lock was released, we should try again lookup for the page
3722 until it's gone - it should disappear eventually when the IO ends. */
3723 continue;
3724 }
3725
3726 buf_block_fix(block);
3727
3728 /* Now safe to release page_hash S lock. */
3729 rw_lock_s_unlock(m_hash_lock);
3730 break;
3731 }
3732
3733 /* Page not in buf_pool: needs to be read from file */
3734 read_page();
3735 }
3736
3737 return DB_SUCCESS;
3738 }
3739
3740 struct Buf_fetch_other : public Buf_fetch<Buf_fetch_other> {
3741 /** Constructor.
3742 @param[in] page_id Page ID of page to fetch.
3743 @param[in] page_size Size of page on disk. */
3744 Buf_fetch_other(const page_id_t &page_id, const page_size_t &page_size)
3745 : Buf_fetch(page_id, page_size) {}
3746
3747 /** Fetch a block from the hash table or read from disk if necessary.
3748 @param[out] block Block to fetch.
3749 @return DB_SUCCESS or error code. */
3750 dberr_t get(buf_block_t *&block) noexcept;
3751 };
3752
3753 dberr_t Buf_fetch_other::get(buf_block_t *&block) noexcept {
3754 for (;;) {
3755 /* Lookup the page in the page hash. If it doesn't exist in the
3756 buffer pool then try and read it in from disk. */
3757
3758 ut_ad(
3759 !rw_lock_own(buf_page_hash_lock_get(m_buf_pool, m_page_id), RW_LOCK_S));
3760
3761 block = lookup();
3762
3763 if (block != nullptr) {
3764 /* Here we have MDL latches making the stale status to not change. */
3765 if (block->page.was_stale()) {
3766 if (!buf_page_free_stale(m_buf_pool, &block->page, m_hash_lock)) {
3767 /* The page is during IO and can't be released. We wait some to not go
3768 into loop that would consume CPU. This is not something that will be
3769 hit frequently. */
3770 std::this_thread::sleep_for(std::chrono::microseconds(100));
3771 }
3772 /* The hash lock was released, we should try again lookup for the page
3773 until it's gone - it should disappear eventually when the IO ends. */
3774 continue;
3775 }
3776
3777 if (m_is_temp_space) {
3778 temp_space_page_handler(block);
3779 } else {
3780 buf_block_fix(block);
3781 }
3782
3783 /* Now safe to release page_hash S lock. */
3784 rw_lock_s_unlock(m_hash_lock);
3785 break;
3786 }
3787
3788 if (m_mode == Page_fetch::IF_IN_POOL_OR_WATCH) {
3789 block = is_on_watch();
3790 }
3791
3792 if (block != nullptr) {
3793 break;
3794 }
3795
3796 if (is_optimistic() || m_mode == Page_fetch::IF_IN_POOL_OR_WATCH) {
3797 /* If it was an optimistic request, return the page only if it was
3798 found in the buffer pool and we haven't been able to find it then
3799 return nullptr (not found). */
3800
3801 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_X));
3802 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_S));
3803
3804 return (DB_NOT_FOUND);
3805 }
3806
3807 /* Page not in buf_pool: needs to be read from file */
3808 read_page();
3809 }
3810
3811 return (DB_SUCCESS);
3812 }
3813
3814 template <typename T>
3815 buf_block_t *Buf_fetch<T>::lookup() {
3816 m_hash_lock = buf_page_hash_lock_get(m_buf_pool, m_page_id);
3817
3818 auto block = m_guess;
3819
3820 rw_lock_s_lock(m_hash_lock, UT_LOCATION_HERE);
3821
3822 /* If not own LRU_list_mutex, page_hash can be changed. */
3823 m_hash_lock =
3824 buf_page_hash_lock_s_confirm(m_hash_lock, m_buf_pool, m_page_id);
3825
3826 if (block != nullptr) {
3827 /* If the m_guess is a compressed page descriptor that has been allocated
3828 by buf_page_alloc_descriptor(), it may have been freed by buf_relocate().
3829 Also, the buffer pool could get resized and m_guess's chunk could get freed,
3830 so we need to check the `block` pointer is still within one of the chunks
3831 before dereferencing it to verify it still contains the same m_page_id */
3832
3833 if (!buf_is_block_in_instance(m_buf_pool, block) ||
3834 m_page_id != block->page.id ||
3835 buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) {
3836 /* Our m_guess was bogus or things have changed since. */
3837 block = m_guess = nullptr;
3838
3839 } else {
3840 ut_ad(!block->page.in_zip_hash);
3841 }
3842 }
3843
3844 if (block == nullptr) {
3845 block = reinterpret_cast<buf_block_t *>(
3846 buf_page_hash_get_low(m_buf_pool, m_page_id));
3847 }
3848
3849 if (block == nullptr) {
3850 rw_lock_s_unlock(m_hash_lock);
3851
3852 return (nullptr);
3853 }
3854
3855 const auto bpage = &block->page;
3856
3857 if (buf_pool_watch_is_sentinel(m_buf_pool, bpage)) {
3858 rw_lock_s_unlock(m_hash_lock);
3859
3860 return (nullptr);
3861 }
3862
3863 return (block);
3864 }
3865
3866 template <typename T>
3867 buf_block_t *Buf_fetch<T>::is_on_watch() {
3868 ut_ad(m_mode == Page_fetch::IF_IN_POOL_OR_WATCH);
3869
3870 rw_lock_x_lock(m_hash_lock, UT_LOCATION_HERE);
3871
3872 /* If not own LRU_list_mutex, page_hash can be changed. */
3873 m_hash_lock =
3874 buf_page_hash_lock_x_confirm(m_hash_lock, m_buf_pool, m_page_id);
3875
3876 auto block = reinterpret_cast<buf_block_t *>(
3877 buf_pool_watch_set(m_page_id, &m_hash_lock));
3878
3879 if (block == nullptr) {
3880 rw_lock_x_unlock(m_hash_lock);
3881 return (nullptr);
3882 }
3883
3884 /* We can release hash_lock after we increment the fix count to make
3885 sure that no state change takes place. */
3886
3887 if (m_is_temp_space) {
3888 temp_space_page_handler(block);
3889 } else {
3890 buf_block_fix(block);
3891 }
3892
3893 rw_lock_x_unlock(m_hash_lock);
3894
3895 return (block);
3896 }
3897
3898 template <typename T>
3899 dberr_t Buf_fetch<T>::zip_page_handler(buf_block_t *&fix_block) {
3900 if (m_mode == Page_fetch::PEEK_IF_IN_POOL) {
3901 /* This m_mode is only used for dropping an adaptive hash index. There
3902 cannot be an adaptive hash index for a compressed-only page, so do
3903 not bother decompressing the page. */
3904
3905 buf_block_unfix(fix_block);
3906
3907 return (DB_NOT_FOUND);
3908 }
3909
3910 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
3911 ut_ad(buf_page_get_mutex(&fix_block->page) == &m_buf_pool->zip_mutex);
3912 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
3913
3914 const auto bpage = &fix_block->page;
3915
3916 /* Note: We have already buffer fixed this block. */
3917 /* We do not hold latches required to prevent io_fix from changing, but this
3918 check is just a heuristic to avoid waiting for I/O under mutex. If we return
3919 DB_FAIL the caller will retry soon, and if we don't then we will repeat an
3920 analogous check few lines below with the protection of buf_page_mutex_enter.*/
3921 if (bpage->buf_fix_count > 1 || bpage->was_io_fixed()) {
3922 /* This condition often occurs when the buffer is not buffer-fixed, but
3923 I/O-fixed by buf_page_init_for_read(). */
3924
3925 buf_block_unfix(fix_block);
3926
3927 /* The block is buffer-fixed or I/O-fixed. Try again later. */
3928 std::this_thread::sleep_for(WAIT_FOR_READ);
3929
3930 return (DB_FAIL);
3931 }
3932
3933 auto block = buf_LRU_get_free_block(m_buf_pool);
3934
3935 mutex_enter(&m_buf_pool->LRU_list_mutex);
3936
3937 /* If not own LRU_list_mutex, page_hash can be changed. */
3938 m_hash_lock = buf_page_hash_lock_get(m_buf_pool, m_page_id);
3939
3940 rw_lock_x_lock(m_hash_lock, UT_LOCATION_HERE);
3941
3942 /* Buffer-fixing prevents the page_hash from changing. */
3943 ut_ad(bpage == buf_page_hash_get_low(m_buf_pool, m_page_id));
3944
3945 buf_block_unfix(fix_block);
3946
3947 buf_page_mutex_enter(block);
3948
3949 mutex_enter(&m_buf_pool->zip_mutex);
3950
3951 if (bpage->buf_fix_count > 0 || buf_page_get_io_fix(bpage) != BUF_IO_NONE) {
3952 mutex_exit(&m_buf_pool->zip_mutex);
3953
3954 /* The block was buffer-fixed or I/O-fixed while buf_pool->mutex was not
3955 held by this thread. Free the block that was allocated and retry.
3956 This should be extremely unlikely, for example, if buf_page_get_zip()
3957 was invoked. */
3958
3959 mutex_exit(&m_buf_pool->LRU_list_mutex);
3960
3961 rw_lock_x_unlock(m_hash_lock);
3962
3963 buf_page_mutex_exit(block);
3964
3965 buf_LRU_block_free_non_file_page(block);
3966
3967 /* Try again */
3968 return (DB_FAIL);
3969 }
3970
3971 /* Move the compressed page from bpage to block, and uncompress it. */
3972
3973 /* Note: this is the uncompressed block and it is not accessible by other
3974 threads yet because it is not in any list or hash table */
3975
3976 buf_relocate(bpage, &block->page);
3977
3978 buf_block_init_low(block);
3979
3980 /* Set after buf_relocate(). */
3981 block->page.buf_fix_count.store(1);
3982
3983 UNIV_MEM_DESC(&block->page.zip.data, page_zip_get_size(&block->page.zip));
3984
3985 if (buf_page_get_state(&block->page) == BUF_BLOCK_ZIP_PAGE) {
3986 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3987 UT_LIST_REMOVE(m_buf_pool->zip_clean, &block->page);
3988 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3989 ut_ad(!block->page.in_flush_list);
3990
3991 } else {
3992 /* Relocate buf_pool->flush_list. */
3993 buf_flush_relocate_on_flush_list(bpage, &block->page);
3994 }
3995
3996 /* Buffer-fix, I/O-fix, and X-latch the block for the duration of the
3997 decompression. Also add the block to the unzip_LRU list. */
3998 block->page.state = BUF_BLOCK_FILE_PAGE;
3999
4000 /* Insert at the front of unzip_LRU list. */
4001 buf_unzip_LRU_add_block(block, false);
4002
4003 mutex_exit(&m_buf_pool->LRU_list_mutex);
4004
4005 buf_block_set_io_fix(block, BUF_IO_READ);
4006
4007 ut::Location loc{m_file, m_line};
4008 rw_lock_x_lock_gen(&block->lock, 0, loc);
4009
4010 rw_lock_x_unlock(m_hash_lock);
4011
4012 mutex_exit(&m_buf_pool->zip_mutex);
4013
4014 const auto access_time = buf_page_is_accessed(&block->page);
4015
4016 buf_page_mutex_exit(block);
4017
4018 m_buf_pool->n_pend_unzip.fetch_add(1);
4019
4020 buf_page_free_descriptor(bpage);
4021
4022 /* Decompress the page while not holding any buf_pool or block->mutex. */
4023
4024 /* Page checksum verification is already done when the page is read from
4025 disk. Hence page checksum verification is not necessary when
4026 decompressing the page. */
4027 {
4028 bool success = buf_zip_decompress(block, false);
4029 ut_a(success);
4030 }
4031
4032 if (!recv_no_ibuf_operations) {
4033 if (access_time != std::chrono::steady_clock::time_point{}) {
4034 #ifdef UNIV_IBUF_COUNT_DEBUG
4035 ut_a(ibuf_count_get(m_page_id) == 0);
4036 #endif /* UNIV_IBUF_COUNT_DEBUG */
4037 } else {
4038 ibuf_merge_or_delete_for_page(block, m_page_id, &m_page_size, true);
4039 }
4040 }
4041
4042 buf_page_mutex_enter(block);
4043
4044 buf_block_set_io_fix(block, BUF_IO_NONE);
4045
4046 buf_page_mutex_exit(block);
4047
4048 m_buf_pool->n_pend_unzip.fetch_sub(1);
4049
4050 rw_lock_x_unlock(&block->lock);
4051
4052 fix_block = block;
4053
4054 return (DB_SUCCESS);
4055 }
4056
4057 template <typename T>
4058 dberr_t Buf_fetch<T>::check_state(buf_block_t *&block) {
4059 switch (buf_block_get_state(block)) {
4060 case BUF_BLOCK_FILE_PAGE:
4061 ut_ad(buf_page_get_mutex(&block->page) != &m_buf_pool->zip_mutex);
4062
4063 {
4064 /* We do not hold latches required to prevent io_fix from changing, but
4065 this check is performed after temp_space_page_handler() has already
4066 incremented buf_fix_count under block mutex. This increment either
4067 happens before or after the check of buf_fix_count in buf_flush_page().
4068 If it was before buf_flush_page() then flush will be aborted because of
4069 seeing buf_fix_count>0. If it was after, then it must also be after
4070 buf_flush_page()'s setting io_fix to BUF_IO_WRITE which it does in the
4071 same critical section, and then we will give up here. */
4072 if (m_is_temp_space && block->page.was_io_fixed()) {
4073 /* This suggest that page is being flushed. Avoid returning
4074 reference to this page. Instead wait for flush action to
4075 complete. For normal page this sync is done using SX lock but for
4076 intrinsic there is no latching. */
4077
4078 buf_block_unfix(block);
4079
4080 std::this_thread::sleep_for(WAIT_FOR_WRITE);
4081
4082 return (DB_FAIL);
4083 }
4084 }
4085
4086 return (DB_SUCCESS);
4087
4088 case BUF_BLOCK_ZIP_PAGE:
4089 case BUF_BLOCK_ZIP_DIRTY:
4090
4091 return (zip_page_handler(block));
4092
4093 case BUF_BLOCK_POOL_WATCH:
4094 case BUF_BLOCK_NOT_USED:
4095 case BUF_BLOCK_READY_FOR_USE:
4096 case BUF_BLOCK_MEMORY:
4097 case BUF_BLOCK_REMOVE_HASH:
4098 ut_error;
4099 break;
4100 }
4101
4102 return (DB_ERROR);
4103 }
4104
4105 template <typename T>
4106 void Buf_fetch<T>::read_page() {
4107 if (buf_read_page(m_page_id, m_page_size)) {
4108 /* Avoid doing read-ahead for parallel scans (well, at least currently this
4109 flag is used only during the parallel scans). This would cause unnecessary
4110 IO when the process is already being parallelized on higher level of
4111 abstraction. */
4112 if (m_mode != Page_fetch::SCAN) {
4113 buf_read_ahead_random(m_page_id, m_page_size, ibuf_inside(m_mtr));
4114 }
4115 m_retries = 0;
4116 } else if (m_retries < BUF_PAGE_READ_MAX_RETRIES) {
4117 ++m_retries;
4118
4119 DBUG_EXECUTE_IF("innodb_page_corruption_retries",
4120 m_retries = BUF_PAGE_READ_MAX_RETRIES;);
4121 } else {
4122 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_74)
4123 << "Unable to read page " << m_page_id << " into the buffer pool after "
4124 << BUF_PAGE_READ_MAX_RETRIES
4125 << " attempts. The most probable cause of this error may"
4126 " be that the table has been corrupted. Or, the table was"
4127 " compressed with with an algorithm that is not supported by "
4128 "this"
4129 " instance. If it is not a decompress failure, you can try to "
4130 "fix"
4131 " this problem by using innodb_force_recovery. Please "
4132 "see " REFMAN " for more details. Aborting...";
4133 }
4134
4135 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4136 ut_ad(fsp_skip_sanity_check(m_page_id.space()) || ++buf_dbg_counter % 5771 ||
4137 buf_validate());
4138 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4139 }
4140
4141 template <typename T>
4142 void Buf_fetch<T>::mtr_add_page(buf_block_t *block) {
4143 mtr_memo_type_t fix_type;
4144
4145 ut::Location loc{m_file, m_line};
4146
4147 switch (m_rw_latch) {
4148 case RW_NO_LATCH:
4149
4150 fix_type = MTR_MEMO_BUF_FIX;
4151 break;
4152
4153 case RW_S_LATCH:
4154 rw_lock_s_lock_gen(&block->lock, 0, loc);
4155 fix_type = MTR_MEMO_PAGE_S_FIX;
4156 break;
4157
4158 case RW_SX_LATCH:
4159 rw_lock_sx_lock_gen(&block->lock, 0, loc);
4160
4161 fix_type = MTR_MEMO_PAGE_SX_FIX;
4162 break;
4163
4164 default:
4165 ut_ad(m_rw_latch == RW_X_LATCH);
4166 rw_lock_x_lock_gen(&block->lock, 0, loc);
4167
4168 fix_type = MTR_MEMO_PAGE_X_FIX;
4169 break;
4170 }
4171
4172 mtr_memo_push(m_mtr, block, fix_type);
4173 }
4174
4175 template <typename T>
4176 bool Buf_fetch<T>::is_optimistic() const {
4177 return (m_mode == Page_fetch::IF_IN_POOL ||
4178 m_mode == Page_fetch::PEEK_IF_IN_POOL);
4179 }
4180
4181 template <typename T>
4182 void Buf_fetch<T>::temp_space_page_handler(buf_block_t *block) {
4183 /* For temporary tablespace, the mutex is being used for synchronization
4184 between user thread and flush thread, instead of block->lock. See
4185 buf_flush_page() for the flush thread counterpart. */
4186 auto block_mutex = buf_page_get_mutex(&block->page);
4187
4188 mutex_enter(block_mutex);
4189
4190 buf_block_fix(block);
4191
4192 mutex_exit(block_mutex);
4193 }
4194
4195 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
4196 template <typename T>
4197 dberr_t Buf_fetch<T>::debug_check(buf_block_t *fix_block) {
4198 if ((m_mode == Page_fetch::IF_IN_POOL ||
4199 m_mode == Page_fetch::IF_IN_POOL_OR_WATCH) &&
4200 (ibuf_debug || buf_debug_execute_is_force_flush())) {
4201 /* Try to evict the block from the buffer pool, to use the
4202 insert buffer (change buffer) as much as possible. */
4203
4204 mutex_enter(&m_buf_pool->LRU_list_mutex);
4205
4206 buf_block_unfix(fix_block);
4207
4208 /* Now we are only holding the buf_pool->LRU_list_mutex,
4209 not block->mutex or m_hash_lock. Blocks cannot be
4210 relocated or enter or exit the buf_pool while we
4211 are holding the buf_pool->LRU_list_mutex. */
4212
4213 auto fix_mutex = buf_page_get_mutex(&fix_block->page);
4214
4215 mutex_enter(fix_mutex);
4216
4217 if (buf_LRU_free_page(&fix_block->page, true)) {
4218 /* If not own LRU_list_mutex, page_hash can be changed. */
4219 m_hash_lock = buf_page_hash_lock_get(m_buf_pool, m_page_id);
4220
4221 rw_lock_x_lock(m_hash_lock, UT_LOCATION_HERE);
4222
4223 /* If not own LRU_list_mutex, page_hash can be changed. */
4224 m_hash_lock =
4225 buf_page_hash_lock_x_confirm(m_hash_lock, m_buf_pool, m_page_id);
4226
4227 buf_block_t *block;
4228
4229 if (m_mode == Page_fetch::IF_IN_POOL_OR_WATCH) {
4230 /* Set the watch, as it would have been set if the page were not in the
4231 buffer pool in the first place. */
4232
4233 block = reinterpret_cast<buf_block_t *>(
4234 buf_pool_watch_set(m_page_id, &m_hash_lock));
4235
4236 } else {
4237 block = reinterpret_cast<buf_block_t *>(
4238 buf_page_hash_get_low(m_buf_pool, m_page_id));
4239 }
4240
4241 rw_lock_x_unlock(m_hash_lock);
4242
4243 if (block != nullptr) {
4244 /* Either the page has been read in or a watch was set on that in the
4245 window where we released the buf_pool::mutex and before we acquire
4246 the m_hash_lock above. Try again. */
4247 m_guess = block;
4248
4249 return (DB_FAIL);
4250 }
4251
4252 ib::info(ER_IB_MSG_75)
4253 << "innodb_change_buffering_debug evict " << m_page_id;
4254
4255 return (DB_NOT_FOUND);
4256 }
4257
4258 if (buf_flush_page_try(m_buf_pool, fix_block)) {
4259 ib::info(ER_IB_MSG_76)
4260 << "innodb_change_buffering_debug flush " << m_page_id;
4261
4262 m_guess = fix_block;
4263
4264 return (DB_FAIL);
4265 }
4266
4267 mutex_exit(&m_buf_pool->LRU_list_mutex);
4268
4269 buf_block_fix(fix_block);
4270
4271 buf_page_mutex_exit(fix_block);
4272
4273 /* Failed to evict the page; change it directly */
4274 }
4275
4276 return (DB_SUCCESS);
4277 }
4278
4279 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
4280
4281 template <typename T>
4282 buf_block_t *Buf_fetch<T>::single_page() {
4283 buf_block_t *block;
4284
4285 Counter::inc(m_buf_pool->stat.m_n_page_gets, m_page_id.page_no());
4286
4287 for (;;) {
4288 if (static_cast<T *>(this)->get(block) == DB_NOT_FOUND) {
4289 return (nullptr);
4290 }
4291 ut_a(!block->page.was_stale());
4292
4293 if (is_optimistic()) {
4294 const auto bpage = &block->page;
4295 auto block_mutex = buf_page_get_mutex(bpage);
4296
4297 mutex_enter(block_mutex);
4298
4299 const auto state = buf_page_get_io_fix(bpage);
4300
4301 mutex_exit(block_mutex);
4302
4303 if (state == BUF_IO_READ) {
4304 /* The page is being read to buffer pool, but we cannot wait around for
4305 the read to complete. */
4306
4307 buf_block_unfix(block);
4308
4309 return (nullptr);
4310 }
4311 }
4312
4313 switch (check_state(block)) {
4314 case DB_NOT_FOUND:
4315 return (nullptr);
4316 case DB_FAIL:
4317 /* Restart the outer for(;;) loop. */
4318 continue;
4319 case DB_SUCCESS:
4320 break;
4321 default:
4322 ut_error;
4323 break;
4324 }
4325
4326 ut_ad(block->page.buf_fix_count > 0);
4327
4328 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_X));
4329
4330 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_S));
4331
4332 ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4333
4334 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
4335 switch (debug_check(block)) {
4336 case DB_NOT_FOUND:
4337 return (nullptr);
4338 case DB_FAIL:
4339 /* Restart the outer for(;;) loop. */
4340 continue;
4341 case DB_SUCCESS:
4342 break;
4343 default:
4344 ut_error;
4345 break;
4346 }
4347 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
4348
4349 /* Break out of the outer for (;;) loop. */
4350 break;
4351 }
4352
4353 ut_ad(block->page.buf_fix_count > 0);
4354
4355 #ifdef UNIV_DEBUG
4356 /* We have already buffer fixed the page, and we are committed to returning
4357 this page to the caller. Register for debugging. Avoid debug latching if
4358 page/block belongs to system temporary tablespace (Not much needed for
4359 table with single threaded access.). */
4360
4361 if (!m_is_temp_space) {
4362 bool ret;
4363 ut::Location loc{m_file, m_line};
4364 ret = rw_lock_s_lock_nowait(&block->debug_latch, loc);
4365 ut_a(ret);
4366 }
4367 #endif /* UNIV_DEBUG */
4368
4369 ut_ad(m_mode == Page_fetch::POSSIBLY_FREED ||
4370 !block->page.file_page_was_freed);
4371
4372 /* Check if this is the first access to the page */
4373 const auto access_time = buf_page_is_accessed(&block->page);
4374
4375 /* This is a heuristic and we don't care about ordering issues. */
4376 if (access_time == std::chrono::steady_clock::time_point{}) {
4377 buf_page_mutex_enter(block);
4378
4379 buf_page_set_accessed(&block->page);
4380
4381 buf_page_mutex_exit(block);
4382 }
4383
4384 /* Don't move the page to the head of the LRU list so that the
4385 page can be discarded quickly if it is not accessed again. */
4386 if (m_mode != Page_fetch::PEEK_IF_IN_POOL && m_mode != Page_fetch::SCAN) {
4387 buf_page_make_young_if_needed(&block->page);
4388 }
4389
4390 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4391 ut_a(fsp_skip_sanity_check(m_page_id.space()) || ++buf_dbg_counter % 5771 ||
4392 buf_validate());
4393 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4394 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4395
4396 /* We have to wait here because the IO_READ state was set under the protection
4397 of the hash_lock and not the block->mutex and block->lock. */
4398 buf_wait_for_read(block);
4399
4400 /* Mark block as dirty if requested by caller. If not requested (false)
4401 then we avoid updating the dirty state of the block and retain the
4402 original one. This is reason why ?
4403 Same block can be shared/pinned by 2 different mtrs. If first mtr
4404 set the dirty state to true and second mtr mark it as false the last
4405 updated dirty state is retained. Which means we can loose flushing of
4406 a modified block. */
4407 if (m_dirty_with_no_latch) {
4408 block->made_dirty_with_no_latch = m_dirty_with_no_latch;
4409 }
4410
4411 mtr_add_page(block);
4412
4413 if (m_mode != Page_fetch::PEEK_IF_IN_POOL &&
4414 access_time == std::chrono::steady_clock::time_point{}) {
4415 /* In the case of a first access, try to apply linear read-ahead */
4416
4417 buf_read_ahead_linear(m_page_id, m_page_size, ibuf_inside(m_mtr));
4418 }
4419
4420 #ifdef UNIV_IBUF_COUNT_DEBUG
4421 ut_ad(ibuf_count_get(block->page.id) == 0);
4422 #endif /* UNIV_IBUF_COUNT_DEBUG */
4423
4424 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_X));
4425 ut_ad(!rw_lock_own(m_hash_lock, RW_LOCK_S));
4426
4427 ut_a(!block->page.was_stale());
4428
4429 return (block);
4430 }
4431
4432 buf_block_t *buf_page_get_gen(const page_id_t &page_id,
4433 const page_size_t &page_size, ulint rw_latch,
4434 buf_block_t *guess, Page_fetch mode,
4435 ut::Location location, mtr_t *mtr,
4436 bool dirty_with_no_latch) {
4437 #ifdef UNIV_DEBUG
4438 ut_ad(mtr->is_active());
4439
4440 ut_ad(rw_latch == RW_S_LATCH || rw_latch == RW_X_LATCH ||
4441 rw_latch == RW_SX_LATCH || rw_latch == RW_NO_LATCH);
4442
4443 ut_ad(!ibuf_inside(mtr) ||
4444 ibuf_page_low(page_id, page_size, false, location, nullptr));
4445
4446 switch (mode) {
4447 case Page_fetch::NO_LATCH:
4448 ut_ad(rw_latch == RW_NO_LATCH);
4449 break;
4450 case Page_fetch::NORMAL:
4451 case Page_fetch::SCAN:
4452 case Page_fetch::IF_IN_POOL:
4453 case Page_fetch::PEEK_IF_IN_POOL:
4454 case Page_fetch::IF_IN_POOL_OR_WATCH:
4455 case Page_fetch::POSSIBLY_FREED:
4456 break;
4457 default:
4458 ib::fatal(UT_LOCATION_HERE, ER_IB_ERR_UNKNOWN_PAGE_FETCH_MODE)
4459 << "Unknown fetch mode: " << (int)mode;
4460 ut_error;
4461 }
4462
4463 bool found;
4464 const page_size_t &space_page_size =
4465 fil_space_get_page_size(page_id.space(), &found);
4466
4467 ut_ad(!found || page_size.equals_to(space_page_size));
4468 #endif /* UNIV_DEBUG */
4469
4470 if (mode == Page_fetch::NORMAL && !fsp_is_system_temporary(page_id.space())) {
4471 Buf_fetch_normal fetch(page_id, page_size);
4472
4473 fetch.m_rw_latch = rw_latch;
4474 fetch.m_guess = guess;
4475 fetch.m_mode = mode;
4476 fetch.m_file = location.filename;
4477 fetch.m_line = location.line;
4478 fetch.m_mtr = mtr;
4479 fetch.m_dirty_with_no_latch = dirty_with_no_latch;
4480
4481 return (fetch.single_page());
4482
4483 } else {
4484 Buf_fetch_other fetch(page_id, page_size);
4485
4486 fetch.m_rw_latch = rw_latch;
4487 fetch.m_guess = guess;
4488 fetch.m_mode = mode;
4489 fetch.m_file = location.filename;
4490 fetch.m_line = location.line;
4491 fetch.m_mtr = mtr;
4492 fetch.m_dirty_with_no_latch = dirty_with_no_latch;
4493
4494 return (fetch.single_page());
4495 }
4496 }
4497
4498 bool buf_page_optimistic_get(ulint rw_latch, buf_block_t *block,
4499 uint64_t modify_clock, Page_fetch fetch_mode,
4500 const char *file, ulint line, mtr_t *mtr) {
4501 ut_ad(mtr->is_active());
4502 ut_ad(rw_latch == RW_S_LATCH || rw_latch == RW_X_LATCH ||
4503 rw_latch == RW_NO_LATCH);
4504
4505 buf_page_mutex_enter(block);
4506
4507 if (buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) {
4508 buf_page_mutex_exit(block);
4509
4510 return (false);
4511 }
4512
4513 buf_block_buf_fix_inc(block, ut::Location{file, line});
4514
4515 const auto access_time = buf_page_is_accessed(&block->page);
4516
4517 buf_page_set_accessed(&block->page);
4518
4519 buf_page_mutex_exit(block);
4520
4521 if (fetch_mode != Page_fetch::SCAN) {
4522 buf_page_make_young_if_needed(&block->page);
4523 }
4524
4525 ut_ad(!ibuf_inside(mtr) ||
4526 ibuf_page(block->page.id, block->page.size, UT_LOCATION_HERE, nullptr));
4527
4528 bool success;
4529 mtr_memo_type_t fix_type;
4530
4531 auto loc = ut::Location{file, line};
4532 switch (rw_latch) {
4533 case RW_S_LATCH:
4534 success = rw_lock_s_lock_nowait(&block->lock, loc);
4535
4536 fix_type = MTR_MEMO_PAGE_S_FIX;
4537 break;
4538 case RW_X_LATCH:
4539 success = rw_lock_x_lock_nowait(&block->lock, loc);
4540
4541 fix_type = MTR_MEMO_PAGE_X_FIX;
4542 break;
4543 default:
4544 ut_ad(rw_latch == RW_NO_LATCH);
4545 fix_type = MTR_MEMO_BUF_FIX;
4546 success = true;
4547 }
4548
4549 if (!success) {
4550 buf_block_buf_fix_dec(block);
4551 return (false);
4552 }
4553
4554 if (modify_clock != block->modify_clock) {
4555 buf_block_dbg_add_level(block, SYNC_NO_ORDER_CHECK);
4556
4557 if (rw_latch == RW_S_LATCH) {
4558 rw_lock_s_unlock(&block->lock);
4559 } else if (rw_latch == RW_X_LATCH) {
4560 rw_lock_x_unlock(&block->lock);
4561 }
4562
4563 buf_block_buf_fix_dec(block);
4564
4565 return (false);
4566 }
4567
4568 mtr_memo_push(mtr, block, fix_type);
4569
4570 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4571 ut_a(fsp_skip_sanity_check(block->page.id.space()) ||
4572 ++buf_dbg_counter % 5771 || buf_validate());
4573 ut_a(block->page.buf_fix_count > 0);
4574 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4575 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4576
4577 ut_d(buf_page_mutex_enter(block));
4578 ut_ad(!block->page.file_page_was_freed);
4579 ut_d(buf_page_mutex_exit(block));
4580
4581 if (access_time == std::chrono::steady_clock::time_point{}) {
4582 /* In the case of a first access, try to apply linear read-ahead */
4583 buf_read_ahead_linear(block->page.id, block->page.size, ibuf_inside(mtr));
4584 }
4585
4586 #ifdef UNIV_IBUF_COUNT_DEBUG
4587 ut_a(ibuf_count_get(block->page.id) == 0);
4588 #endif /* UNIV_IBUF_COUNT_DEBUG */
4589
4590 {
4591 auto buf_pool = buf_pool_from_block(block);
4592 Counter::inc(buf_pool->stat.m_n_page_gets, block->page.id.page_no());
4593 }
4594
4595 return (true);
4596 }
4597
4598 bool buf_page_get_known_nowait(ulint rw_latch, buf_block_t *block,
4599 Cache_hint hint, const char *file, ulint line,
4600 mtr_t *mtr) {
4601 ut_ad(mtr->is_active());
4602 ut_ad((rw_latch == RW_S_LATCH) || (rw_latch == RW_X_LATCH));
4603
4604 buf_page_mutex_enter(block);
4605
4606 if (buf_block_get_state(block) == BUF_BLOCK_REMOVE_HASH) {
4607 /* Another thread is just freeing the block from the LRU list
4608 of the buffer pool: do not try to access this page; this
4609 attempt to access the page can only come through the hash
4610 index because when the buffer block state is ..._REMOVE_HASH,
4611 we have already removed it from the page address hash table
4612 of the buffer pool. */
4613
4614 buf_page_mutex_exit(block);
4615
4616 return (false);
4617 }
4618
4619 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4620
4621 buf_block_buf_fix_inc(block, ut::Location{file, line});
4622
4623 buf_page_set_accessed(&block->page);
4624
4625 buf_page_mutex_exit(block);
4626
4627 auto buf_pool = buf_pool_from_block(block);
4628
4629 if (hint == Cache_hint::MAKE_YOUNG) {
4630 buf_page_make_young_if_needed(&block->page);
4631 }
4632
4633 ut_ad(!ibuf_inside(mtr) || hint == Cache_hint::KEEP_OLD);
4634
4635 bool success;
4636 mtr_memo_type_t fix_type;
4637
4638 auto loc = ut::Location{file, line};
4639 switch (rw_latch) {
4640 case RW_S_LATCH:
4641 success = rw_lock_s_lock_nowait(&block->lock, loc);
4642 fix_type = MTR_MEMO_PAGE_S_FIX;
4643 break;
4644 case RW_X_LATCH:
4645 success = rw_lock_x_lock_nowait(&block->lock, loc);
4646
4647 fix_type = MTR_MEMO_PAGE_X_FIX;
4648 break;
4649 default:
4650 ut_error; /* RW_SX_LATCH is not implemented yet */
4651 }
4652
4653 if (!success) {
4654 buf_block_buf_fix_dec(block);
4655
4656 return (false);
4657 }
4658
4659 mtr_memo_push(mtr, block, fix_type);
4660
4661 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4662 ut_a(++buf_dbg_counter % 5771 || buf_validate());
4663 ut_a(block->page.buf_fix_count > 0);
4664 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4665 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4666
4667 #ifdef UNIV_DEBUG
4668 if (hint != Cache_hint::KEEP_OLD) {
4669 /* If hint == BUF_KEEP_OLD, we are executing an I/O
4670 completion routine. Avoid a bogus assertion failure
4671 when ibuf_merge_or_delete_for_page() is processing a
4672 page that was just freed due to DROP INDEX, or
4673 deleting a record from SYS_INDEXES. This check will be
4674 skipped in recv_recover_page() as well. */
4675
4676 buf_page_mutex_enter(block);
4677 ut_a(!block->page.file_page_was_freed);
4678 buf_page_mutex_exit(block);
4679 }
4680 #endif /* UNIV_DEBUG */
4681
4682 #ifdef UNIV_IBUF_COUNT_DEBUG
4683 ut_a((hint == Cache_hint::KEEP_OLD) || ibuf_count_get(block->page.id) == 0);
4684 #endif /* UNIV_IBUF_COUNT_DEBUG */
4685
4686 Counter::inc(buf_pool->stat.m_n_page_gets, block->page.id.page_no());
4687
4688 return (true);
4689 }
4690
4691 const buf_block_t *buf_page_try_get(const page_id_t &page_id,
4692 ut::Location location, mtr_t *mtr) {
4693 buf_block_t *block;
4694 buf_pool_t *buf_pool = buf_pool_get(page_id);
4695 rw_lock_t *hash_lock;
4696
4697 ut_ad(mtr);
4698 ut_ad(mtr->is_active());
4699
4700 block = buf_block_hash_get_s_locked(buf_pool, page_id, &hash_lock);
4701
4702 if (!block || buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) {
4703 if (block) {
4704 rw_lock_s_unlock(hash_lock);
4705 }
4706 return (nullptr);
4707 }
4708
4709 ut_ad(!buf_pool_watch_is_sentinel(buf_pool, &block->page));
4710
4711 buf_page_mutex_enter(block);
4712 rw_lock_s_unlock(hash_lock);
4713 ut_ad(!block->page.was_stale());
4714
4715 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4716 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4717 ut_a(page_id == block->page.id);
4718 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4719
4720 buf_block_buf_fix_inc(block, location);
4721 buf_page_mutex_exit(block);
4722
4723 mtr_memo_type_t fix_type = MTR_MEMO_PAGE_S_FIX;
4724 auto success = rw_lock_s_lock_nowait(&block->lock, location);
4725
4726 if (!success) {
4727 /* Let us try to get an X-latch. If the current thread
4728 is holding an X-latch on the page, we cannot get an
4729 S-latch. */
4730
4731 fix_type = MTR_MEMO_PAGE_X_FIX;
4732 success = rw_lock_x_lock_nowait(&block->lock, location);
4733 }
4734
4735 if (!success) {
4736 buf_block_buf_fix_dec(block);
4737
4738 return (nullptr);
4739 }
4740
4741 mtr_memo_push(mtr, block, fix_type);
4742
4743 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
4744 ut_a(fsp_skip_sanity_check(block->page.id.space()) ||
4745 ++buf_dbg_counter % 5771 || buf_validate());
4746 ut_a(block->page.buf_fix_count > 0);
4747 ut_a(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
4748 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
4749
4750 ut_d(buf_page_mutex_enter(block));
4751 ut_d(ut_a(!block->page.file_page_was_freed));
4752 ut_d(buf_page_mutex_exit(block));
4753
4754 buf_block_dbg_add_level(block, SYNC_NO_ORDER_CHECK);
4755
4756 Counter::inc(buf_pool->stat.m_n_page_gets, block->page.id.page_no());
4757
4758 #ifdef UNIV_IBUF_COUNT_DEBUG
4759 ut_a(ibuf_count_get(block->page.id) == 0);
4760 #endif /* UNIV_IBUF_COUNT_DEBUG */
4761
4762 return (block);
4763 }
4764
4765 /** Initialize some fields of a control block.
4766 @param[in,out] bpage Block to initialize. */
4767 static void buf_page_init_low(buf_page_t *bpage) noexcept {
4768 ut_ad(bpage->id.space() != UINT32_UNDEFINED);
4769 ut_ad(bpage->id.page_no() != UINT32_UNDEFINED);
4770 ut_ad(mutex_own(buf_page_get_mutex(bpage)));
4771
4772 bpage->flush_type = BUF_FLUSH_LRU;
4773 bpage->reinit_io_fix();
4774 bpage->buf_fix_count.store(0);
4775 bpage->freed_page_clock = 0;
4776 bpage->access_time = {};
4777 bpage->set_newest_lsn(0);
4778 bpage->set_clean();
4779
4780 HASH_INVALIDATE(bpage, hash);
4781
4782 ut_d(bpage->file_page_was_freed = false);
4783 }
4784
4785 /** Inits a page to the buffer buf_pool. The block pointer must be private to
4786 the calling thread at the start of this function.
4787 @param[in,out] buf_pool buffer pool
4788 @param[in] page_id page id
4789 @param[in] page_size page size
4790 @param[in,out] block block to init */
4791 static void buf_page_init(buf_pool_t *buf_pool, const page_id_t &page_id,
4792 const page_size_t &page_size, buf_block_t *block) {
4793 buf_page_t *hash_page;
4794
4795 ut_ad(buf_pool == buf_pool_get(page_id));
4796
4797 ut_ad(mutex_own(buf_page_get_mutex(&block->page)));
4798 ut_a(buf_block_get_state(block) == BUF_BLOCK_READY_FOR_USE);
4799
4800 ut_ad(rw_lock_own(buf_page_hash_lock_get(buf_pool, page_id), RW_LOCK_X));
4801
4802 /* Set the state of the block */
4803 buf_block_set_file_page(block, page_id);
4804
4805 #ifdef UNIV_DEBUG_VALGRIND
4806 if (fsp_is_system_or_temp_tablespace(page_id.space())) {
4807 /* Silence valid Valgrind warnings about uninitialized
4808 data being written to data files. There are some unused
4809 bytes on some pages that InnoDB does not initialize. */
4810 UNIV_MEM_VALID(block->frame, UNIV_PAGE_SIZE);
4811 }
4812 #endif /* UNIV_DEBUG_VALGRIND */
4813
4814 buf_block_init_low(block);
4815
4816 buf_page_init_low(&block->page);
4817
4818 /* Insert into the hash table of file pages */
4819
4820 ut_ad(!block->page.was_stale());
4821
4822 hash_page = buf_page_hash_get_low(buf_pool, page_id);
4823
4824 if (hash_page == nullptr) {
4825 /* Block not found in hash table */
4826 } else if (buf_pool_watch_is_sentinel(buf_pool, hash_page)) {
4827 /* Preserve the reference count. */
4828 uint32_t buf_fix_count = hash_page->buf_fix_count;
4829
4830 ut_a(buf_fix_count > 0);
4831
4832 block->page.buf_fix_count.fetch_add(buf_fix_count);
4833
4834 buf_pool_watch_remove(buf_pool, hash_page);
4835 } else {
4836 ib::error(ER_IB_MSG_77)
4837 << "Page " << page_id
4838 << " already found in the hash table: " << hash_page << ", " << block;
4839
4840 ut_d(buf_print());
4841 ut_d(buf_LRU_print());
4842 ut_d(buf_validate());
4843 ut_d(buf_LRU_validate());
4844 ut_d(ut_error);
4845 }
4846
4847 ut_ad(!block->page.in_zip_hash);
4848 ut_ad(!block->page.in_page_hash);
4849 ut_d(block->page.in_page_hash = true);
4850
4851 ut_a(block->page.id == page_id);
4852 block->page.size.copy_from(page_size);
4853
4854 HASH_INSERT(buf_page_t, hash, buf_pool->page_hash, page_id.hash(),
4855 &block->page);
4856
4857 if (page_size.is_compressed()) {
4858 page_zip_set_size(&block->page.zip, page_size.physical());
4859 }
4860 }
4861
4862 buf_page_t *buf_page_init_for_read(ulint mode, const page_id_t &page_id,
4863 const page_size_t &page_size, bool unzip) {
4864 buf_block_t *block;
4865 rw_lock_t *hash_lock;
4866 mtr_t mtr;
4867 void *data = nullptr;
4868 buf_pool_t *buf_pool = buf_pool_get(page_id);
4869
4870 ut_ad(buf_pool);
4871
4872 if (mode == BUF_READ_IBUF_PAGES_ONLY) {
4873 /* It is a read-ahead within an ibuf routine */
4874
4875 ut_ad(!ibuf_bitmap_page(page_id, page_size));
4876
4877 ibuf_mtr_start(&mtr);
4878
4879 if (!recv_no_ibuf_operations &&
4880 !ibuf_page(page_id, page_size, UT_LOCATION_HERE, &mtr)) {
4881 ibuf_mtr_commit(&mtr);
4882
4883 return (nullptr);
4884 }
4885 } else {
4886 ut_ad(mode == BUF_READ_ANY_PAGE);
4887 }
4888
4889 if (page_size.is_compressed() && !unzip && !recv_recovery_is_on()) {
4890 block = nullptr;
4891 } else {
4892 block = buf_LRU_get_free_block(buf_pool);
4893 ut_ad(block);
4894 ut_ad(!block->page.someone_has_io_responsibility());
4895 ut_ad(buf_pool_from_block(block) == buf_pool);
4896 }
4897
4898 buf_page_t *bpage = nullptr;
4899 if (block == nullptr) {
4900 bpage = buf_page_alloc_descriptor();
4901 }
4902
4903 if ((block != nullptr && page_size.is_compressed()) || block == nullptr) {
4904 data = buf_buddy_alloc(buf_pool, page_size.physical());
4905 }
4906
4907 mutex_enter(&buf_pool->LRU_list_mutex);
4908
4909 hash_lock = buf_page_hash_lock_get(buf_pool, page_id);
4910
4911 rw_lock_x_lock(hash_lock, UT_LOCATION_HERE);
4912
4913 buf_page_t *watch_page;
4914
4915 watch_page = buf_page_hash_get_low(buf_pool, page_id);
4916
4917 if (watch_page != nullptr &&
4918 !buf_pool_watch_is_sentinel(buf_pool, watch_page)) {
4919 /* The page is already in the buffer pool. */
4920 watch_page = nullptr;
4921
4922 mutex_exit(&buf_pool->LRU_list_mutex);
4923
4924 rw_lock_x_unlock(hash_lock);
4925
4926 if (bpage != nullptr) {
4927 buf_page_free_descriptor(bpage);
4928 }
4929
4930 if (data != nullptr) {
4931 buf_buddy_free(buf_pool, data, page_size.physical());
4932 }
4933
4934 if (block != nullptr) {
4935 buf_LRU_block_free_non_file_page(block);
4936 }
4937
4938 bpage = nullptr;
4939
4940 goto func_exit;
4941 }
4942
4943 if (block != nullptr) {
4944 ut_ad(!bpage);
4945 bpage = &block->page;
4946
4947 ut_ad(buf_pool_from_bpage(bpage) == buf_pool);
4948
4949 buf_page_mutex_enter(block);
4950
4951 buf_page_init(buf_pool, page_id, page_size, block);
4952
4953 /* Note: We are using the hash_lock for protection. This is
4954 safe because no other thread can lookup the block from the
4955 page hashtable yet. */
4956
4957 buf_page_set_io_fix(bpage, BUF_IO_READ);
4958
4959 /* The block must be put to the LRU list, to the old blocks */
4960 buf_LRU_add_block(bpage, true /* to old blocks */);
4961
4962 if (page_size.is_compressed()) {
4963 block->page.zip.data = (page_zip_t *)data;
4964
4965 /* To maintain the invariant
4966 block->in_unzip_LRU_list
4967 == buf_page_belongs_to_unzip_LRU(&block->page)
4968 we have to add this block to unzip_LRU
4969 after block->page.zip.data is set. */
4970 ut_ad(buf_page_belongs_to_unzip_LRU(&block->page));
4971 buf_unzip_LRU_add_block(block, true);
4972 }
4973
4974 mutex_exit(&buf_pool->LRU_list_mutex);
4975
4976 /* We set a pass-type x-lock on the frame because then
4977 the same thread which called for the read operation
4978 (and is running now at this point of code) can wait
4979 for the read to complete by waiting for the x-lock on
4980 the frame; if the x-lock were recursive, the same
4981 thread would illegally get the x-lock before the page
4982 read is completed. The x-lock is cleared by the
4983 io-handler thread. */
4984
4985 rw_lock_x_lock_gen(&block->lock, BUF_IO_READ, UT_LOCATION_HERE);
4986
4987 rw_lock_x_unlock(hash_lock);
4988
4989 buf_page_mutex_exit(block);
4990 } else {
4991 /* Initialize the buf_pool pointer. */
4992 bpage->buf_pool_index = buf_pool_index(buf_pool);
4993
4994 page_zip_des_init(&bpage->zip);
4995 page_zip_set_size(&bpage->zip, page_size.physical());
4996 ut_ad(data);
4997 bpage->zip.data = (page_zip_t *)data;
4998
4999 bpage->size.copy_from(page_size);
5000
5001 mutex_enter(&buf_pool->zip_mutex);
5002 UNIV_MEM_DESC(bpage->zip.data, bpage->size.physical());
5003
5004 /* So that we can attach the fil_space_t instance. */
5005 bpage->reset_page_id(page_id);
5006 bpage->reset_flush_observer();
5007 bpage->state = BUF_BLOCK_ZIP_PAGE;
5008 bpage->init_io_fix();
5009
5010 buf_page_init_low(bpage);
5011
5012 ut_ad(bpage->state == BUF_BLOCK_ZIP_PAGE);
5013 ut_ad(bpage->id == page_id);
5014
5015 ut_d(bpage->in_page_hash = false);
5016 ut_d(bpage->in_zip_hash = false);
5017 ut_d(bpage->in_flush_list = false);
5018 ut_d(bpage->in_free_list = false);
5019 ut_d(bpage->in_LRU_list = false);
5020
5021 ut_d(bpage->in_page_hash = true);
5022
5023 if (watch_page != nullptr) {
5024 /* Preserve the reference count. */
5025 uint32_t buf_fix_count;
5026
5027 buf_fix_count = watch_page->buf_fix_count;
5028
5029 ut_a(buf_fix_count > 0);
5030
5031 bpage->buf_fix_count.fetch_add(buf_fix_count);
5032
5033 ut_ad(buf_pool_watch_is_sentinel(buf_pool, watch_page));
5034 buf_pool_watch_remove(buf_pool, watch_page);
5035 }
5036
5037 HASH_INSERT(buf_page_t, hash, buf_pool->page_hash, bpage->id.hash(), bpage);
5038
5039 rw_lock_x_unlock(hash_lock);
5040
5041 /* The block must be put to the LRU list, to the old blocks.
5042 The zip size is already set into the page zip */
5043 buf_LRU_add_block(bpage, true /* to old blocks */);
5044 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
5045 buf_LRU_insert_zip_clean(bpage);
5046 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
5047 mutex_exit(&buf_pool->LRU_list_mutex);
5048 buf_page_set_io_fix(bpage, BUF_IO_READ);
5049
5050 mutex_exit(&buf_pool->zip_mutex);
5051 }
5052
5053 buf_pool->n_pend_reads.fetch_add(1);
5054 func_exit:
5055
5056 if (mode == BUF_READ_IBUF_PAGES_ONLY) {
5057 ibuf_mtr_commit(&mtr);
5058 }
5059
5060 ut_ad(!rw_lock_own(hash_lock, RW_LOCK_X));
5061 ut_ad(!rw_lock_own(hash_lock, RW_LOCK_S));
5062 ut_ad(!bpage || buf_page_in_file(bpage));
5063
5064 return (bpage);
5065 }
5066
5067 buf_block_t *buf_page_create(const page_id_t &page_id,
5068 const page_size_t &page_size,
5069 rw_lock_type_t rw_latch, mtr_t *mtr) {
5070 buf_frame_t *frame;
5071 buf_block_t *block;
5072 buf_block_t *free_block = nullptr;
5073 buf_pool_t *buf_pool = buf_pool_get(page_id);
5074 rw_lock_t *hash_lock;
5075
5076 ut_ad(mtr->is_active());
5077 ut_ad(page_id.space() != 0 || !page_size.is_compressed());
5078
5079 free_block = buf_LRU_get_free_block(buf_pool);
5080
5081 for (;;) {
5082 mutex_enter(&buf_pool->LRU_list_mutex);
5083
5084 hash_lock = buf_page_hash_lock_get(buf_pool, page_id);
5085
5086 rw_lock_x_lock(hash_lock, UT_LOCATION_HERE);
5087
5088 block = (buf_block_t *)buf_page_hash_get_low(buf_pool, page_id);
5089
5090 if (block && buf_page_in_file(&block->page) &&
5091 !buf_pool_watch_is_sentinel(buf_pool, &block->page)) {
5092 if (block->page.was_stale()) {
5093 /* We must release page hash latch. The LRU mutex protects the block
5094 from being relocated or freed. */
5095 rw_lock_x_unlock(hash_lock);
5096
5097 if (!buf_page_free_stale(buf_pool, &block->page)) {
5098 /* The page is during IO and can't be released. We wait some to not go
5099 into loop that would consume CPU. This is not something that will be
5100 hit frequently. */
5101 mutex_exit(&buf_pool->LRU_list_mutex);
5102 std::this_thread::sleep_for(std::chrono::microseconds(100));
5103 }
5104 /* The hash lock was released, we should try again lookup for the page
5105 until it's gone - it should disappear eventually when the IO ends. */
5106 continue;
5107 }
5108
5109 #ifdef UNIV_IBUF_COUNT_DEBUG
5110 ut_a(ibuf_count_get(page_id) == 0);
5111 #endif /* UNIV_IBUF_COUNT_DEBUG */
5112
5113 ut_d(block->page.file_page_was_freed = false);
5114
5115 ut_ad(!block->page.was_stale());
5116
5117 /* Page can be found in buf_pool */
5118 mutex_exit(&buf_pool->LRU_list_mutex);
5119 rw_lock_x_unlock(hash_lock);
5120
5121 buf_block_free(free_block);
5122
5123 return (
5124 buf_page_get(page_id, page_size, rw_latch, UT_LOCATION_HERE, mtr));
5125 }
5126 break;
5127 }
5128 /* If we get here, the page was not in buf_pool: init it there */
5129
5130 DBUG_PRINT("ib_buf", ("create page " UINT32PF ":" UINT32PF, page_id.space(),
5131 page_id.page_no()));
5132
5133 block = free_block;
5134
5135 buf_page_mutex_enter(block);
5136
5137 buf_page_init(buf_pool, page_id, page_size, block);
5138
5139 buf_block_buf_fix_inc(block, UT_LOCATION_HERE);
5140
5141 buf_page_set_accessed(&block->page);
5142
5143 mutex_exit(&block->mutex);
5144
5145 /* Latch the page before releasing hash lock so that concurrent request for
5146 this page doesn't see half initialized page. ALTER tablespace for encryption
5147 and clone page copy can request page for any page id within tablespace
5148 size limit. */
5149 mtr_memo_type_t mtr_latch_type;
5150
5151 if (rw_latch == RW_X_LATCH) {
5152 rw_lock_x_lock(&block->lock, UT_LOCATION_HERE);
5153 mtr_latch_type = MTR_MEMO_PAGE_X_FIX;
5154 } else {
5155 rw_lock_sx_lock(&block->lock, UT_LOCATION_HERE);
5156 mtr_latch_type = MTR_MEMO_PAGE_SX_FIX;
5157 }
5158 mtr_memo_push(mtr, block, mtr_latch_type);
5159
5160 rw_lock_x_unlock(hash_lock);
5161
5162 /* The block must be put to the LRU list */
5163 buf_LRU_add_block(&block->page, false);
5164
5165 buf_pool->stat.n_pages_created.fetch_add(1);
5166
5167 if (page_size.is_compressed()) {
5168 mutex_exit(&buf_pool->LRU_list_mutex);
5169
5170 auto data = buf_buddy_alloc(buf_pool, page_size.physical());
5171
5172 mutex_enter(&buf_pool->LRU_list_mutex);
5173
5174 buf_page_mutex_enter(block);
5175 block->page.zip.data = (page_zip_t *)data;
5176 buf_page_mutex_exit(block);
5177
5178 /* To maintain the invariant
5179 block->in_unzip_LRU_list
5180 == buf_page_belongs_to_unzip_LRU(&block->page)
5181 we have to add this block to unzip_LRU after
5182 block->page.zip.data is set. */
5183 ut_ad(buf_page_belongs_to_unzip_LRU(&block->page));
5184 buf_unzip_LRU_add_block(block, false);
5185 }
5186
5187 mutex_exit(&buf_pool->LRU_list_mutex);
5188
5189 /* Change buffer will not contain entries for undo tablespaces or temporary
5190 tablespaces. */
5191 bool skip_ibuf = fsp_is_system_temporary(page_id.space()) ||
5192 fsp_is_undo_tablespace(page_id.space());
5193
5194 if (!skip_ibuf) {
5195 /* Delete possible entries for the page from the insert buffer:
5196 such can exist if the page belonged to an index which was dropped */
5197 ibuf_merge_or_delete_for_page(nullptr, page_id, &page_size, true);
5198 }
5199
5200 frame = block->frame;
5201
5202 memset(frame + FIL_PAGE_PREV, 0xff, 4);
5203 memset(frame + FIL_PAGE_NEXT, 0xff, 4);
5204 mach_write_to_2(frame + FIL_PAGE_TYPE, FIL_PAGE_TYPE_ALLOCATED);
5205
5206 /* These 8 bytes are also repurposed for PageIO compression and must
5207 be reset when the frame is assigned to a new page id. See fil0fil.h.
5208
5209 The LSN stored at offset FIL_PAGE_FILE_FLUSH_LSN is used on the
5210 following pages:
5211 (1) The first page of the InnoDB system tablespace (page 0:0)
5212 (2) FIL_RTREE_SPLIT_SEQ_NUM on R-tree pages .
5213
5214 Therefore we don't transparently compress such pages. */
5215
5216 memset(frame + FIL_PAGE_FILE_FLUSH_LSN, 0, 8);
5217
5218 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
5219 ut_a(++buf_dbg_counter % 5771 || buf_validate());
5220 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
5221 #ifdef UNIV_IBUF_COUNT_DEBUG
5222 ut_a(ibuf_count_get(block->page.id) == 0);
5223 #endif
5224 return (block);
5225 }
5226
5227 /** Monitor the buffer page read/write activity, and increment corresponding
5228 counter value if MONITOR_MODULE_BUF_PAGE (module_buf_page) module is
5229 enabled. */
5230 static void buf_page_monitor(
5231 const buf_page_t *bpage, /*!< in: pointer to the block */
5232 enum buf_io_fix io_type) /*!< in: io_fix types */
5233 {
5234 monitor_id_t counter;
5235
5236 ut_a(io_type == BUF_IO_READ || io_type == BUF_IO_WRITE);
5237
5238 const byte *frame = bpage->zip.data != nullptr
5239 ? bpage->zip.data
5240 : ((buf_block_t *)bpage)->frame;
5241
5242 const ulint page_type = fil_page_get_type(frame);
5243
5244 bool is_leaf = false;
5245 bool is_ibuf = false;
5246
5247 if (page_type == FIL_PAGE_INDEX || page_type == FIL_PAGE_RTREE) {
5248 is_leaf = page_is_leaf(frame);
5249
5250 const space_index_t ibuf_index_id =
5251 static_cast<space_index_t>(DICT_IBUF_ID_MIN + IBUF_SPACE_ID);
5252
5253 const uint32_t space_id = bpage->id.space();
5254 const space_index_t idx_id = btr_page_get_index_id(frame);
5255
5256 is_ibuf = space_id == IBUF_SPACE_ID && idx_id == ibuf_index_id;
5257
5258 /* Account reading of leaf pages into the buffer pool(s). */
5259 if (is_leaf && io_type == BUF_IO_READ) {
5260 buf_stat_per_index->inc(index_id_t(space_id, idx_id));
5261 }
5262 }
5263
5264 if (!MONITOR_IS_ON(MONITOR_MODULE_BUF_PAGE)) {
5265 return;
5266 }
5267
5268 switch (page_type) {
5269 case FIL_PAGE_INDEX:
5270 /* Check if it is an index page for insert buffer */
5271 if (is_ibuf) {
5272 if (is_leaf) {
5273 counter = MONITOR_RW_COUNTER(io_type, MONITOR_INDEX_IBUF_LEAF_PAGE);
5274 } else {
5275 counter =
5276 MONITOR_RW_COUNTER(io_type, MONITOR_INDEX_IBUF_NON_LEAF_PAGE);
5277 }
5278 break;
5279 }
5280 [[fallthrough]];
5281 case FIL_PAGE_RTREE:
5282 if (is_leaf) {
5283 counter = MONITOR_RW_COUNTER(io_type, MONITOR_INDEX_LEAF_PAGE);
5284 } else {
5285 counter = MONITOR_RW_COUNTER(io_type, MONITOR_INDEX_NON_LEAF_PAGE);
5286 }
5287 break;
5288
5289 case FIL_PAGE_UNDO_LOG:
5290 counter = MONITOR_RW_COUNTER(io_type, MONITOR_UNDO_LOG_PAGE);
5291 break;
5292
5293 case FIL_PAGE_INODE:
5294 counter = MONITOR_RW_COUNTER(io_type, MONITOR_INODE_PAGE);
5295 break;
5296
5297 case FIL_PAGE_IBUF_FREE_LIST:
5298 counter = MONITOR_RW_COUNTER(io_type, MONITOR_IBUF_FREELIST_PAGE);
5299 break;
5300
5301 case FIL_PAGE_IBUF_BITMAP:
5302 counter = MONITOR_RW_COUNTER(io_type, MONITOR_IBUF_BITMAP_PAGE);
5303 break;
5304
5305 case FIL_PAGE_TYPE_SYS:
5306 counter = MONITOR_RW_COUNTER(io_type, MONITOR_SYSTEM_PAGE);
5307 break;
5308
5309 case FIL_PAGE_TYPE_TRX_SYS:
5310 counter = MONITOR_RW_COUNTER(io_type, MONITOR_TRX_SYSTEM_PAGE);
5311 break;
5312
5313 case FIL_PAGE_TYPE_FSP_HDR:
5314 counter = MONITOR_RW_COUNTER(io_type, MONITOR_FSP_HDR_PAGE);
5315 break;
5316
5317 case FIL_PAGE_TYPE_XDES:
5318 counter = MONITOR_RW_COUNTER(io_type, MONITOR_XDES_PAGE);
5319 break;
5320
5321 case FIL_PAGE_TYPE_BLOB:
5322 counter = MONITOR_RW_COUNTER(io_type, MONITOR_BLOB_PAGE);
5323 break;
5324
5325 case FIL_PAGE_TYPE_ZBLOB:
5326 counter = MONITOR_RW_COUNTER(io_type, MONITOR_ZBLOB_PAGE);
5327 break;
5328
5329 case FIL_PAGE_TYPE_ZBLOB2:
5330 counter = MONITOR_RW_COUNTER(io_type, MONITOR_ZBLOB2_PAGE);
5331 break;
5332
5333 case FIL_PAGE_TYPE_RSEG_ARRAY:
5334 counter = MONITOR_RW_COUNTER(io_type, MONITOR_RSEG_ARRAY_PAGE);
5335 break;
5336
5337 default:
5338 counter = MONITOR_RW_COUNTER(io_type, MONITOR_OTHER_PAGE);
5339 }
5340
5341 MONITOR_INC_NOCHECK(counter);
5342 }
5343
5344 /** Unfixes the page, unlatches the page,
5345 removes it from page_hash and removes it from LRU.
5346 @param[in,out] bpage pointer to the block */
5347 void buf_read_page_handle_error(buf_page_t *bpage) {
5348 buf_pool_t *buf_pool = buf_pool_from_bpage(bpage);
5349 const auto uncompressed = (buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE);
5350
5351 /* First unfix and release lock on the bpage */
5352 mutex_enter(&buf_pool->LRU_list_mutex);
5353
5354 rw_lock_t *hash_lock = buf_page_hash_lock_get(buf_pool, bpage->id);
5355
5356 rw_lock_x_lock(hash_lock, UT_LOCATION_HERE);
5357
5358 mutex_enter(buf_page_get_mutex(bpage));
5359
5360 ut_ad(buf_page_get_io_fix(bpage) == BUF_IO_READ);
5361 ut_ad(bpage->buf_fix_count == 0);
5362
5363 /* Set BUF_IO_NONE before we remove the block from LRU list */
5364 buf_page_set_io_fix(bpage, BUF_IO_NONE);
5365
5366 if (uncompressed) {
5367 rw_lock_x_unlock_gen(&((buf_block_t *)bpage)->lock, BUF_IO_READ);
5368 }
5369
5370 /* The hash lock and block mutex will be released during the "free" */
5371 buf_LRU_free_one_page(bpage, true);
5372
5373 ut_ad(!rw_lock_own(hash_lock, RW_LOCK_X) &&
5374 !rw_lock_own(hash_lock, RW_LOCK_S));
5375
5376 mutex_exit(&buf_pool->LRU_list_mutex);
5377
5378 ut_ad(buf_pool->n_pend_reads > 0);
5379 buf_pool->n_pend_reads.fetch_sub(1);
5380 }
5381
5382 bool buf_page_free_stale(buf_pool_t *buf_pool, buf_page_t *bpage) noexcept {
5383 /* If a page was seen as stale it will still be stale, because we have LRU
5384 mutex.*/
5385 ut_ad(bpage->was_stale());
5386 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
5387
5388 auto *block_mutex = buf_page_get_mutex(bpage);
5389
5390 mutex_enter(block_mutex);
5391
5392 /* At this point the page can be queued for flushing. */
5393
5394 const auto io_type = buf_page_get_io_fix(bpage);
5395
5396 bool success = false;
5397 if (io_type == BUF_IO_NONE) {
5398 if (bpage->is_dirty()) {
5399 buf_flush_remove(bpage);
5400 }
5401 success = buf_LRU_free_page(bpage, true);
5402 }
5403
5404 if (success) {
5405 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
5406 } else {
5407 mutex_exit(block_mutex);
5408 ut_ad(mutex_own(&buf_pool->LRU_list_mutex));
5409 }
5410
5411 ut_ad(!mutex_own(block_mutex));
5412 return success;
5413 }
5414
5415 bool buf_page_free_stale(buf_pool_t *buf_pool, buf_page_t *bpage,
5416 rw_lock_t *hash_lock) noexcept {
5417 /* This method's task is to acquire the LRU mutex so that the LRU version of
5418 this method can be called.*/
5419
5420 /* hash_lock protects access to bpage's cell, so it could not be freed in
5421 meantime by someone else. */
5422 ut_ad(hash_lock == buf_page_hash_lock_get(buf_pool, bpage->id));
5423 /* the lock is taken in S-mode */
5424 ut_ad(rw_lock_own(hash_lock, RW_LOCK_S));
5425 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
5426
5427 if (bpage->was_io_fixed()) {
5428 /* This method must release the hash lock before exiting. */
5429 rw_lock_s_unlock(hash_lock);
5430 return false;
5431 }
5432
5433 /* Hash lock is lower in order than the LRU list mutex, we have to release
5434 it in order to acquire the LRU mutex. To prevent other threads from freeing
5435 the stale block we increase the fix count so that the page can't be freed
5436 by other threads.
5437 The block fixing is only valid for file pages.
5438 Currently only the non-compressed tables can be truncated (instead of space
5439 being deleted and replaced with a new one with the same name, but different
5440 ID. Thus more strict `buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE`
5441 would currently hold. */
5442 ut_ad(buf_page_in_file(bpage));
5443 buf_block_fix(bpage);
5444
5445 rw_lock_s_unlock(hash_lock);
5446
5447 DBUG_EXECUTE_IF("buf_page_free_stale_delay_lru_mutex_acquisition",
5448 std::this_thread::sleep_for(std::chrono::milliseconds(10)););
5449
5450 mutex_enter(&buf_pool->LRU_list_mutex);
5451
5452 /* Prepare to free, we own the LRU. */
5453 buf_block_unfix(bpage);
5454
5455 auto success = buf_page_free_stale(buf_pool, bpage);
5456
5457 if (!success) {
5458 mutex_exit(&buf_pool->LRU_list_mutex);
5459 }
5460
5461 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
5462 return success;
5463 }
5464
5465 void buf_page_free_stale_during_write(buf_page_t *bpage,
5466 bool owns_sx_lock) noexcept {
5467 auto buf_pool = buf_pool_from_bpage(bpage);
5468
5469 ut_a(bpage->is_io_fix_write());
5470 ut_ad(bpage->current_thread_has_io_responsibility());
5471
5472 mutex_enter(&buf_pool->LRU_list_mutex);
5473
5474 auto block_mutex = buf_page_get_mutex(bpage);
5475 mutex_enter(block_mutex);
5476
5477 /* The page is IO-fixed, so if it was seen stale, it would not be freed in
5478 meantime. */
5479 ut_a(bpage->was_stale());
5480 ut_a(buf_page_in_file(bpage));
5481
5482 if (owns_sx_lock) {
5483 rw_lock_sx_unlock_gen(&((buf_block_t *)bpage)->lock, BUF_IO_WRITE);
5484 }
5485
5486 const auto io_type = buf_page_get_io_fix(bpage);
5487 const auto flush_type = buf_page_get_flush_type(bpage);
5488
5489 ut_a(io_type == BUF_IO_WRITE);
5490
5491 mutex_enter(&buf_pool->flush_state_mutex);
5492
5493 if (bpage->is_dirty()) {
5494 buf_flush_remove(bpage);
5495 }
5496
5497 /* The current thread is responsible for the write IO, so we are allowed to
5498 reset it back to BUF_IO_NONE. */
5499 buf_page_set_io_fix(bpage, BUF_IO_NONE);
5500
5501 ut_a(owns_sx_lock || buf_page_get_state(bpage) != BUF_BLOCK_FILE_PAGE);
5502
5503 /* Since we aborted a write request. We need to adjust the number of
5504 of outstanding write requests. */
5505 --buf_pool->n_flush[flush_type];
5506
5507 mutex_exit(&buf_pool->flush_state_mutex);
5508
5509 /* Free the page. This can fail, if some other thread start to free this stale
5510 page during page creation - the buf_page_free_stale will buf fix the page to
5511 acquire the LRU mutex, and right before that acquisition happens our thread
5512 can be during a flush that will end up on this line.*/
5513 if (!buf_LRU_free_page(bpage, true)) {
5514 mutex_exit(block_mutex);
5515 mutex_exit(&buf_pool->LRU_list_mutex);
5516 }
5517
5518 ut_ad(!mutex_own(block_mutex));
5519 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
5520 }
5521
5522 #ifdef UNIV_DEBUG
5523 /* Possible io_buf states and transitions between them, with latches required
5524 for transition.
5525 @see buf_page_t::Latching_rules_helpers::get_owned_latches() for the meaning of
5526 the numbers on edges.
5527
5528 +-----------+ +------------+
5529 |BUF_IO_NONE| --------0&&2-----> |BUF_IO_READ |
5530 | | <-------0&&2------ +------------+
5531 | |
5532 | | +------------+
5533 | | -----0&&1&&2-----> |BUF_IO_WRITE|
5534 | | <----0&&1&&2------ +------------+
5535 | |
5536 | | +------------+
5537 | | ---------0--------> | BUF_IO_PIN |
5538 +-----------+ <--------0--------- +------------+
5539 */
5540 using Buf_io_fix_latching_rules = ut::Stateful_latching_rules<buf_io_fix, 3>;
5541 Buf_io_fix_latching_rules buf_io_fix_latching_rules{
5542 {BUF_IO_NONE, BUF_IO_READ, BUF_IO_WRITE, BUF_IO_PIN},
5543 {
5544 {BUF_IO_NONE, {0, 2}, BUF_IO_READ},
5545 {BUF_IO_READ, {0, 2}, BUF_IO_NONE},
5546 {BUF_IO_NONE, {0, 1, 2}, BUF_IO_WRITE},
5547 {BUF_IO_WRITE, {0, 1, 2}, BUF_IO_NONE},
5548 {BUF_IO_NONE, {0}, BUF_IO_PIN},
5549 {BUF_IO_PIN, {0}, BUF_IO_NONE},
5550 },
5551 };
5552 /** The purpose of this class is to hide the knowledge that
5553 Buf_io_fix_latching_rules even exists from users of buf_page_t class, while also
5554 avoiding having to tediously repeat yourself in each place where buf_page_t's
5555 implementation needs to pass typical arguments to Buf_io_fix_latching_rules such
5556 as owned_latches or current state, which require access to private fields of
5557 buf_page_t.
5558 So, the members of Latching_rules_helpers are conceptually like private methods
5559 of buf_page_t, but not exposed in the buf0buf.h file, so nobody else has to
5560 know about them. */
5561 class buf_page_t::Latching_rules_helpers {
5562 public:
5563 /** Retrieves the set of latches held by current thread which are relevant to
5564 latching rules for the io_fix field of a given page.
5565 @param[in] page the page which has the io_fix field we care about
5566 @return the latches currently held by current thread */
5567 static Buf_io_fix_latching_rules::latches_set_t get_owned_latches(
5568 const buf_page_t &page) {
5569 const auto buf_pool = buf_pool_from_bpage(&page);
5570 Buf_io_fix_latching_rules::latches_set_t result{};
5571 result[0] = mutex_own(buf_page_get_mutex(&page));
5572 result[1] = mutex_own(&buf_pool->flush_state_mutex);
5573 result[2] = page.io_responsibility.current_thread_is_responsible();
5574 return result;
5575 }
5576 /** Checks if the current thread owns latches which are sufficient for a
5577 given page to meaningfully ask a question if page's io_fix value belongs to
5578 set A as opposed to set B. In particular it assumes that current thread indeed
5579 holds the latches preventing a state transition from A to outside of A, and
5580 from B to outside of B. Otherwise it prints error message to stderr and
5581 triggers assertion failure.
5582 @param[in] page the page which has the io_fix field we care about
5583 @param[in] A first set of buf_io_fix values
5584 @param[in] B second set of buf_io_fix values */
5585 static void assert_latches_let_distinguish(
5586 const buf_page_t &page, const Buf_io_fix_latching_rules::nodes_set_t &A,
5587 const Buf_io_fix_latching_rules::nodes_set_t &B) {
5588 buf_io_fix_latching_rules.assert_latches_let_distinguish(
5589 get_owned_latches(page), A, B);
5590 }
5591 /** This is a convenience function the special case of the
5592 @see own_latches_to_distinguish(page,A,B) where B is the complement of A.
5593 @param[in] page the page which has the io_fix field we care about
5594 @param[in] A a set of buf_io_fix values */
5595 static void assert_latches_let_distinguish(
5596 const buf_page_t &page, const Buf_io_fix_latching_rules::nodes_set_t &A) {
5597 buf_io_fix_latching_rules.assert_latches_let_distinguish(
5598 get_owned_latches(page), A);
5599 }
5600
5601 /** Verifies that the current thread holds one of allowed sets of latches for
5602 a given transition from current page's io_fix state to new_state. Otherwise
5603 prints an error to std::cerr and triggers assertion failure
5604 @param[in] page the page which will change io_fix state
5605 @param[in] new_state the new desired state of io_fix for this page */
5606 static void on_transition_to(
5607 const buf_page_t &page,
5608 const Buf_io_fix_latching_rules::node_t &new_state) {
5609 buf_io_fix_latching_rules.on_transition(page.io_fix, new_state,
5610 get_owned_latches(page));
5611 }
5612 };
5613 #endif /* UNIV_DEBUG */
5614
5615 bool buf_page_t::is_io_fix_write() const {
5616 ut_d(Latching_rules_helpers::assert_latches_let_distinguish(*this,
5617 {BUF_IO_WRITE}));
5618 return get_io_fix_snapshot() == BUF_IO_WRITE;
5619 }
5620
5621 bool buf_page_t::is_io_fix_read() const {
5622 ut_d(Latching_rules_helpers::assert_latches_let_distinguish(*this,
5623 {BUF_IO_READ}));
5624 return get_io_fix_snapshot() == BUF_IO_READ;
5625 }
5626
5627 bool buf_page_t::is_io_fix_read_as_opposed_to_write() const {
5628 ut_d(Latching_rules_helpers::assert_latches_let_distinguish(
5629 *this, {BUF_IO_READ}, {BUF_IO_WRITE}));
5630 const auto seen = get_io_fix_snapshot();
5631 ut_a(seen == BUF_IO_READ || seen == BUF_IO_WRITE);
5632 return seen == BUF_IO_READ;
5633 }
5634
5635 void buf_page_t::set_io_fix(buf_io_fix io_fix) {
5636 ut_ad(is_correct_io_fix_value(io_fix));
5637 ut_ad(mutex_own(buf_page_get_mutex(this)));
5638 #ifdef UNIV_DEBUG
5639 const auto old_io_fix = this->io_fix.load();
5640 if (old_io_fix == BUF_IO_NONE &&
5641 (io_fix == BUF_IO_READ || io_fix == BUF_IO_WRITE)) {
5642 take_io_responsibility();
5643 }
5644 #endif
5645 ut_d(Latching_rules_helpers::on_transition_to(*this, io_fix));
5646 this->io_fix.store(io_fix, std::memory_order_relaxed);
5647 #ifdef UNIV_DEBUG
5648 if ((old_io_fix == BUF_IO_READ || old_io_fix == BUF_IO_WRITE) &&
5649 io_fix == BUF_IO_NONE) {
5650 release_io_responsibility();
5651 }
5652 #endif
5653 }
5654
5655 bool buf_page_io_complete(buf_page_t *bpage, bool evict) {
5656 auto buf_pool = buf_pool_from_bpage(bpage);
5657 const bool uncompressed = (buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE);
5658
5659 ut_a(buf_page_in_file(bpage));
5660
5661 /* We do not need protect io_fix here by mutex to read it because this is the
5662 only function where we can change the value from BUF_IO_READ or BUF_IO_WRITE
5663 to some other value, and our code ensures that this is the only thread that
5664 handles the i/o for this block. There are other methods that reset the IO to
5665 NONE, but they must do that before the IO is requested to OS and must be done
5666 as a part of cleanup in thread that was trying to make such IO request. */
5667
5668 ut_ad(bpage->current_thread_has_io_responsibility());
5669 const auto io_type =
5670 bpage->is_io_fix_read_as_opposed_to_write() ? BUF_IO_READ : BUF_IO_WRITE;
5671 const auto flush_type = buf_page_get_flush_type(bpage);
5672
5673 if (io_type == BUF_IO_READ) {
5674 bool compressed_page;
5675 byte *frame{};
5676 page_no_t read_page_no;
5677 space_id_t read_space_id;
5678 bool is_wrong_page_id [[maybe_unused]] = false;
5679
5680 if (bpage->size.is_compressed()) {
5681 frame = bpage->zip.data;
5682 buf_pool->n_pend_unzip.fetch_add(1);
5683 if (uncompressed && !buf_zip_decompress((buf_block_t *)bpage, false)) {
5684 buf_pool->n_pend_unzip.fetch_sub(1);
5685
5686 compressed_page = false;
5687 goto corrupt;
5688 }
5689 buf_pool->n_pend_unzip.fetch_sub(1);
5690 } else {
5691 frame = reinterpret_cast<buf_block_t *>(bpage)->frame;
5692 ut_a(uncompressed);
5693 }
5694
5695 /* If this page is not uninitialized and not in the
5696 doublewrite buffer, then the page number and space id
5697 should be the same as in block. */
5698 read_page_no = mach_read_from_4(frame + FIL_PAGE_OFFSET);
5699 read_space_id = mach_read_from_4(frame + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
5700
5701 if (bpage->id.space() == TRX_SYS_SPACE &&
5702 dblwr::v1::is_inside(bpage->id.page_no())) {
5703 ib::error(ER_IB_MSG_78) << "Reading page " << bpage->id
5704 << ", which is in the doublewrite buffer!";
5705
5706 } else if (read_space_id == 0 && read_page_no == 0) {
5707 /* This is likely an uninitialized page. */
5708 } else if ((bpage->id.space() != 0 && bpage->id.space() != read_space_id) ||
5709 bpage->id.page_no() != read_page_no) {
5710 /* We did not compare space_id to read_space_id
5711 if bpage->space == 0, because the field on the
5712 page may contain garbage in MySQL < 4.1.1,
5713 which only supported bpage->space == 0. */
5714
5715 ib::error(ER_IB_MSG_79) << "Space id and page number stored in "
5716 "the page read in are "
5717 << page_id_t(read_space_id, read_page_no)
5718 << ", should be " << bpage->id;
5719 is_wrong_page_id = true;
5720 }
5721
5722 compressed_page = Compression::is_compressed_page(frame);
5723
5724 /* If the decompress failed then the most likely case is
5725 that we are reading in a page for which this instance doesn't
5726 support the compression algorithm. */
5727 if (compressed_page) {
5728 Compression::meta_t meta;
5729
5730 Compression::deserialize_header(frame, &meta);
5731
5732 ib::error(ER_IB_MSG_80)
5733 << "Page " << bpage->id << " "
5734 << "compressed with " << Compression::to_string(meta) << " "
5735 << "that is not supported by this instance";
5736 }
5737
5738 /* From version 3.23.38 up we store the page checksum
5739 to the 4 first bytes of the page end lsn field */
5740 bool is_corrupted;
5741 {
5742 BlockReporter reporter =
5743 BlockReporter(true, frame, bpage->size,
5744 fsp_is_checksum_disabled(bpage->id.space()));
5745 is_corrupted = reporter.is_corrupted();
5746 }
5747
5748 #ifdef UNIV_LINUX
5749 /* A crash during extending file might cause the inconsistent contents.
5750 No problem for the cases. Just fills with zero for them.
5751 - The next log record to apply is initializing
5752 - No redo log record for the page yet (brand new page) */
5753 if (recv_recovery_is_on() && (is_corrupted || is_wrong_page_id) &&
5754 recv_page_is_brand_new((buf_block_t *)bpage)) {
5755 memset(frame, 0, bpage->size.logical());
5756 is_corrupted = false;
5757 }
5758 #endif /* UNIV_LINUX */
5759
5760 if (compressed_page || is_corrupted) {
5761 /* Not a real corruption if it was triggered by
5762 error injection */
5763 DBUG_EXECUTE_IF("buf_page_import_corrupt_failure",
5764 goto page_not_corrupt;);
5765
5766 corrupt:
5767 /* Compressed pages are basically gibberish avoid
5768 printing the contents. */
5769 if (!compressed_page) {
5770 ib::error(ER_IB_MSG_81)
5771 << "Database page corruption on disk"
5772 " or a failed file read of page "
5773 << bpage->id << ". You may have to recover from "
5774 << "a backup.";
5775
5776 buf_page_print(frame, bpage->size, BUF_PAGE_PRINT_NO_CRASH);
5777
5778 ib::info(ER_IB_MSG_82) << "It is also possible that your"
5779 " operating system has corrupted"
5780 " its own file cache and rebooting"
5781 " your computer removes the error."
5782 " If the corrupt page is an index page."
5783 " You can also try to fix the"
5784 " corruption by dumping, dropping,"
5785 " and reimporting the corrupt table."
5786 " You can use CHECK TABLE to scan"
5787 " your table for corruption. "
5788 << FORCE_RECOVERY_MSG;
5789 }
5790
5791 if (srv_force_recovery < SRV_FORCE_IGNORE_CORRUPT) {
5792 /* We do not have to mark any index as
5793 corrupted here, since we only know the space
5794 id but not the exact index id. There could
5795 be multiple tables/indexes in the same space,
5796 so we will mark it later in upper layer */
5797
5798 buf_read_page_handle_error(bpage);
5799 return (false);
5800 }
5801 }
5802
5803 DBUG_EXECUTE_IF("buf_page_import_corrupt_failure", page_not_corrupt
5804 : bpage = bpage;);
5805
5806 if (recv_recovery_is_on()) {
5807 /* Pages must be uncompressed for crash recovery. */
5808 ut_a(uncompressed);
5809 recv_recover_page(true, (buf_block_t *)bpage);
5810 }
5811
5812 if (uncompressed && !Compression::is_compressed_page(frame) &&
5813 !recv_no_ibuf_operations &&
5814 fil_page_get_type(frame) == FIL_PAGE_INDEX && page_is_leaf(frame) &&
5815 !fsp_is_system_temporary(bpage->id.space()) &&
5816 !fsp_is_undo_tablespace(bpage->id.space()) && !bpage->was_stale()) {
5817 ibuf_merge_or_delete_for_page((buf_block_t *)bpage, bpage->id,
5818 &bpage->size, true);
5819 }
5820 }
5821
5822 bool has_LRU_mutex = false;
5823
5824 auto block_mutex = buf_page_get_mutex(bpage);
5825
5826 if (io_type == BUF_IO_WRITE) {
5827 /* We decide whether or not to evict the page from the
5828 LRU list based on the flush_type.
5829 - BUF_FLUSH_LIST: don't evict
5830 - BUF_FLUSH_LRU: always evict
5831 - BUF_FLUSH_SINGLE_PAGE: eviction preference is passed
5832 by the caller explicitly. */
5833 ut_ad(!(flush_type == BUF_FLUSH_LIST && evict));
5834 if (flush_type == BUF_FLUSH_LRU) {
5835 evict = true;
5836 }
5837 if (evict
5838 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
5839 /* The LRU mutex is required on debug in this path:
5840 buf_flush_write_complete (called later in this method) ->
5841 buf_flush_remove -> buf_LRU_insert_zip_clean().
5842 It is safe to query the page state without mutex protection, as
5843 transition to BUF_BLOCK_ZIP_DIRTY is possible only when the page
5844 descriptor is initialized. Assuming this thread has the IO
5845 responsibility (which is assured earlier in this method), the
5846 transitions from the BUF_BLOCK_ZIP_DIRTY are only allowed from this
5847 thread and no one else can modify the state. */
5848 || buf_page_get_state(bpage) == BUF_BLOCK_ZIP_DIRTY
5849 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
5850 ) {
5851 has_LRU_mutex = true;
5852 mutex_enter(&buf_pool->LRU_list_mutex);
5853 }
5854 }
5855 mutex_enter(block_mutex);
5856
5857 #ifdef UNIV_IBUF_COUNT_DEBUG
5858 if (io_type == BUF_IO_WRITE || uncompressed) {
5859 /* For BUF_IO_READ of compressed-only blocks, the
5860 buffered operations will be merged by buf_page_get_gen()
5861 after the block has been uncompressed. */
5862 ut_a(ibuf_count_get(bpage->id) == 0);
5863 }
5864 #endif /* UNIV_IBUF_COUNT_DEBUG */
5865
5866 /* Because this thread which does the unlocking is not the same that
5867 did the locking, we use a pass value != 0 in unlock, which simply
5868 removes the newest lock debug record, without checking the thread
5869 id. */
5870
5871 buf_page_monitor(bpage, io_type);
5872
5873 switch (io_type) {
5874 case BUF_IO_READ:
5875
5876 ut_ad(!has_LRU_mutex);
5877
5878 buf_page_set_io_fix(bpage, BUF_IO_NONE);
5879
5880 /* NOTE that the call to ibuf may have moved the ownership of
5881 the x-latch to this OS thread: do not let this confuse you in
5882 debugging! */
5883
5884 if (uncompressed) {
5885 rw_lock_x_unlock_gen(&((buf_block_t *)bpage)->lock, BUF_IO_READ);
5886 }
5887
5888 mutex_exit(block_mutex);
5889
5890 ut_ad(buf_pool->n_pend_reads > 0);
5891 buf_pool->n_pend_reads.fetch_sub(1);
5892 buf_pool->stat.n_pages_read.fetch_add(1);
5893
5894 break;
5895
5896 case BUF_IO_WRITE:
5897 /* Write means a flush operation: call the completion
5898 routine in the flush system */
5899
5900 buf_flush_write_complete(bpage);
5901
5902 if (uncompressed) {
5903 rw_lock_sx_unlock_gen(&((buf_block_t *)bpage)->lock, BUF_IO_WRITE);
5904 }
5905
5906 buf_pool->stat.n_pages_written.fetch_add(1);
5907
5908 ut_ad(!(evict && !has_LRU_mutex));
5909 if (evict && buf_LRU_free_page(bpage, true)) {
5910 has_LRU_mutex = false;
5911 } else {
5912 mutex_exit(block_mutex);
5913 }
5914 if (has_LRU_mutex) {
5915 mutex_exit(&buf_pool->LRU_list_mutex);
5916 }
5917
5918 break;
5919
5920 default:
5921 ut_error;
5922 }
5923
5924 DBUG_PRINT("ib_buf", ("%s page " UINT32PF ":" UINT32PF,
5925 io_type == BUF_IO_READ ? "read" : "wrote",
5926 bpage->id.space(), bpage->id.page_no()));
5927
5928 return (true);
5929 }
5930
5931 /** Asserts that all file pages in the buffer are in a replaceable state.
5932 @param[in] buf_pool buffer pool instance */
5933 static void buf_assert_all_are_replaceable(buf_pool_t *buf_pool) {
5934 ut_ad(buf_pool);
5935
5936 buf_chunk_t *chunk = buf_pool->chunks;
5937
5938 for (auto i = buf_pool->n_chunks; i--; chunk++) {
5939 mutex_enter(&buf_pool->LRU_list_mutex);
5940 buf_assert_all_are_replaceable(chunk);
5941 mutex_exit(&buf_pool->LRU_list_mutex);
5942 }
5943 }
5944
5945 /** Refreshes the statistics used to print per-second averages.
5946 @param[in,out] buf_pool buffer pool instance */
5947 static void buf_refresh_io_stats(buf_pool_t *buf_pool) {
5948 buf_pool->last_printout_time = std::chrono::steady_clock::now();
5949
5950 buf_pool_stat_t::copy(buf_pool->old_stat, buf_pool->stat);
5951 }
5952
5953 /** Invalidates file pages in one buffer pool instance
5954 @param[in] buf_pool buffer pool instance */
5955 static void buf_pool_invalidate_instance(buf_pool_t *buf_pool) {
5956 ulint i;
5957
5958 ut_ad(!mutex_own(&buf_pool->LRU_list_mutex));
5959
5960 mutex_enter(&buf_pool->flush_state_mutex);
5961
5962 for (i = BUF_FLUSH_LRU; i < BUF_FLUSH_N_TYPES; i++) {
5963 /* As this function is called during startup and
5964 during redo application phase during recovery, InnoDB
5965 is single threaded (apart from IO helper threads) at
5966 this stage. No new write batch can be in initialization
5967 stage at this point. */
5968 ut_ad(buf_pool->init_flush[i] == false);
5969
5970 /* However, it is possible that a write batch that has
5971 been posted earlier is still not complete. For buffer
5972 pool invalidation to proceed we must ensure there is NO
5973 write activity happening. */
5974 if (buf_pool->n_flush[i] > 0) {
5975 buf_flush_t type = static_cast<buf_flush_t>(i);
5976
5977 mutex_exit(&buf_pool->flush_state_mutex);
5978 buf_flush_wait_batch_end(buf_pool, type);
5979 mutex_enter(&buf_pool->flush_state_mutex);
5980 }
5981 }
5982
5983 mutex_exit(&buf_pool->flush_state_mutex);
5984
5985 ut_d(buf_assert_all_are_replaceable(buf_pool));
5986
5987 while (buf_LRU_scan_and_free_block(buf_pool, true)) {
5988 }
5989
5990 mutex_enter(&buf_pool->LRU_list_mutex);
5991
5992 ut_ad(UT_LIST_GET_LEN(buf_pool->LRU) == 0);
5993 ut_ad(UT_LIST_GET_LEN(buf_pool->unzip_LRU) == 0);
5994
5995 buf_pool->freed_page_clock = 0;
5996 buf_pool->LRU_old = nullptr;
5997 buf_pool->LRU_old_len = 0;
5998
5999 mutex_exit(&buf_pool->LRU_list_mutex);
6000
6001 buf_pool->stat.reset();
6002 buf_refresh_io_stats(buf_pool);
6003 }
6004
6005 /** Invalidates the file pages in the buffer pool when an archive recovery is
6006 completed. All the file pages buffered must be in a replaceable state when
6007 this function is called: not latched and not modified. */
6008 void buf_pool_invalidate(void) {
6009 ulint i;
6010
6011 for (i = 0; i < srv_buf_pool_instances; i++) {
6012 buf_pool_invalidate_instance(buf_pool_from_array(i));
6013 }
6014 }
6015
6016 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
6017 /** Validates data in one buffer pool instance
6018 @param[in] buf_pool buffer pool instance */
6019 static void buf_pool_validate_instance(buf_pool_t *buf_pool) {
6020 buf_chunk_t *chunk;
6021 ulint i;
6022 ulint n_lru_flush = 0;
6023 ulint n_page_flush = 0;
6024 ulint n_list_flush = 0;
6025 ulint n_lru = 0;
6026 ulint n_flush = 0;
6027 ulint n_free = 0;
6028 ulint n_zip = 0;
6029
6030 ut_ad(buf_pool);
6031
6032 mutex_enter(&buf_pool->chunks_mutex);
6033 mutex_enter(&buf_pool->LRU_list_mutex);
6034 hash_lock_x_all(buf_pool->page_hash);
6035 mutex_enter(&buf_pool->zip_mutex);
6036 mutex_enter(&buf_pool->free_list_mutex);
6037 mutex_enter(&buf_pool->flush_state_mutex);
6038
6039 chunk = buf_pool->chunks;
6040
6041 /* Check the uncompressed blocks. */
6042
6043 for (i = buf_pool->n_chunks; i--; chunk++) {
6044 ulint j;
6045 buf_block_t *block = chunk->blocks;
6046
6047 for (j = chunk->size; j--; block++) {
6048 switch (buf_block_get_state(block)) {
6049 case BUF_BLOCK_POOL_WATCH:
6050 case BUF_BLOCK_ZIP_PAGE:
6051 case BUF_BLOCK_ZIP_DIRTY:
6052 /* These should only occur on
6053 zip_clean, zip_free[], or flush_list. */
6054 ut_error;
6055 break;
6056
6057 case BUF_BLOCK_FILE_PAGE:
6058 ut_a(buf_page_hash_get_low(buf_pool, block->page.id) == &block->page);
6059 /* We can't latch buf_page_mutex_enter(block) as we already hold
6060 lower level latches like free_list_mutex and flush_state_mutex
6061 thus there is no reliable way here to prevent some io_fix
6062 transitions here. Fortunately transitions to and from BUF_IO_WRITE
6063 require flush_state_mutex. */
6064 if (block->page.is_io_fix_write()) {
6065 /* buf_page_set_flush_type() is only called when holding
6066 flush_state_mutex, so we can safely check flush_type value here. */
6067 switch (buf_page_get_flush_type(&block->page)) {
6068 case BUF_FLUSH_LRU:
6069 case BUF_FLUSH_SINGLE_PAGE:
6070 case BUF_FLUSH_LIST:
6071 break;
6072 default:
6073 ut_error;
6074 }
6075 }
6076
6077 n_lru++;
6078 break;
6079
6080 case BUF_BLOCK_NOT_USED:
6081 n_free++;
6082 break;
6083
6084 case BUF_BLOCK_READY_FOR_USE:
6085 case BUF_BLOCK_MEMORY:
6086 case BUF_BLOCK_REMOVE_HASH:
6087 /* do nothing */
6088 break;
6089 }
6090 }
6091 }
6092
6093 /* Check clean compressed-only blocks. */
6094
6095 for (auto b : buf_pool->zip_clean) {
6096 ut_a(buf_page_get_state(b) == BUF_BLOCK_ZIP_PAGE);
6097 switch (buf_page_get_io_fix(b)) {
6098 case BUF_IO_NONE:
6099 case BUF_IO_PIN:
6100 /* All clean blocks should be I/O-unfixed. */
6101 break;
6102 case BUF_IO_READ:
6103 /* In buf_LRU_free_page(), we temporarily set
6104 b->io_fix = BUF_IO_READ for a newly allocated
6105 control block in order to prevent
6106 buf_page_get_gen() from decompressing the block. */
6107 break;
6108 default:
6109 ut_error;
6110 break;
6111 }
6112
6113 /* It is OK to read oldest_modification here because
6114 we have acquired buf_pool->zip_mutex above which acts
6115 as the 'block->mutex' for these bpages. */
6116 ut_a(!b->is_dirty());
6117 ut_a(buf_page_hash_get_low(buf_pool, b->id) == b);
6118 n_lru++;
6119 n_zip++;
6120 }
6121
6122 /* Check dirty blocks. */
6123
6124 buf_flush_list_mutex_enter(buf_pool);
6125 for (auto b : buf_pool->flush_list) {
6126 ut_ad(b->in_flush_list);
6127 ut_a(b->is_dirty());
6128 n_flush++;
6129
6130 switch (buf_page_get_state(b)) {
6131 case BUF_BLOCK_ZIP_DIRTY:
6132 n_lru++;
6133 n_zip++;
6134 [[fallthrough]];
6135 case BUF_BLOCK_FILE_PAGE:
6136 if (b->is_io_fix_write()) {
6137 switch (buf_page_get_flush_type(b)) {
6138 case BUF_FLUSH_LRU:
6139 n_lru_flush++;
6140 break;
6141 case BUF_FLUSH_SINGLE_PAGE:
6142 n_page_flush++;
6143 break;
6144 case BUF_FLUSH_LIST:
6145 n_list_flush++;
6146 break;
6147 default:
6148 ut_error;
6149 }
6150 }
6151 break;
6152 case BUF_BLOCK_POOL_WATCH:
6153 case BUF_BLOCK_ZIP_PAGE:
6154 case BUF_BLOCK_NOT_USED:
6155 case BUF_BLOCK_READY_FOR_USE:
6156 case BUF_BLOCK_MEMORY:
6157 case BUF_BLOCK_REMOVE_HASH:
6158 ut_error;
6159 break;
6160 }
6161 ut_a(buf_page_hash_get_low(buf_pool, b->id) == b);
6162 }
6163
6164 ut_a(UT_LIST_GET_LEN(buf_pool->flush_list) == n_flush);
6165
6166 hash_unlock_x_all(buf_pool->page_hash);
6167 buf_flush_list_mutex_exit(buf_pool);
6168
6169 mutex_exit(&buf_pool->zip_mutex);
6170
6171 if (buf_pool->curr_size == buf_pool->old_size &&
6172 n_lru + n_free > buf_pool->curr_size + n_zip) {
6173 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_84)
6174 << "n_LRU " << n_lru << ", n_free " << n_free << ", pool "
6175 << buf_pool->curr_size << " zip " << n_zip << ". Aborting...";
6176 }
6177
6178 ut_a(UT_LIST_GET_LEN(buf_pool->LRU) == n_lru);
6179
6180 mutex_exit(&buf_pool->LRU_list_mutex);
6181 mutex_exit(&buf_pool->chunks_mutex);
6182
6183 if (buf_pool->curr_size == buf_pool->old_size &&
6184 UT_LIST_GET_LEN(buf_pool->free) > n_free) {
6185 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_85)
6186 << "Free list len " << UT_LIST_GET_LEN(buf_pool->free)
6187 << ", free blocks " << n_free << ". Aborting...";
6188 }
6189
6190 mutex_exit(&buf_pool->free_list_mutex);
6191
6192 ut_a(buf_pool->n_flush[BUF_FLUSH_LIST] == n_list_flush);
6193 ut_a(buf_pool->n_flush[BUF_FLUSH_LRU] == n_lru_flush);
6194 ut_a(buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE] == n_page_flush);
6195
6196 mutex_exit(&buf_pool->flush_state_mutex);
6197
6198 buf_LRU_validate_instance(buf_pool);
6199 ut_a(buf_flush_validate(buf_pool));
6200 }
6201
6202 /** Validates the buffer buf_pool data structure.
6203 @return true */
6204 bool buf_validate(void) {
6205 ulint i;
6206
6207 for (i = 0; i < srv_buf_pool_instances; i++) {
6208 buf_pool_t *buf_pool;
6209
6210 buf_pool = buf_pool_from_array(i);
6211
6212 buf_pool_validate_instance(buf_pool);
6213 }
6214 return true;
6215 }
6216
6217 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
6218
6219 #if defined UNIV_DEBUG_PRINT || defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
6220 /** Prints info of the buffer buf_pool data structure for one instance.
6221 @param[in] buf_pool buffer pool instance */
6222 static void buf_print_instance(buf_pool_t *buf_pool) {
6223 index_id_t *index_ids;
6224 ulint *counts;
6225 ulint size;
6226 ulint i;
6227 ulint j;
6228 ulint n_found;
6229 buf_chunk_t *chunk;
6230
6231 ut_ad(buf_pool);
6232
6233 size = buf_pool->curr_size;
6234
6235 index_ids = static_cast<index_id_t *>(
6236 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, size * sizeof *index_ids));
6237
6238 counts = static_cast<ulint *>(
6239 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(ulint) * size));
6240
6241 mutex_enter(&buf_pool->LRU_list_mutex);
6242 mutex_enter(&buf_pool->free_list_mutex);
6243 mutex_enter(&buf_pool->flush_state_mutex);
6244 buf_flush_list_mutex_enter(buf_pool);
6245
6246 ib::info(ER_IB_MSG_86) << *buf_pool;
6247
6248 buf_flush_list_mutex_exit(buf_pool);
6249 mutex_exit(&buf_pool->flush_state_mutex);
6250 mutex_exit(&buf_pool->free_list_mutex);
6251
6252 /* Count the number of blocks belonging to each index in the buffer */
6253
6254 n_found = 0;
6255
6256 chunk = buf_pool->chunks;
6257
6258 for (i = buf_pool->n_chunks; i--; chunk++) {
6259 buf_block_t *block = chunk->blocks;
6260 ulint n_blocks = chunk->size;
6261
6262 for (; n_blocks--; block++) {
6263 const buf_frame_t *frame = block->frame;
6264
6265 if (fil_page_index_page_check(frame)) {
6266 index_id_t id(block->page.id.space(), btr_page_get_index_id(frame));
6267
6268 /* Look for the id in the index_ids array */
6269 j = 0;
6270
6271 while (j < n_found) {
6272 if (index_ids[j] == id) {
6273 counts[j]++;
6274
6275 break;
6276 }
6277 j++;
6278 }
6279
6280 if (j == n_found) {
6281 n_found++;
6282 index_ids[j] = id;
6283 counts[j] = 1;
6284 }
6285 }
6286 }
6287 }
6288
6289 mutex_exit(&buf_pool->LRU_list_mutex);
6290
6291 for (i = 0; i < n_found; i++) {
6292 ib::info info(ER_IB_MSG_1217);
6293
6294 info << "Block count for index " << index_ids[i] << " in buffer is about "
6295 << counts[i];
6296 }
6297
6298 ut::free(index_ids);
6299 ut::free(counts);
6300
6301 buf_pool_validate_instance(buf_pool);
6302 }
6303
6304 /** Prints info of the buffer buf_pool data structure. */
6305 void buf_print(void) {
6306 ulint i;
6307
6308 for (i = 0; i < srv_buf_pool_instances; i++) {
6309 buf_pool_t *buf_pool;
6310
6311 buf_pool = buf_pool_from_array(i);
6312 buf_print_instance(buf_pool);
6313 }
6314 }
6315 #endif /* UNIV_DEBUG_PRINT || UNIV_DEBUG || UNIV_BUF_DEBUG */
6316
6317 #ifdef UNIV_DEBUG
6318 /** Returns the number of latched pages in the buffer pool.
6319 @param[in] buf_pool buffer pool instance
6320 @return number of latched pages */
6321 static ulint buf_get_latched_pages_number_instance(buf_pool_t *buf_pool) {
6322 ulint i;
6323 buf_chunk_t *chunk;
6324 ulint fixed_pages_number = 0;
6325
6326 mutex_enter(&buf_pool->LRU_list_mutex);
6327
6328 chunk = buf_pool->chunks;
6329
6330 for (i = buf_pool->n_chunks; i--; chunk++) {
6331 buf_block_t *block;
6332 ulint j;
6333
6334 block = chunk->blocks;
6335
6336 for (j = chunk->size; j--; block++) {
6337 if (buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) {
6338 continue;
6339 }
6340 /* We read io_fix without block mutex because we don't care about
6341 consistent results for this statistics as much as speed */
6342 if (block->page.buf_fix_count != 0 || block->page.was_io_fixed()) {
6343 fixed_pages_number++;
6344 }
6345 }
6346 }
6347
6348 mutex_exit(&buf_pool->LRU_list_mutex);
6349
6350 mutex_enter(&buf_pool->zip_mutex);
6351
6352 /* Traverse the lists of clean and dirty compressed-only blocks. */
6353
6354 for (auto b : buf_pool->zip_clean) {
6355 ut_a(buf_page_get_state(b) == BUF_BLOCK_ZIP_PAGE);
6356 ut_a(buf_page_get_io_fix(b) != BUF_IO_WRITE);
6357
6358 if (b->buf_fix_count != 0 || buf_page_get_io_fix(b) != BUF_IO_NONE) {
6359 fixed_pages_number++;
6360 }
6361 }
6362
6363 buf_flush_list_mutex_enter(buf_pool);
6364 for (auto b : buf_pool->flush_list) {
6365 ut_ad(b->in_flush_list);
6366
6367 switch (buf_page_get_state(b)) {
6368 case BUF_BLOCK_ZIP_DIRTY:
6369 if (b->buf_fix_count != 0 || buf_page_get_io_fix(b) != BUF_IO_NONE) {
6370 fixed_pages_number++;
6371 }
6372 break;
6373 case BUF_BLOCK_FILE_PAGE:
6374 /* uncompressed page */
6375 break;
6376 case BUF_BLOCK_REMOVE_HASH:
6377 /* We hold flush list but not LRU list mutex here.
6378 Thus encountering BUF_BLOCK_REMOVE_HASH pages is
6379 possible. */
6380 break;
6381 case BUF_BLOCK_POOL_WATCH:
6382 case BUF_BLOCK_ZIP_PAGE:
6383 case BUF_BLOCK_NOT_USED:
6384 case BUF_BLOCK_READY_FOR_USE:
6385 case BUF_BLOCK_MEMORY:
6386 ut_error;
6387 break;
6388 }
6389 }
6390
6391 buf_flush_list_mutex_exit(buf_pool);
6392 mutex_exit(&buf_pool->zip_mutex);
6393
6394 return (fixed_pages_number);
6395 }
6396
6397 /** Returns the number of latched pages in all the buffer pools.
6398 @return number of latched pages */
6399 ulint buf_get_latched_pages_number(void) {
6400 ulint i;
6401 ulint total_latched_pages = 0;
6402
6403 for (i = 0; i < srv_buf_pool_instances; i++) {
6404 buf_pool_t *buf_pool;
6405
6406 buf_pool = buf_pool_from_array(i);
6407
6408 total_latched_pages += buf_get_latched_pages_number_instance(buf_pool);
6409 }
6410
6411 return (total_latched_pages);
6412 }
6413
6414 #endif /* UNIV_DEBUG */
6415
6416 /** Returns the number of pending buf pool read ios.
6417 @return number of pending read I/O operations */
6418 ulint buf_get_n_pending_read_ios(void) {
6419 ulint pend_ios = 0;
6420
6421 os_rmb;
6422 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
6423 pend_ios += buf_pool_from_array(i)->n_pend_reads;
6424 }
6425
6426 return (pend_ios);
6427 }
6428
6429 /** Returns the ratio in percents of modified pages in the buffer pool /
6430 database pages in the buffer pool.
6431 @return modified page percentage ratio */
6432 double buf_get_modified_ratio_pct(void) {
6433 double ratio;
6434 ulint lru_len = 0;
6435 ulint free_len = 0;
6436 ulint flush_list_len = 0;
6437
6438 buf_get_total_list_len(&lru_len, &free_len, &flush_list_len);
6439
6440 ratio = static_cast<double>(100 * flush_list_len) / (1 + lru_len + free_len);
6441
6442 /* 1 + is there to avoid division by zero */
6443
6444 return (ratio);
6445 }
6446
6447 /** Aggregates a pool stats information with the total buffer pool stats */
6448 static void buf_stats_aggregate_pool_info(
6449 buf_pool_info_t *total_info, /*!< in/out: the buffer pool
6450 info to store aggregated
6451 result */
6452 const buf_pool_info_t *pool_info) /*!< in: individual buffer pool
6453 stats info */
6454 {
6455 ut_a(total_info && pool_info);
6456
6457 /* Nothing to copy if total_info is the same as pool_info */
6458 if (total_info == pool_info) {
6459 return;
6460 }
6461
6462 total_info->pool_size += pool_info->pool_size;
6463 total_info->lru_len += pool_info->lru_len;
6464 total_info->old_lru_len += pool_info->old_lru_len;
6465 total_info->free_list_len += pool_info->free_list_len;
6466 total_info->flush_list_len += pool_info->flush_list_len;
6467 total_info->n_pend_unzip += pool_info->n_pend_unzip;
6468 total_info->n_pend_reads += pool_info->n_pend_reads;
6469 total_info->n_pending_flush_lru += pool_info->n_pending_flush_lru;
6470 total_info->n_pending_flush_list += pool_info->n_pending_flush_list;
6471 total_info->n_pages_made_young += pool_info->n_pages_made_young;
6472 total_info->n_pages_not_made_young += pool_info->n_pages_not_made_young;
6473 total_info->n_pages_read += pool_info->n_pages_read;
6474 total_info->n_pages_created += pool_info->n_pages_created;
6475 total_info->n_pages_written += pool_info->n_pages_written;
6476 total_info->n_page_gets += pool_info->n_page_gets;
6477 total_info->n_ra_pages_read_rnd += pool_info->n_ra_pages_read_rnd;
6478 total_info->n_ra_pages_read += pool_info->n_ra_pages_read;
6479 total_info->n_ra_pages_evicted += pool_info->n_ra_pages_evicted;
6480 total_info->page_made_young_rate += pool_info->page_made_young_rate;
6481 total_info->page_not_made_young_rate += pool_info->page_not_made_young_rate;
6482 total_info->pages_read_rate += pool_info->pages_read_rate;
6483 total_info->pages_created_rate += pool_info->pages_created_rate;
6484 total_info->pages_written_rate += pool_info->pages_written_rate;
6485 total_info->n_page_get_delta += pool_info->n_page_get_delta;
6486 total_info->page_read_delta += pool_info->page_read_delta;
6487 total_info->young_making_delta += pool_info->young_making_delta;
6488 total_info->not_young_making_delta += pool_info->not_young_making_delta;
6489 total_info->pages_readahead_rnd_rate += pool_info->pages_readahead_rnd_rate;
6490 total_info->pages_readahead_rate += pool_info->pages_readahead_rate;
6491 total_info->pages_evicted_rate += pool_info->pages_evicted_rate;
6492 total_info->unzip_lru_len += pool_info->unzip_lru_len;
6493 total_info->io_sum += pool_info->io_sum;
6494 total_info->io_cur += pool_info->io_cur;
6495 total_info->unzip_sum += pool_info->unzip_sum;
6496 total_info->unzip_cur += pool_info->unzip_cur;
6497 }
6498 /** Collect buffer pool stats information for a buffer pool. Also
6499 record aggregated stats if there are more than one buffer pool
6500 in the server */
6501 void buf_stats_get_pool_info(
6502 buf_pool_t *buf_pool, /*!< in: buffer pool */
6503 ulint pool_id, /*!< in: buffer pool ID */
6504 buf_pool_info_t *all_pool_info) /*!< in/out: buffer pool info
6505 to fill */
6506 {
6507 buf_pool_info_t *pool_info;
6508
6509 /* Find appropriate pool_info to store stats for this buffer pool */
6510 pool_info = &all_pool_info[pool_id];
6511
6512 pool_info->pool_unique_id = pool_id;
6513
6514 pool_info->pool_size = buf_pool->curr_size;
6515
6516 pool_info->lru_len = UT_LIST_GET_LEN(buf_pool->LRU);
6517
6518 pool_info->old_lru_len = buf_pool->LRU_old_len;
6519
6520 pool_info->free_list_len = UT_LIST_GET_LEN(buf_pool->free);
6521
6522 pool_info->flush_list_len = UT_LIST_GET_LEN(buf_pool->flush_list);
6523
6524 pool_info->n_pend_unzip = UT_LIST_GET_LEN(buf_pool->unzip_LRU);
6525
6526 pool_info->n_pend_reads = buf_pool->n_pend_reads;
6527
6528 pool_info->n_pending_flush_lru =
6529 (buf_pool->n_flush[BUF_FLUSH_LRU] + buf_pool->init_flush[BUF_FLUSH_LRU]);
6530
6531 pool_info->n_pending_flush_list = (buf_pool->n_flush[BUF_FLUSH_LIST] +
6532 buf_pool->init_flush[BUF_FLUSH_LIST]);
6533
6534 pool_info->n_pending_flush_single_page =
6535 (buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE] +
6536 buf_pool->init_flush[BUF_FLUSH_SINGLE_PAGE]);
6537
6538 const auto time_elapsed_s =
6539 0.001 +
6540 std::chrono::duration_cast<std::chrono::duration<double>>(
6541 std::chrono::steady_clock::now() - buf_pool->last_printout_time)
6542 .count();
6543
6544 pool_info->n_pages_made_young = buf_pool->stat.n_pages_made_young;
6545
6546 pool_info->n_pages_not_made_young = buf_pool->stat.n_pages_not_made_young;
6547
6548 pool_info->n_pages_read = buf_pool->stat.n_pages_read;
6549
6550 pool_info->n_pages_created = buf_pool->stat.n_pages_created;
6551
6552 pool_info->n_pages_written = buf_pool->stat.n_pages_written;
6553
6554 pool_info->n_page_gets = Counter::total(buf_pool->stat.m_n_page_gets);
6555
6556 pool_info->n_ra_pages_read_rnd = buf_pool->stat.n_ra_pages_read_rnd;
6557 pool_info->n_ra_pages_read = buf_pool->stat.n_ra_pages_read;
6558
6559 pool_info->n_ra_pages_evicted = buf_pool->stat.n_ra_pages_evicted;
6560
6561 pool_info->page_made_young_rate = (buf_pool->stat.n_pages_made_young -
6562 buf_pool->old_stat.n_pages_made_young) /
6563 time_elapsed_s;
6564
6565 pool_info->page_not_made_young_rate =
6566 (buf_pool->stat.n_pages_not_made_young -
6567 buf_pool->old_stat.n_pages_not_made_young) /
6568 time_elapsed_s;
6569
6570 pool_info->pages_read_rate =
6571 (buf_pool->stat.n_pages_read - buf_pool->old_stat.n_pages_read) /
6572 time_elapsed_s;
6573
6574 pool_info->pages_created_rate =
6575 (buf_pool->stat.n_pages_created - buf_pool->old_stat.n_pages_created) /
6576 time_elapsed_s;
6577
6578 pool_info->pages_written_rate =
6579 (buf_pool->stat.n_pages_written - buf_pool->old_stat.n_pages_written) /
6580 time_elapsed_s;
6581
6582 pool_info->n_page_get_delta =
6583 Counter::total(buf_pool->stat.m_n_page_gets) -
6584 Counter::total(buf_pool->old_stat.m_n_page_gets);
6585
6586 if (pool_info->n_page_get_delta) {
6587 pool_info->page_read_delta =
6588 buf_pool->stat.n_pages_read - buf_pool->old_stat.n_pages_read;
6589
6590 pool_info->young_making_delta = buf_pool->stat.n_pages_made_young -
6591 buf_pool->old_stat.n_pages_made_young;
6592
6593 pool_info->not_young_making_delta =
6594 buf_pool->stat.n_pages_not_made_young -
6595 buf_pool->old_stat.n_pages_not_made_young;
6596 }
6597 pool_info->pages_readahead_rnd_rate =
6598 (buf_pool->stat.n_ra_pages_read_rnd -
6599 buf_pool->old_stat.n_ra_pages_read_rnd) /
6600 time_elapsed_s;
6601
6602 pool_info->pages_readahead_rate =
6603 (buf_pool->stat.n_ra_pages_read - buf_pool->old_stat.n_ra_pages_read) /
6604 time_elapsed_s;
6605
6606 pool_info->pages_evicted_rate = (buf_pool->stat.n_ra_pages_evicted -
6607 buf_pool->old_stat.n_ra_pages_evicted) /
6608 time_elapsed_s;
6609
6610 pool_info->unzip_lru_len = UT_LIST_GET_LEN(buf_pool->unzip_LRU);
6611
6612 pool_info->io_sum = buf_LRU_stat_sum.io;
6613
6614 pool_info->io_cur = buf_LRU_stat_cur.io;
6615
6616 pool_info->unzip_sum = buf_LRU_stat_sum.unzip;
6617
6618 pool_info->unzip_cur = buf_LRU_stat_cur.unzip;
6619
6620 buf_refresh_io_stats(buf_pool);
6621 }
6622
6623 /** Prints info of the buffer i/o. */
6624 static void buf_print_io_instance(
6625 buf_pool_info_t *pool_info, /*!< in: buffer pool info */
6626 FILE *file) /*!< in/out: buffer where to print */
6627 {
6628 ut_ad(pool_info);
6629
6630 fprintf(file,
6631 "Buffer pool size " ULINTPF
6632 "\n"
6633 "Free buffers " ULINTPF
6634 "\n"
6635 "Database pages " ULINTPF
6636 "\n"
6637 "Old database pages " ULINTPF
6638 "\n"
6639 "Modified db pages " ULINTPF
6640 "\n"
6641 "Pending reads " ULINTPF
6642 "\n"
6643 "Pending writes: LRU " ULINTPF ", flush list " ULINTPF
6644 ", single page " ULINTPF "\n",
6645 pool_info->pool_size, pool_info->free_list_len, pool_info->lru_len,
6646 pool_info->old_lru_len, pool_info->flush_list_len,
6647 pool_info->n_pend_reads, pool_info->n_pending_flush_lru,
6648 pool_info->n_pending_flush_list,
6649 pool_info->n_pending_flush_single_page);
6650
6651 fprintf(file,
6652 "Pages made young " ULINTPF ", not young " ULINTPF
6653 "\n"
6654 "%.2f youngs/s, %.2f non-youngs/s\n"
6655 "Pages read " ULINTPF ", created " ULINTPF ", written " ULINTPF
6656 "\n"
6657 "%.2f reads/s, %.2f creates/s, %.2f writes/s\n",
6658 pool_info->n_pages_made_young, pool_info->n_pages_not_made_young,
6659 pool_info->page_made_young_rate, pool_info->page_not_made_young_rate,
6660 pool_info->n_pages_read, pool_info->n_pages_created,
6661 pool_info->n_pages_written, pool_info->pages_read_rate,
6662 pool_info->pages_created_rate, pool_info->pages_written_rate);
6663
6664 if (pool_info->n_page_get_delta) {
6665 fprintf(file,
6666 "Buffer pool hit rate %lu / 1000,"
6667 " young-making rate %lu / 1000 not %lu / 1000\n",
6668 (ulong)(1000 - (1000 * pool_info->page_read_delta /
6669 pool_info->n_page_get_delta)),
6670 (ulong)(1000 * pool_info->young_making_delta /
6671 pool_info->n_page_get_delta),
6672 (ulong)(1000 * pool_info->not_young_making_delta /
6673 pool_info->n_page_get_delta));
6674 } else {
6675 fputs("No buffer pool page gets since the last printout\n", file);
6676 }
6677
6678 /* Statistics about read ahead algorithm */
6679 fprintf(file,
6680 "Pages read ahead %.2f/s,"
6681 " evicted without access %.2f/s,"
6682 " Random read ahead %.2f/s\n",
6683
6684 pool_info->pages_readahead_rate, pool_info->pages_evicted_rate,
6685 pool_info->pages_readahead_rnd_rate);
6686
6687 /* Print some values to help us with visualizing what is
6688 happening with LRU eviction. */
6689 fprintf(file,
6690 "LRU len: " ULINTPF ", unzip_LRU len: " ULINTPF
6691 "\n"
6692 "I/O sum[" ULINTPF "]:cur[" ULINTPF
6693 "], "
6694 "unzip sum[" ULINTPF "]:cur[" ULINTPF "]\n",
6695 pool_info->lru_len, pool_info->unzip_lru_len, pool_info->io_sum,
6696 pool_info->io_cur, pool_info->unzip_sum, pool_info->unzip_cur);
6697 }
6698
6699 /** Prints info of the buffer i/o. */
6700 void buf_print_io(FILE *file) /*!< in/out: buffer where to print */
6701 {
6702 ulint i;
6703 buf_pool_info_t *pool_info;
6704 buf_pool_info_t *pool_info_total;
6705
6706 /* If srv_buf_pool_instances is greater than 1, allocate
6707 one extra buf_pool_info_t, the last one stores
6708 aggregated/total values from all pools */
6709 if (srv_buf_pool_instances > 1) {
6710 pool_info = (buf_pool_info_t *)ut::zalloc_withkey(
6711 UT_NEW_THIS_FILE_PSI_KEY,
6712 (srv_buf_pool_instances + 1) * sizeof *pool_info);
6713
6714 pool_info_total = &pool_info[srv_buf_pool_instances];
6715 } else {
6716 ut_a(srv_buf_pool_instances == 1);
6717
6718 pool_info_total = pool_info = static_cast<buf_pool_info_t *>(
6719 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof *pool_info));
6720 }
6721
6722 os_rmb;
6723
6724 for (i = 0; i < srv_buf_pool_instances; i++) {
6725 buf_pool_t *buf_pool;
6726
6727 buf_pool = buf_pool_from_array(i);
6728
6729 /* Fetch individual buffer pool info and calculate
6730 aggregated stats along the way */
6731 buf_stats_get_pool_info(buf_pool, i, pool_info);
6732
6733 /* If we have more than one buffer pool, store
6734 the aggregated stats */
6735 if (srv_buf_pool_instances > 1) {
6736 buf_stats_aggregate_pool_info(pool_info_total, &pool_info[i]);
6737 }
6738 }
6739
6740 /* Print the aggregate buffer pool info */
6741 buf_print_io_instance(pool_info_total, file);
6742
6743 /* If there are more than one buffer pool, print each individual pool
6744 info */
6745 if (srv_buf_pool_instances > 1) {
6746 fputs(
6747 "----------------------\n"
6748 "INDIVIDUAL BUFFER POOL INFO\n"
6749 "----------------------\n",
6750 file);
6751
6752 for (i = 0; i < srv_buf_pool_instances; i++) {
6753 fprintf(file, "---BUFFER POOL " ULINTPF "\n", i);
6754 buf_print_io_instance(&pool_info[i], file);
6755 }
6756 }
6757
6758 ut::free(pool_info);
6759 }
6760
6761 /** Refreshes the statistics used to print per-second averages. */
6762 void buf_refresh_io_stats_all(void) {
6763 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
6764 buf_pool_t *buf_pool;
6765
6766 buf_pool = buf_pool_from_array(i);
6767
6768 buf_refresh_io_stats(buf_pool);
6769 }
6770 }
6771
6772 void buf_assert_all_are_replaceable() {
6773 for (size_t i = 0; i < srv_buf_pool_instances; i++) {
6774 buf_assert_all_are_replaceable(buf_pool_from_array(i));
6775 }
6776 }
6777
6778 size_t buf_pool_pending_io_reads_count() {
6779 size_t pending_io_reads = 0;
6780 for (size_t i = 0; i < srv_buf_pool_instances; i++) {
6781 pending_io_reads += buf_pool_from_array(i)->n_pend_reads;
6782 }
6783 return pending_io_reads;
6784 }
6785
6786 size_t buf_pool_pending_io_writes_count() {
6787 size_t pending_io_writes = 0;
6788 for (size_t i = 0; i < srv_buf_pool_instances; i++) {
6789 buf_pool_t *buf_pool = buf_pool_from_array(i);
6790 mutex_enter(&buf_pool->flush_state_mutex);
6791 pending_io_writes += buf_pool->n_flush[BUF_FLUSH_LRU] +
6792 buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE] +
6793 buf_pool->n_flush[BUF_FLUSH_LIST];
6794 mutex_exit(&buf_pool->flush_state_mutex);
6795 }
6796 return pending_io_writes;
6797 }
6798 void buf_pool_wait_for_no_pending_io() {
6799 uint32_t sleep_time_us = 100;
6800 uint32_t sleep_time_since_info_emitted_us = 0;
6801 constexpr uint32_t MAX_SLEEP_TIME_US = 1000 * 1000;
6802 while (true) {
6803 const size_t pending_io =
6804 buf_pool_pending_io_reads_count() + buf_pool_pending_io_writes_count();
6805 if (pending_io == 0) {
6806 break;
6807 }
6808 /* Print a message every around 60 seconds,
6809 if we are waiting for pending IO. */
6810 if (sleep_time_since_info_emitted_us >= 60 * 1000 * 1000) {
6811 const int error_code = srv_shutdown_state.load() != SRV_SHUTDOWN_NONE
6812 ? ER_IB_MSG_BUF_PENDING_IO_ON_SHUTDOWN
6813 : ER_IB_MSG_BUF_PENDING_IO;
6814 ib::info(error_code, pending_io);
6815 sleep_time_since_info_emitted_us = 0;
6816 }
6817
6818 sleep_time_us = std::min(sleep_time_us * 2, MAX_SLEEP_TIME_US);
6819 std::this_thread::sleep_for(std::chrono::microseconds(sleep_time_us));
6820
6821 sleep_time_since_info_emitted_us += sleep_time_us;
6822 }
6823 }
6824
6825 #else /* !UNIV_HOTBACKUP */
6826
6827 /** Inits a page to the buffer buf_pool, for use in mysqlbackup --restore.
6828 @param[in] page_id page id
6829 @param[in] page_size page size
6830 @param[in,out] block block to init */
6831 void meb_page_init(const page_id_t &page_id, const page_size_t &page_size,
6832 buf_block_t *block) {
6833 block->page.state = BUF_BLOCK_FILE_PAGE;
6834 block->page.id = page_id;
6835 block->page.size.copy_from(page_size);
6836
6837 page_zip_des_init(&block->page.zip);
6838
6839 /* We assume that block->page.data has been allocated
6840 with page_size == univ_page_size. */
6841 if (page_size.is_compressed()) {
6842 page_zip_set_size(&block->page.zip, page_size.physical());
6843 block->page.zip.data = block->frame + page_size.logical();
6844 } else {
6845 page_zip_set_size(&block->page.zip, 0);
6846 }
6847
6848 ib::trace_1() << "meb_page_init: space_id " << block->page.id.space()
6849 << " zip_size " << block->page.size.physical() << " page_size "
6850 << block->page.size.logical();
6851 }
6852
6853 #endif /* !UNIV_HOTBACKUP */
6854
6855 /** Print the given buf_pool_t object.
6856 @param[in,out] out the output stream
6857 @param[in] buf_pool the buf_pool_t object to be printed
6858 @return the output stream */
6859 std::ostream &operator<<(std::ostream &out, const buf_pool_t &buf_pool) {
6860 #ifndef UNIV_HOTBACKUP
6861 /* These locking requirements might be relaxed if desired */
6862 ut_ad(mutex_own(&buf_pool.LRU_list_mutex));
6863 ut_ad(mutex_own(&buf_pool.free_list_mutex));
6864 ut_ad(mutex_own(&buf_pool.flush_state_mutex));
6865 ut_ad(buf_flush_list_mutex_own(&buf_pool));
6866
6867 out << "[buffer pool instance: "
6868 << "buf_pool size=" << buf_pool.curr_size
6869 << ", database pages=" << UT_LIST_GET_LEN(buf_pool.LRU)
6870 << ", free pages=" << UT_LIST_GET_LEN(buf_pool.free)
6871 << ", modified database pages=" << UT_LIST_GET_LEN(buf_pool.flush_list)
6872 << ", n pending decompressions=" << buf_pool.n_pend_unzip
6873 << ", n pending reads=" << buf_pool.n_pend_reads
6874 << ", n pending flush LRU=" << buf_pool.n_flush[BUF_FLUSH_LRU]
6875 << " list=" << buf_pool.n_flush[BUF_FLUSH_LIST]
6876 << " single page=" << buf_pool.n_flush[BUF_FLUSH_SINGLE_PAGE]
6877 << ", pages made young=" << buf_pool.stat.n_pages_made_young
6878 << ", not young=" << buf_pool.stat.n_pages_not_made_young
6879 << ", pages read=" << buf_pool.stat.n_pages_read
6880 << ", created=" << buf_pool.stat.n_pages_created
6881 << ", written=" << buf_pool.stat.n_pages_written << "]";
6882 #endif /* !UNIV_HOTBACKUP */
6883 return (out);
6884 }
6885
6886 const char *buf_block_t::get_page_type_str() const noexcept {
6887 page_type_t type = get_page_type();
6888 return fil_get_page_type_str(type);
6889 }
6890
6891 #ifndef UNIV_HOTBACKUP
6892 /** Frees the buffer pool instances and the global data structures. */
6893 void buf_pool_free_all() {
6894 for (ulint i = 0; i < srv_buf_pool_instances; ++i) {
6895 buf_pool_t *ptr = &buf_pool_ptr[i];
6896
6897 buf_pool_free_instance(ptr);
6898 }
6899
6900 buf_pool_free();
6901 }
6902 #endif /* !UNIV_HOTBACKUP */
6903
6904 uint16_t buf_block_t::get_page_level() const {
6905 ut_ad(frame != nullptr);
6906 ut_ad(get_page_type() == FIL_PAGE_INDEX);
6907 uint16_t level = mach_read_from_2(frame + PAGE_HEADER + PAGE_LEVEL);
6908 ut_ad(level <= BTR_MAX_NODE_LEVEL);
6909 return level;
6910 }
6911
6912 bool buf_block_t::is_empty() const {
6913 return page_rec_is_supremum(page_rec_get_next(page_get_infimum_rec(frame)));
6914 }
6915
6916 #ifndef UNIV_HOTBACKUP
6917 namespace {
6918 /** Print the page's access_time as duration between first access and now, or
6919 0.0 if never accessed
6920 @param[in] access_time the time_point when page was first accessed
6921 @return time elapsed since access_time */
6922 int64_t time_elapsed(std::chrono::steady_clock::time_point access_time) {
6923 if (access_time == std::chrono::steady_clock::time_point{}) {
6924 return 0;
6925 }
6926 return static_cast<int64_t>(
6927 std::chrono::duration_cast<std::chrono::seconds>(
6928 std::chrono::steady_clock::now() - access_time)
6929 .count());
6930 }
6931 } // namespace
6932
6933 std::ostream &operator<<(std::ostream &outs, const buf_page_t &page) {
6934 /* Print in json format: "key":"value" */
6935
6936 ut_ad(mutex_own(buf_page_get_mutex(&page)));
6937 ut_ad(buf_page_in_file(&page));
6938
6939 return outs << "{\"page\":{\"id\":\"" << page.id << "\",\"size\":\""
6940 << page.size << "\",\"page_type\":\""
6941 << reinterpret_cast<const buf_block_t &>(page).get_page_type_str()
6942 << "\",\"was_stale\":" << page.was_stale()
6943 << ",\"buf_fix_count\":" << page.buf_fix_count.load()
6944 << ",\"io_fix\":\"" << page.get_io_fix_snapshot()
6945 << "\",\"newest_lsn\":" << page.get_newest_lsn()
6946 << ",\"oldest_lsn\":" << page.get_oldest_lsn()
6947 << ",\"is_dirty\":" << page.is_dirty() << ",\"flush_type\":\""
6948 << page.flush_type
6949 << "\",\"dblwr_batch_id\":" << page.get_dblwr_batch_id()
6950 << ",\"old\":" << page.old
6951 << ",\"first_accessed\":" << time_elapsed(page.access_time)
6952 #ifdef UNIV_DEBUG
6953 << ",\"file_page_was_freed\":" << page.file_page_was_freed
6954 << ",\"someone_has_io_responsibility\":"
6955 << page.someone_has_io_responsibility()
6956 << ",\"current_thread_has_io_responsibility\":"
6957 << page.current_thread_has_io_responsibility()
6958 << ",\"in_flush_list\":" << page.in_flush_list
6959 << ",\"in_free_list\":" << page.in_free_list
6960 << ",\"in_LRU_list\":" << page.in_LRU_list
6961 << ",\"in_page_hash\":" << page.in_page_hash
6962 << ",\"in_zip_hash\":" << page.in_zip_hash
6963 #endif /* UNIV_DEBUG */
6964 << "}}";
6965 }
6966
6967 std::ostream &operator<<(std::ostream &outs, const buf_block_t &block) {
6968 /* Print in json format: "key":"value" */
6969
6970 /* Block state corresponding to buf_page_state_str */
6971 outs << "{\"block\":{\"state\":\"" << buf_block_get_state(&block)
6972 << "\",\"buf_pool_index\":" << unsigned{block.page.buf_pool_index};
6973
6974 if (buf_page_in_file(&block.page)) {
6975 ut_ad(mutex_own(buf_page_get_mutex(&block.page)));
6976 outs << ",\"page\":" << block.page;
6977 }
6978
6979 return outs << ",\"made_dirty_without_latch\":"
6980 << block.made_dirty_with_no_latch
6981 << ",\"modify_clock\":" << block.modify_clock
6982 #ifdef UNIV_DEBUG
6983 << ",\"in_unzip_LRU_list\":" << block.in_unzip_LRU_list
6984 << ",\"in_withdraw_list\":" << block.in_withdraw_list
6985 << ",\"rw_lock_t\":\"" << block.lock.to_string() << "\""
6986 #endif /* UNIV_DEBUG */
6987 << "}}";
6988 }
6989 #endif /* !UNIV_HOTBACKUP */