Debian Codegraph @

storage/innobase/ibuf/ibuf0ibuf.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1997, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file ibuf/ibuf0ibuf.cc
29 Insert buffer
30
31 Created 7/19/1997 Heikki Tuuri
32 *******************************************************/
33
34 #include <sys/types.h>
35
36 #include "btr0sea.h"
37 #include "ha_prototypes.h"
38 #include "ibuf0ibuf.h"
39 #include "sync0sync.h"
40
41 #include <debug_sync.h>
42 #include "my_dbug.h"
43
44 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
45 bool srv_ibuf_disable_background_merge;
46 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
47
48 /** Number of bits describing a single page */
49 constexpr size_t IBUF_BITS_PER_PAGE = 4;
50 static_assert(IBUF_BITS_PER_PAGE % 2 == 0,
51 "IBUF_BITS_PER_PAGE must be an even number!");
52 /** The start address for an insert buffer bitmap page bitmap */
53 constexpr uint32_t IBUF_BITMAP = PAGE_DATA;
54
55 #ifndef UNIV_HOTBACKUP
56
57 #include "btr0btr.h"
58 #include "btr0cur.h"
59 #include "btr0pcur.h"
60 #include "buf0buf.h"
61 #include "buf0rea.h"
62 #include "dict0boot.h"
63 #include "fil0fil.h"
64 #include "fsp0fsp.h"
65 #include "fsp0sysspace.h"
66 #include "fut0lst.h"
67 #include "lock0lock.h"
68 #include "log0buf.h"
69 #include "log0chkp.h"
70 #include "log0recv.h"
71 #include "que0que.h"
72 #include "rem0cmp.h"
73 #include "rem0rec.h"
74 #include "row0upd.h"
75 #include "srv0start.h"
76 #include "trx0sys.h"
77
78 /* STRUCTURE OF AN INSERT BUFFER RECORD
79
80 In versions < 4.1.x:
81
82 1. The first field is the page number.
83 2. The second field is an array which stores type info for each subsequent
84 field. We store the information which affects the ordering of records, and
85 also the physical storage size of an SQL NULL value. E.g., for CHAR(10) it
86 is 10 bytes.
87 3. Next we have the fields of the actual index record.
88
89 In versions >= 4.1.x:
90
91 Note that contrary to what we planned in the 1990's, there will only be one
92 insert buffer tree, and that is in the system tablespace of InnoDB.
93
94 1. The first field is the space id.
95 2. The second field is a one-byte marker (0) which differentiates records from
96 the < 4.1.x storage format.
97 3. The third field is the page number.
98 4. The fourth field contains the type info, where we have also added 2 bytes to
99 store the charset. In the compressed table format of 5.0.x we must add more
100 information here so that we can build a dummy 'index' struct which 5.0.x
101 can use in the binary search on the index page in the ibuf merge phase.
102 5. The rest of the fields contain the fields of the actual index record.
103
104 In versions >= 5.0.3:
105
106 The first byte of the fourth field is an additional marker (0) if the record
107 is in the compact format. The presence of this marker can be detected by
108 looking at the length of the field modulo DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE.
109
110 The high-order bit of the character set field in the type info is the
111 "nullable" flag for the field.
112
113 In versions >= 5.5:
114
115 The optional marker byte at the start of the fourth field is replaced by
116 mandatory 3 fields, totaling 4 bytes:
117
118 1. 2 bytes: Counter field, used to sort records within a (space id, page
119 no) in the order they were added. This is needed so that for example the
120 sequence of operations "INSERT x, DEL MARK x, INSERT x" is handled
121 correctly.
122
123 2. 1 byte: Operation type (see ibuf_op_t).
124
125 3. 1 byte: Flags. Currently only one flag exists, IBUF_REC_COMPACT.
126
127 To ensure older records, which do not have counters to enforce correct
128 sorting, are merged before any new records, ibuf_insert checks if we're
129 trying to insert to a position that contains old-style records, and if so,
130 refuses the insert. Thus, ibuf pages are gradually converted to the new
131 format as their corresponding buffer pool pages are read into memory.
132 */
133
134 /* PREVENTING DEADLOCKS IN THE INSERT BUFFER SYSTEM
135
136 If an OS thread performs any operation that brings in disk pages from
137 non-system tablespaces into the buffer pool, or creates such a page there,
138 then the operation may have as a side effect an insert buffer index tree
139 compression. Thus, the tree latch of the insert buffer tree may be acquired
140 in the x-mode, and also the file space latch of the system tablespace may
141 be acquired in the x-mode.
142
143 Also, an insert to an index in a non-system tablespace can have the same
144 effect. How do we know this cannot lead to a deadlock of OS threads? There
145 is a problem with the i\o-handler threads: they break the latching order
146 because they own x-latches to pages which are on a lower level than the
147 insert buffer tree latch, its page latches, and the tablespace latch an
148 insert buffer operation can reserve.
149
150 The solution is the following: Let all the tree and page latches connected
151 with the insert buffer be later in the latching order than the fsp latch and
152 fsp page latches.
153
154 Insert buffer pages must be such that the insert buffer is never invoked
155 when these pages are accessed as this would result in a recursion violating
156 the latching order. We let a special i/o-handler thread take care of i/o to
157 the insert buffer pages and the ibuf bitmap pages, as well as the fsp bitmap
158 pages and the first inode page, which contains the inode of the ibuf tree: let
159 us call all these ibuf pages. To prevent deadlocks, we do not let a read-ahead
160 access both non-ibuf and ibuf pages.
161
162 Then an i/o-handler for the insert buffer never needs to access recursively the
163 insert buffer tree and thus obeys the latching order. On the other hand, other
164 i/o-handlers for other tablespaces may require access to the insert buffer,
165 but because all kinds of latches they need to access there are later in the
166 latching order, no violation of the latching order occurs in this case,
167 either.
168
169 A problem is how to grow and contract an insert buffer tree. As it is later
170 in the latching order than the fsp management, we have to reserve the fsp
171 latch first, before adding or removing pages from the insert buffer tree.
172 We let the insert buffer tree have its own file space management: a free
173 list of pages linked to the tree root. To prevent recursive using of the
174 insert buffer when adding pages to the tree, we must first load these pages
175 to memory, obtaining a latch on them, and only after that add them to the
176 free list of the insert buffer tree. More difficult is removing of pages
177 from the free list. If there is an excess of pages in the free list of the
178 ibuf tree, they might be needed if some thread reserves the fsp latch,
179 intending to allocate more file space. So we do the following: if a thread
180 reserves the fsp latch, we check the writer count field of the latch. If
181 this field has value 1, it means that the thread did not own the latch
182 before entering the fsp system, and the mtr of the thread contains no
183 modifications to the fsp pages. Now we are free to reserve the ibuf latch,
184 and check if there is an excess of pages in the free list. We can then, in a
185 separate mini-transaction, take them out of the free list and free them to
186 the fsp system.
187
188 To avoid deadlocks in the ibuf system, we divide file pages into three levels:
189
190 (1) non-ibuf pages,
191 (2) ibuf tree pages and the pages in the ibuf tree free list, and
192 (3) ibuf bitmap pages.
193
194 No OS thread is allowed to access higher level pages if it has latches to
195 lower level pages; even if the thread owns a B-tree latch it must not access
196 the B-tree non-leaf pages if it has latches on lower level pages. Read-ahead
197 is only allowed for level 1 and 2 pages. Dedicated i/o-handler threads handle
198 exclusively level 1 i/o. A dedicated i/o handler thread handles exclusively
199 level 2 i/o. However, if an OS thread does the i/o handling for itself, i.e.,
200 it uses synchronous aio, it can access any pages, as long as it obeys the
201 access order rules. */
202
203 /** Operations that can currently be buffered. */
204 ulong innodb_change_buffering = IBUF_USE_ALL;
205
206 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
207 /** Flag to control insert buffer debugging. */
208 uint ibuf_debug;
209 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
210
211 /** The insert buffer control structure */
212 ibuf_t *ibuf = nullptr;
213
214 #ifdef UNIV_IBUF_COUNT_DEBUG
215 /** Number of tablespaces in the ibuf_counts array */
216 constexpr uint32_t IBUF_COUNT_N_SPACES = 4;
217 /** Number of pages within each tablespace in the ibuf_counts array */
218 constexpr uint32_t IBUF_COUNT_N_PAGES = 130000;
219
220 /** Buffered entry counts for file pages, used in debugging */
221 static ulint ibuf_counts[IBUF_COUNT_N_SPACES][IBUF_COUNT_N_PAGES];
222
223 /** Checks that the indexes to ibuf_counts[][] are within limits.
224 @param[in] page_id page id */
225 static inline void ibuf_count_check(const page_id_t &page_id) {
226 if (page_id.space() < IBUF_COUNT_N_SPACES &&
227 page_id.page_no() < IBUF_COUNT_N_PAGES) {
228 return;
229 }
230
231 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_605)
232 << "UNIV_IBUF_COUNT_DEBUG limits space_id and page_no"
233 " and breaks crash recovery. space_id="
234 << page_id.space() << ", should be 0<=space_id<" << IBUF_COUNT_N_SPACES
235 << ". page_no=" << page_id.page_no() << ", should be 0<=page_no<"
236 << IBUF_COUNT_N_PAGES;
237 }
238 #endif
239
240 /** @name Offsets to the per-page bits in the insert buffer bitmap */
241 /** @{ */
242 /** Bits indicating the amount of free space */
243 constexpr uint32_t IBUF_BITMAP_FREE = 0;
244 /** true if there are buffered changes for the page */
245 constexpr uint32_t IBUF_BITMAP_BUFFERED = 2;
246 /** true if page is a part of the ibuf tree, excluding the root page, or is in
247 the free list of the ibuf */
248 constexpr uint32_t IBUF_BITMAP_IBUF = 3;
249 /** @} */
250
251 /** in the pre-4.1 format, the page number. later, the space_id */
252 constexpr uint32_t IBUF_REC_FIELD_SPACE = 0;
253 /** starting with 4.1, a marker consisting of 1 byte that is 0 */
254 constexpr uint32_t IBUF_REC_FIELD_MARKER = 1;
255 /** starting with 4.1, the page number */
256 constexpr uint32_t IBUF_REC_FIELD_PAGE = 2;
257 /** the metadata field */
258 constexpr uint32_t IBUF_REC_FIELD_METADATA = 3;
259 /** first user field */
260 constexpr uint32_t IBUF_REC_FIELD_USER = 4;
261
262 /* Various constants for checking the type of an ibuf record and extracting
263 data from it. For details, see the description of the record format at the
264 top of this file. */
265
266 /** @name Format of the IBUF_REC_FIELD_METADATA of an insert buffer record
267 The fourth column in the MySQL 5.5 format contains an operation
268 type, counter, and some flags. */
269 /** Combined size of info fields at the beginning of the fourth field */
270 constexpr uint32_t IBUF_REC_INFO_SIZE = 4;
271 static_assert(IBUF_REC_INFO_SIZE < DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE,
272 "IBUF_REC_INFO_SIZE >= DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE");
273
274 /* Offsets for the fields at the beginning of the fourth field */
275 /** Operation counter */
276 constexpr uint32_t IBUF_REC_OFFSET_COUNTER = 0;
277 /** Type of operation */
278 constexpr uint32_t IBUF_REC_OFFSET_TYPE = 2;
279 /** Additional flags */
280 constexpr uint32_t IBUF_REC_OFFSET_FLAGS = 3;
281
282 /* Record flag masks */
283 /** Set in IBUF_REC_OFFSET_FLAGS if the user index is in COMPACT format or later
284 */
285 constexpr uint32_t IBUF_REC_COMPACT = 0x1;
286 /** The mutex used to block pessimistic inserts to ibuf trees */
287 static ib_mutex_t ibuf_pessimistic_insert_mutex;
288
289 /** The mutex protecting the insert buffer structs */
290 static ib_mutex_t ibuf_mutex;
291
292 /** The mutex protecting the insert buffer bitmaps */
293 static ib_mutex_t ibuf_bitmap_mutex;
294
295 /** The area in pages from which contract looks for page numbers for merge */
296 const ulint IBUF_MERGE_AREA = 8;
297
298 /** Inside the merge area, pages which have at most 1 per this number less
299 buffered entries compared to maximum volume that can buffered for a single
300 page are merged along with the page whose buffer became full */
301 const ulint IBUF_MERGE_THRESHOLD = 4;
302
303 /** In ibuf_contract at most this number of pages is read to memory in one
304 batch, in order to merge the entries for them in the insert buffer */
305 const ulint IBUF_MAX_N_PAGES_MERGED = IBUF_MERGE_AREA;
306
307 /** If the combined size of the ibuf trees exceeds ibuf->max_size by this
308 many pages, we start to contract it in connection to inserts there, using
309 non-synchronous contract */
310 const ulint IBUF_CONTRACT_ON_INSERT_NON_SYNC = 0;
311
312 /** If the combined size of the ibuf trees exceeds ibuf->max_size by this
313 many pages, we start to contract it in connection to inserts there, using
314 synchronous contract */
315 const ulint IBUF_CONTRACT_ON_INSERT_SYNC = 5;
316
317 /** If the combined size of the ibuf trees exceeds ibuf->max_size by
318 this many pages, we start to contract it synchronous contract, but do
319 not insert */
320 const ulint IBUF_CONTRACT_DO_NOT_INSERT = 10;
321
322 /* TODO: how to cope with drop table if there are records in the insert
323 buffer for the indexes of the table? Is there actually any problem,
324 because ibuf merge is done to a page when it is read in, and it is
325 still physically like the index page even if the index would have been
326 dropped! So, there seems to be no problem. */
327
328 /** Sets the flag in the current mini-transaction record indicating we're
329 inside an insert buffer routine. */
330 static inline void ibuf_enter(mtr_t *mtr) /*!< in/out: mini-transaction */
331 {
332 ut_ad(!mtr->is_inside_ibuf());
333 mtr->enter_ibuf();
334 }
335
336 /** Sets the flag in the current mini-transaction record indicating we're
337 exiting an insert buffer routine. */
338 static inline void ibuf_exit(mtr_t *mtr) /*!< in/out: mini-transaction */
339 {
340 ut_ad(mtr->is_inside_ibuf());
341 mtr->exit_ibuf();
342 }
343
344 /** Commits an insert buffer mini-transaction and sets the persistent
345 cursor latch mode to BTR_NO_LATCHES, that is, detaches the cursor. */
346 static inline void ibuf_btr_pcur_commit_specify_mtr(
347 btr_pcur_t *pcur, /*!< in/out: persistent cursor */
348 mtr_t *mtr) /*!< in/out: mini-transaction */
349 {
350 ut_d(ibuf_exit(mtr));
351 pcur->commit_specify_mtr(mtr);
352 }
353
354 /** Gets the ibuf header page and x-latches it.
355 @return insert buffer header page */
356 static page_t *ibuf_header_page_get(mtr_t *mtr) /*!< in/out: mini-transaction */
357 {
358 buf_block_t *block;
359
360 ut_ad(!ibuf_inside(mtr));
361
362 block = buf_page_get(page_id_t(IBUF_SPACE_ID, FSP_IBUF_HEADER_PAGE_NO),
363 univ_page_size, RW_X_LATCH, UT_LOCATION_HERE, mtr);
364
365 buf_block_dbg_add_level(block, SYNC_IBUF_HEADER);
366
367 return (buf_block_get_frame(block));
368 }
369
370 /** Gets the root page and sx-latches it.
371 @return insert buffer tree root page */
372 static page_t *ibuf_tree_root_get(mtr_t *mtr) /*!< in: mtr */
373 {
374 buf_block_t *block;
375 page_t *root;
376
377 ut_ad(ibuf_inside(mtr));
378 ut_ad(mutex_own(&ibuf_mutex));
379
380 mtr_sx_lock(dict_index_get_lock(ibuf->index), mtr, UT_LOCATION_HERE);
381
382 /* only segment list access is exclusive each other */
383 block = buf_page_get(page_id_t(IBUF_SPACE_ID, FSP_IBUF_TREE_ROOT_PAGE_NO),
384 univ_page_size, RW_SX_LATCH, UT_LOCATION_HERE, mtr);
385
386 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE_NEW);
387
388 root = buf_block_get_frame(block);
389
390 ut_ad(page_get_space_id(root) == IBUF_SPACE_ID);
391 ut_ad(page_get_page_no(root) == FSP_IBUF_TREE_ROOT_PAGE_NO);
392 ut_ad(ibuf->empty == page_is_empty(root));
393
394 return (root);
395 }
396
397 #ifdef UNIV_IBUF_COUNT_DEBUG
398
399 /** Gets the ibuf count for a given page.
400 @param[in] page_id page id
401 @return number of entries in the insert buffer currently buffered for
402 this page */
403 ulint ibuf_count_get(const page_id_t &page_id) {
404 ibuf_count_check(page_id);
405
406 return (ibuf_counts[page_id.space()][page_id.page_no()]);
407 }
408
409 /** Sets the ibuf count for a given page.
410 @param[in] page_id page id
411 @param[in] val value to set */
412 static void ibuf_count_set(const page_id_t &page_id, ulint val) {
413 ibuf_count_check(page_id);
414 ut_a(val < UNIV_PAGE_SIZE);
415
416 ibuf_counts[page_id.space()][page_id.page_no()] = val;
417 }
418 #endif
419
420 /** Closes insert buffer and frees the data structures. */
421 void ibuf_close(void) {
422 if (ibuf == nullptr) {
423 return;
424 }
425
426 mutex_free(&ibuf_pessimistic_insert_mutex);
427
428 mutex_free(&ibuf_mutex);
429
430 mutex_free(&ibuf_bitmap_mutex);
431
432 dict_table_t *ibuf_table = ibuf->index->table;
433 rw_lock_free(&ibuf->index->lock);
434 dict_mem_index_free(ibuf->index);
435 dict_mem_table_free(ibuf_table);
436
437 ut::free(ibuf);
438 ibuf = nullptr;
439 }
440
441 /** Updates the size information of the ibuf, assuming the segment size has not
442 changed. */
443 static void ibuf_size_update(const page_t *root) /*!< in: ibuf tree root */
444 {
445 ut_ad(mutex_own(&ibuf_mutex));
446
447 ibuf->free_list_len =
448 flst_get_len(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST);
449
450 ibuf->height = 1 + btr_page_get_level(root);
451
452 /* the '1 +' is the ibuf header page */
453 ibuf->size = ibuf->seg_size - (1 + ibuf->free_list_len);
454 }
455
456 /** Creates the insert buffer data structure at a database startup and
457 initializes the data structures for the insert buffer. */
458 void ibuf_init_at_db_start(void) {
459 page_t *root;
460 mtr_t mtr;
461 ulint n_used;
462 page_t *header_page;
463
464 ibuf = static_cast<ibuf_t *>(
465 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(ibuf_t)));
466
467 /* At startup we initialize ibuf to have a maximum of
468 CHANGE_BUFFER_DEFAULT_SIZE in terms of percentage of the
469 buffer pool size. Once ibuf struct is initialized this
470 value is updated with the user supplied size by calling
471 ibuf_max_size_update(). */
472 ibuf->max_size = ((buf_pool_get_curr_size() / UNIV_PAGE_SIZE) *
473 CHANGE_BUFFER_DEFAULT_SIZE) /
474 100;
475
476 mutex_create(LATCH_ID_IBUF, &ibuf_mutex);
477
478 mutex_create(LATCH_ID_IBUF_BITMAP, &ibuf_bitmap_mutex);
479
480 mutex_create(LATCH_ID_IBUF_PESSIMISTIC_INSERT,
481 &ibuf_pessimistic_insert_mutex);
482
483 mtr_start(&mtr);
484
485 mtr_x_lock_space(fil_space_get_sys_space(), &mtr);
486
487 mutex_enter(&ibuf_mutex);
488
489 header_page = ibuf_header_page_get(&mtr);
490
491 fseg_n_reserved_pages(header_page + IBUF_HEADER + IBUF_TREE_SEG_HEADER,
492 &n_used, &mtr);
493 ibuf_enter(&mtr);
494
495 ut_ad(n_used >= 2);
496
497 ibuf->seg_size = n_used;
498
499 {
500 buf_block_t *block;
501
502 block = buf_page_get(page_id_t(IBUF_SPACE_ID, FSP_IBUF_TREE_ROOT_PAGE_NO),
503 univ_page_size, RW_X_LATCH, UT_LOCATION_HERE, &mtr);
504
505 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
506
507 root = buf_block_get_frame(block);
508 }
509
510 ibuf_size_update(root);
511 mutex_exit(&ibuf_mutex);
512
513 ibuf->empty = page_is_empty(root);
514 ibuf_mtr_commit(&mtr);
515
516 ibuf->index =
517 dict_mem_index_create("innodb_change_buffer", "CLUST_IND", IBUF_SPACE_ID,
518 DICT_CLUSTERED | DICT_IBUF, 1);
519 ibuf->index->id = DICT_IBUF_ID_MIN + IBUF_SPACE_ID;
520 ibuf->index->table = dict_mem_table_create("innodb_change_buffer",
521 IBUF_SPACE_ID, 1, 0, 0, 0, 0);
522 ibuf->index->n_uniq = REC_MAX_N_FIELDS;
523 rw_lock_create(index_tree_rw_lock_key, &ibuf->index->lock,
524 LATCH_ID_IBUF_INDEX_TREE);
525 ibuf->index->search_info = btr_search_info_create(ibuf->index->heap);
526 ibuf->index->page = FSP_IBUF_TREE_ROOT_PAGE_NO;
527 ut_d(ibuf->index->cached = true);
528 }
529
530 /** Updates the max_size value for ibuf. */
531 void ibuf_max_size_update(ulint new_val) /*!< in: new value in terms of
532 percentage of the buffer pool size */
533 {
534 ulint new_size =
535 ((buf_pool_get_curr_size() / UNIV_PAGE_SIZE) * new_val) / 100;
536 mutex_enter(&ibuf_mutex);
537 ibuf->max_size = new_size;
538 mutex_exit(&ibuf_mutex);
539 }
540
541 #endif /* !UNIV_HOTBACKUP */
542 /** Initializes an ibuf bitmap page. */
543 void ibuf_bitmap_page_init(buf_block_t *block, /*!< in: bitmap page */
544 mtr_t *mtr) /*!< in: mtr */
545 {
546 page_t *page;
547 ulint byte_offset;
548
549 page = buf_block_get_frame(block);
550 fil_page_set_type(page, FIL_PAGE_IBUF_BITMAP);
551
552 /* Write all zeros to the bitmap */
553
554 byte_offset =
555 UT_BITS_IN_BYTES(block->page.size.physical() * IBUF_BITS_PER_PAGE);
556
557 memset(page + IBUF_BITMAP, 0, byte_offset);
558
559 /* The remaining area (up to the page trailer) is uninitialized. */
560
561 #ifndef UNIV_HOTBACKUP
562 mlog_write_initial_log_record(page, MLOG_IBUF_BITMAP_INIT, mtr);
563 #endif /* !UNIV_HOTBACKUP */
564 }
565
566 byte *ibuf_parse_bitmap_init(byte *ptr, byte *end_ptr [[maybe_unused]],
567 buf_block_t *block, mtr_t *mtr) {
568 if (block) {
569 ibuf_bitmap_page_init(block, mtr);
570 }
571
572 return (ptr);
573 }
574 #ifndef UNIV_HOTBACKUP
575 /** Gets the desired bits for a given page from a bitmap page.
576 @param[in] page Bitmap page
577 @param[in] page_id Page id whose bits to get
578 @param[in] page_size Page size
579 @param[in] latch_type MTR_MEMO_PAGE_X_FIX, MTR_MEMO_BUF_FIX, ...
580 @param[in,out] mtr Mini-transaction holding latch_type on the
581 bitmap page
582 @param[in] bit IBUF_BITMAP_FREE, IBUF_BITMAP_BUFFERED, ...
583 @return value of bits */
584 static inline ulint ibuf_bitmap_page_get_bits_low(
585 const page_t *page, const page_id_t &page_id, const page_size_t &page_size,
586 IF_DEBUG(ulint latch_type, mtr_t *mtr, ) ulint bit) {
587 ulint byte_offset;
588 ulint bit_offset;
589 ulint map_byte;
590 ulint value;
591
592 ut_ad(bit < IBUF_BITS_PER_PAGE);
593 static_assert(IBUF_BITS_PER_PAGE % 2 == 0,
594 "IBUF_BITS_PER_PAGE must be an even number!");
595 ut_ad(mtr_memo_contains_page(mtr, page, latch_type));
596
597 bit_offset =
598 (page_id.page_no() % page_size.physical()) * IBUF_BITS_PER_PAGE + bit;
599
600 byte_offset = bit_offset / 8;
601 bit_offset = bit_offset % 8;
602
603 ut_ad(byte_offset + IBUF_BITMAP < UNIV_PAGE_SIZE);
604
605 map_byte = mach_read_from_1(page + IBUF_BITMAP + byte_offset);
606
607 value = ut_bit_get_nth(map_byte, bit_offset);
608
609 if (bit == IBUF_BITMAP_FREE) {
610 ut_ad(bit_offset + 1 < 8);
611
612 value = value * 2 + ut_bit_get_nth(map_byte, bit_offset + 1);
613 }
614
615 return (value);
616 }
617
618 /** Gets the desired bits for a given page from a bitmap page.
619 @param[in] page Bitmap page
620 @param[in] page_id Page id whose bits to get
621 @param[in] page_size Page id whose bits to get
622 @param[in] bit IBUF_BITMAP_FREE, IBUF_BITMAP_BUFFERED, ...
623 @param[in,out] mtr Mini-transaction holding an x-latch on the
624 bitmap page
625 @return value of bits */
626 inline ulint ibuf_bitmap_page_get_bits(const page_t *page,
627 const page_id_t &page_id,
628 const page_size_t &page_size, ulint bit,
629 mtr_t *mtr [[maybe_unused]]) {
630 return ibuf_bitmap_page_get_bits_low(
631 page, page_id, page_size, IF_DEBUG(MTR_MEMO_PAGE_X_FIX, mtr, ) bit);
632 }
633
634 /** Sets the desired bit for a given page in a bitmap page.
635 @param[in,out] page bitmap page
636 @param[in] page_id page id whose bits to set
637 @param[in] page_size page size
638 @param[in] bit IBUF_BITMAP_FREE, IBUF_BITMAP_BUFFERED, ...
639 @param[in] val value to set
640 @param[in,out] mtr mtr containing an x-latch to the bitmap page */
641 static void ibuf_bitmap_page_set_bits(page_t *page, const page_id_t &page_id,
642 const page_size_t &page_size, ulint bit,
643 ulint val, mtr_t *mtr) {
644 ulint byte_offset;
645 ulint bit_offset;
646 ulint map_byte;
647
648 ut_ad(bit < IBUF_BITS_PER_PAGE);
649 static_assert(IBUF_BITS_PER_PAGE % 2 == 0,
650 "IBUF_BITS_PER_PAGE must be an even number!");
651 ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX));
652 #ifdef UNIV_IBUF_COUNT_DEBUG
653 ut_a((bit != IBUF_BITMAP_BUFFERED) || (val != 0) ||
654 (0 == ibuf_count_get(page_id)));
655 #endif
656
657 bit_offset =
658 (page_id.page_no() % page_size.physical()) * IBUF_BITS_PER_PAGE + bit;
659
660 byte_offset = bit_offset / 8;
661 bit_offset = bit_offset % 8;
662
663 ut_ad(byte_offset + IBUF_BITMAP < UNIV_PAGE_SIZE);
664
665 map_byte = mach_read_from_1(page + IBUF_BITMAP + byte_offset);
666
667 if (bit == IBUF_BITMAP_FREE) {
668 ut_ad(bit_offset + 1 < 8);
669 ut_ad(val <= 3);
670
671 map_byte = ut_bit_set_nth(map_byte, bit_offset, val / 2);
672 map_byte = ut_bit_set_nth(map_byte, bit_offset + 1, val % 2);
673 } else {
674 ut_ad(val <= 1);
675 map_byte = ut_bit_set_nth(map_byte, bit_offset, val);
676 }
677
678 mlog_write_ulint(page + IBUF_BITMAP + byte_offset, map_byte, MLOG_1BYTE, mtr);
679 }
680
681 /** Calculates the bitmap page number for a given page number.
682 @param[in] page_id page id
683 @param[in] page_size page size
684 @return the bitmap page id where the file page is mapped */
685 static inline const page_id_t ibuf_bitmap_page_no_calc(
686 const page_id_t &page_id, const page_size_t &page_size) {
687 page_no_t bitmap_page_no;
688
689 bitmap_page_no = FSP_IBUF_BITMAP_OFFSET +
690 (page_id.page_no() & ~(page_size.physical() - 1));
691
692 return (page_id_t(page_id.space(), bitmap_page_no));
693 }
694
695 /** Gets the ibuf bitmap page where the bits describing a given file page are
696 stored.
697 @param[in] page_id Page id of the file page
698 @param[in] page_size Page size of the file page
699 @param[in] location Location where called
700 @param[in,out] mtr Mini-transaction
701 @return bitmap page where the file page is mapped, that is, the bitmap
702 page containing the descriptor bits for the file page; the bitmap page
703 is x-latched */
704 static page_t *ibuf_bitmap_get_map_page(const page_id_t &page_id,
705 const page_size_t &page_size,
706 ut::Location location, mtr_t *mtr) {
707 buf_block_t *block;
708
709 block =
710 buf_page_get_gen(ibuf_bitmap_page_no_calc(page_id, page_size), page_size,
711 RW_X_LATCH, nullptr, Page_fetch::NORMAL, location, mtr);
712
713 buf_block_dbg_add_level(block, SYNC_IBUF_BITMAP);
714
715 return (buf_block_get_frame(block));
716 }
717
718 /** Sets the free bits of the page in the ibuf bitmap. This is done in a
719 separate mini-transaction, hence this operation does not restrict further work
720 to only ibuf bitmap operations, which would result if the latch to the bitmap
721 page were kept. */
722 static inline void ibuf_set_free_bits_low(
723 const buf_block_t *block, /*!< in: index page; free bits are set if
724 the index is non-clustered and page
725 level is 0 */
726 ulint val, /*!< in: value to set: < 4 */
727 mtr_t *mtr) /*!< in/out: mtr */
728 {
729 page_t *bitmap_page;
730
731 if (!page_is_leaf(buf_block_get_frame(block))) {
732 return;
733 }
734
735 bitmap_page = ibuf_bitmap_get_map_page(block->page.id, block->page.size,
736 UT_LOCATION_HERE, mtr);
737
738 #ifdef UNIV_IBUF_DEBUG
739 ut_a(val <= ibuf_index_page_calc_free(block));
740 #endif /* UNIV_IBUF_DEBUG */
741
742 ibuf_bitmap_page_set_bits(bitmap_page, block->page.id, block->page.size,
743 IBUF_BITMAP_FREE, val, mtr);
744 }
745
746 /** Sets the free bit of the page in the ibuf bitmap. This is done in a separate
747 mini-transaction, hence this operation does not restrict further work to only
748 ibuf bitmap operations, which would result if the latch to the bitmap page
749 were kept. */
750 void ibuf_set_free_bits_func(
751 buf_block_t *block, /*!< in: index page of a non-clustered index;
752 free bit is reset if page level is 0 */
753 #ifdef UNIV_IBUF_DEBUG
754 ulint max_val, /*!< in: ULINT_UNDEFINED or a maximum
755 value which the bits must have before
756 setting; this is for debugging */
757 #endif /* UNIV_IBUF_DEBUG */
758 ulint val) /*!< in: value to set: < 4 */
759 {
760 mtr_t mtr;
761 page_t *page;
762 page_t *bitmap_page;
763
764 page = buf_block_get_frame(block);
765
766 if (!page_is_leaf(page)) {
767 return;
768 }
769
770 mtr_start(&mtr);
771
772 const fil_space_t *space = fil_space_get(block->page.id.space());
773
774 bitmap_page = ibuf_bitmap_get_map_page(block->page.id, block->page.size,
775 UT_LOCATION_HERE, &mtr);
776
777 switch (space->purpose) {
778 case FIL_TYPE_TABLESPACE:
779 break;
780 case FIL_TYPE_TEMPORARY:
781 case FIL_TYPE_IMPORT:
782 mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO);
783 }
784
785 #ifdef UNIV_IBUF_DEBUG
786 if (max_val != ULINT_UNDEFINED) {
787 ulint old_val;
788
789 old_val = ibuf_bitmap_page_get_bits(bitmap_page, block->page.id,
790 IBUF_BITMAP_FREE, &mtr);
791 #if 0
792 if (old_val != max_val) {
793 fprintf(stderr,
794 "Ibuf: page %lu old val %lu max val %lu\n",
795 page_get_page_no(page),
796 old_val, max_val);
797 }
798 #endif
799
800 ut_a(old_val <= max_val);
801 }
802 #if 0
803 fprintf(stderr, "Setting page no %lu free bits to %lu should be %lu\n",
804 page_get_page_no(page), val,
805 ibuf_index_page_calc_free(block));
806 #endif
807
808 ut_a(val <= ibuf_index_page_calc_free(block));
809 #endif /* UNIV_IBUF_DEBUG */
810
811 ibuf_bitmap_page_set_bits(bitmap_page, block->page.id, block->page.size,
812 IBUF_BITMAP_FREE, val, &mtr);
813
814 mtr_commit(&mtr);
815 }
816
817 /** Resets the free bits of the page in the ibuf bitmap. This is done in a
818 separate mini-transaction, hence this operation does not restrict
819 further work to only ibuf bitmap operations, which would result if the
820 latch to the bitmap page were kept. NOTE: The free bits in the insert
821 buffer bitmap must never exceed the free space on a page. It is safe
822 to decrement or reset the bits in the bitmap in a mini-transaction
823 that is committed before the mini-transaction that affects the free
824 space. */
825 void ibuf_reset_free_bits(
826 buf_block_t *block) /*!< in: index page; free bits are set to 0
827 if the index is a non-clustered
828 non-unique, and page level is 0 */
829 {
830 ibuf_set_free_bits(block, 0, ULINT_UNDEFINED);
831 }
832
833 /** Updates the free bits for an uncompressed page to reflect the present
834 state. Does this in the mtr given, which means that the latching
835 order rules virtually prevent any further operations for this OS
836 thread until mtr is committed. NOTE: The free bits in the insert
837 buffer bitmap must never exceed the free space on a page. It is safe
838 to set the free bits in the same mini-transaction that updated the
839 page. */
840 void ibuf_update_free_bits_low(const buf_block_t *block, /*!< in: index page */
841 ulint max_ins_size, /*!< in: value of
842 maximum insert size
843 with reorganize before
844 the latest operation
845 performed to the page */
846 mtr_t *mtr) /*!< in/out: mtr */
847 {
848 ulint before;
849 ulint after;
850
851 ut_a(!buf_block_get_page_zip(block));
852
853 before =
854 ibuf_index_page_calc_free_bits(block->page.size.logical(), max_ins_size);
855
856 after = ibuf_index_page_calc_free(block);
857
858 /* This approach cannot be used on compressed pages, since the
859 computed value of "before" often does not match the current
860 state of the bitmap. This is because the free space may
861 increase or decrease when a compressed page is reorganized. */
862 if (before != after) {
863 ibuf_set_free_bits_low(block, after, mtr);
864 }
865 }
866
867 /** Updates the free bits for a compressed page to reflect the present
868 state. Does this in the mtr given, which means that the latching
869 order rules virtually prevent any further operations for this OS
870 thread until mtr is committed. NOTE: The free bits in the insert
871 buffer bitmap must never exceed the free space on a page. It is safe
872 to set the free bits in the same mini-transaction that updated the
873 page. */
874 void ibuf_update_free_bits_zip(buf_block_t *block, /*!< in/out: index page */
875 mtr_t *mtr) /*!< in/out: mtr */
876 {
877 page_t *bitmap_page;
878 ulint after;
879
880 ut_a(page_is_leaf(buf_block_get_frame(block)));
881 ut_a(block->page.size.is_compressed());
882
883 bitmap_page = ibuf_bitmap_get_map_page(block->page.id, block->page.size,
884 UT_LOCATION_HERE, mtr);
885
886 after = ibuf_index_page_calc_free_zip(block);
887
888 if (after == 0) {
889 /* We move the page to the front of the buffer pool LRU list:
890 the purpose of this is to prevent those pages to which we
891 cannot make inserts using the insert buffer from slipping
892 out of the buffer pool */
893
894 buf_page_make_young(&block->page);
895 }
896
897 ibuf_bitmap_page_set_bits(bitmap_page, block->page.id, block->page.size,
898 IBUF_BITMAP_FREE, after, mtr);
899 }
900
901 /** Updates the free bits for the two pages to reflect the present state.
902 Does this in the mtr given, which means that the latching order rules
903 virtually prevent any further operations until mtr is committed.
904 NOTE: The free bits in the insert buffer bitmap must never exceed the
905 free space on a page. It is safe to set the free bits in the same
906 mini-transaction that updated the pages. */
907 void ibuf_update_free_bits_for_two_pages_low(
908 buf_block_t *block1, /*!< in: index page */
909 buf_block_t *block2, /*!< in: index page */
910 mtr_t *mtr) /*!< in: mtr */
911 {
912 ulint state;
913 ut_ad(!fsp_is_system_temporary(block1->page.id.space()));
914 ut_ad(block1->page.id.space() == block2->page.id.space());
915
916 /* As we have to x-latch two random bitmap pages, we have to acquire
917 the bitmap mutex to prevent a deadlock with a similar operation
918 performed by another OS thread. */
919
920 mutex_enter(&ibuf_bitmap_mutex);
921
922 state = ibuf_index_page_calc_free(block1);
923
924 ibuf_set_free_bits_low(block1, state, mtr);
925
926 state = ibuf_index_page_calc_free(block2);
927
928 ibuf_set_free_bits_low(block2, state, mtr);
929
930 mutex_exit(&ibuf_bitmap_mutex);
931 }
932
933 /** Returns true if the page is one of the fixed address ibuf pages.
934 @param[in] page_id page id
935 @param[in] page_size page size
936 @return true if a fixed address ibuf i/o page */
937 static inline bool ibuf_fixed_addr_page(const page_id_t &page_id,
938 const page_size_t &page_size) {
939 return ((page_id.space() == IBUF_SPACE_ID &&
940 page_id.page_no() == IBUF_TREE_ROOT_PAGE_NO) ||
941 ibuf_bitmap_page(page_id, page_size));
942 }
943
944 /** Checks if a page is a level 2 or 3 page in the ibuf hierarchy of pages.
945 Must not be called when recv_no_ibuf_operations==true.
946 @param[in] page_id page id
947 @param[in] page_size page size
948 @param[in] x_latch false if relaxed check (avoid latching the
949 bitmap page)
950 @param[in] location Location where called
951 @param[in,out] mtr mtr which will contain an x-latch to the
952 bitmap page if the page is not one of the fixed address ibuf pages, or NULL,
953 in which case a new transaction is created.
954 @return true if level 2 or level 3 page */
955 bool ibuf_page_low(const page_id_t &page_id, const page_size_t &page_size,
956 IF_DEBUG(bool x_latch, ) ut::Location location, mtr_t *mtr) {
957 ulint ret;
958 mtr_t local_mtr;
959 page_t *bitmap_page;
960
961 ut_ad(!recv_no_ibuf_operations);
962 ut_ad(x_latch || mtr == nullptr);
963
964 if (ibuf_fixed_addr_page(page_id, page_size)) {
965 return true;
966 } else if (page_id.space() != IBUF_SPACE_ID) {
967 return false;
968 }
969
970 ut_ad(fil_space_get_type(IBUF_SPACE_ID) == FIL_TYPE_TABLESPACE);
971
972 #ifdef UNIV_DEBUG
973 if (!x_latch) {
974 mtr_start(&local_mtr);
975
976 /* Get the bitmap page without a page latch, so that
977 we will not be violating the latching order when
978 another bitmap page has already been latched by this
979 thread. The page will be buffer-fixed, and thus it
980 cannot be removed or relocated while we are looking at
981 it. The contents of the page could change, but the
982 IBUF_BITMAP_IBUF bit that we are interested in should
983 not be modified by any other thread. Nobody should be
984 calling ibuf_add_free_page() or ibuf_remove_free_page()
985 while the page is linked to the insert buffer b-tree. */
986
987 bitmap_page = buf_block_get_frame(buf_page_get_gen(
988 ibuf_bitmap_page_no_calc(page_id, page_size), page_size, RW_NO_LATCH,
989 nullptr, Page_fetch::NO_LATCH, location, &local_mtr));
990
991 ret = ibuf_bitmap_page_get_bits_low(bitmap_page, page_id, page_size,
992 MTR_MEMO_BUF_FIX, &local_mtr,
993 IBUF_BITMAP_IBUF);
994
995 mtr_commit(&local_mtr);
996 return (ret);
997 }
998 #endif /* UNIV_DEBUG */
999
1000 if (mtr == nullptr) {
1001 mtr = &local_mtr;
1002 mtr_start(mtr);
1003 }
1004
1005 bitmap_page = ibuf_bitmap_get_map_page(page_id, page_size, location, mtr);
1006
1007 ret = ibuf_bitmap_page_get_bits(bitmap_page, page_id, page_size,
1008 IBUF_BITMAP_IBUF, mtr);
1009
1010 if (mtr == &local_mtr) {
1011 mtr_commit(mtr);
1012 }
1013
1014 return ret != 0;
1015 }
1016
1017 /** Returns the page number field of an ibuf record.
1018 @param[in] mtr mini-transaction owning rec
1019 @param[in] rec ibuf record
1020 @return page number */
1021 static page_no_t ibuf_rec_get_page_no_func(IF_DEBUG(mtr_t *mtr, )
1022 const rec_t *rec) {
1023 const byte *field;
1024 ulint len;
1025
1026 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
1027 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
1028 ut_ad(ibuf_inside(mtr));
1029 ut_ad(rec_get_n_fields_old_raw(rec) > 2);
1030
1031 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_MARKER, &len);
1032
1033 ut_a(len == 1);
1034
1035 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_PAGE, &len);
1036
1037 ut_a(len == 4);
1038
1039 return (mach_read_from_4(field));
1040 }
1041
1042 static inline page_no_t ibuf_rec_get_page_no(mtr_t *mtr [[maybe_unused]],
1043 const rec_t *rec) {
1044 return ibuf_rec_get_page_no_func(IF_DEBUG(mtr, ) rec);
1045 }
1046
1047 /** Returns the space id field of an ibuf record. For < 4.1.x format records
1048 returns 0.
1049 @param[in] mtr mini-transaction owning rec
1050 @param[in] rec ibuf record
1051 @return space id */
1052 static space_id_t ibuf_rec_get_space_func(IF_DEBUG(mtr_t *mtr, )
1053 const rec_t *rec) {
1054 const byte *field;
1055 ulint len;
1056
1057 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
1058 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
1059 ut_ad(ibuf_inside(mtr));
1060 ut_ad(rec_get_n_fields_old_raw(rec) > 2);
1061
1062 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_MARKER, &len);
1063
1064 ut_a(len == 1);
1065
1066 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_SPACE, &len);
1067
1068 ut_a(len == 4);
1069
1070 return (mach_read_from_4(field));
1071 }
1072
1073 static inline space_id_t ibuf_rec_get_space(mtr_t *mtr [[maybe_unused]],
1074 const rec_t *rec) {
1075 return ibuf_rec_get_space_func(IF_DEBUG(mtr, ) rec);
1076 }
1077
1078 /** Get various information about an ibuf record in >= 4.1.x format.
1079 @param[in] mtr Mini-transaction owning rec, or nullptr if this
1080 is called from ibuf_rec_has_multi_value().
1081 Because it's from page_validate() which doesn't
1082 have mtr at hand
1083 @param[in] rec Ibuf record
1084 @param[in,out] op Operation type, or NULL
1085 @param[in,out] comp Compact flag, or NULL
1086 @param[in,out] info_len Length of info fields at the start of the fourth
1087 field, or NULL
1088 @param[in] counter Counter value, or NULL */
1089 static void ibuf_rec_get_info_func(IF_DEBUG(mtr_t *mtr, ) const rec_t *rec,
1090 ibuf_op_t *op, bool *comp, ulint *info_len,
1091 ulint *counter) {
1092 const byte *types;
1093 ulint fields;
1094 ulint len;
1095
1096 /* Local variables to shadow arguments. */
1097 ibuf_op_t op_local;
1098 bool comp_local;
1099 ulint info_len_local;
1100 ulint counter_local;
1101
1102 ut_ad(mtr == nullptr ||
1103 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
1104 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
1105 ut_ad(mtr == nullptr || ibuf_inside(mtr));
1106 fields = rec_get_n_fields_old_raw(rec);
1107 ut_a(fields > IBUF_REC_FIELD_USER);
1108
1109 types = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_METADATA, &len);
1110
1111 info_len_local = len % DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE;
1112
1113 switch (info_len_local) {
1114 case 0:
1115 case 1:
1116 op_local = IBUF_OP_INSERT;
1117 comp_local = info_len_local;
1118 ut_ad(!counter);
1119 counter_local = ULINT_UNDEFINED;
1120 break;
1121
1122 case IBUF_REC_INFO_SIZE:
1123 op_local = (ibuf_op_t)types[IBUF_REC_OFFSET_TYPE];
1124 comp_local = types[IBUF_REC_OFFSET_FLAGS] & IBUF_REC_COMPACT;
1125 counter_local = mach_read_from_2(types + IBUF_REC_OFFSET_COUNTER);
1126 break;
1127
1128 default:
1129 ut_error;
1130 }
1131
1132 ut_a(op_local < IBUF_OP_COUNT);
1133 ut_a((len - info_len_local) ==
1134 (fields - IBUF_REC_FIELD_USER) * DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE);
1135
1136 if (op) {
1137 *op = op_local;
1138 }
1139
1140 if (comp) {
1141 *comp = comp_local;
1142 }
1143
1144 if (info_len) {
1145 *info_len = info_len_local;
1146 }
1147
1148 if (counter) {
1149 *counter = counter_local;
1150 }
1151 }
1152
1153 inline void ibuf_rec_get_info(mtr_t *mtr [[maybe_unused]], const rec_t *rec,
1154 ibuf_op_t *op, bool *comp, ulint *info_len,
1155 ulint *counter) {
1156 ibuf_rec_get_info_func(IF_DEBUG(mtr, ) rec, op, comp, info_len, counter);
1157 }
1158
1159 /** Returns the operation type field of an ibuf record.
1160 @param[in] mtr mini-transaction owning rec
1161 @param[in] rec ibuf record
1162 @return operation type */
1163 static ibuf_op_t ibuf_rec_get_op_type_func(IF_DEBUG(mtr_t *mtr, )
1164 const rec_t *rec) {
1165 ulint len;
1166
1167 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
1168 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
1169 ut_ad(ibuf_inside(mtr));
1170 ut_ad(rec_get_n_fields_old_raw(rec) > 2);
1171
1172 (void)rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_MARKER, &len);
1173
1174 if (len > 1) {
1175 /* This is a < 4.1.x format record */
1176
1177 return (IBUF_OP_INSERT);
1178 } else {
1179 ibuf_op_t op;
1180
1181 ibuf_rec_get_info_func(IF_DEBUG(mtr, ) rec, &op, nullptr, nullptr, nullptr);
1182
1183 return (op);
1184 }
1185 }
1186
1187 inline ibuf_op_t ibuf_rec_get_op_type(mtr_t *mtr [[maybe_unused]],
1188 const rec_t *rec) {
1189 return ibuf_rec_get_op_type_func(IF_DEBUG(mtr, ) rec);
1190 }
1191
1192 /** Read the first two bytes from a record's fourth field (counter field in
1193 new records; something else in older records).
1194 @return "counter" field, or ULINT_UNDEFINED if for some reason it
1195 can't be read */
1196 ulint ibuf_rec_get_counter(const rec_t *rec) /*!< in: ibuf record */
1197 {
1198 const byte *ptr;
1199 ulint len;
1200
1201 if (rec_get_n_fields_old_raw(rec) <= IBUF_REC_FIELD_METADATA) {
1202 return (ULINT_UNDEFINED);
1203 }
1204
1205 /* nullptr for index as it can't be clustered index */
1206 ptr = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_METADATA, &len);
1207
1208 if (len >= 2) {
1209 return (mach_read_from_2(ptr));
1210 } else {
1211 return (ULINT_UNDEFINED);
1212 }
1213 }
1214
1215 bool ibuf_rec_has_multi_value(const rec_t *rec) {
1216 ulint len;
1217 ulint info_len;
1218 uint32_t n_fields = rec_get_n_fields_old_raw(rec) - IBUF_REC_FIELD_USER;
1219 /* nullptr for index as it can't be clustered index */
1220 const byte *types =
1221 rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_METADATA, &len);
1222
1223 ibuf_rec_get_info(nullptr, rec, nullptr, nullptr, &info_len, nullptr);
1224 types += info_len;
1225
1226 for (uint32_t i = 0; i < n_fields; ++i) {
1227 dtype_t dtype;
1228
1229 dtype_new_read_for_order_and_null_size(&dtype, types);
1230
1231 if ((dtype.prtype & DATA_MULTI_VALUE) != 0) {
1232 return (true);
1233 }
1234
1235 types += DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE;
1236 }
1237
1238 return (false);
1239 }
1240
1241 /** Add accumulated operation counts to a permanent array. Both arrays must be
1242 of size IBUF_OP_COUNT. */
1243 static void ibuf_add_ops(
1244 std::atomic<ulint> *arr, /*!< in/out: array to modify */
1245 const ulint *ops) /*!< in: operation counts */
1246
1247 {
1248 ulint i;
1249
1250 for (i = 0; i < IBUF_OP_COUNT; i++) {
1251 arr[i].fetch_add(ops[i]);
1252 }
1253 }
1254
1255 /** Print operation counts. The array must be of size IBUF_OP_COUNT. */
1256 static void ibuf_print_ops(
1257 const std::atomic<ulint> *ops, /*!< in: operation counts */
1258 FILE *file) /*!< in: file where to print */
1259 {
1260 static const char *op_names[] = {"insert", "delete mark", "delete"};
1261 ulint i;
1262
1263 static_assert(UT_ARR_SIZE(op_names) == IBUF_OP_COUNT);
1264
1265 for (i = 0; i < IBUF_OP_COUNT; i++) {
1266 fprintf(file, "%s %lu%s", op_names[i], (ulong)ops[i].load(),
1267 (i < (IBUF_OP_COUNT - 1)) ? ", " : "");
1268 }
1269
1270 putc('\n', file);
1271 }
1272
1273 /** Creates a dummy index for inserting a record to a non-clustered index.
1274 @return dummy index */
1275 static dict_index_t *ibuf_dummy_index_create(
1276 ulint n, /*!< in: number of fields */
1277 bool comp) /*!< in: true=use compact record format */
1278 {
1279 dict_table_t *table;
1280 dict_index_t *index;
1281
1282 table = dict_mem_table_create("IBUF_DUMMY", DICT_HDR_SPACE, n, 0, 0,
1283 comp ? DICT_TF_COMPACT : 0, 0);
1284
1285 index =
1286 dict_mem_index_create("IBUF_DUMMY", "IBUF_DUMMY", DICT_HDR_SPACE, 0, n);
1287
1288 index->table = table;
1289
1290 /* avoid ut_ad(index->cached) in dict_index_get_n_unique_in_tree */
1291 index->cached = true;
1292
1293 return (index);
1294 }
1295 /** Add a column to the dummy index */
1296 static void ibuf_dummy_index_add_col(
1297 dict_index_t *index, /*!< in: dummy index */
1298 const dtype_t *type, /*!< in: the data type of the column */
1299 ulint len) /*!< in: length of the column */
1300 {
1301 ulint i = index->table->n_def;
1302 dict_mem_table_add_col(index->table, nullptr, nullptr, dtype_get_mtype(type),
1303 dtype_get_prtype(type), dtype_get_len(type), true);
1304 dict_index_add_col(index, index->table, index->table->get_col(i), len, true);
1305 }
1306 /** Deallocates a dummy index for inserting a record to a non-clustered index.
1307 */
1308 static void ibuf_dummy_index_free(
1309 dict_index_t *index) /*!< in, own: dummy index */
1310 {
1311 dict_table_t *table = index->table;
1312
1313 dict_mem_index_free(index);
1314 dict_mem_table_free(table);
1315 }
1316
1317 /** Builds the entry used to
1318
1319 1) IBUF_OP_INSERT: insert into a non-clustered index
1320
1321 2) IBUF_OP_DELETE_MARK: find the record whose delete-mark flag we need to
1322 activate
1323
1324 3) IBUF_OP_DELETE: find the record we need to delete
1325
1326 when we have the corresponding record in an ibuf index.
1327
1328 NOTE that as we copy pointers to fields in ibuf_rec, the caller must
1329 hold a latch to the ibuf_rec page as long as the entry is used!
1330 @param[in] mtr mini-transaction owning rec
1331 @param[in] ibuf_rec record in an insert buffer
1332 @param[in] heap heap where built
1333 @param[out] pindex own: dummy index that describes the entry
1334 @return own: entry to insert to a non-clustered index */
1335 static dtuple_t *ibuf_build_entry_from_ibuf_rec_func(IF_DEBUG(mtr_t *mtr, )
1336 const rec_t *ibuf_rec,
1337 mem_heap_t *heap,
1338 dict_index_t **pindex) {
1339 dtuple_t *tuple;
1340 dfield_t *field;
1341 ulint n_fields;
1342 const byte *types;
1343 const byte *data;
1344 ulint len;
1345 ulint info_len;
1346 ulint i;
1347 bool comp;
1348 dict_index_t *index;
1349
1350 ut_ad(mtr_memo_contains_page(mtr, ibuf_rec, MTR_MEMO_PAGE_X_FIX) ||
1351 mtr_memo_contains_page(mtr, ibuf_rec, MTR_MEMO_PAGE_S_FIX));
1352 ut_ad(ibuf_inside(mtr));
1353
1354 data = rec_get_nth_field_old(nullptr, ibuf_rec, IBUF_REC_FIELD_MARKER, &len);
1355
1356 ut_a(len == 1);
1357 ut_a(*data == 0);
1358 ut_a(rec_get_n_fields_old_raw(ibuf_rec) > IBUF_REC_FIELD_USER);
1359
1360 n_fields = rec_get_n_fields_old_raw(ibuf_rec) - IBUF_REC_FIELD_USER;
1361
1362 tuple = dtuple_create(heap, n_fields);
1363
1364 types =
1365 rec_get_nth_field_old(nullptr, ibuf_rec, IBUF_REC_FIELD_METADATA, &len);
1366
1367 ibuf_rec_get_info_func(IF_DEBUG(mtr, ) ibuf_rec, nullptr, &comp, &info_len,
1368 nullptr);
1369
1370 index = ibuf_dummy_index_create(n_fields, comp);
1371
1372 len -= info_len;
1373 types += info_len;
1374
1375 ut_a(len == n_fields * DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE);
1376
1377 for (i = 0; i < n_fields; i++) {
1378 field = dtuple_get_nth_field(tuple, i);
1379
1380 data =
1381 rec_get_nth_field_old(nullptr, ibuf_rec, i + IBUF_REC_FIELD_USER, &len);
1382
1383 dfield_set_data(field, data, len);
1384
1385 dtype_new_read_for_order_and_null_size(
1386 dfield_get_type(field), types + i * DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE);
1387
1388 ibuf_dummy_index_add_col(index, dfield_get_type(field), len);
1389 }
1390
1391 /* Prevent an ut_ad() failure in page_zip_write_rec() by
1392 adding system columns to the dummy table pointed to by the
1393 dummy secondary index. The insert buffer is only used for
1394 secondary indexes, whose records never contain any system
1395 columns, such as DB_TRX_ID. */
1396 ut_d(dict_table_add_system_columns(index->table, index->table->heap));
1397
1398 *pindex = index;
1399
1400 return (tuple);
1401 }
1402
1403 inline dtuple_t *ibuf_build_entry_from_ibuf_rec(mtr_t *mtr [[maybe_unused]],
1404 const rec_t *ibuf_rec,
1405 mem_heap_t *heap,
1406 dict_index_t **pindex) {
1407 return ibuf_build_entry_from_ibuf_rec_func(IF_DEBUG(mtr, ) ibuf_rec, heap,
1408 pindex);
1409 }
1410 /** Get the data size.
1411 @return size of fields */
1412 static inline ulint ibuf_rec_get_size(
1413 const rec_t *rec, /*!< in: ibuf record */
1414 const byte *types, /*!< in: fields */
1415 ulint n_fields, /*!< in: number of fields */
1416 bool comp) /*!< in: 0=ROW_FORMAT=REDUNDANT,
1417 nonzero=ROW_FORMAT=COMPACT */
1418 {
1419 ulint i;
1420 ulint field_offset;
1421 ulint types_offset;
1422 ulint size = 0;
1423
1424 field_offset = IBUF_REC_FIELD_USER;
1425 types_offset = DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE;
1426
1427 for (i = 0; i < n_fields; i++) {
1428 ulint len;
1429 dtype_t dtype;
1430
1431 /* nullptr for index as it can't be clustered index */
1432 rec_get_nth_field_offs_old(nullptr, rec, i + field_offset, &len);
1433
1434 if (len != UNIV_SQL_NULL) {
1435 size += len;
1436 } else {
1437 dtype_new_read_for_order_and_null_size(&dtype, types);
1438
1439 size += dtype_get_sql_null_size(&dtype, comp);
1440 }
1441
1442 types += types_offset;
1443 }
1444
1445 return (size);
1446 }
1447
1448 /** Returns the space taken by a stored non-clustered index entry if converted
1449 to an index record.
1450 @param[in] mtr mini-transaction owning rec
1451 @param[in] ibuf_rec ibuf record
1452 @return size of index record in bytes + an upper limit of the space
1453 taken in the page directory */
1454 static ulint ibuf_rec_get_volume_func(IF_DEBUG(mtr_t *mtr, )
1455 const rec_t *ibuf_rec) {
1456 ulint len;
1457 const byte *data;
1458 const byte *types;
1459 ulint n_fields;
1460 ulint data_size;
1461 bool comp;
1462 ibuf_op_t op;
1463 ulint info_len;
1464
1465 ut_ad(mtr_memo_contains_page(mtr, ibuf_rec, MTR_MEMO_PAGE_X_FIX) ||
1466 mtr_memo_contains_page(mtr, ibuf_rec, MTR_MEMO_PAGE_S_FIX));
1467 ut_ad(ibuf_inside(mtr));
1468 ut_ad(rec_get_n_fields_old_raw(ibuf_rec) > 2);
1469
1470 data = rec_get_nth_field_old(nullptr, ibuf_rec, IBUF_REC_FIELD_MARKER, &len);
1471 ut_a(len == 1);
1472 ut_a(*data == 0);
1473
1474 types =
1475 rec_get_nth_field_old(nullptr, ibuf_rec, IBUF_REC_FIELD_METADATA, &len);
1476
1477 ibuf_rec_get_info_func(IF_DEBUG(mtr, ) ibuf_rec, &op, &comp, &info_len,
1478 nullptr);
1479
1480 if (op == IBUF_OP_DELETE_MARK || op == IBUF_OP_DELETE) {
1481 /* Delete-marking a record doesn't take any
1482 additional space, and while deleting a record
1483 actually frees up space, we have to play it safe and
1484 pretend it takes no additional space (the record
1485 might not exist, etc.). */
1486
1487 return (0);
1488 } else if (comp) {
1489 dtuple_t *entry;
1490 ulint volume;
1491 dict_index_t *dummy_index;
1492 mem_heap_t *heap = mem_heap_create(500, UT_LOCATION_HERE);
1493
1494 entry = ibuf_build_entry_from_ibuf_rec_func(IF_DEBUG(mtr, ) ibuf_rec, heap,
1495 &dummy_index);
1496
1497 volume = rec_get_converted_size(dummy_index, entry);
1498
1499 ibuf_dummy_index_free(dummy_index);
1500 mem_heap_free(heap);
1501
1502 return (volume + page_dir_calc_reserved_space(1));
1503 }
1504
1505 types += info_len;
1506 n_fields = rec_get_n_fields_old_raw(ibuf_rec) - IBUF_REC_FIELD_USER;
1507
1508 data_size = ibuf_rec_get_size(ibuf_rec, types, n_fields, comp);
1509
1510 return (data_size + rec_get_converted_extra_size(data_size, n_fields, false) +
1511 page_dir_calc_reserved_space(1));
1512 }
1513
1514 inline ulint ibuf_rec_get_volume(mtr_t *mtr [[maybe_unused]],
1515 const rec_t *rec) {
1516 return ibuf_rec_get_volume_func(IF_DEBUG(mtr, ) rec);
1517 }
1518
1519 /** Builds the tuple to insert to an ibuf tree when we have an entry for a
1520 non-clustered index.
1521
1522 NOTE that the original entry must be kept because we copy pointers to
1523 its fields.
1524
1525 @return own: entry to insert into an ibuf index tree */
1526 static dtuple_t *ibuf_entry_build(
1527 ibuf_op_t op, /*!< in: operation type */
1528 dict_index_t *index, /*!< in: non-clustered index */
1529 const dtuple_t *entry, /*!< in: entry for a non-clustered index */
1530 space_id_t space, /*!< in: space id */
1531 page_no_t page_no, /*!< in: index page number where entry should
1532 be inserted */
1533 ulint counter, /*!< in: counter value;
1534 ULINT_UNDEFINED=not used */
1535 mem_heap_t *heap) /*!< in: heap into which to build */
1536 {
1537 dtuple_t *tuple;
1538 dfield_t *field;
1539 const dfield_t *entry_field;
1540 dtype_t fake_type;
1541 ulint n_fields;
1542 byte *buf;
1543 byte *ti;
1544 byte *type_info;
1545 ulint i;
1546
1547 ut_ad(counter != ULINT_UNDEFINED || op == IBUF_OP_INSERT);
1548 ut_ad(counter == ULINT_UNDEFINED || counter <= 0xFFFF);
1549 ut_ad(op < IBUF_OP_COUNT);
1550
1551 memset(&fake_type, 0, sizeof(dtype_t));
1552
1553 /* We have to build a tuple with the following fields:
1554
1555 1-4) These are described at the top of this file.
1556
1557 5) The rest of the fields are copied from the entry.
1558
1559 All fields in the tuple are ordered like the type binary in our
1560 insert buffer tree. */
1561
1562 n_fields = dtuple_get_n_fields(entry);
1563
1564 tuple = dtuple_create(heap, n_fields + IBUF_REC_FIELD_USER);
1565
1566 /* 1) Space Id */
1567
1568 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_SPACE);
1569
1570 buf = static_cast<byte *>(mem_heap_alloc(heap, 4));
1571
1572 mach_write_to_4(buf, space);
1573
1574 dfield_set_data(field, buf, 4);
1575
1576 dfield_set_type(field, &fake_type);
1577
1578 /* 2) Marker byte */
1579
1580 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_MARKER);
1581
1582 buf = static_cast<byte *>(mem_heap_alloc(heap, 1));
1583
1584 /* We set the marker byte zero */
1585
1586 mach_write_to_1(buf, 0);
1587
1588 dfield_set_data(field, buf, 1);
1589
1590 dfield_set_type(field, &fake_type);
1591
1592 /* 3) Page number */
1593
1594 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_PAGE);
1595
1596 buf = static_cast<byte *>(mem_heap_alloc(heap, 4));
1597
1598 mach_write_to_4(buf, page_no);
1599
1600 dfield_set_data(field, buf, 4);
1601
1602 dfield_set_type(field, &fake_type);
1603
1604 /* 4) Type info, part #1 */
1605
1606 if (counter == ULINT_UNDEFINED) {
1607 i = dict_table_is_comp(index->table) ? 1 : 0;
1608 } else {
1609 ut_ad(counter <= 0xFFFF);
1610 i = IBUF_REC_INFO_SIZE;
1611 }
1612
1613 ti = type_info = static_cast<byte *>(
1614 mem_heap_alloc(heap, i + n_fields * DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE));
1615
1616 switch (i) {
1617 default:
1618 ut_error;
1619 break;
1620 case 1:
1621 /* set the flag for ROW_FORMAT=COMPACT */
1622 *ti++ = 0;
1623 [[fallthrough]];
1624 case 0:
1625 /* the old format does not allow delete buffering */
1626 ut_ad(op == IBUF_OP_INSERT);
1627 break;
1628 case IBUF_REC_INFO_SIZE:
1629 mach_write_to_2(ti + IBUF_REC_OFFSET_COUNTER, counter);
1630
1631 ti[IBUF_REC_OFFSET_TYPE] = (byte)op;
1632 ti[IBUF_REC_OFFSET_FLAGS] =
1633 dict_table_is_comp(index->table) ? IBUF_REC_COMPACT : 0;
1634 ti += IBUF_REC_INFO_SIZE;
1635 break;
1636 }
1637
1638 /* 5+) Fields from the entry */
1639
1640 for (i = 0; i < n_fields; i++) {
1641 ulint fixed_len;
1642 const dict_field_t *ifield;
1643
1644 field = dtuple_get_nth_field(tuple, i + IBUF_REC_FIELD_USER);
1645 entry_field = dtuple_get_nth_field(entry, i);
1646 dfield_copy(field, entry_field);
1647
1648 ifield = index->get_field(i);
1649 /* Prefix index columns of fixed-length columns are of
1650 fixed length. However, in the function call below,
1651 dfield_get_type(entry_field) contains the fixed length
1652 of the column in the clustered index. Replace it with
1653 the fixed length of the secondary index column. */
1654 fixed_len = ifield->fixed_len;
1655
1656 #ifdef UNIV_DEBUG
1657 if (fixed_len) {
1658 /* dict_index_add_col() should guarantee these */
1659 ut_ad(fixed_len <= (ulint)dfield_get_type(entry_field)->len);
1660 if (ifield->prefix_len) {
1661 ut_ad(ifield->prefix_len == fixed_len);
1662 } else {
1663 ut_ad(fixed_len == (ulint)dfield_get_type(entry_field)->len);
1664 }
1665 }
1666 #endif /* UNIV_DEBUG */
1667
1668 dtype_new_store_for_order_and_null_size(ti, dfield_get_type(entry_field),
1669 fixed_len);
1670 ti += DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE;
1671 }
1672
1673 /* 4) Type info, part #2 */
1674
1675 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_METADATA);
1676
1677 dfield_set_data(field, type_info, ti - type_info);
1678
1679 dfield_set_type(field, &fake_type);
1680
1681 /* Set all the types in the new tuple binary */
1682
1683 dtuple_set_types_binary(tuple, n_fields + IBUF_REC_FIELD_USER);
1684
1685 return (tuple);
1686 }
1687
1688 /** Builds a search tuple used to search buffered inserts for an index page.
1689 This is for >= 4.1.x format records.
1690 @return own: search tuple */
1691 static dtuple_t *ibuf_search_tuple_build(
1692 space_id_t space, /*!< in: space id */
1693 page_no_t page_no, /*!< in: index page number */
1694 mem_heap_t *heap) /*!< in: heap into which to build */
1695 {
1696 dtuple_t *tuple;
1697 dfield_t *field;
1698 dtype_t fake_type;
1699 byte *buf;
1700
1701 memset(&fake_type, 0, sizeof(dtype_t));
1702
1703 tuple = dtuple_create(heap, IBUF_REC_FIELD_METADATA);
1704
1705 /* Store the space id in tuple */
1706
1707 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_SPACE);
1708
1709 buf = static_cast<byte *>(mem_heap_alloc(heap, 4));
1710
1711 mach_write_to_4(buf, space);
1712
1713 dfield_set_data(field, buf, 4);
1714
1715 dfield_set_type(field, &fake_type);
1716
1717 /* Store the new format record marker byte */
1718
1719 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_MARKER);
1720
1721 buf = static_cast<byte *>(mem_heap_alloc(heap, 1));
1722
1723 mach_write_to_1(buf, 0);
1724
1725 dfield_set_data(field, buf, 1);
1726
1727 dfield_set_type(field, &fake_type);
1728
1729 /* Store the page number in tuple */
1730
1731 field = dtuple_get_nth_field(tuple, IBUF_REC_FIELD_PAGE);
1732
1733 buf = static_cast<byte *>(mem_heap_alloc(heap, 4));
1734
1735 mach_write_to_4(buf, page_no);
1736
1737 dfield_set_data(field, buf, 4);
1738
1739 dfield_set_type(field, &fake_type);
1740
1741 dtuple_set_types_binary(tuple, IBUF_REC_FIELD_METADATA);
1742
1743 return (tuple);
1744 }
1745
1746 /** Checks if there are enough pages in the free list of the ibuf tree that we
1747 dare to start a pessimistic insert to the insert buffer.
1748 @return true if enough free pages in list */
1749 static inline bool ibuf_data_enough_free_for_insert(void) {
1750 ut_ad(mutex_own(&ibuf_mutex));
1751
1752 /* We want a big margin of free pages, because a B-tree can sometimes
1753 grow in size also if records are deleted from it, as the node pointers
1754 can change, and we must make sure that we are able to delete the
1755 inserts buffered for pages that we read to the buffer pool, without
1756 any risk of running out of free space in the insert buffer. */
1757
1758 return (ibuf->free_list_len >= (ibuf->size / 2) + 3 * ibuf->height);
1759 }
1760
1761 /** Checks if there are enough pages in the free list of the ibuf tree that we
1762 should remove them and free to the file space management.
1763 @return true if enough free pages in list */
1764 static inline bool ibuf_data_too_much_free(void) {
1765 ut_ad(mutex_own(&ibuf_mutex));
1766
1767 return (ibuf->free_list_len >= 3 + (ibuf->size / 2) + 3 * ibuf->height);
1768 }
1769
1770 /** Allocates a new page from the ibuf file segment and adds it to the free
1771 list.
1772 @return true on success, false if no space left */
1773 static bool ibuf_add_free_page(void) {
1774 mtr_t mtr;
1775 page_t *header_page;
1776 buf_block_t *block;
1777 page_t *page;
1778 page_t *root;
1779 page_t *bitmap_page;
1780
1781 fil_space_t *space = fil_space_get_sys_space();
1782
1783 mtr_start(&mtr);
1784
1785 /* Acquire the fsp latch before the ibuf header, obeying the latching
1786 order */
1787 mtr_x_lock(&space->latch, &mtr, UT_LOCATION_HERE);
1788 header_page = ibuf_header_page_get(&mtr);
1789
1790 /* Allocate a new page: NOTE that if the page has been a part of a
1791 non-clustered index which has subsequently been dropped, then the
1792 page may have buffered inserts in the insert buffer, and these
1793 should be deleted from there. These get deleted when the page
1794 allocation creates the page in buffer. Thus the call below may end
1795 up calling the insert buffer routines and, as we yet have no latches
1796 to insert buffer tree pages, these routines can run without a risk
1797 of a deadlock. This is the reason why we created a special ibuf
1798 header page apart from the ibuf tree. */
1799
1800 block = fseg_alloc_free_page(header_page + IBUF_HEADER + IBUF_TREE_SEG_HEADER,
1801 0, FSP_UP, &mtr);
1802
1803 if (block == nullptr) {
1804 mtr_commit(&mtr);
1805
1806 return false;
1807 }
1808
1809 ut_ad(rw_lock_get_x_lock_count(&block->lock) == 1);
1810 ibuf_enter(&mtr);
1811 mutex_enter(&ibuf_mutex);
1812 root = ibuf_tree_root_get(&mtr);
1813
1814 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE_NEW);
1815 page = buf_block_get_frame(block);
1816
1817 /* Add the page to the free list and update the ibuf size data */
1818
1819 flst_add_last(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
1820 page + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, &mtr);
1821
1822 mlog_write_ulint(page + FIL_PAGE_TYPE, FIL_PAGE_IBUF_FREE_LIST, MLOG_2BYTES,
1823 &mtr);
1824
1825 ibuf->seg_size++;
1826 ibuf->free_list_len++;
1827
1828 /* Set the bit indicating that this page is now an ibuf tree page
1829 (level 2 page) */
1830
1831 const page_id_t page_id(IBUF_SPACE_ID, block->page.id.page_no());
1832 const page_size_t page_size(space->flags);
1833
1834 bitmap_page =
1835 ibuf_bitmap_get_map_page(page_id, page_size, UT_LOCATION_HERE, &mtr);
1836
1837 mutex_exit(&ibuf_mutex);
1838
1839 ibuf_bitmap_page_set_bits(bitmap_page, page_id, page_size, IBUF_BITMAP_IBUF,
1840 true, &mtr);
1841
1842 ibuf_mtr_commit(&mtr);
1843
1844 return true;
1845 }
1846
1847 /** Removes a page from the free list and frees it to the fsp system. */
1848 static void ibuf_remove_free_page(void) {
1849 mtr_t mtr;
1850 mtr_t mtr2;
1851 page_t *header_page;
1852 page_no_t page_no;
1853 page_t *page;
1854 page_t *root;
1855 page_t *bitmap_page;
1856
1857 fil_space_t *space = fil_space_get_sys_space();
1858
1859 mtr_start(&mtr);
1860
1861 const page_size_t page_size(space->flags);
1862
1863 /* Acquire the fsp latch before the ibuf header, obeying the latching
1864 order */
1865
1866 mtr_x_lock(&space->latch, &mtr, UT_LOCATION_HERE);
1867 header_page = ibuf_header_page_get(&mtr);
1868
1869 /* Prevent pessimistic inserts to insert buffer trees for a while */
1870 ibuf_enter(&mtr);
1871 mutex_enter(&ibuf_pessimistic_insert_mutex);
1872 mutex_enter(&ibuf_mutex);
1873
1874 if (!ibuf_data_too_much_free()) {
1875 mutex_exit(&ibuf_mutex);
1876 mutex_exit(&ibuf_pessimistic_insert_mutex);
1877
1878 ibuf_mtr_commit(&mtr);
1879
1880 return;
1881 }
1882
1883 ibuf_mtr_start(&mtr2);
1884
1885 root = ibuf_tree_root_get(&mtr2);
1886
1887 mutex_exit(&ibuf_mutex);
1888
1889 page_no =
1890 flst_get_last(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, &mtr2).page;
1891
1892 /* NOTE that we must release the latch on the ibuf tree root
1893 because in fseg_free_page we access level 1 pages, and the root
1894 is a level 2 page. */
1895
1896 ibuf_mtr_commit(&mtr2);
1897 ibuf_exit(&mtr);
1898
1899 /* Since pessimistic inserts were prevented, we know that the
1900 page is still in the free list. NOTE that also deletes may take
1901 pages from the free list, but they take them from the start, and
1902 the free list was so long that they cannot have taken the last
1903 page from it. */
1904
1905 fseg_free_page(header_page + IBUF_HEADER + IBUF_TREE_SEG_HEADER,
1906 IBUF_SPACE_ID, page_no, false, &mtr);
1907
1908 const page_id_t page_id(IBUF_SPACE_ID, page_no);
1909
1910 ut_d(buf_page_reset_file_page_was_freed(page_id));
1911
1912 ibuf_enter(&mtr);
1913
1914 mutex_enter(&ibuf_mutex);
1915
1916 root = ibuf_tree_root_get(&mtr);
1917
1918 ut_ad(page_no ==
1919 flst_get_last(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, &mtr).page);
1920
1921 {
1922 buf_block_t *block;
1923
1924 block = buf_page_get(page_id, univ_page_size, RW_X_LATCH, UT_LOCATION_HERE,
1925 &mtr);
1926
1927 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
1928
1929 page = buf_block_get_frame(block);
1930 }
1931
1932 /* Remove the page from the free list and update the ibuf size data */
1933
1934 flst_remove(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
1935 page + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, &mtr);
1936
1937 mutex_exit(&ibuf_pessimistic_insert_mutex);
1938
1939 ibuf->seg_size--;
1940 ibuf->free_list_len--;
1941
1942 /* Set the bit indicating that this page is no more an ibuf tree page
1943 (level 2 page) */
1944
1945 bitmap_page =
1946 ibuf_bitmap_get_map_page(page_id, page_size, UT_LOCATION_HERE, &mtr);
1947
1948 mutex_exit(&ibuf_mutex);
1949
1950 ibuf_bitmap_page_set_bits(bitmap_page, page_id, page_size, IBUF_BITMAP_IBUF,
1951 false, &mtr);
1952
1953 ut_d(buf_page_set_file_page_was_freed(page_id));
1954
1955 ibuf_mtr_commit(&mtr);
1956 }
1957
1958 /** Frees excess pages from the ibuf free list. This function is called when an
1959 OS thread calls fsp services to allocate a new file segment, or a new page to a
1960 file segment, and the thread did not own the fsp latch before this call. */
1961 void ibuf_free_excess_pages(void) {
1962 ut_ad(rw_lock_own(fil_space_get_latch(IBUF_SPACE_ID), RW_LOCK_X));
1963
1964 ut_ad(rw_lock_get_x_lock_count(fil_space_get_latch(IBUF_SPACE_ID)) == 1);
1965
1966 /* NOTE: We require that the thread did not own the latch before,
1967 because then we know that we can obey the correct latching order
1968 for ibuf latches */
1969
1970 if (!ibuf) {
1971 /* Not yet initialized; not sure if this is possible, but
1972 does no harm to check for it. */
1973
1974 return;
1975 }
1976
1977 /* Free at most a few pages at a time, so that we do not delay the
1978 requested service too much */
1979
1980 for (ulint i = 0; i < 4; i++) {
1981 mutex_enter(&ibuf_mutex);
1982 auto too_much_free = ibuf_data_too_much_free();
1983 mutex_exit(&ibuf_mutex);
1984
1985 if (!too_much_free) {
1986 return;
1987 }
1988
1989 ibuf_remove_free_page();
1990 }
1991 }
1992
1993 /** Reads page numbers from a leaf in an ibuf tree.
1994 @param[in] contract true if this function is called to contract the tree, false
1995 if this is called when a single page becomes full and we look if it pays to
1996 read also nearby pages
1997 @param[in] rec insert buffer record
1998 @param[in] mtr mini-transaction holding rec
1999 @param[in,out] space_ids space id's of the pages
2000 @param[in,out] page_nos buffer for at least IBUF_MAX_N_PAGES_MERGED many page
2001 numbers; the page numbers are in an ascending order
2002 @param[out] n_stored number of page numbers stored to page_nos in this function
2003 @return a lower limit for the combined volume of records which will be
2004 merged */
2005 static ulint ibuf_get_merge_page_nos_func(bool contract, const rec_t *rec,
2006 IF_DEBUG(mtr_t *mtr, )
2007 space_id_t *space_ids,
2008 page_no_t *page_nos,
2009 ulint *n_stored) {
2010 page_no_t prev_page_no;
2011 space_id_t prev_space_id;
2012 page_no_t first_page_no;
2013 space_id_t first_space_id;
2014 page_no_t rec_page_no;
2015 space_id_t rec_space_id;
2016 ulint sum_volumes;
2017 ulint volume_for_page;
2018 ulint rec_volume;
2019 ulint limit;
2020 ulint n_pages;
2021 #ifndef UNIV_DEBUG
2022 mtr_t *mtr = nullptr;
2023 #endif
2024
2025 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
2026 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
2027 ut_ad(ibuf_inside(mtr));
2028
2029 *n_stored = 0;
2030
2031 limit = std::min(IBUF_MAX_N_PAGES_MERGED, buf_pool_get_curr_size() / 4);
2032
2033 if (page_rec_is_supremum(rec)) {
2034 rec = page_rec_get_prev_const(rec);
2035 }
2036
2037 if (page_rec_is_infimum(rec)) {
2038 rec = page_rec_get_next_const(rec);
2039 }
2040
2041 if (page_rec_is_supremum(rec)) {
2042 return (0);
2043 }
2044
2045 first_page_no = ibuf_rec_get_page_no(mtr, rec);
2046 first_space_id = ibuf_rec_get_space(mtr, rec);
2047 n_pages = 0;
2048 prev_page_no = 0;
2049 prev_space_id = 0;
2050
2051 /* Go backwards from the first rec until we reach the border of the
2052 'merge area', or the page start or the limit of storable pages is
2053 reached */
2054
2055 while (!page_rec_is_infimum(rec) && UNIV_LIKELY(n_pages < limit)) {
2056 rec_page_no = ibuf_rec_get_page_no(mtr, rec);
2057 rec_space_id = ibuf_rec_get_space(mtr, rec);
2058
2059 if (rec_space_id != first_space_id ||
2060 (rec_page_no / IBUF_MERGE_AREA) != (first_page_no / IBUF_MERGE_AREA)) {
2061 break;
2062 }
2063
2064 if (rec_page_no != prev_page_no || rec_space_id != prev_space_id) {
2065 n_pages++;
2066 }
2067
2068 prev_page_no = rec_page_no;
2069 prev_space_id = rec_space_id;
2070
2071 rec = page_rec_get_prev_const(rec);
2072 }
2073
2074 rec = page_rec_get_next_const(rec);
2075
2076 /* At the loop start there is no prev page; we mark this with a pair
2077 of space id, page no (0, 0) for which there can never be entries in
2078 the insert buffer */
2079
2080 prev_page_no = 0;
2081 prev_space_id = 0;
2082 sum_volumes = 0;
2083 volume_for_page = 0;
2084
2085 while (*n_stored < limit) {
2086 if (page_rec_is_supremum(rec)) {
2087 /* When no more records available, mark this with
2088 another 'impossible' pair of space id, page no */
2089 rec_page_no = 1;
2090 rec_space_id = 0;
2091 } else {
2092 rec_page_no = ibuf_rec_get_page_no(mtr, rec);
2093 rec_space_id = ibuf_rec_get_space(mtr, rec);
2094 /* In the system tablespace the smallest
2095 possible secondary index leaf page number is
2096 bigger than FSP_DICT_HDR_PAGE_NO (7).
2097 In all tablespaces, pages 0 and 1 are reserved
2098 for the allocation bitmap and the change
2099 buffer bitmap. In file-per-table tablespaces,
2100 a file segment inode page will be created at
2101 page 2 and the clustered index tree is created
2102 at page 3. So for file-per-table tablespaces,
2103 page 4 is the smallest possible secondary
2104 index leaf page. CREATE TABLESPACE also initially
2105 uses pages 2 and 3 for the first created table,
2106 but that table may be dropped, allowing page 2
2107 to be reused for a secondary index leaf page.
2108 To keep this assertion simple, just
2109 make sure the page is >= 2. */
2110 ut_ad(rec_page_no >= FSP_FIRST_INODE_PAGE_NO);
2111 }
2112
2113 #ifdef UNIV_IBUF_DEBUG
2114 ut_a(*n_stored < IBUF_MAX_N_PAGES_MERGED);
2115 #endif
2116 if ((rec_space_id != prev_space_id || rec_page_no != prev_page_no) &&
2117 (prev_space_id != 0 || prev_page_no != 0)) {
2118 if (contract ||
2119 (prev_page_no == first_page_no && prev_space_id == first_space_id) ||
2120 (volume_for_page > ((IBUF_MERGE_THRESHOLD - 1) * 4 * UNIV_PAGE_SIZE /
2121 IBUF_PAGE_SIZE_PER_FREE_SPACE) /
2122 IBUF_MERGE_THRESHOLD)) {
2123 space_ids[*n_stored] = prev_space_id;
2124 page_nos[*n_stored] = prev_page_no;
2125
2126 (*n_stored)++;
2127
2128 sum_volumes += volume_for_page;
2129 }
2130
2131 if (rec_space_id != first_space_id ||
2132 rec_page_no / IBUF_MERGE_AREA != first_page_no / IBUF_MERGE_AREA) {
2133 break;
2134 }
2135
2136 volume_for_page = 0;
2137 }
2138
2139 if (rec_page_no == 1 && rec_space_id == 0) {
2140 /* Supremum record */
2141
2142 break;
2143 }
2144
2145 rec_volume = ibuf_rec_get_volume(mtr, rec);
2146
2147 volume_for_page += rec_volume;
2148
2149 prev_page_no = rec_page_no;
2150 prev_space_id = rec_space_id;
2151
2152 rec = page_rec_get_next_const(rec);
2153 }
2154
2155 #ifdef UNIV_IBUF_DEBUG
2156 ut_a(*n_stored <= IBUF_MAX_N_PAGES_MERGED);
2157 #endif
2158 #if 0
2159 fprintf(stderr, "Ibuf merge batch %lu pages %lu volume\n",
2160 *n_stored, sum_volumes);
2161 #endif
2162 return (sum_volumes);
2163 }
2164
2165 /** Get the matching records for space id.
2166 @return current rec or NULL */
2167 [[nodiscard]] static const rec_t *ibuf_get_user_rec(
2168 btr_pcur_t *pcur, /*!< in: the current cursor */
2169 mtr_t *mtr) /*!< in: mini-transaction */
2170 {
2171 do {
2172 const rec_t *rec = pcur->get_rec();
2173
2174 if (page_rec_is_user_rec(rec)) {
2175 return (rec);
2176 }
2177 } while (pcur->move_to_next(mtr));
2178
2179 return (nullptr);
2180 }
2181
2182 inline ulint ibuf_get_merge_page_nos(bool contract, const rec_t *rec,
2183 mtr_t *mtr [[maybe_unused]],
2184 space_id_t *ids, page_no_t *pages,
2185 ulint *n_stored) {
2186 return ibuf_get_merge_page_nos_func(contract, rec, IF_DEBUG(mtr, ) ids, pages,
2187 n_stored);
2188 }
2189
2190 /** Reads page numbers for a space id from an ibuf tree.
2191 @return a lower limit for the combined volume of records which will be
2192 merged */
2193 [[nodiscard]] static ulint ibuf_get_merge_pages(
2194 btr_pcur_t *pcur, /*!< in/out: cursor */
2195 space_id_t space, /*!< in: space for which to merge */
2196 ulint limit, /*!< in: max page numbers to read */
2197 page_no_t *pages, /*!< out: pages read */
2198 space_id_t *spaces, /*!< out: spaces read */
2199 ulint *n_pages, /*!< out: number of pages read */
2200 mtr_t *mtr) /*!< in: mini-transaction */
2201 {
2202 const rec_t *rec;
2203 ulint volume = 0;
2204
2205 ut_a(space != SPACE_UNKNOWN);
2206
2207 *n_pages = 0;
2208
2209 while ((rec = ibuf_get_user_rec(pcur, mtr)) != nullptr &&
2210 ibuf_rec_get_space(mtr, rec) == space && *n_pages < limit) {
2211 page_no_t page_no = ibuf_rec_get_page_no(mtr, rec);
2212
2213 if (*n_pages == 0 || pages[*n_pages - 1] != page_no) {
2214 spaces[*n_pages] = space;
2215 pages[*n_pages] = page_no;
2216 ++*n_pages;
2217 }
2218
2219 volume += ibuf_rec_get_volume(mtr, rec);
2220
2221 pcur->move_to_next(mtr);
2222 }
2223
2224 return (volume);
2225 }
2226
2227 /** Contracts insert buffer trees by reading pages to the buffer pool.
2228 @return a lower limit for the combined size in bytes of entries which
2229 will be merged from ibuf trees to the pages read, 0 if ibuf is
2230 empty */
2231 static ulint ibuf_merge_pages(
2232 ulint *n_pages, /*!< out: number of pages to which merged */
2233 bool sync) /*!< in: true if the caller wants to wait for
2234 the issued read with the highest tablespace
2235 address to complete */
2236 {
2237 mtr_t mtr;
2238 btr_pcur_t pcur;
2239 ulint sum_sizes;
2240 page_no_t page_nos[IBUF_MAX_N_PAGES_MERGED];
2241 space_id_t space_ids[IBUF_MAX_N_PAGES_MERGED];
2242
2243 *n_pages = 0;
2244
2245 /* The buf_read_ibuf_merge_pages(sync,..) will result in changes being applied
2246 to pages, which will generate redo log, so it is important to ensure redo log
2247 has enough space, if sync=true. We don't call log_free_check() here because
2248 during ibuf contraction, we are starting a nested mtr and, log_free_check()
2249 should have been called *before* starting the parent mtr. Usual background
2250 thread does not start under a parent mtr to do the page merges. It always
2251 does async IO though */
2252 ut_ad(mtr_t::is_this_thread_inside_mtr() || !sync);
2253
2254 ibuf_mtr_start(&mtr);
2255
2256 /* Open a cursor to a randomly chosen leaf of the tree, at a random
2257 position within the leaf */
2258 bool available;
2259
2260 available = pcur.set_random_position(ibuf->index, BTR_SEARCH_LEAF, &mtr,
2261 UT_LOCATION_HERE);
2262 /* No one should make this index unavailable when server is running */
2263 ut_a(available);
2264
2265 ut_ad(page_validate(pcur.get_page(), ibuf->index));
2266
2267 if (page_is_empty(pcur.get_page())) {
2268 /* If a B-tree page is empty, it must be the root page
2269 and the whole B-tree must be empty. InnoDB does not
2270 allow empty B-tree pages other than the root. */
2271 ut_ad(ibuf->empty);
2272 ut_ad(page_get_space_id(pcur.get_page()) == IBUF_SPACE_ID);
2273 ut_ad(page_get_page_no(pcur.get_page()) == FSP_IBUF_TREE_ROOT_PAGE_NO);
2274 ut_ad(!mtr.has_any_log_record());
2275
2276 ibuf_mtr_commit(&mtr);
2277 pcur.close();
2278
2279 return (0);
2280 }
2281
2282 sum_sizes = ibuf_get_merge_page_nos(true, pcur.get_rec(), &mtr, space_ids,
2283 page_nos, n_pages);
2284 ut_ad(!mtr.has_any_log_record());
2285 ibuf_mtr_commit(&mtr);
2286 pcur.close();
2287
2288 buf_read_ibuf_merge_pages(sync, space_ids, page_nos, *n_pages);
2289
2290 return (sum_sizes + 1);
2291 }
2292
2293 /** Contracts insert buffer trees by reading pages referring to space_id
2294 to the buffer pool.
2295 @returns number of pages merged.*/
2296 ulint ibuf_merge_space(space_id_t space) /*!< in: tablespace id to merge */
2297 {
2298 mtr_t mtr;
2299 btr_pcur_t pcur;
2300 mem_heap_t *heap = mem_heap_create(512, UT_LOCATION_HERE);
2301 dtuple_t *tuple = ibuf_search_tuple_build(space, 0, heap);
2302 ulint n_pages = 0;
2303
2304 ut_ad(!dict_sys_t::is_reserved(space));
2305
2306 ibuf_mtr_start(&mtr);
2307
2308 /* Position the cursor on the first matching record. */
2309
2310 pcur.open(ibuf->index, 0, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &mtr,
2311 UT_LOCATION_HERE);
2312
2313 mem_heap_free(heap);
2314
2315 ut_ad(page_validate(pcur.get_page(), ibuf->index));
2316
2317 ulint sum_sizes = 0;
2318 page_no_t pages[IBUF_MAX_N_PAGES_MERGED];
2319 space_id_t spaces[IBUF_MAX_N_PAGES_MERGED];
2320
2321 if (page_is_empty(pcur.get_page())) {
2322 /* If a B-tree page is empty, it must be the root page
2323 and the whole B-tree must be empty. InnoDB does not
2324 allow empty B-tree pages other than the root. */
2325 ut_ad(ibuf->empty);
2326 ut_ad(page_get_space_id(pcur.get_page()) == IBUF_SPACE_ID);
2327 ut_ad(page_get_page_no(pcur.get_page()) == FSP_IBUF_TREE_ROOT_PAGE_NO);
2328
2329 } else {
2330 sum_sizes = ibuf_get_merge_pages(&pcur, space, IBUF_MAX_N_PAGES_MERGED,
2331 &pages[0], &spaces[0], &n_pages, &mtr);
2332 ib::info(ER_IB_MSG_606) << "Size of pages merged " << sum_sizes;
2333 }
2334
2335 ibuf_mtr_commit(&mtr);
2336
2337 pcur.close();
2338
2339 if (n_pages > 0) {
2340 ut_ad(n_pages <= UT_ARR_SIZE(pages));
2341
2342 #ifdef UNIV_DEBUG
2343 for (ulint i = 0; i < n_pages; ++i) {
2344 ut_ad(spaces[i] == space);
2345 }
2346 #endif /* UNIV_DEBUG */
2347
2348 buf_read_ibuf_merge_pages(true, spaces, pages, n_pages);
2349 }
2350
2351 return (n_pages);
2352 }
2353
2354 /** Contract the change buffer by reading pages to the buffer pool.
2355 @param[out] n_pages number of pages merged
2356 @param[in] sync whether the caller waits for
2357 the issued reads to complete
2358 @return a lower limit for the combined size in bytes of entries which
2359 will be merged from ibuf trees to the pages read, 0 if ibuf is
2360 empty */
2361 [[nodiscard]] static ulint ibuf_merge(ulint *n_pages, bool sync) {
2362 *n_pages = 0;
2363
2364 /* We perform a dirty read of ibuf->empty, without latching
2365 the insert buffer root page. We trust this dirty read except
2366 when a slow shutdown is being executed. During a slow
2367 shutdown, the insert buffer merge must be completed. */
2368
2369 if (ibuf->empty && srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
2370 return (0);
2371 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
2372 } else if (ibuf_debug) {
2373 return (0);
2374 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
2375 } else {
2376 return (ibuf_merge_pages(n_pages, sync));
2377 }
2378 }
2379
2380 /** Contract the change buffer by reading pages to the buffer pool.
2381 @param[in] sync whether the caller waits for
2382 the issued reads to complete
2383 @return a lower limit for the combined size in bytes of entries which
2384 will be merged from ibuf trees to the pages read, 0 if ibuf is empty */
2385 static ulint ibuf_contract(bool sync) {
2386 ulint n_pages;
2387 DEBUG_SYNC_C("ibuf_contract_started");
2388 return (ibuf_merge_pages(&n_pages, sync));
2389 }
2390
2391 /** Contract the change buffer by reading pages to the buffer pool.
2392 @param[in] full If true, do a full contraction based
2393 on PCT_IO(100). If false, the size of contract batch is determined
2394 based on the current size of the change buffer.
2395 @return a lower limit for the combined size in bytes of entries which
2396 will be merged from ibuf trees to the pages read, 0 if ibuf is
2397 empty */
2398 ulint ibuf_merge_in_background(bool full) {
2399 ulint sum_bytes = 0;
2400 ulint sum_pages = 0;
2401 ulint n_pag2;
2402 ulint n_pages;
2403
2404 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
2405 if (srv_ibuf_disable_background_merge) {
2406 return (0);
2407 }
2408 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
2409
2410 if (full) {
2411 /* Caller has requested a full batch */
2412 n_pages = PCT_IO(100);
2413 } else {
2414 /* By default we do a batch of 5% of the io_capacity */
2415 n_pages = PCT_IO(5);
2416
2417 mutex_enter(&ibuf_mutex);
2418
2419 /* If the ibuf->size is more than half the max_size
2420 then we make more aggressive contraction.
2421 +1 is to avoid division by zero. */
2422 if (ibuf->size > ibuf->max_size / 2) {
2423 ulint diff = ibuf->size - ibuf->max_size / 2;
2424 /* limits to around 100% value, for shrinking max_size case */
2425 diff = std::min(diff, ibuf->max_size);
2426 n_pages += PCT_IO((diff * 100) / (ibuf->max_size + 1));
2427 }
2428
2429 mutex_exit(&ibuf_mutex);
2430 }
2431
2432 while (sum_pages < n_pages) {
2433 ulint n_bytes;
2434
2435 n_bytes = ibuf_merge(&n_pag2, false);
2436
2437 if (n_bytes == 0) {
2438 return (sum_bytes);
2439 }
2440
2441 sum_bytes += n_bytes;
2442 sum_pages += n_pag2;
2443 }
2444
2445 return (sum_bytes);
2446 }
2447
2448 /** Contract insert buffer trees after insert if they are too big. */
2449 static inline void ibuf_contract_after_insert(
2450 ulint entry_size) /*!< in: size of a record which was inserted
2451 into an ibuf tree */
2452 {
2453 /* Perform dirty reads of ibuf->size and ibuf->max_size, to
2454 reduce ibuf_mutex contention. ibuf->max_size remains constant
2455 after ibuf_init_at_db_start(), but ibuf->size should be
2456 protected by ibuf_mutex. Given that ibuf->size fits in a
2457 machine word, this should be OK; at worst we are doing some
2458 excessive ibuf_contract() or occasionally skipping a
2459 ibuf_contract(). */
2460 auto size = ibuf->size;
2461 auto max_size = ibuf->max_size;
2462
2463 if (size < max_size + IBUF_CONTRACT_ON_INSERT_NON_SYNC) {
2464 return;
2465 }
2466
2467 auto sync = (size >= max_size + IBUF_CONTRACT_ON_INSERT_SYNC);
2468
2469 /* Contract at least entry_size many bytes */
2470 ulint sum_sizes = 0;
2471 size = 1;
2472
2473 do {
2474 size = ibuf_contract(sync);
2475 sum_sizes += size;
2476 } while (size > 0 && sum_sizes < entry_size);
2477 }
2478
2479 /** Determine if an insert buffer record has been encountered already.
2480 @return true if a new record, false if possible duplicate */
2481 static bool ibuf_get_volume_buffered_hash(
2482 const rec_t *rec, /*!< in: ibuf record in post-4.1 format */
2483 const byte *types, /*!< in: fields */
2484 const byte *data, /*!< in: start of user record data */
2485 ulint comp, /*!< in: 0=ROW_FORMAT=REDUNDANT,
2486 nonzero=ROW_FORMAT=COMPACT */
2487 ulint *hash, /*!< in/out: hash array */
2488 ulint size) /*!< in: number of elements in hash array */
2489 {
2490 ulint len;
2491 ulint bitmask;
2492
2493 len = ibuf_rec_get_size(
2494 rec, types, rec_get_n_fields_old_raw(rec) - IBUF_REC_FIELD_USER, comp);
2495 const auto hash_value = ut::hash_binary(data, len);
2496
2497 hash += (hash_value / (CHAR_BIT * sizeof *hash)) % size;
2498 bitmask = static_cast<ulint>(1) << (hash_value % (CHAR_BIT * sizeof(*hash)));
2499
2500 if (*hash & bitmask) {
2501 return false;
2502 }
2503
2504 /* We have not seen this record yet. Insert it. */
2505 *hash |= bitmask;
2506
2507 return true;
2508 }
2509
2510 /** Update the estimate of the number of records on a page, and
2511 get the space taken by merging the buffered record to the index page.
2512 @param[in] mtr mini-transaction owning rec
2513 @param[in] rec insert buffer record
2514 @param[in,out] hash hash array
2515 @param[in] size number of elements in hash array
2516 @param[in,out] n_recs estimated number of records on the page that rec points
2517 to
2518 @return size of index record in bytes + an upper limit of the space
2519 taken in the page directory */
2520 static ulint ibuf_get_volume_buffered_count_func(IF_DEBUG(mtr_t *mtr, )
2521 const rec_t *rec,
2522 ulint *hash, ulint size,
2523 lint *n_recs) {
2524 ulint len;
2525 ibuf_op_t ibuf_op;
2526 const byte *types;
2527 ulint n_fields;
2528
2529 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
2530 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
2531 ut_ad(ibuf_inside(mtr));
2532
2533 n_fields = rec_get_n_fields_old_raw(rec);
2534 ut_ad(n_fields > IBUF_REC_FIELD_USER);
2535 n_fields -= IBUF_REC_FIELD_USER;
2536
2537 /* nullptr for index as it can't be clustered index */
2538 rec_get_nth_field_offs_old(nullptr, rec, 1, &len);
2539 /* This function is only invoked when buffering new
2540 operations. All pre-4.1 records should have been merged
2541 when the database was started up. */
2542 ut_a(len == 1);
2543
2544 if (rec_get_deleted_flag(rec, 0)) {
2545 /* This record has been merged already,
2546 but apparently the system crashed before
2547 the change was discarded from the buffer.
2548 Pretend that the record does not exist. */
2549 return (0);
2550 }
2551
2552 types = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_METADATA, &len);
2553
2554 switch (UNIV_EXPECT(len % DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE,
2555 IBUF_REC_INFO_SIZE)) {
2556 default:
2557 ut_error;
2558 case 0:
2559 /* This ROW_TYPE=REDUNDANT record does not include an
2560 operation counter. Exclude it from the *n_recs,
2561 because deletes cannot be buffered if there are
2562 old-style inserts buffered for the page. */
2563
2564 len = ibuf_rec_get_size(rec, types, n_fields, 0);
2565
2566 return (len + rec_get_converted_extra_size(len, n_fields, false) +
2567 page_dir_calc_reserved_space(1));
2568 case 1:
2569 /* This ROW_TYPE=COMPACT record does not include an
2570 operation counter. Exclude it from the *n_recs,
2571 because deletes cannot be buffered if there are
2572 old-style inserts buffered for the page. */
2573 goto get_volume_comp;
2574
2575 case IBUF_REC_INFO_SIZE:
2576 ibuf_op = (ibuf_op_t)types[IBUF_REC_OFFSET_TYPE];
2577 break;
2578 }
2579
2580 switch (ibuf_op) {
2581 case IBUF_OP_INSERT:
2582 /* Inserts can be done by updating a delete-marked record.
2583 Because delete-mark and insert operations can be pointing to
2584 the same records, we must not count duplicates. */
2585 case IBUF_OP_DELETE_MARK:
2586 /* There must be a record to delete-mark.
2587 See if this record has been already buffered. */
2588 if (n_recs &&
2589 ibuf_get_volume_buffered_hash(
2590 rec, types + IBUF_REC_INFO_SIZE, types + len,
2591 types[IBUF_REC_OFFSET_FLAGS] & IBUF_REC_COMPACT, hash, size)) {
2592 (*n_recs)++;
2593 }
2594
2595 if (ibuf_op == IBUF_OP_DELETE_MARK) {
2596 /* Setting the delete-mark flag does not
2597 affect the available space on the page. */
2598 return (0);
2599 }
2600 break;
2601 case IBUF_OP_DELETE:
2602 /* A record will be removed from the page. */
2603 if (n_recs) {
2604 (*n_recs)--;
2605 }
2606 /* While deleting a record actually frees up space,
2607 we have to play it safe and pretend that it takes no
2608 additional space (the record might not exist, etc.). */
2609 return (0);
2610 default:
2611 ut_error;
2612 }
2613
2614 ut_ad(ibuf_op == IBUF_OP_INSERT);
2615
2616 get_volume_comp : {
2617 dtuple_t *entry;
2618 ulint volume;
2619 dict_index_t *dummy_index;
2620 mem_heap_t *heap = mem_heap_create(500, UT_LOCATION_HERE);
2621
2622 entry = ibuf_build_entry_from_ibuf_rec_func(IF_DEBUG(mtr, ) rec, heap,
2623 &dummy_index);
2624
2625 volume = rec_get_converted_size(dummy_index, entry);
2626
2627 ibuf_dummy_index_free(dummy_index);
2628 mem_heap_free(heap);
2629
2630 return (volume + page_dir_calc_reserved_space(1));
2631 }
2632 }
2633
2634 inline static ulint ibuf_get_volume_buffered_count(mtr_t *mtr [[maybe_unused]],
2635 const rec_t *rec,
2636 ulint *hash, ulint size,
2637 lint *n_recs) {
2638 return ibuf_get_volume_buffered_count_func(IF_DEBUG(mtr, ) rec, hash, size,
2639 n_recs);
2640 }
2641
2642 /** Gets an upper limit for the combined size of entries buffered in the
2643 insert buffer for a given page.
2644 @return upper limit for the volume of buffered inserts for the index
2645 page, in bytes; UNIV_PAGE_SIZE, if the entries for the index page span
2646 several pages in the insert buffer */
2647 static ulint ibuf_get_volume_buffered(
2648 const btr_pcur_t *pcur, /*!< in: pcur positioned at a place in an
2649 insert buffer tree where we would insert an
2650 entry for the index page whose number is
2651 page_no, latch mode has to be BTR_MODIFY_PREV
2652 or BTR_MODIFY_TREE */
2653 space_id_t space, /*!< in: space id */
2654 page_no_t page_no, /*!< in: page number of an index page */
2655 lint *n_recs, /*!< in/out: minimum number of records on the
2656 page after the buffered changes have been
2657 applied, or NULL to disable the counting */
2658 mtr_t *mtr) /*!< in: mini-transaction of pcur */
2659 {
2660 ulint volume;
2661 const rec_t *rec;
2662 const page_t *page;
2663 page_no_t prev_page_no;
2664 const page_t *prev_page;
2665 page_no_t next_page_no;
2666 const page_t *next_page;
2667 /* bitmap of buffered recs */
2668 ulint hash_bitmap[128 / sizeof(ulint)];
2669
2670 ut_ad((pcur->m_latch_mode == BTR_MODIFY_PREV) ||
2671 (pcur->m_latch_mode == BTR_MODIFY_TREE));
2672
2673 /* Count the volume of inserts earlier in the alphabetical order than
2674 pcur */
2675
2676 volume = 0;
2677
2678 if (n_recs) {
2679 memset(hash_bitmap, 0, sizeof hash_bitmap);
2680 }
2681
2682 rec = pcur->get_rec();
2683 page = page_align(rec);
2684 ut_ad(page_validate(page, ibuf->index));
2685
2686 if (page_rec_is_supremum(rec)) {
2687 rec = page_rec_get_prev_const(rec);
2688 }
2689
2690 for (; !page_rec_is_infimum(rec); rec = page_rec_get_prev_const(rec)) {
2691 ut_ad(page_align(rec) == page);
2692
2693 if (page_no != ibuf_rec_get_page_no(mtr, rec) ||
2694 space != ibuf_rec_get_space(mtr, rec)) {
2695 goto count_later;
2696 }
2697
2698 volume += ibuf_get_volume_buffered_count(mtr, rec, hash_bitmap,
2699 UT_ARR_SIZE(hash_bitmap), n_recs);
2700 }
2701
2702 /* Look at the previous page */
2703
2704 prev_page_no = btr_page_get_prev(page, mtr);
2705
2706 if (prev_page_no == FIL_NULL) {
2707 goto count_later;
2708 }
2709
2710 {
2711 buf_block_t *block;
2712
2713 block = buf_page_get(page_id_t(IBUF_SPACE_ID, prev_page_no), univ_page_size,
2714 RW_X_LATCH, UT_LOCATION_HERE, mtr);
2715
2716 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
2717
2718 prev_page = buf_block_get_frame(block);
2719 ut_ad(page_validate(prev_page, ibuf->index));
2720 }
2721
2722 #ifdef UNIV_BTR_DEBUG
2723 ut_a(btr_page_get_next(prev_page, mtr) == page_get_page_no(page));
2724 #endif /* UNIV_BTR_DEBUG */
2725
2726 rec = page_get_supremum_rec(prev_page);
2727 rec = page_rec_get_prev_const(rec);
2728
2729 for (;; rec = page_rec_get_prev_const(rec)) {
2730 ut_ad(page_align(rec) == prev_page);
2731
2732 if (page_rec_is_infimum(rec)) {
2733 /* We cannot go to yet a previous page, because we
2734 do not have the x-latch on it, and cannot acquire one
2735 because of the latching order: we have to give up */
2736
2737 return (UNIV_PAGE_SIZE);
2738 }
2739
2740 if (page_no != ibuf_rec_get_page_no(mtr, rec) ||
2741 space != ibuf_rec_get_space(mtr, rec)) {
2742 goto count_later;
2743 }
2744
2745 volume += ibuf_get_volume_buffered_count(mtr, rec, hash_bitmap,
2746 UT_ARR_SIZE(hash_bitmap), n_recs);
2747 }
2748
2749 count_later:
2750 rec = pcur->get_rec();
2751
2752 if (!page_rec_is_supremum(rec)) {
2753 rec = page_rec_get_next_const(rec);
2754 }
2755
2756 for (; !page_rec_is_supremum(rec); rec = page_rec_get_next_const(rec)) {
2757 if (page_no != ibuf_rec_get_page_no(mtr, rec) ||
2758 space != ibuf_rec_get_space(mtr, rec)) {
2759 return (volume);
2760 }
2761
2762 volume += ibuf_get_volume_buffered_count(mtr, rec, hash_bitmap,
2763 UT_ARR_SIZE(hash_bitmap), n_recs);
2764 }
2765
2766 /* Look at the next page */
2767
2768 next_page_no = btr_page_get_next(page, mtr);
2769
2770 if (next_page_no == FIL_NULL) {
2771 return (volume);
2772 }
2773
2774 {
2775 buf_block_t *block;
2776
2777 block = buf_page_get(page_id_t(IBUF_SPACE_ID, next_page_no), univ_page_size,
2778 RW_X_LATCH, UT_LOCATION_HERE, mtr);
2779
2780 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
2781
2782 next_page = buf_block_get_frame(block);
2783 ut_ad(page_validate(next_page, ibuf->index));
2784 }
2785
2786 #ifdef UNIV_BTR_DEBUG
2787 ut_a(btr_page_get_prev(next_page, mtr) == page_get_page_no(page));
2788 #endif /* UNIV_BTR_DEBUG */
2789
2790 rec = page_get_infimum_rec(next_page);
2791 rec = page_rec_get_next_const(rec);
2792
2793 for (;; rec = page_rec_get_next_const(rec)) {
2794 ut_ad(page_align(rec) == next_page);
2795
2796 if (page_rec_is_supremum(rec)) {
2797 /* We give up */
2798
2799 return (UNIV_PAGE_SIZE);
2800 }
2801
2802 if (page_no != ibuf_rec_get_page_no(mtr, rec) ||
2803 space != ibuf_rec_get_space(mtr, rec)) {
2804 return (volume);
2805 }
2806
2807 volume += ibuf_get_volume_buffered_count(mtr, rec, hash_bitmap,
2808 UT_ARR_SIZE(hash_bitmap), n_recs);
2809 }
2810 }
2811
2812 /** Reads the biggest tablespace id from the high end of the insert buffer
2813 tree and updates the counter in fil_system. */
2814 void ibuf_update_max_tablespace_id(void) {
2815 space_id_t max_space_id;
2816 const rec_t *rec;
2817 const byte *field;
2818 ulint len;
2819 btr_pcur_t pcur;
2820 mtr_t mtr;
2821
2822 ut_a(!dict_table_is_comp(ibuf->index->table));
2823
2824 ibuf_mtr_start(&mtr);
2825
2826 pcur.open_at_side(false, ibuf->index, BTR_SEARCH_LEAF, true, 0, &mtr);
2827
2828 ut_ad(page_validate(pcur.get_page(), ibuf->index));
2829
2830 pcur.move_to_prev(&mtr);
2831
2832 if (pcur.is_before_first_on_page()) {
2833 /* The tree is empty */
2834
2835 max_space_id = 0;
2836 } else {
2837 rec = pcur.get_rec();
2838
2839 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_SPACE, &len);
2840
2841 ut_a(len == 4);
2842
2843 max_space_id = mach_read_from_4(field);
2844 }
2845
2846 pcur.close();
2847 ibuf_mtr_commit(&mtr);
2848
2849 /* printf("Maximum space id in insert buffer %lu\n", max_space_id); */
2850
2851 fil_set_max_space_id_if_bigger(max_space_id);
2852 }
2853
2854 /** Helper function for ibuf_get_entry_counter_func. Checks if rec is for
2855 (space, page_no), and if so, reads counter value from it and returns
2856 that + 1.
2857 @param[in] mtr mini-transaction of rec
2858 @param[in] rec insert buffer record
2859 @param[in] space space id
2860 @param[in] page_no page number
2861 @retval ULINT_UNDEFINED if the record does not contain any counter
2862 @retval 0 if the record is not for (space, page_no)
2863 @retval 1 + previous counter value, otherwise */
2864 static ulint ibuf_get_entry_counter_low_func(IF_DEBUG(mtr_t *mtr, )
2865 const rec_t *rec,
2866 space_id_t space,
2867 page_no_t page_no) {
2868 ulint counter;
2869 const byte *field;
2870 ulint len;
2871
2872 ut_ad(ibuf_inside(mtr));
2873 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX) ||
2874 mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
2875 ut_ad(rec_get_n_fields_old_raw(rec) > 2);
2876
2877 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_MARKER, &len);
2878
2879 ut_a(len == 1);
2880
2881 /* Check the tablespace identifier. */
2882 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_SPACE, &len);
2883
2884 ut_a(len == 4);
2885
2886 if (mach_read_from_4(field) != space) {
2887 return (0);
2888 }
2889
2890 /* Check the page offset. */
2891 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_PAGE, &len);
2892 ut_a(len == 4);
2893
2894 if (mach_read_from_4(field) != page_no) {
2895 return (0);
2896 }
2897
2898 /* Check if the record contains a counter field. */
2899 field = rec_get_nth_field_old(nullptr, rec, IBUF_REC_FIELD_METADATA, &len);
2900
2901 switch (len % DATA_NEW_ORDER_NULL_TYPE_BUF_SIZE) {
2902 default:
2903 ut_error;
2904 case 0: /* ROW_FORMAT=REDUNDANT */
2905 case 1: /* ROW_FORMAT=COMPACT */
2906 return (ULINT_UNDEFINED);
2907
2908 case IBUF_REC_INFO_SIZE:
2909 counter = mach_read_from_2(field + IBUF_REC_OFFSET_COUNTER);
2910 ut_a(counter < 0xFFFF);
2911 return (counter + 1);
2912 }
2913 }
2914
2915 /** Calculate the counter field for an entry based on the current
2916 last record in ibuf for (space, page_no).
2917 @return the counter field, or ULINT_UNDEFINED
2918 if we should abort this insertion to ibuf
2919 @param[in] space space id of entry
2920 @param[in] page_no page number of entry
2921 @param[in] rec the record preceding the insertion point
2922 @param mtr mini-transaction
2923 @param[in] only_leaf true if this is the only leaf page that can contain
2924 entries for (space,page_no), that is, there was no exact match for
2925 (space,page_no) in the node pointer */
2926 static ulint ibuf_get_entry_counter_func(
2927 space_id_t space, page_no_t page_no, const rec_t *rec,
2928 IF_DEBUG(mtr_t *mtr, ) bool only_leaf) {
2929 ut_ad(ibuf_inside(mtr));
2930 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_X_FIX));
2931 ut_ad(page_validate(page_align(rec), ibuf->index));
2932
2933 if (page_rec_is_supremum(rec)) {
2934 /* This is just for safety. The record should be a
2935 page infimum or a user record. */
2936 ut_d(ut_error);
2937 ut_o(return (ULINT_UNDEFINED));
2938 } else if (!page_rec_is_infimum(rec)) {
2939 return (
2940 ibuf_get_entry_counter_low_func(IF_DEBUG(mtr, ) rec, space, page_no));
2941 } else if (only_leaf || fil_page_get_prev(page_align(rec)) == FIL_NULL) {
2942 /* The parent node pointer did not contain the
2943 searched for (space, page_no), which means that the
2944 search ended on the correct page regardless of the
2945 counter value, and since we're at the infimum record,
2946 there are no existing records. */
2947 return (0);
2948 } else {
2949 /* We used to read the previous page here. It would
2950 break the latching order, because the caller has
2951 buffer-fixed an insert buffer bitmap page. */
2952 return (ULINT_UNDEFINED);
2953 }
2954 }
2955
2956 inline ulint ibuf_get_entry_counter(space_id_t space, page_no_t page_no,
2957 const rec_t *rec,
2958 mtr_t *mtr [[maybe_unused]],
2959 bool exact_leaf) {
2960 return ibuf_get_entry_counter_func(space, page_no, rec,
2961 IF_DEBUG(mtr, ) exact_leaf);
2962 }
2963
2964 /** Buffer an operation in the insert/delete buffer, instead of doing it
2965 directly to the disk page, if this is possible.
2966 @param[in] mode BTR_MODIFY_PREV or BTR_MODIFY_TREE
2967 @param[in] op operation type
2968 @param[in] no_counter true=use 5.0.3 format; false=allow delete
2969 buffering
2970 @param[in] entry index entry to insert
2971 @param[in] entry_size rec_get_converted_size(index, entry)
2972 @param[in,out] index index where to insert; must not be
2973 unique or clustered
2974 @param[in] page_id page id where to insert
2975 @param[in] page_size page size
2976 @param[in,out] thr query thread
2977 @return DB_SUCCESS, DB_STRONG_FAIL or other error */
2978 [[nodiscard]] static dberr_t ibuf_insert_low(
2979 ulint mode, ibuf_op_t op, bool no_counter, const dtuple_t *entry,
2980 ulint entry_size, dict_index_t *index, const page_id_t &page_id,
2981 const page_size_t &page_size, que_thr_t *thr) {
2982 big_rec_t *dummy_big_rec;
2983 btr_pcur_t pcur;
2984 btr_cur_t *cursor;
2985 dtuple_t *ibuf_entry;
2986 mem_heap_t *offsets_heap = nullptr;
2987 mem_heap_t *heap;
2988 ulint *offsets = nullptr;
2989 ulint buffered;
2990 lint min_n_recs;
2991 rec_t *ins_rec;
2992 bool old_bit_value;
2993 page_t *bitmap_page;
2994 buf_block_t *block;
2995 page_t *root;
2996 dberr_t err;
2997 space_id_t space_ids[IBUF_MAX_N_PAGES_MERGED];
2998 page_no_t page_nos[IBUF_MAX_N_PAGES_MERGED];
2999 ulint n_stored = 0;
3000 mtr_t mtr;
3001 mtr_t bitmap_mtr;
3002
3003 ut_a(!index->is_clustered());
3004 ut_ad(!dict_index_is_spatial(index));
3005 ut_ad(dtuple_check_typed(entry));
3006 ut_ad(!no_counter || op == IBUF_OP_INSERT);
3007 ut_a(op < IBUF_OP_COUNT);
3008
3009 auto do_merge = false;
3010
3011 /* Perform dirty reads of ibuf->size and ibuf->max_size, to
3012 reduce ibuf_mutex contention. Given that ibuf->max_size and
3013 ibuf->size fit in a machine word, this should be OK; at worst
3014 we are doing some excessive ibuf_contract() or occasionally
3015 skipping an ibuf_contract(). */
3016 if (ibuf->max_size == 0) {
3017 return (DB_STRONG_FAIL);
3018 }
3019
3020 if (ibuf->size >= ibuf->max_size + IBUF_CONTRACT_DO_NOT_INSERT) {
3021 /* Insert buffer is now too big, contract it but do not try
3022 to insert */
3023
3024 #ifdef UNIV_IBUF_DEBUG
3025 ib::info() << "Ibuf too big";
3026 #endif
3027 ibuf_contract(true);
3028
3029 return (DB_STRONG_FAIL);
3030 }
3031
3032 heap = mem_heap_create(1024, UT_LOCATION_HERE);
3033
3034 /* Build the entry which contains the space id and the page number
3035 as the first fields and the type information for other fields, and
3036 which will be inserted to the insert buffer. Using a counter value
3037 of 0xFFFF we find the last record for (space, page_no), from which
3038 we can then read the counter value N and use N + 1 in the record we
3039 insert. (We patch the ibuf_entry's counter field to the correct
3040 value just before actually inserting the entry.) */
3041
3042 ibuf_entry =
3043 ibuf_entry_build(op, index, entry, page_id.space(), page_id.page_no(),
3044 no_counter ? ULINT_UNDEFINED : 0xFFFF, heap);
3045
3046 /* Open a cursor to the insert buffer tree to calculate if we can add
3047 the new entry to it without exceeding the free space limit for the
3048 page. */
3049
3050 if (BTR_LATCH_MODE_WITHOUT_INTENTION(mode) == BTR_MODIFY_TREE) {
3051 for (;;) {
3052 mutex_enter(&ibuf_pessimistic_insert_mutex);
3053 mutex_enter(&ibuf_mutex);
3054
3055 if (UNIV_LIKELY(ibuf_data_enough_free_for_insert())) {
3056 break;
3057 }
3058
3059 mutex_exit(&ibuf_mutex);
3060 mutex_exit(&ibuf_pessimistic_insert_mutex);
3061
3062 if (!ibuf_add_free_page()) {
3063 mem_heap_free(heap);
3064 return (DB_STRONG_FAIL);
3065 }
3066 }
3067 }
3068
3069 ibuf_mtr_start(&mtr);
3070
3071 pcur.open(ibuf->index, 0, ibuf_entry, PAGE_CUR_LE, mode, &mtr,
3072 UT_LOCATION_HERE);
3073 ut_ad(page_validate(pcur.get_page(), ibuf->index));
3074
3075 /* Find out the volume of already buffered inserts for the same index
3076 page */
3077 min_n_recs = 0;
3078 buffered = ibuf_get_volume_buffered(
3079 &pcur, page_id.space(), page_id.page_no(),
3080 op == IBUF_OP_DELETE ? &min_n_recs : nullptr, &mtr);
3081
3082 if (op == IBUF_OP_DELETE &&
3083 (min_n_recs < 2 || buf_pool_watch_occurred(page_id))) {
3084 /* The page could become empty after the record is
3085 deleted, or the page has been read in to the buffer
3086 pool. Refuse to buffer the operation. */
3087
3088 /* The buffer pool watch is needed for IBUF_OP_DELETE
3089 because of latching order considerations. We can
3090 check buf_pool_watch_occurred() only after latching
3091 the insert buffer B-tree pages that contain buffered
3092 changes for the page. We never buffer IBUF_OP_DELETE,
3093 unless some IBUF_OP_INSERT or IBUF_OP_DELETE_MARK have
3094 been previously buffered for the page. Because there
3095 are buffered operations for the page, the insert
3096 buffer B-tree page latches held by mtr will guarantee
3097 that no changes for the user page will be merged
3098 before mtr_commit(&mtr). We must not mtr_commit(&mtr)
3099 until after the IBUF_OP_DELETE has been buffered. */
3100
3101 fail_exit:
3102 if (BTR_LATCH_MODE_WITHOUT_INTENTION(mode) == BTR_MODIFY_TREE) {
3103 mutex_exit(&ibuf_mutex);
3104 mutex_exit(&ibuf_pessimistic_insert_mutex);
3105 }
3106
3107 err = DB_STRONG_FAIL;
3108 goto func_exit;
3109 }
3110
3111 /* After this point, the page could still be loaded to the
3112 buffer pool, but we do not have to care about it, since we are
3113 holding a latch on the insert buffer leaf page that contains
3114 buffered changes for (space, page_no). If the page enters the
3115 buffer pool, buf_page_io_complete() for (space, page_no) will
3116 have to acquire a latch on the same insert buffer leaf page,
3117 which it cannot do until we have buffered the IBUF_OP_DELETE
3118 and done mtr_commit(&mtr) to release the latch. */
3119
3120 #ifdef UNIV_IBUF_COUNT_DEBUG
3121 ut_a((buffered == 0) || ibuf_count_get(page_id));
3122 #endif
3123 ibuf_mtr_start(&bitmap_mtr);
3124
3125 bitmap_page = ibuf_bitmap_get_map_page(page_id, page_size, UT_LOCATION_HERE,
3126 &bitmap_mtr);
3127
3128 /* We check if the index page is suitable for buffered entries */
3129
3130 if (buf_page_peek(page_id) || lock_rec_expl_exist_on_page(page_id)) {
3131 ibuf_mtr_commit(&bitmap_mtr);
3132 goto fail_exit;
3133 }
3134
3135 if (op == IBUF_OP_INSERT) {
3136 ulint bits = ibuf_bitmap_page_get_bits(bitmap_page, page_id, page_size,
3137 IBUF_BITMAP_FREE, &bitmap_mtr);
3138
3139 if (buffered + entry_size + page_dir_calc_reserved_space(1) >
3140 ibuf_index_page_calc_free_from_bits(page_size, bits)) {
3141 /* Release the bitmap page latch early. */
3142 ibuf_mtr_commit(&bitmap_mtr);
3143
3144 /* It may not fit */
3145 do_merge = true;
3146
3147 ibuf_get_merge_page_nos(false, pcur.get_rec(), &mtr, space_ids, page_nos,
3148 &n_stored);
3149
3150 goto fail_exit;
3151 }
3152 }
3153
3154 if (!no_counter) {
3155 /* Patch correct counter value to the entry to
3156 insert. This can change the insert position, which can
3157 result in the need to abort in some cases. */
3158 ulint counter = ibuf_get_entry_counter(
3159 page_id.space(), page_id.page_no(), pcur.get_rec(), &mtr,
3160 pcur.get_btr_cur()->low_match < IBUF_REC_FIELD_METADATA);
3161 dfield_t *field;
3162
3163 if (counter == ULINT_UNDEFINED) {
3164 ibuf_mtr_commit(&bitmap_mtr);
3165 goto fail_exit;
3166 }
3167
3168 field = dtuple_get_nth_field(ibuf_entry, IBUF_REC_FIELD_METADATA);
3169 mach_write_to_2((byte *)dfield_get_data(field) + IBUF_REC_OFFSET_COUNTER,
3170 counter);
3171 }
3172
3173 /* Set the bitmap bit denoting that the insert buffer contains
3174 buffered entries for this index page, if the bit is not set yet */
3175
3176 old_bit_value = ibuf_bitmap_page_get_bits(bitmap_page, page_id, page_size,
3177 IBUF_BITMAP_BUFFERED, &bitmap_mtr);
3178
3179 if (!old_bit_value) {
3180 ibuf_bitmap_page_set_bits(bitmap_page, page_id, page_size,
3181 IBUF_BITMAP_BUFFERED, true, &bitmap_mtr);
3182 }
3183
3184 ibuf_mtr_commit(&bitmap_mtr);
3185
3186 cursor = pcur.get_btr_cur();
3187
3188 if (mode == BTR_MODIFY_PREV) {
3189 err = btr_cur_optimistic_insert(BTR_NO_LOCKING_FLAG, cursor, &offsets,
3190 &offsets_heap, ibuf_entry, &ins_rec,
3191 &dummy_big_rec, thr, &mtr);
3192 block = btr_cur_get_block(cursor);
3193 ut_ad(block->page.id.space() == IBUF_SPACE_ID);
3194
3195 /* If this is the root page, update ibuf->empty. */
3196 if (block->page.id.page_no() == FSP_IBUF_TREE_ROOT_PAGE_NO) {
3197 const page_t *root = buf_block_get_frame(block);
3198
3199 ut_ad(page_get_space_id(root) == IBUF_SPACE_ID);
3200 ut_ad(page_get_page_no(root) == FSP_IBUF_TREE_ROOT_PAGE_NO);
3201
3202 ibuf->empty = page_is_empty(root);
3203 }
3204 } else {
3205 ut_ad(BTR_LATCH_MODE_WITHOUT_INTENTION(mode) == BTR_MODIFY_TREE);
3206
3207 /* We acquire an sx-latch to the root page before the insert,
3208 because a pessimistic insert releases the tree x-latch,
3209 which would cause the sx-latching of the root after that to
3210 break the latching order. */
3211
3212 root = ibuf_tree_root_get(&mtr);
3213
3214 err = btr_cur_optimistic_insert(BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG,
3215 cursor, &offsets, &offsets_heap, ibuf_entry,
3216 &ins_rec, &dummy_big_rec, thr, &mtr);
3217
3218 if (err == DB_FAIL) {
3219 err = btr_cur_pessimistic_insert(
3220 BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG, cursor, &offsets,
3221 &offsets_heap, ibuf_entry, &ins_rec, &dummy_big_rec, thr, &mtr);
3222 }
3223
3224 mutex_exit(&ibuf_pessimistic_insert_mutex);
3225 ibuf_size_update(root);
3226 mutex_exit(&ibuf_mutex);
3227 ibuf->empty = page_is_empty(root);
3228
3229 block = btr_cur_get_block(cursor);
3230 ut_ad(block->page.id.space() == IBUF_SPACE_ID);
3231 }
3232
3233 if (offsets_heap) {
3234 mem_heap_free(offsets_heap);
3235 }
3236
3237 if (err == DB_SUCCESS && op != IBUF_OP_DELETE) {
3238 /* Update the page max trx id field */
3239 page_update_max_trx_id(block, nullptr, thr_get_trx(thr)->id, &mtr);
3240 }
3241
3242 func_exit:
3243 #ifdef UNIV_IBUF_COUNT_DEBUG
3244 if (err == DB_SUCCESS) {
3245 ib::info(ER_IB_MSG_607)
3246 << "Incrementing ibuf count of page " << page_id << " from "
3247 << ibuf_count_get(space, page_no) << " by 1";
3248
3249 ibuf_count_set(page_id, ibuf_count_get(page_id) + 1);
3250 }
3251 #endif
3252
3253 ibuf_mtr_commit(&mtr);
3254 pcur.close();
3255
3256 mem_heap_free(heap);
3257
3258 if (err == DB_SUCCESS &&
3259 BTR_LATCH_MODE_WITHOUT_INTENTION(mode) == BTR_MODIFY_TREE) {
3260 ibuf_contract_after_insert(entry_size);
3261 }
3262
3263 if (do_merge) {
3264 #ifdef UNIV_IBUF_DEBUG
3265 ut_a(n_stored <= IBUF_MAX_N_PAGES_MERGED);
3266 #endif
3267 buf_read_ibuf_merge_pages(false, space_ids, page_nos, n_stored);
3268 }
3269
3270 return (err);
3271 }
3272
3273 /** Buffer an operation in the insert/delete buffer, instead of doing it
3274 directly to the disk page, if this is possible. Does not do it if the index
3275 is clustered or unique.
3276 @param[in] op operation type
3277 @param[in] entry index entry to insert
3278 @param[in,out] index index where to insert
3279 @param[in] page_id page id where to insert
3280 @param[in] page_size page size
3281 @param[in,out] thr query thread
3282 @return true if success */
3283 bool ibuf_insert(ibuf_op_t op, const dtuple_t *entry, dict_index_t *index,
3284 const page_id_t &page_id, const page_size_t &page_size,
3285 que_thr_t *thr) {
3286 dberr_t err;
3287 ulint entry_size;
3288 /* Read the settable global variable ibuf_use only once in
3289 this function, so that we will have a consistent view of it. */
3290 assert(innodb_change_buffering <= IBUF_USE_ALL);
3291 ibuf_use_t use = static_cast<ibuf_use_t>(innodb_change_buffering);
3292
3293 DBUG_TRACE;
3294
3295 DBUG_PRINT("ibuf", ("op: %d, space: " UINT32PF ", page_no: " UINT32PF, op,
3296 page_id.space(), page_id.page_no()));
3297
3298 ut_ad(dtuple_check_typed(entry));
3299 ut_ad(!fsp_is_system_temporary(page_id.space()));
3300
3301 ut_a(!index->is_clustered());
3302
3303 auto no_counter = use <= IBUF_USE_INSERT;
3304
3305 switch (op) {
3306 case IBUF_OP_INSERT:
3307 switch (use) {
3308 case IBUF_USE_NONE:
3309 case IBUF_USE_DELETE:
3310 case IBUF_USE_DELETE_MARK:
3311 return false;
3312 case IBUF_USE_INSERT:
3313 case IBUF_USE_INSERT_DELETE_MARK:
3314 case IBUF_USE_ALL:
3315 goto check_watch;
3316 }
3317 break;
3318 case IBUF_OP_DELETE_MARK:
3319 switch (use) {
3320 case IBUF_USE_NONE:
3321 case IBUF_USE_INSERT:
3322 return false;
3323 case IBUF_USE_DELETE_MARK:
3324 case IBUF_USE_DELETE:
3325 case IBUF_USE_INSERT_DELETE_MARK:
3326 case IBUF_USE_ALL:
3327 ut_ad(!no_counter);
3328 goto check_watch;
3329 }
3330 break;
3331 case IBUF_OP_DELETE:
3332 switch (use) {
3333 case IBUF_USE_NONE:
3334 case IBUF_USE_INSERT:
3335 case IBUF_USE_INSERT_DELETE_MARK:
3336 return false;
3337 case IBUF_USE_DELETE_MARK:
3338 case IBUF_USE_DELETE:
3339 case IBUF_USE_ALL:
3340 ut_ad(!no_counter);
3341 goto skip_watch;
3342 }
3343 break;
3344 case IBUF_OP_COUNT:
3345 break;
3346 }
3347
3348 /* unknown op or use */
3349 ut_error;
3350
3351 check_watch:
3352 /* If a thread attempts to buffer an insert on a page while a
3353 purge is in progress on the same page, the purge must not be
3354 buffered, because it could remove a record that was
3355 re-inserted later. For simplicity, we block the buffering of
3356 all operations on a page that has a purge pending.
3357
3358 We do not check this in the IBUF_OP_DELETE case, because that
3359 would always trigger the buffer pool watch during purge and
3360 thus prevent the buffering of delete operations. We assume
3361 that the issuer of IBUF_OP_DELETE has called
3362 buf_pool_watch_set(space, page_no). */
3363
3364 {
3365 buf_pool_t *buf_pool = buf_pool_get(page_id);
3366 buf_page_t *bpage = buf_page_get_also_watch(buf_pool, page_id);
3367
3368 if (bpage != nullptr) {
3369 /* A buffer pool watch has been set or the
3370 page has been read into the buffer pool.
3371 Do not buffer the request. If a purge operation
3372 is being buffered, have this request executed
3373 directly on the page in the buffer pool after the
3374 buffered entries for this page have been merged. */
3375 return false;
3376 }
3377 }
3378
3379 skip_watch:
3380 entry_size = rec_get_converted_size(index, entry);
3381
3382 if (entry_size >=
3383 page_get_free_space_of_empty(dict_table_is_comp(index->table)) / 2) {
3384 return false;
3385 }
3386
3387 err = ibuf_insert_low(BTR_MODIFY_PREV, op, no_counter, entry, entry_size,
3388 index, page_id, page_size, thr);
3389 if (err == DB_FAIL) {
3390 err =
3391 ibuf_insert_low(BTR_MODIFY_TREE | BTR_LATCH_FOR_INSERT, op, no_counter,
3392 entry, entry_size, index, page_id, page_size, thr);
3393 }
3394
3395 if (err == DB_SUCCESS) {
3396 /*
3397 #if defined(UNIV_IBUF_DEBUG)
3398 fprintf(stderr, "Ibuf insert for page no %lu of index %s\n",
3399 page_no, index->name);
3400 #endif
3401 */
3402 return true;
3403
3404 } else {
3405 ut_a(err == DB_STRONG_FAIL || err == DB_TOO_BIG_RECORD);
3406
3407 return false;
3408 }
3409 }
3410
3411 /** During merge, inserts to an index page a secondary index entry extracted
3412 from the insert buffer.
3413 @return newly inserted record */
3414 static rec_t *ibuf_insert_to_index_page_low(
3415 const dtuple_t *entry, /*!< in: buffered entry to insert */
3416 buf_block_t *block, /*!< in/out: index page where the buffered
3417 entry should be placed */
3418 dict_index_t *index, /*!< in: record descriptor */
3419 ulint **offsets, /*!< out: offsets on *rec */
3420 mem_heap_t *heap, /*!< in/out: memory heap */
3421 mtr_t *mtr, /*!< in/out: mtr */
3422 page_cur_t *page_cur) /*!< in/out: cursor positioned on the record
3423 after which to insert the buffered entry */
3424 {
3425 const page_t *page;
3426 const page_t *bitmap_page;
3427 ulint old_bits;
3428 rec_t *rec;
3429 DBUG_TRACE;
3430
3431 rec = page_cur_tuple_insert(page_cur, entry, index, offsets, &heap, mtr);
3432 if (rec != nullptr) {
3433 return rec;
3434 }
3435
3436 /* Page reorganization or recompression should already have
3437 been attempted by page_cur_tuple_insert(). Besides, per
3438 ibuf_index_page_calc_free_zip() the page should not have been
3439 recompressed or reorganized. */
3440 ut_ad(!buf_block_get_page_zip(block));
3441
3442 /* If the record did not fit, reorganize */
3443
3444 btr_page_reorganize(page_cur, index, mtr);
3445
3446 /* This time the record must fit */
3447
3448 rec = page_cur_tuple_insert(page_cur, entry, index, offsets, &heap, mtr);
3449 if (rec != nullptr) {
3450 return rec;
3451 }
3452
3453 page = buf_block_get_frame(block);
3454
3455 ib::error(ER_IB_MSG_608) << "Insert buffer insert fails; page free "
3456 << page_get_max_insert_size(page, 1)
3457 << ", dtuple size "
3458 << rec_get_converted_size(index, entry);
3459
3460 fputs("InnoDB: Cannot insert index record ", stderr);
3461 dtuple_print(stderr, entry);
3462 fputs(
3463 "\nInnoDB: The table where this index record belongs\n"
3464 "InnoDB: is now probably corrupt. Please run CHECK TABLE on\n"
3465 "InnoDB: that table.\n",
3466 stderr);
3467
3468 bitmap_page = ibuf_bitmap_get_map_page(block->page.id, block->page.size,
3469 UT_LOCATION_HERE, mtr);
3470 old_bits = ibuf_bitmap_page_get_bits(bitmap_page, block->page.id,
3471 block->page.size, IBUF_BITMAP_FREE, mtr);
3472
3473 ib::error(ER_IB_MSG_609) << "page " << block->page.id << ", size "
3474 << block->page.size.physical() << ", bitmap bits "
3475 << old_bits;
3476
3477 ib::error(ER_IB_MSG_610) << BUG_REPORT_MSG;
3478
3479 ut_d(ut_error);
3480 ut_o(return nullptr);
3481 }
3482
3483 /************************************************************************
3484 During merge, inserts to an index page a secondary index entry extracted
3485 from the insert buffer. */
3486 static void ibuf_insert_to_index_page(
3487 const dtuple_t *entry, /*!< in: buffered entry to insert */
3488 buf_block_t *block, /*!< in/out: index page where the buffered entry
3489 should be placed */
3490 dict_index_t *index, /*!< in: record descriptor */
3491 mtr_t *mtr) /*!< in: mtr */
3492 {
3493 page_cur_t page_cur;
3494 ulint low_match;
3495 page_t *page = buf_block_get_frame(block);
3496 rec_t *rec;
3497 ulint *offsets;
3498 mem_heap_t *heap;
3499
3500 DBUG_TRACE;
3501
3502 DBUG_PRINT("ibuf", ("page " UINT32PF ":" UINT32PF, block->page.id.space(),
3503 block->page.id.page_no()));
3504
3505 ut_ad(!dict_index_is_online_ddl(index)); // this is an ibuf_dummy index
3506 ut_ad(ibuf_inside(mtr));
3507 ut_ad(dtuple_check_typed(entry));
3508 ut_d(entry->validate_for_index(index));
3509 /* A change buffer merge must occur before users are granted
3510 any access to the page. No adaptive hash index entries may
3511 point to a freshly read page. */
3512 ut_ad(!block->ahi.index);
3513 block->ahi.assert_empty();
3514
3515 if (UNIV_UNLIKELY(dict_table_is_comp(index->table) != page_is_comp(page))) {
3516 ib::warn(ER_IB_MSG_611)
3517 << "Trying to insert a record from the insert"
3518 " buffer to an index page but the 'compact' flag does"
3519 " not match!";
3520 goto dump;
3521 }
3522
3523 rec = page_rec_get_next(page_get_infimum_rec(page));
3524
3525 if (page_rec_is_supremum(rec)) {
3526 ib::warn(ER_IB_MSG_612) << "Trying to insert a record from the insert"
3527 " buffer to an index page but the index page"
3528 " is empty!";
3529 goto dump;
3530 }
3531
3532 if (!rec_n_fields_is_sane(index, rec, entry)) {
3533 ib::warn(ER_IB_MSG_613)
3534 << "Trying to insert a record from the insert"
3535 " buffer to an index page but the number of fields"
3536 " does not match!";
3537 rec_print(stderr, rec, index);
3538 dump:
3539 dtuple_print(stderr, entry);
3540 ib::warn(ER_IB_MSG_614)
3541 << "The table where this index record belongs"
3542 " is now probably corrupt. Please run CHECK TABLE on"
3543 " your tables. "
3544 << BUG_REPORT_MSG;
3545
3546 ut_d(ut_error);
3547
3548 ut_o(return);
3549 }
3550
3551 low_match = page_cur_search(block, index, entry, &page_cur);
3552
3553 heap = mem_heap_create(
3554 sizeof(upd_t) + REC_OFFS_HEADER_SIZE * sizeof(*offsets) +
3555 dtuple_get_n_fields(entry) * (sizeof(upd_field_t) + sizeof *offsets),
3556 UT_LOCATION_HERE);
3557
3558 if (UNIV_UNLIKELY(low_match == dtuple_get_n_fields(entry))) {
3559 upd_t *update;
3560 page_zip_des_t *page_zip;
3561
3562 rec = page_cur_get_rec(&page_cur);
3563
3564 /* This is based on
3565 row_ins_sec_index_entry_by_modify(BTR_MODIFY_LEAF). */
3566 ut_ad(rec_get_deleted_flag(rec, page_is_comp(page)));
3567
3568 offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED,
3569 UT_LOCATION_HERE, &heap);
3570 update = row_upd_build_sec_rec_difference_binary(rec, index, offsets, entry,
3571 heap);
3572
3573 page_zip = buf_block_get_page_zip(block);
3574
3575 if (update->n_fields == 0) {
3576 /* The records only differ in the delete-mark.
3577 Clear the delete-mark, like we did before
3578 Bug #56680 was fixed. */
3579 btr_cur_set_deleted_flag_for_ibuf(rec, page_zip, false, mtr);
3580 goto updated_in_place;
3581 }
3582
3583 /* Copy the info bits. Clear the delete-mark. */
3584 update->info_bits = rec_get_info_bits(rec, page_is_comp(page));
3585 update->info_bits &= ~REC_INFO_DELETED_FLAG;
3586
3587 /* We cannot invoke btr_cur_optimistic_update() here,
3588 because we do not have a btr_cur_t or que_thr_t,
3589 as the insert buffer merge occurs at a very low level. */
3590 if (!row_upd_changes_field_size_or_external(index, offsets, update) &&
3591 (!page_zip ||
3592 btr_cur_update_alloc_zip(page_zip, &page_cur, index, offsets,
3593 rec_offs_size(offsets), false, mtr))) {
3594 /* This is the easy case. Do something similar
3595 to btr_cur_update_in_place(). */
3596 rec = page_cur_get_rec(&page_cur);
3597 row_upd_rec_in_place(rec, index, offsets, update, page_zip);
3598
3599 /* Log the update in place operation. During recovery
3600 MLOG_COMP_REC_UPDATE_IN_PLACE/MLOG_REC_UPDATE_IN_PLACE
3601 expects trx_id, roll_ptr for secondary indexes. So we
3602 just write dummy trx_id(0), roll_ptr(0) */
3603 btr_cur_update_in_place_log(BTR_KEEP_SYS_FLAG, rec, index, update, 0, 0,
3604 mtr);
3605
3606 DBUG_EXECUTE_IF("crash_after_log_ibuf_upd_inplace",
3607 log_buffer_flush_to_disk();
3608 ib::info(ER_IB_MSG_615) << "Wrote log record for ibuf"
3609 " update in place operation";
3610 DBUG_SUICIDE(););
3611
3612 goto updated_in_place;
3613 }
3614
3615 /* btr_cur_update_alloc_zip() may have changed this */
3616 rec = page_cur_get_rec(&page_cur);
3617
3618 /* A collation may identify values that differ in
3619 storage length.
3620 Some examples (1 or 2 bytes):
3621 utf8mb3_turkish_ci: I = U+0131 LATIN SMALL LETTER DOTLESS I
3622 utf8mb3_general_ci: S = U+00DF LATIN SMALL LETTER SHARP S
3623 utf8mb3_general_ci: A = U+00E4 LATIN SMALL LETTER A WITH DIAERESIS
3624
3625 latin1_german2_ci: SS = U+00DF LATIN SMALL LETTER SHARP S
3626
3627 Examples of a character (3-byte UTF-8 sequence)
3628 identified with 2 or 4 characters (1-byte UTF-8 sequences):
3629
3630 utf8mb3_unicode_ci: 'II' = U+2171 SMALL ROMAN NUMERAL TWO
3631 utf8mb3_unicode_ci: '(10)' = U+247D PARENTHESIZED NUMBER TEN
3632 */
3633
3634 /* Delete the different-length record, and insert the
3635 buffered one. */
3636
3637 lock_rec_store_on_page_infimum(block, rec);
3638 page_cur_delete_rec(&page_cur, index, offsets, mtr);
3639 page_cur_move_to_prev(&page_cur);
3640 rec = ibuf_insert_to_index_page_low(entry, block, index, &offsets, heap,
3641 mtr, &page_cur);
3642
3643 ut_ad(!cmp_dtuple_rec(entry, rec, index, offsets));
3644 lock_rec_restore_from_page_infimum(block, rec, block);
3645 } else {
3646 offsets = nullptr;
3647 ibuf_insert_to_index_page_low(entry, block, index, &offsets, heap, mtr,
3648 &page_cur);
3649 }
3650 updated_in_place:
3651 mem_heap_free(heap);
3652 }
3653
3654 /** During merge, sets the delete mark on a record for a secondary index
3655 entry. */
3656 static void ibuf_set_del_mark(
3657 const dtuple_t *entry, /*!< in: entry */
3658 buf_block_t *block, /*!< in/out: block */
3659 const dict_index_t *index, /*!< in: record descriptor */
3660 mtr_t *mtr) /*!< in: mtr */
3661 {
3662 page_cur_t page_cur;
3663 ulint low_match;
3664
3665 ut_ad(ibuf_inside(mtr));
3666 ut_ad(dtuple_check_typed(entry));
3667
3668 low_match = page_cur_search(block, index, entry, &page_cur);
3669
3670 if (low_match == dtuple_get_n_fields(entry)) {
3671 rec_t *rec;
3672 page_zip_des_t *page_zip;
3673
3674 rec = page_cur_get_rec(&page_cur);
3675 page_zip = page_cur_get_page_zip(&page_cur);
3676
3677 /* Delete mark the old index record. According to a
3678 comment in row_upd_sec_index_entry(), it can already
3679 have been delete marked if a lock wait occurred in
3680 row_ins_sec_index_entry() in a previous invocation of
3681 row_upd_sec_index_entry(). */
3682
3683 if (UNIV_LIKELY(
3684 !rec_get_deleted_flag(rec, dict_table_is_comp(index->table)))) {
3685 btr_cur_set_deleted_flag_for_ibuf(rec, page_zip, true, mtr);
3686 }
3687 } else {
3688 const page_t *page = page_cur_get_page(&page_cur);
3689 const buf_block_t *block = page_cur_get_block(&page_cur);
3690
3691 ib::error(ER_IB_MSG_616) << "Unable to find a record to delete-mark";
3692 fputs("InnoDB: tuple ", stderr);
3693 dtuple_print(stderr, entry);
3694 fputs(
3695 "\n"
3696 "InnoDB: record ",
3697 stderr);
3698 rec_print(stderr, page_cur_get_rec(&page_cur), index);
3699
3700 ib::error(ER_IB_MSG_617)
3701 << "page " << block->page.id << " (" << page_get_n_recs(page)
3702 << " records, index id " << btr_page_get_index_id(page) << ").";
3703
3704 ib::error(ER_IB_MSG_618) << BUG_REPORT_MSG;
3705 ut_d(ut_error);
3706 }
3707 }
3708
3709 /** During merge, delete a record for a secondary index entry. */
3710 static void ibuf_delete(const dtuple_t *entry, /*!< in: entry */
3711 buf_block_t *block, /*!< in/out: block */
3712 dict_index_t *index, /*!< in: record descriptor */
3713 mtr_t *mtr) /*!< in/out: mtr; must be committed
3714 before latching any further pages */
3715 {
3716 page_cur_t page_cur;
3717 ulint low_match;
3718
3719 ut_ad(ibuf_inside(mtr));
3720 ut_ad(dtuple_check_typed(entry));
3721 ut_ad(!dict_index_is_spatial(index));
3722
3723 low_match = page_cur_search(block, index, entry, &page_cur);
3724
3725 if (low_match == dtuple_get_n_fields(entry)) {
3726 page_zip_des_t *page_zip = buf_block_get_page_zip(block);
3727 page_t *page = buf_block_get_frame(block);
3728 rec_t *rec = page_cur_get_rec(&page_cur);
3729
3730 /* TODO: the below should probably be a separate function,
3731 it's a bastardized version of btr_cur_optimistic_delete. */
3732
3733 ulint offsets_[REC_OFFS_NORMAL_SIZE];
3734 ulint *offsets = offsets_;
3735 mem_heap_t *heap = nullptr;
3736 ulint max_ins_size = 0;
3737
3738 rec_offs_init(offsets_);
3739
3740 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
3741 UT_LOCATION_HERE, &heap);
3742
3743 if (page_get_n_recs(page) <= 1 ||
3744 !(REC_INFO_DELETED_FLAG & rec_get_info_bits(rec, page_is_comp(page)))) {
3745 /* Refuse to purge the last record or a
3746 record that has not been marked for deletion. */
3747 ib::error(ER_IB_MSG_619) << "Unable to purge a record";
3748 fputs("InnoDB: tuple ", stderr);
3749 dtuple_print(stderr, entry);
3750 fputs(
3751 "\n"
3752 "InnoDB: record ",
3753 stderr);
3754 rec_print_new(stderr, rec, offsets);
3755 fprintf(stderr,
3756 "\nspace " UINT32PF " offset " UINT32PF
3757 " (%u records, index id %llu)\n"
3758 "InnoDB: Submit a detailed bug report"
3759 " to http://bugs.mysql.com\n",
3760 block->page.id.space(), block->page.id.page_no(),
3761 (unsigned)page_get_n_recs(page),
3762 (ulonglong)btr_page_get_index_id(page));
3763
3764 ut_d(ut_error);
3765 ut_o(return);
3766 }
3767
3768 lock_update_delete(block, rec);
3769
3770 if (!page_zip) {
3771 max_ins_size = page_get_max_insert_size_after_reorganize(page, 1);
3772 }
3773 #ifdef UNIV_ZIP_DEBUG
3774 ut_a(!page_zip || page_zip_validate(page_zip, page, index));
3775 #endif /* UNIV_ZIP_DEBUG */
3776 page_cur_delete_rec(&page_cur, index, offsets, mtr);
3777 #ifdef UNIV_ZIP_DEBUG
3778 ut_a(!page_zip || page_zip_validate(page_zip, page, index));
3779 #endif /* UNIV_ZIP_DEBUG */
3780
3781 if (page_zip) {
3782 ibuf_update_free_bits_zip(block, mtr);
3783 } else {
3784 ibuf_update_free_bits_low(block, max_ins_size, mtr);
3785 }
3786
3787 if (UNIV_LIKELY_NULL(heap)) {
3788 mem_heap_free(heap);
3789 }
3790 } else {
3791 /* The record must have been purged already. */
3792 }
3793 }
3794
3795 /** Restores insert buffer tree cursor position
3796 @param[in] space_id Tablespace id
3797 @param[in] page_no index page number where the record should belong
3798 @param [in] search_tuple search tuple for entries of page_no
3799 @param[in] mode BTR_MODIFY_LEAF or BTR_MODIFY_TREE
3800 @param[in,out] pcur persistent cursor whose position is to be restored
3801 @param[in, out] mtr mini-transaction
3802 @return true if the position was restored; false if not */
3803 static bool ibuf_restore_pos(space_id_t space_id, page_no_t page_no,
3804 const dtuple_t *search_tuple, ulint mode,
3805 btr_pcur_t *pcur, mtr_t *mtr) {
3806 ut_ad(mode == BTR_MODIFY_LEAF ||
3807 BTR_LATCH_MODE_WITHOUT_INTENTION(mode) == BTR_MODIFY_TREE);
3808
3809 if (pcur->restore_position(mode, mtr, UT_LOCATION_HERE)) {
3810 return true;
3811 }
3812
3813 if (const auto space = fil_space_acquire_silent(space_id); space == nullptr) {
3814 /* The tablespace has been(or being) deleted. Do not complain. */
3815 ibuf_btr_pcur_commit_specify_mtr(pcur, mtr);
3816 } else {
3817 fil_space_release(space);
3818 ib::error(ER_IB_MSG_620) << "ibuf cursor restoration fails!."
3819 " ibuf record inserted to page "
3820 << space_id << ":" << page_no;
3821
3822 ib::error(ER_IB_MSG_621) << BUG_REPORT_MSG;
3823
3824 rec_print_old(stderr, pcur->get_rec());
3825 rec_print_old(stderr, pcur->m_old_rec);
3826 dtuple_print(stderr, search_tuple);
3827
3828 rec_print_old(stderr, page_rec_get_next(pcur->get_rec()));
3829
3830 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_622)
3831 << "Failed to restore ibuf position.";
3832 }
3833
3834 return false;
3835 }
3836
3837 /** Deletes from ibuf the record on which pcur is positioned. If we have to
3838 resort to a pessimistic delete, this function commits mtr and closes
3839 the cursor.
3840 @return true if mtr was committed and pcur closed in this operation */
3841 [[nodiscard]] static bool ibuf_delete_rec(
3842 space_id_t space, /*!< in: space id */
3843 page_no_t page_no, /*!< in: index page number that the record
3844 should belong to */
3845 btr_pcur_t *pcur, /*!< in: pcur positioned on the record to
3846 delete, having latch mode BTR_MODIFY_LEAF */
3847 const dtuple_t *search_tuple,
3848 /*!< in: search tuple for entries of page_no */
3849 mtr_t *mtr) /*!< in: mtr */
3850 {
3851 page_t *root;
3852 dberr_t err;
3853
3854 ut_ad(ibuf_inside(mtr));
3855 ut_ad(page_rec_is_user_rec(pcur->get_rec()));
3856 ut_ad(ibuf_rec_get_page_no(mtr, pcur->get_rec()) == page_no);
3857 ut_ad(ibuf_rec_get_space(mtr, pcur->get_rec()) == space);
3858
3859 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
3860 if (ibuf_debug == 2) {
3861 /* Inject a fault (crash). We do this before trying
3862 optimistic delete, because a pessimistic delete in the
3863 change buffer would require a larger test case. */
3864
3865 /* Flag the buffered record as processed, to avoid
3866 an assertion failure after crash recovery. */
3867 btr_cur_set_deleted_flag_for_ibuf(pcur->get_rec(), nullptr, true, mtr);
3868
3869 ibuf_mtr_commit(mtr);
3870 log_buffer_flush_to_disk();
3871 DBUG_SUICIDE();
3872 }
3873 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
3874
3875 auto success = btr_cur_optimistic_delete(pcur->get_btr_cur(), 0, mtr);
3876
3877 const page_id_t page_id(space, page_no);
3878
3879 if (success) {
3880 if (page_is_empty(pcur->get_page())) {
3881 /* If a B-tree page is empty, it must be the root page
3882 and the whole B-tree must be empty. InnoDB does not
3883 allow empty B-tree pages other than the root. */
3884 root = pcur->get_page();
3885
3886 ut_ad(page_get_space_id(root) == IBUF_SPACE_ID);
3887 ut_ad(page_get_page_no(root) == FSP_IBUF_TREE_ROOT_PAGE_NO);
3888
3889 /* ibuf->empty is protected by the root page latch.
3890 Before the deletion, it had to be false. */
3891 ut_ad(!ibuf->empty);
3892 ibuf->empty = true;
3893 }
3894
3895 #ifdef UNIV_IBUF_COUNT_DEBUG
3896 ib::info(ER_IB_MSG_623)
3897 << "Decrementing ibuf count of space " << space << " page " << page_no
3898 << " from " << ibuf_count_get(page_id) << " by 1";
3899
3900 ibuf_count_set(page_id, ibuf_count_get(page_id) - 1);
3901 #endif /* UNIV_IBUF_COUNT_DEBUG */
3902
3903 return false;
3904 }
3905
3906 ut_ad(page_rec_is_user_rec(pcur->get_rec()));
3907 ut_ad(ibuf_rec_get_page_no(mtr, pcur->get_rec()) == page_no);
3908 ut_ad(ibuf_rec_get_space(mtr, pcur->get_rec()) == space);
3909
3910 /* We have to resort to a pessimistic delete from ibuf.
3911 Delete-mark the record so that it will not be applied again,
3912 in case the server crashes before the pessimistic delete is
3913 made persistent. */
3914 btr_cur_set_deleted_flag_for_ibuf(pcur->get_rec(), nullptr, true, mtr);
3915
3916 pcur->store_position(mtr);
3917 ibuf_btr_pcur_commit_specify_mtr(pcur, mtr);
3918
3919 ibuf_mtr_start(mtr);
3920
3921 mutex_enter(&ibuf_mutex);
3922
3923 if (!ibuf_restore_pos(space, page_no, search_tuple,
3924 BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE, pcur, mtr)) {
3925 mutex_exit(&ibuf_mutex);
3926 ut_ad(mtr->has_committed());
3927 goto func_exit;
3928 }
3929
3930 root = ibuf_tree_root_get(mtr);
3931
3932 btr_cur_pessimistic_delete(&err, true, pcur->get_btr_cur(), 0, false, 0, 0, 0,
3933 mtr, nullptr, nullptr);
3934 ut_a(err == DB_SUCCESS);
3935
3936 #ifdef UNIV_IBUF_COUNT_DEBUG
3937 ibuf_count_set(page_id, ibuf_count_get(page_id) - 1);
3938 #endif /* UNIV_IBUF_COUNT_DEBUG */
3939
3940 ibuf_size_update(root);
3941 mutex_exit(&ibuf_mutex);
3942
3943 ibuf->empty = page_is_empty(root);
3944 ibuf_btr_pcur_commit_specify_mtr(pcur, mtr);
3945
3946 func_exit:
3947 ut_ad(mtr->has_committed());
3948 pcur->close();
3949
3950 return true;
3951 }
3952
3953 /** When an index page is read from a disk to the buffer pool, this function
3954 applies any buffered operations to the page and deletes the entries from the
3955 insert buffer. If the page is not read, but created in the buffer pool, this
3956 function deletes its buffered entries from the insert buffer; there can
3957 exist entries for such a page if the page belonged to an index which
3958 subsequently was dropped.
3959 @param[in,out] block if page has been read from disk,
3960 pointer to the page x-latched, else NULL
3961 @param[in] page_id page id of the index page
3962 @param[in] update_ibuf_bitmap normally this is set to true, but
3963 if we have deleted or are deleting the tablespace, then we naturally do not
3964 want to update a non-existent bitmap page
3965 @param[in] page_size page size */
3966 void ibuf_merge_or_delete_for_page(buf_block_t *block, const page_id_t &page_id,
3967 const page_size_t *page_size,
3968 bool update_ibuf_bitmap) {
3969 mem_heap_t *heap;
3970 btr_pcur_t pcur;
3971 dtuple_t *search_tuple;
3972 #ifdef UNIV_IBUF_DEBUG
3973 ulint volume = 0;
3974 #endif /* UNIV_IBUF_DEBUG */
3975 page_zip_des_t *page_zip = nullptr;
3976 fil_space_t *space = nullptr;
3977 bool corruption_noticed = false;
3978 bool success;
3979 mtr_t mtr;
3980
3981 /* Counts for merged & discarded operations. */
3982 ulint mops[IBUF_OP_COUNT];
3983 ulint dops[IBUF_OP_COUNT];
3984
3985 ut_ad(block == nullptr || page_id == block->page.id);
3986 ut_ad(block == nullptr || block->page.is_io_fix_read());
3987
3988 if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE ||
3989 trx_sys_hdr_page(page_id) || fsp_is_system_temporary(page_id.space())) {
3990 return;
3991 }
3992
3993 /* We cannot refer to page_size in the following, because it is passed
3994 as NULL (it is unknown) when buf_read_ibuf_merge_pages() is merging
3995 (discarding) changes for a dropped tablespace. When block != NULL or
3996 update_ibuf_bitmap is specified, then page_size must be known.
3997 That is why we will repeat the check below, with page_size in
3998 place of univ_page_size. Passing univ_page_size assumes that the
3999 uncompressed page size always is a power-of-2 multiple of the
4000 compressed page size. */
4001
4002 if (ibuf_fixed_addr_page(page_id, univ_page_size) ||
4003 fsp_descr_page(page_id, univ_page_size)) {
4004 return;
4005 }
4006
4007 if (update_ibuf_bitmap) {
4008 ut_ad(page_size != nullptr);
4009
4010 if (ibuf_fixed_addr_page(page_id, *page_size) ||
4011 fsp_descr_page(page_id, *page_size)) {
4012 return;
4013 }
4014
4015 space = fil_space_acquire_silent(page_id.space());
4016
4017 if (space == nullptr) {
4018 /* Do not try to read the bitmap page from space;
4019 just delete the ibuf records for the page */
4020
4021 block = nullptr;
4022 update_ibuf_bitmap = false;
4023 } else {
4024 page_t *bitmap_page;
4025 ulint bitmap_bits;
4026
4027 ibuf_mtr_start(&mtr);
4028
4029 bitmap_page =
4030 ibuf_bitmap_get_map_page(page_id, *page_size, UT_LOCATION_HERE, &mtr);
4031
4032 bitmap_bits = ibuf_bitmap_page_get_bits(bitmap_page, page_id, *page_size,
4033 IBUF_BITMAP_BUFFERED, &mtr);
4034
4035 ibuf_mtr_commit(&mtr);
4036
4037 if (!bitmap_bits) {
4038 /* No inserts buffered for this page */
4039
4040 fil_space_release(space);
4041 return;
4042 }
4043 }
4044 } else if (block != nullptr && (ibuf_fixed_addr_page(page_id, *page_size) ||
4045 fsp_descr_page(page_id, *page_size))) {
4046 return;
4047 }
4048
4049 heap = mem_heap_create(512, UT_LOCATION_HERE);
4050
4051 search_tuple =
4052 ibuf_search_tuple_build(page_id.space(), page_id.page_no(), heap);
4053
4054 if (block != nullptr) {
4055 /* Move the ownership of the x-latch on the page to this OS
4056 thread, so that we can acquire a second x-latch on it. This
4057 is needed for the insert operations to the index page to pass
4058 the debug checks. */
4059
4060 rw_lock_x_lock_move_ownership(&(block->lock));
4061 page_zip = buf_block_get_page_zip(block);
4062
4063 if (!fil_page_index_page_check(block->frame) ||
4064 !page_is_leaf(block->frame)) {
4065 corruption_noticed = true;
4066
4067 ib::error(ER_IB_MSG_624) << "Corruption in the tablespace. Bitmap"
4068 " shows insert buffer records to page "
4069 << page_id << " though the page type is "
4070 << fil_page_get_type(block->frame)
4071 << ", which is not an index leaf page. We try"
4072 " to resolve the problem by skipping the"
4073 " insert buffer merge for this page. Please"
4074 " run CHECK TABLE on your tables to determine"
4075 " if they are corrupt after this.";
4076
4077 ib::error(ER_IB_MSG_625) << "Please submit a detailed bug"
4078 " report to http://bugs.mysql.com";
4079 ut_d(ut_error);
4080 }
4081 }
4082
4083 memset(mops, 0, sizeof(mops));
4084 memset(dops, 0, sizeof(dops));
4085
4086 loop:
4087 ibuf_mtr_start(&mtr);
4088
4089 /* Position pcur in the insert buffer at the first entry for this
4090 index page */
4091 pcur.open_on_user_rec(ibuf->index, search_tuple, PAGE_CUR_GE, BTR_MODIFY_LEAF,
4092 &mtr, UT_LOCATION_HERE);
4093
4094 if (block != nullptr) {
4095 auto success = buf_page_get_known_nowait(
4096 RW_X_LATCH, block, Cache_hint::KEEP_OLD, __FILE__, __LINE__, &mtr);
4097
4098 ut_a(success);
4099
4100 /* This is a user page (secondary index leaf page),
4101 but we pretend that it is a change buffer page in
4102 order to obey the latching order. This should be OK,
4103 because buffered changes are applied immediately while
4104 the block is io-fixed. Other threads must not try to
4105 latch an io-fixed block. */
4106 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
4107 }
4108
4109 if (!pcur.is_on_user_rec()) {
4110 ut_ad(pcur.is_after_last_in_tree(&mtr));
4111
4112 goto reset_bit;
4113 }
4114
4115 for (;;) {
4116 rec_t *rec;
4117
4118 ut_ad(pcur.is_on_user_rec());
4119
4120 rec = pcur.get_rec();
4121
4122 /* Check if the entry is for this index page */
4123 if (ibuf_rec_get_page_no(&mtr, rec) != page_id.page_no() ||
4124 ibuf_rec_get_space(&mtr, rec) != page_id.space()) {
4125 if (block != nullptr) {
4126 page_header_reset_last_insert(block->frame, page_zip, &mtr);
4127 }
4128
4129 goto reset_bit;
4130 }
4131
4132 if (corruption_noticed) {
4133 fputs("InnoDB: Discarding record\n ", stderr);
4134 rec_print_old(stderr, rec);
4135 fputs("\nInnoDB: from the insert buffer!\n\n", stderr);
4136 } else if (block != nullptr && !rec_get_deleted_flag(rec, 0)) {
4137 /* Now we have at pcur a record which should be
4138 applied on the index page; NOTE that the call below
4139 copies pointers to fields in rec, and we must
4140 keep the latch to the rec page until the
4141 insertion is finished! */
4142 dtuple_t *entry;
4143 trx_id_t max_trx_id;
4144 dict_index_t *dummy_index;
4145 ibuf_op_t op = ibuf_rec_get_op_type(&mtr, rec);
4146
4147 max_trx_id = page_get_max_trx_id(page_align(rec));
4148 page_update_max_trx_id(block, page_zip, max_trx_id, &mtr);
4149
4150 ut_ad(page_validate(page_align(rec), ibuf->index));
4151
4152 entry = ibuf_build_entry_from_ibuf_rec(&mtr, rec, heap, &dummy_index);
4153
4154 ut_ad(page_validate(block->frame, dummy_index));
4155
4156 switch (op) {
4157 case IBUF_OP_INSERT:
4158 #ifdef UNIV_IBUF_DEBUG
4159 volume += rec_get_converted_size(dummy_index, entry);
4160
4161 volume += page_dir_calc_reserved_space(1);
4162
4163 ut_a(volume <= 4 * UNIV_PAGE_SIZE / IBUF_PAGE_SIZE_PER_FREE_SPACE);
4164 #endif
4165 ibuf_insert_to_index_page(entry, block, dummy_index, &mtr);
4166 break;
4167
4168 case IBUF_OP_DELETE_MARK:
4169 ibuf_set_del_mark(entry, block, dummy_index, &mtr);
4170 break;
4171
4172 case IBUF_OP_DELETE:
4173 ibuf_delete(entry, block, dummy_index, &mtr);
4174 /* Because ibuf_delete() will latch an
4175 insert buffer bitmap page, commit mtr
4176 before latching any further pages.
4177 Store and restore the cursor position. */
4178 ut_ad(rec == pcur.get_rec());
4179 ut_ad(page_rec_is_user_rec(rec));
4180 ut_ad(ibuf_rec_get_page_no(&mtr, rec) == page_id.page_no());
4181 ut_ad(ibuf_rec_get_space(&mtr, rec) == page_id.space());
4182
4183 /* Mark the change buffer record processed,
4184 so that it will not be merged again in case
4185 the server crashes between the following
4186 mtr_commit() and the subsequent mtr_commit()
4187 of deleting the change buffer record. */
4188
4189 btr_cur_set_deleted_flag_for_ibuf(pcur.get_rec(), nullptr, true,
4190 &mtr);
4191
4192 pcur.store_position(&mtr);
4193 ibuf_btr_pcur_commit_specify_mtr(&pcur, &mtr);
4194
4195 ibuf_mtr_start(&mtr);
4196
4197 success =
4198 buf_page_get_known_nowait(RW_X_LATCH, block, Cache_hint::KEEP_OLD,
4199 __FILE__, __LINE__, &mtr);
4200 ut_a(success);
4201
4202 /* This is a user page (secondary
4203 index leaf page), but it should be OK
4204 to use too low latching order for it,
4205 as the block is io-fixed. */
4206 buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE);
4207
4208 if (!ibuf_restore_pos(page_id.space(), page_id.page_no(),
4209 search_tuple, BTR_MODIFY_LEAF, &pcur, &mtr)) {
4210 ut_ad(mtr.has_committed());
4211 mops[op]++;
4212 ibuf_dummy_index_free(dummy_index);
4213 goto loop;
4214 }
4215
4216 break;
4217 default:
4218 ut_error;
4219 }
4220
4221 mops[op]++;
4222
4223 ibuf_dummy_index_free(dummy_index);
4224 } else {
4225 dops[ibuf_rec_get_op_type(&mtr, rec)]++;
4226 }
4227
4228 /* Delete the record from ibuf */
4229 if (ibuf_delete_rec(page_id.space(), page_id.page_no(), &pcur, search_tuple,
4230 &mtr)) {
4231 /* Deletion was pessimistic and mtr was committed:
4232 we start from the beginning again */
4233
4234 ut_ad(mtr.has_committed());
4235 goto loop;
4236 } else if (pcur.is_after_last_on_page()) {
4237 ibuf_mtr_commit(&mtr);
4238 pcur.close();
4239
4240 goto loop;
4241 }
4242 }
4243
4244 reset_bit:
4245 if (update_ibuf_bitmap) {
4246 page_t *bitmap_page;
4247
4248 bitmap_page =
4249 ibuf_bitmap_get_map_page(page_id, *page_size, UT_LOCATION_HERE, &mtr);
4250
4251 ibuf_bitmap_page_set_bits(bitmap_page, page_id, *page_size,
4252 IBUF_BITMAP_BUFFERED, false, &mtr);
4253
4254 if (block != nullptr) {
4255 ulint old_bits = ibuf_bitmap_page_get_bits(
4256 bitmap_page, page_id, *page_size, IBUF_BITMAP_FREE, &mtr);
4257
4258 ulint new_bits = ibuf_index_page_calc_free(block);
4259
4260 if (old_bits != new_bits) {
4261 ibuf_bitmap_page_set_bits(bitmap_page, page_id, *page_size,
4262 IBUF_BITMAP_FREE, new_bits, &mtr);
4263 }
4264 }
4265 }
4266
4267 ibuf_mtr_commit(&mtr);
4268 pcur.close();
4269 mem_heap_free(heap);
4270
4271 ibuf->n_merges.fetch_add(1);
4272 ibuf_add_ops(ibuf->n_merged_ops, mops);
4273 ibuf_add_ops(ibuf->n_discarded_ops, dops);
4274
4275 if (space != nullptr) {
4276 fil_space_release(space);
4277 }
4278
4279 #ifdef UNIV_IBUF_COUNT_DEBUG
4280 ut_a(ibuf_count_get(page_id) == 0);
4281 #endif
4282 }
4283
4284 /** Deletes all entries in the insert buffer for a given space id. This is used
4285 in DISCARD TABLESPACE and IMPORT TABLESPACE.
4286 NOTE: this does not update the page free bitmaps in the space. The space will
4287 become CORRUPT when you call this function! */
4288 void ibuf_delete_for_discarded_space(space_id_t space) /*!< in: space id */
4289 {
4290 mem_heap_t *heap;
4291 btr_pcur_t pcur;
4292 dtuple_t *search_tuple;
4293 const rec_t *ibuf_rec;
4294 page_no_t page_no;
4295 mtr_t mtr;
4296
4297 /* Counts for discarded operations. */
4298 ulint dops[IBUF_OP_COUNT];
4299
4300 heap = mem_heap_create(512, UT_LOCATION_HERE);
4301
4302 /* Use page number 0 to build the search tuple so that we get the
4303 cursor positioned at the first entry for this space id */
4304
4305 search_tuple = ibuf_search_tuple_build(space, 0, heap);
4306
4307 memset(dops, 0, sizeof(dops));
4308 loop:
4309 ibuf_mtr_start(&mtr);
4310
4311 /* Position pcur in the insert buffer at the first entry for the
4312 space */
4313 pcur.open_on_user_rec(ibuf->index, search_tuple, PAGE_CUR_GE, BTR_MODIFY_LEAF,
4314 &mtr, UT_LOCATION_HERE);
4315
4316 if (!pcur.is_on_user_rec()) {
4317 ut_ad(pcur.is_after_last_in_tree(&mtr));
4318
4319 goto leave_loop;
4320 }
4321
4322 for (;;) {
4323 ut_ad(pcur.is_on_user_rec());
4324
4325 ibuf_rec = pcur.get_rec();
4326
4327 /* Check if the entry is for this space */
4328 if (ibuf_rec_get_space(&mtr, ibuf_rec) != space) {
4329 goto leave_loop;
4330 }
4331
4332 page_no = ibuf_rec_get_page_no(&mtr, ibuf_rec);
4333
4334 dops[ibuf_rec_get_op_type(&mtr, ibuf_rec)]++;
4335
4336 /* Delete the record from ibuf */
4337 if (ibuf_delete_rec(space, page_no, &pcur, search_tuple, &mtr)) {
4338 /* Deletion was pessimistic and mtr was committed:
4339 we start from the beginning again */
4340
4341 ut_ad(mtr.has_committed());
4342 goto loop;
4343 }
4344
4345 if (pcur.is_after_last_on_page()) {
4346 ibuf_mtr_commit(&mtr);
4347 pcur.close();
4348
4349 goto loop;
4350 }
4351 }
4352
4353 leave_loop:
4354 ibuf_mtr_commit(&mtr);
4355 pcur.close();
4356
4357 ibuf_add_ops(ibuf->n_discarded_ops, dops);
4358
4359 mem_heap_free(heap);
4360 }
4361
4362 /** Looks if the insert buffer is empty.
4363 @return true if empty */
4364 bool ibuf_is_empty(void) {
4365 bool is_empty;
4366 const page_t *root;
4367 mtr_t mtr;
4368
4369 ibuf_mtr_start(&mtr);
4370
4371 mutex_enter(&ibuf_mutex);
4372 root = ibuf_tree_root_get(&mtr);
4373 mutex_exit(&ibuf_mutex);
4374
4375 is_empty = page_is_empty(root);
4376 ut_a(is_empty == ibuf->empty);
4377 ibuf_mtr_commit(&mtr);
4378
4379 return (is_empty);
4380 }
4381
4382 /** Prints info of ibuf. */
4383 void ibuf_print(FILE *file) /*!< in: file where to print */
4384 {
4385 #ifdef UNIV_IBUF_COUNT_DEBUG
4386 space_id_t i;
4387 page_no_t j;
4388 #endif
4389
4390 mutex_enter(&ibuf_mutex);
4391
4392 fprintf(file,
4393 "Ibuf: size %lu, free list len %lu,"
4394 " seg size %lu, %lu merges\n",
4395 (ulong)ibuf->size, (ulong)ibuf->free_list_len, (ulong)ibuf->seg_size,
4396 (ulong)ibuf->n_merges);
4397
4398 fputs("merged operations:\n ", file);
4399 ibuf_print_ops(ibuf->n_merged_ops, file);
4400
4401 fputs("discarded operations:\n ", file);
4402 ibuf_print_ops(ibuf->n_discarded_ops, file);
4403
4404 #ifdef UNIV_IBUF_COUNT_DEBUG
4405 for (i = 0; i < IBUF_COUNT_N_SPACES; i++) {
4406 for (j = 0; j < IBUF_COUNT_N_PAGES; j++) {
4407 ulint count = ibuf_count_get(page_id_t(i, j, 0));
4408
4409 if (count > 0) {
4410 fprintf(stderr,
4411 "Ibuf count for space/page %lu/%lu"
4412 " is %lu\n",
4413 (ulong)i, (ulong)j, (ulong)count);
4414 }
4415 }
4416 }
4417 #endif /* UNIV_IBUF_COUNT_DEBUG */
4418
4419 mutex_exit(&ibuf_mutex);
4420 }
4421
4422 /** Checks the insert buffer bitmaps on IMPORT TABLESPACE.
4423 @return DB_SUCCESS or error code */
4424 dberr_t ibuf_check_bitmap_on_import(
4425 const trx_t *trx, /*!< in: transaction */
4426 space_id_t space_id) /*!< in: tablespace identifier */
4427 {
4428 page_no_t size;
4429 page_no_t page_no;
4430
4431 ut_ad(space_id);
4432 ut_ad(trx->mysql_thd);
4433
4434 bool found;
4435
4436 const page_size_t &page_size = fil_space_get_page_size(space_id, &found);
4437
4438 if (!found) {
4439 return (DB_TABLE_NOT_FOUND);
4440 }
4441
4442 size = fil_space_get_size(space_id);
4443
4444 if (size == 0) {
4445 return (DB_TABLE_NOT_FOUND);
4446 }
4447
4448 mutex_enter(&ibuf_mutex);
4449
4450 /* The two bitmap pages (allocation bitmap and ibuf bitmap) repeat
4451 every page_size pages. For example if page_size is 16 KiB, then the
4452 two bitmap pages repeat every 16 KiB * 16384 = 256 MiB. In the loop
4453 below page_no is measured in number of pages since the beginning of
4454 the space, as usual. */
4455
4456 for (page_no = 0; page_no < size;
4457 page_no += static_cast<page_no_t>(page_size.physical())) {
4458 mtr_t mtr;
4459 page_t *bitmap_page;
4460 page_no_t i;
4461
4462 if (trx_is_interrupted(trx)) {
4463 mutex_exit(&ibuf_mutex);
4464 return (DB_INTERRUPTED);
4465 }
4466
4467 mtr_start(&mtr);
4468
4469 mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO);
4470
4471 ibuf_enter(&mtr);
4472
4473 bitmap_page = ibuf_bitmap_get_map_page(page_id_t(space_id, page_no),
4474 page_size, UT_LOCATION_HERE, &mtr);
4475
4476 if (buf_page_is_zeroes(bitmap_page, page_size)) {
4477 /* This means we got all-zero page instead of
4478 ibuf bitmap page. The subsequent page should be
4479 all-zero pages. */
4480 #ifdef UNIV_DEBUG
4481 for (page_no_t curr_page = page_no + 1; curr_page < page_size.physical();
4482 curr_page++) {
4483 buf_block_t *block =
4484 buf_page_get(page_id_t(space_id, curr_page), page_size, RW_S_LATCH,
4485 UT_LOCATION_HERE, &mtr);
4486 page_t *page = buf_block_get_frame(block);
4487 ut_ad(buf_page_is_zeroes(page, page_size));
4488 }
4489 #endif /* UNIV_DEBUG */
4490 ibuf_exit(&mtr);
4491 mtr_commit(&mtr);
4492 continue;
4493 }
4494
4495 for (i = FSP_IBUF_BITMAP_OFFSET + 1;
4496 i < static_cast<page_no_t>(page_size.physical()); i++) {
4497 const page_no_t offset = page_no + i;
4498
4499 const page_id_t cur_page_id(space_id, offset);
4500
4501 if (ibuf_bitmap_page_get_bits(bitmap_page, cur_page_id, page_size,
4502 IBUF_BITMAP_IBUF, &mtr)) {
4503 mutex_exit(&ibuf_mutex);
4504 ibuf_exit(&mtr);
4505 mtr_commit(&mtr);
4506
4507 ib_errf(trx->mysql_thd, IB_LOG_LEVEL_ERROR, ER_INNODB_INDEX_CORRUPT,
4508 "Space %u page %u"
4509 " is wrongly flagged to belong to the"
4510 " insert buffer",
4511 (unsigned)space_id, (unsigned)offset);
4512
4513 return (DB_CORRUPTION);
4514 }
4515
4516 if (ibuf_bitmap_page_get_bits(bitmap_page, cur_page_id, page_size,
4517 IBUF_BITMAP_BUFFERED, &mtr)) {
4518 ib_errf(trx->mysql_thd, IB_LOG_LEVEL_WARN, ER_INNODB_INDEX_CORRUPT,
4519 "Buffered changes"
4520 " for space %u page %u are lost",
4521 (unsigned)space_id, (unsigned)offset);
4522
4523 /* Tolerate this error, so that
4524 slightly corrupted tables can be
4525 imported and dumped. Clear the bit. */
4526 ibuf_bitmap_page_set_bits(bitmap_page, cur_page_id, page_size,
4527 IBUF_BITMAP_BUFFERED, false, &mtr);
4528 }
4529 }
4530
4531 ibuf_exit(&mtr);
4532 mtr_commit(&mtr);
4533 }
4534
4535 mutex_exit(&ibuf_mutex);
4536 return (DB_SUCCESS);
4537 }
4538
4539 /** Updates free bits and buffered bits for bulk loaded page.
4540 @param[in] block index page
4541 @param[in] reset flag if reset free val */
4542 void ibuf_set_bitmap_for_bulk_load(buf_block_t *block, bool reset) {
4543 page_t *bitmap_page;
4544 mtr_t mtr;
4545 ulint free_val;
4546
4547 ut_a(page_is_leaf(buf_block_get_frame(block)));
4548
4549 free_val = ibuf_index_page_calc_free(block);
4550
4551 mtr_start(&mtr);
4552
4553 bitmap_page = ibuf_bitmap_get_map_page(block->page.id, block->page.size,
4554 UT_LOCATION_HERE, &mtr);
4555
4556 free_val = reset ? 0 : ibuf_index_page_calc_free(block);
4557 ibuf_bitmap_page_set_bits(bitmap_page, block->page.id, block->page.size,
4558 IBUF_BITMAP_FREE, free_val, &mtr);
4559
4560 ibuf_bitmap_page_set_bits(bitmap_page, block->page.id, block->page.size,
4561 IBUF_BITMAP_BUFFERED, false, &mtr);
4562
4563 mtr_commit(&mtr);
4564 }
4565
4566 #endif /* !UNIV_HOTBACKUP */