Debian Codegraph @

storage/innobase/fsp/fsp0fsp.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file fsp/fsp0fsp.cc
29 File space management
30
31 Created 11/29/1995 Heikki Tuuri
32 ***********************************************************************/
33
34 #include "fsp0fsp.h"
35 #include "buf0buf.h"
36 #include "fil0fil.h"
37 #include "ha_prototypes.h"
38 #include "mtr0log.h"
39
40 #include "my_dbug.h"
41
42 #include "page0page.h"
43 #include "page0zip.h"
44 #include "ut0byte.h"
45 #ifdef UNIV_HOTBACKUP
46 #include "fut0lst.h"
47 #endif /* UNIV_HOTBACKUP */
48 #include <my_aes.h>
49
50 #ifndef UNIV_HOTBACKUP
51 #include <debug_sync.h>
52 #include "btr0btr.h"
53 #include "btr0sea.h"
54 #include "dict0boot.h"
55 #include "dict0dd.h"
56 #include "fut0fut.h"
57 #include "ibuf0ibuf.h"
58 #include "log0buf.h"
59 #include "srv0srv.h"
60 #endif /* !UNIV_HOTBACKUP */
61 #include "clone0api.h"
62 #include "dict0mem.h"
63 #include "fsp0sysspace.h"
64 #include "srv0start.h"
65 #include "trx0purge.h"
66
67 double fseg_reserve_pct = FSEG_RESERVE_PCT_DFLT;
68
69 #ifndef UNIV_HOTBACKUP
70
71 #include "dd/types/tablespace.h"
72 #include "dict0dd.h"
73 #include "mysqld.h"
74 #include "sql/dd/dictionary.h"
75 #include "sql_backup_lock.h"
76 #include "sql_thd_internal_api.h"
77 #include "thd_raii.h"
78 #include "transaction.h"
79 #include "ut0stage.h"
80
81 /** DDL records for tablespace (un)encryption. */
82 std::vector<DDL_Record *> ts_encrypt_ddl_records;
83
84 #ifdef UNIV_DEBUG
85 std::vector<space_id_t> flag_mismatch_spaces;
86 #endif
87
88 /** Group of pages to be marked dirty together during (un)encryption. */
89 constexpr uint32_t PAGE_GROUP_SIZE = 1;
90
91 /** Returns an extent to the free list of a space.
92 @param[in] page_id Page id in the extent
93 @param[in] page_size Page size
94 @param[in,out] mtr Mini-transaction */
95 static void fsp_free_extent(const page_id_t &page_id,
96 const page_size_t &page_size, mtr_t *mtr);
97
98 /** Determine if extent belongs to a given segment.
99 @param[in] descr Extent descriptor
100 @param[in] seg_id Segment identifier
101 @param[in] mtr Mini-transaction
102 @return true if extent is part of the segment, false otherwise */
103 static bool xdes_in_segment(const xdes_t *descr, ib_id_t seg_id, mtr_t *mtr);
104
105 /** Marks a page used. The page must reside within the extents of the given
106 segment.
107 @param[in] space_id Tablespace identifier
108 @param[in] page_size Size of each page in the tablespace.
109 @param[in] seg_inode The file segment inode pointer
110 @param[in] page The page number to be marked as used.
111 @param[in] descr Extent descriptor containing information about page.
112 @param[in] mtr Mini-transaction context for modification. */
113 static void fseg_mark_page_used(space_id_t space_id,
114 const page_size_t &page_size,
115 fseg_inode_t *seg_inode, page_no_t page,
116 xdes_t *descr, mtr_t *mtr);
117
118 /** Returns the first extent descriptor for a segment.
119 We think of the extent lists of the segment catenated in the order
120 FSEG_FULL -> FSEG_NOT_FULL -> FSEG_FREE.
121 @param[in] inode Segment inode
122 @param[in] space_id Space id
123 @param[in] page_size Page size
124 @param[in,out] mtr Mini-transaction
125 @return the first extent descriptor, or NULL if none */
126 static xdes_t *fseg_get_first_extent(fseg_inode_t *inode, space_id_t space_id,
127 const page_size_t &page_size, mtr_t *mtr);
128
129 /** Put new extents to the free list if there are free extents above the free
130 limit. If an extent happens to contain an extent descriptor page, the extent
131 is put to the FSP_FREE_FRAG list with the page marked as used.
132 @param[in] init_space True if this is a single-table tablespace
133 and we are only initializing the first extent and the first bitmap pages;
134 then we will not allocate more extents
135 @param[in,out] space Tablespace
136 @param[in,out] header Tablespace header
137 @param[in,out] mtr Mini-transaction */
138 static UNIV_COLD void fsp_fill_free_list(bool init_space, fil_space_t *space,
139 fsp_header_t *header, mtr_t *mtr);
140
141 /** Allocates a single free page from a segment.
142 This function implements the intelligent allocation strategy which tries to
143 minimize file space fragmentation.
144 @param[in,out] space Tablespace
145 @param[in] page_size Page size
146 @param[in,out] seg_inode Segment inode
147 @param[in] hint Hint of which page would be desirable
148 @param[in] direction If the new page is needed because of
149 an index page split, and records are inserted there in order, into which
150 direction they go alphabetically: FSP_DOWN, FSP_UP, FSP_NO_DIR
151 @param[in] rw_latch RW_SX_LATCH, RW_X_LATCH
152 @param[in,out] mtr Mini-transaction
153 @param[in,out] init_mtr mtr or another mini-transaction in
154 which the page should be initialized. If init_mtr != mtr, but the page is
155 already latched in mtr, do not initialize the page
156 @param[in] has_done_reservation true if the space has already been
157 reserved, in this case we will never return NULL
158 @retval NULL if no page could be allocated
159 @retval block rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
160 (init_mtr == mtr, or the page was not previously freed in mtr),
161 returned block is not allocated nor initialized otherwise */
162 [[nodiscard]] static buf_block_t *fseg_alloc_free_page_low(
163 fil_space_t *space, const page_size_t &page_size, fseg_inode_t *seg_inode,
164 page_no_t hint, byte direction, rw_lock_type_t rw_latch, mtr_t *mtr,
165 mtr_t *init_mtr IF_DEBUG(, bool has_done_reservation));
166 #endif /* !UNIV_HOTBACKUP */
167
168 /** Get the segment identifier to which the extent belongs to.
169 @param[in] descr extent descriptor
170 @return the segment identifier */
171 inline ib_id_t xdes_get_segment_id(const xdes_t *descr) {
172 return (mach_read_from_8(descr + XDES_ID));
173 }
174
175 /** Get the segment identifier to which the extent belongs to.
176 @param[in] descr Extent descriptor
177 @param[in] mtr Mini-transaction
178 @return the segment identifier */
179 inline ib_id_t xdes_get_segment_id(const xdes_t *descr, mtr_t *mtr) {
180 #ifndef UNIV_HOTBACKUP
181 ut_ad(mtr_memo_contains_page_flagged(
182 mtr, descr,
183 MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX));
184 #endif /* !UNIV_HOTBACKUP */
185
186 return (xdes_get_segment_id(descr));
187 }
188
189 #ifndef UNIV_HOTBACKUP
190 fsp_header_t *fsp_get_space_header_block(space_id_t id,
191 const page_size_t &page_size,
192 mtr_t *mtr, buf_block_t **block) {
193 buf_block_t *blk;
194 fsp_header_t *header;
195
196 ut_ad(id != 0 || !page_size.is_compressed());
197
198 blk = buf_page_get(page_id_t(id, 0), page_size, RW_SX_LATCH, UT_LOCATION_HERE,
199 mtr);
200 header = FSP_HEADER_OFFSET + buf_block_get_frame(blk);
201 buf_block_dbg_add_level(blk, SYNC_FSP_PAGE);
202
203 ut_ad(id == mach_read_from_4(FSP_SPACE_ID + header));
204 #ifdef UNIV_DEBUG
205 const uint32_t flags = mach_read_from_4(FSP_SPACE_FLAGS + header);
206 ut_ad(page_size_t(flags).equals_to(page_size));
207 #endif /* UNIV_DEBUG */
208 *block = blk;
209 return (header);
210 }
211
212 fsp_header_t *fsp_get_space_header(space_id_t id, const page_size_t &page_size,
213 mtr_t *mtr) {
214 buf_block_t *block;
215 fsp_header_t *header;
216 header = fsp_get_space_header_block(id, page_size, mtr, &block);
217 return (header);
218 }
219
220 /** Convert a 32 bit integer tablespace flags to the 32 bit table flags.
221 This can only be done for a tablespace that was built as a file-per-table
222 tablespace. Note that the fsp_flags cannot show the difference between a
223 Compact and Redundant table, so an extra Compact boolean must be supplied.
224 Low order bit
225 | REDUNDANT | COMPACT | COMPRESSED | DYNAMIC
226 fil_space_t::flags | 0 | 0 | 1 | 1
227 dict_table_t::flags | 0 | 1 | 1 | 1
228 @param[in] fsp_flags fil_space_t::flags
229 @param[in] compact true if not Redundant row format
230 @return tablespace flags (fil_space_t::flags) */
231 uint32_t fsp_flags_to_dict_tf(uint32_t fsp_flags, bool compact) {
232 /* If the table in this file-per-table tablespace is Compact
233 row format, the low order bit will not indicate Compact. */
234 bool post_antelope = FSP_FLAGS_GET_POST_ANTELOPE(fsp_flags);
235 ulint zip_ssize = FSP_FLAGS_GET_ZIP_SSIZE(fsp_flags);
236 bool atomic_blobs = FSP_FLAGS_HAS_ATOMIC_BLOBS(fsp_flags);
237 bool data_dir = FSP_FLAGS_HAS_DATA_DIR(fsp_flags);
238 bool shared_space = FSP_FLAGS_GET_SHARED(fsp_flags);
239 /* FSP_FLAGS_GET_TEMPORARY(fsp_flags) does not have an equivalent
240 flag position in the table flags. But it would go into flags2 if
241 any code is created where that is needed. */
242
243 uint32_t flags = dict_tf_init(post_antelope | compact, zip_ssize,
244 atomic_blobs, data_dir, shared_space);
245
246 return (flags);
247 }
248 #endif /* !UNIV_HOTBACKUP */
249
250 /** Check if tablespace is dd tablespace.
251 @param[in] space_id tablespace ID
252 @return true if tablespace is dd tablespace. */
253 bool fsp_is_dd_tablespace(space_id_t space_id) {
254 return (space_id == dict_sys_t::s_dict_space_id);
255 }
256
257 /** Check whether a space id is an undo tablespace ID
258 Undo tablespaces have space_id's starting 1 less than the redo logs.
259 They are numbered down from this. Since rseg_id=0 always refers to the
260 system tablespace, undo_space_num values start at 1. The current limit
261 is 127. The translation from an undo_space_num is:
262 undo space_id = log_first_space_id - undo_space_num
263 @param[in] space_id space id to check
264 @return true if it is undo tablespace else false. */
265 bool fsp_is_undo_tablespace(space_id_t space_id) {
266 /* Starting with v8, undo space_ids have a unique range. */
267 if (space_id >= dict_sys_t::s_min_undo_space_id &&
268 space_id <= dict_sys_t::s_max_undo_space_id) {
269 return (true);
270 }
271
272 /* If upgrading from 5.7, there may be a list of old-style
273 undo tablespaces. Search them. */
274 if (trx_sys_undo_spaces != nullptr) {
275 return (trx_sys_undo_spaces->contains(space_id));
276 }
277
278 return (false);
279 }
280
281 /** Check if tablespace is global temporary.
282 @param[in] space_id tablespace ID
283 @return true if tablespace is global temporary. */
284 bool fsp_is_global_temporary(space_id_t space_id) {
285 return (space_id == srv_tmp_space.space_id());
286 }
287
288 /** Check if the tablespace is session temporary.
289 @param[in] space_id tablespace ID
290 @return true if tablespace is a session temporary tablespace. */
291 bool fsp_is_session_temporary(space_id_t space_id) {
292 return (space_id > dict_sys_t::s_min_temp_space_id &&
293 space_id <= dict_sys_t::s_max_temp_space_id);
294 }
295
296 /** Check if tablespace is system temporary.
297 @param[in] space_id tablespace ID
298 @return true if tablespace is system temporary. */
299 bool fsp_is_system_temporary(space_id_t space_id) {
300 return (fsp_is_global_temporary(space_id) ||
301 fsp_is_session_temporary(space_id));
302 }
303
304 /** Check if checksum is disabled for the given space.
305 @param[in] space_id tablespace ID
306 @return true if checksum is disabled for given space. */
307 bool fsp_is_checksum_disabled(space_id_t space_id) {
308 return (fsp_is_system_temporary(space_id));
309 }
310
311 #ifndef UNIV_HOTBACKUP
312 #ifdef UNIV_DEBUG
313
314 /** Skip some of the sanity checks that are time consuming even in debug mode
315 and can affect frequent verification runs that are done to ensure stability of
316 the product.
317 @return true if check should be skipped for given space. */
318 bool fsp_skip_sanity_check(space_id_t space_id) {
319 return (srv_skip_temp_table_checks_debug &&
320 fsp_is_system_temporary(space_id));
321 }
322
323 #endif /* UNIV_DEBUG */
324
325 /** Gets a descriptor bit of a page.
326 @return true if free */
327 static inline bool xdes_mtr_get_bit(
328 const xdes_t *descr, /*!< in: descriptor */
329 ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */
330 page_no_t offset, /*!< in: page offset within extent:
331 0 ... FSP_EXTENT_SIZE - 1 */
332 mtr_t *mtr) /*!< in: mini-transaction */
333 {
334 ut_ad(mtr->is_active());
335 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
336
337 return (xdes_get_bit(descr, bit, offset));
338 }
339
340 /** Sets a descriptor bit of a page. */
341 static inline void xdes_set_bit(
342 xdes_t *descr, /*!< in: descriptor */
343 ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */
344 page_no_t offset, /*!< in: page offset within extent:
345 0 ... FSP_EXTENT_SIZE - 1 */
346 bool val, /*!< in: bit value */
347 mtr_t *mtr) /*!< in/out: mini-transaction */
348 {
349 ulint index;
350 ulint byte_index;
351 ulint bit_index;
352 ulint descr_byte;
353
354 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
355 ut_ad((bit == XDES_FREE_BIT) || (bit == XDES_CLEAN_BIT));
356 ut_ad(offset < FSP_EXTENT_SIZE);
357
358 index = bit + XDES_BITS_PER_PAGE * offset;
359
360 byte_index = index / 8;
361 bit_index = index % 8;
362
363 descr_byte = mach_read_from_1(descr + XDES_BITMAP + byte_index);
364 descr_byte = ut_bit_set_nth(descr_byte, bit_index, val);
365
366 mlog_write_ulint(descr + XDES_BITMAP + byte_index, descr_byte, MLOG_1BYTE,
367 mtr);
368 }
369
370 /** Looks for a descriptor bit having the desired value. Starts from hint
371 and scans upward; at the end of the extent the search is wrapped to
372 the start of the extent.
373 @return bit index of the bit, ULINT_UNDEFINED if not found */
374 static inline page_no_t xdes_find_bit(
375 xdes_t *descr, /*!< in: descriptor */
376 ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */
377 bool val, /*!< in: desired bit value */
378 page_no_t hint, /*!< in: hint of which bit position
379 would be desirable */
380 mtr_t *mtr) /*!< in/out: mini-transaction */
381 {
382 page_no_t i;
383
384 ut_ad(descr && mtr);
385 ut_ad(hint < FSP_EXTENT_SIZE);
386 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
387 for (i = hint; i < FSP_EXTENT_SIZE; i++) {
388 if (val == xdes_mtr_get_bit(descr, bit, i, mtr)) {
389 return (i);
390 }
391 }
392
393 for (i = 0; i < hint; i++) {
394 if (val == xdes_mtr_get_bit(descr, bit, i, mtr)) {
395 return (i);
396 }
397 }
398
399 return (FIL_NULL);
400 }
401
402 /** Returns the number of used pages in a descriptor.
403 @return number of pages used */
404 static inline page_no_t xdes_get_n_used(
405 const xdes_t *descr, /*!< in: descriptor */
406 mtr_t *mtr) /*!< in/out: mini-transaction */
407 {
408 page_no_t count = 0;
409
410 ut_ad(descr && mtr);
411 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
412 for (page_no_t i = 0; i < FSP_EXTENT_SIZE; ++i) {
413 if (false == xdes_mtr_get_bit(descr, XDES_FREE_BIT, i, mtr)) {
414 count++;
415 }
416 }
417
418 return (count);
419 }
420
421 #ifdef UNIV_DEBUG
422 /** Check if the state of extent descriptor is valid.
423 @param[in] state the extent descriptor state
424 @return true if state is valid, false otherwise */
425 bool xdes_state_is_valid(ulint state) {
426 switch (state) {
427 case XDES_NOT_INITED:
428 case XDES_FREE:
429 case XDES_FREE_FRAG:
430 case XDES_FULL_FRAG:
431 case XDES_FSEG:
432 case XDES_FSEG_FRAG:
433 return (true);
434 }
435 return (false);
436 }
437 #endif /* UNIV_DEBUG */
438
439 /** Returns true if extent contains no used pages.
440 @return true if totally free */
441 static inline bool xdes_is_free(const xdes_t *descr, /*!< in: descriptor */
442 mtr_t *mtr) /*!< in/out: mini-transaction */
443 {
444 if (0 == xdes_get_n_used(descr, mtr)) {
445 ut_ad(xdes_get_state(descr, mtr) != XDES_FSEG_FRAG);
446
447 return true;
448 }
449
450 return false;
451 }
452
453 /** Returns true if extent contains no free pages.
454 @return true if full */
455 static inline bool xdes_is_full(const xdes_t *descr, /*!< in: descriptor */
456 mtr_t *mtr) /*!< in/out: mini-transaction */
457 {
458 if (FSP_EXTENT_SIZE == xdes_get_n_used(descr, mtr)) {
459 return true;
460 }
461
462 return false;
463 }
464
465 /** Sets the state of an xdes. */
466 static inline void xdes_set_state(xdes_t *descr, /*!< in/out: descriptor */
467 xdes_state_t state, /*!< in: state to set */
468 mtr_t *mtr) /*!< in/out: mini-transaction */
469 {
470 ut_ad(descr && mtr);
471 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
472
473 #ifdef UNIV_DEBUG
474 switch (xdes_get_state(descr, mtr)) {
475 case XDES_FREE:
476 ut_ad(state == XDES_FSEG || state == XDES_FREE_FRAG);
477 break;
478 case XDES_FREE_FRAG:
479 ut_ad(state == XDES_FULL_FRAG || state == XDES_FSEG_FRAG ||
480 state == XDES_FREE);
481 break;
482 case XDES_FULL_FRAG:
483 ut_ad(state == XDES_FREE_FRAG);
484 break;
485 case XDES_FSEG:
486 ut_ad(state == XDES_FREE);
487 break;
488 case XDES_FSEG_FRAG:
489 ut_ad(state == XDES_FREE_FRAG || state == XDES_FULL_FRAG ||
490 state == XDES_FREE);
491 break;
492 case XDES_NOT_INITED:
493 /* The state is not yet initialized. */
494 ut_ad(state == XDES_FREE);
495 break;
496 }
497 #endif /* UNIV_DEBUG */
498
499 mlog_write_ulint(descr + XDES_STATE, state, MLOG_4BYTES, mtr);
500 }
501
502 /** Update the segment identifier to which the extent belongs to.
503 @param[in,out] descr Extent descriptor
504 @param[in,out] seg_id Segment identifier
505 @param[in] state State of the extent.
506 @param[in,out] mtr Mini-transaction. */
507 inline void xdes_set_segment_id(xdes_t *descr, const ib_id_t seg_id,
508 xdes_state_t state, mtr_t *mtr) {
509 ut_ad(mtr != nullptr);
510 mlog_write_ull(descr + XDES_ID, seg_id, mtr);
511 xdes_set_state(descr, state, mtr);
512 }
513
514 /** Inits an extent descriptor to the free and clean state. */
515 static inline void xdes_init(xdes_t *descr, /*!< in: descriptor */
516 mtr_t *mtr) /*!< in/out: mini-transaction */
517 {
518 ulint i;
519
520 ut_ad(descr && mtr);
521 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
522 ut_ad((XDES_SIZE - XDES_BITMAP) % 4 == 0);
523
524 xdes_set_segment_id(descr, 0, XDES_FREE, mtr);
525 flst_write_addr(descr + XDES_FLST_NODE + FLST_PREV, fil_addr_null, mtr);
526 flst_write_addr(descr + XDES_FLST_NODE + FLST_NEXT, fil_addr_null, mtr);
527
528 for (i = XDES_BITMAP; i < XDES_SIZE; i += 4) {
529 mlog_write_ulint(descr + i, 0xFFFFFFFFUL, MLOG_4BYTES, mtr);
530 }
531 }
532
533 /** Get pointer to a the extent descriptor of a page.
534 @param[in,out] sp_header Tablespace header page, x-latched
535 @param[in] space Tablespace identifier
536 @param[in] offset Page offset
537 @param[in,out] mtr Mini-transaction
538 @param[in] init_space Whether the tablespace is being initialized
539 @param[out] desc_block Descriptor block, or NULL if it is
540 the same as the tablespace header
541 @return pointer to the extent descriptor, NULL if the page does not
542 exist in the space or if the offset exceeds free limit */
543 [[nodiscard]] static inline xdes_t *xdes_get_descriptor_with_space_hdr(
544 fsp_header_t *sp_header, space_id_t space, page_no_t offset, mtr_t *mtr,
545 bool init_space = false, buf_block_t **desc_block = nullptr) {
546 ulint limit;
547 ulint size;
548 page_no_t descr_page_no;
549 uint32_t flags;
550 page_t *descr_page;
551 #ifdef UNIV_DEBUG
552 const fil_space_t *fspace = fil_space_get(space);
553 ut_ad(fspace != nullptr);
554 #endif /* UNIV_DEBUG */
555 ut_ad(mtr_memo_contains(mtr, &fspace->latch, MTR_MEMO_X_LOCK));
556 ut_ad(mtr_memo_contains_page(mtr, sp_header, MTR_MEMO_PAGE_SX_FIX));
557 ut_ad(page_offset(sp_header) == FSP_HEADER_OFFSET);
558 /* Read free limit and space size */
559 limit = mach_read_from_4(sp_header + FSP_FREE_LIMIT);
560 size = mach_read_from_4(sp_header + FSP_SIZE);
561 flags = mach_read_from_4(sp_header + FSP_SPACE_FLAGS);
562 ut_ad(limit == fspace->free_limit ||
563 (fspace->free_limit == 0 &&
564 (init_space || fspace->purpose == FIL_TYPE_TEMPORARY ||
565 (srv_startup_is_before_trx_rollback_phase &&
566 fsp_is_undo_tablespace(fspace->id)))));
567 ut_ad(size == fspace->size_in_header);
568 #ifdef UNIV_DEBUG
569 /* Exclude Encryption flag as it might have been changed In Memory flags but
570 not on disk. */
571 ut_ad(!((flags ^ fspace->flags) & ~(FSP_FLAGS_MASK_ENCRYPTION)));
572 #endif /* UNIV_DEBUG */
573
574 if ((offset >= size) || (offset >= limit)) {
575 return (nullptr);
576 }
577
578 const page_size_t page_size(flags);
579
580 descr_page_no = xdes_calc_descriptor_page(page_size, offset);
581
582 buf_block_t *block;
583
584 if (descr_page_no == 0) {
585 /* It is on the space header page */
586
587 descr_page = page_align(sp_header);
588 block = nullptr;
589 } else {
590 block = buf_page_get(page_id_t(space, descr_page_no), page_size,
591 RW_SX_LATCH, UT_LOCATION_HERE, mtr);
592
593 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
594
595 descr_page = buf_block_get_frame(block);
596 }
597
598 if (desc_block != nullptr) {
599 *desc_block = block;
600 }
601
602 return (descr_page + XDES_ARR_OFFSET +
603 XDES_SIZE * xdes_calc_descriptor_index(page_size, offset));
604 }
605
606 /** Gets pointer to a the extent descriptor of a page.
607 The page where the extent descriptor resides is x-locked. If the page offset
608 is equal to the free limit of the space, adds new extents from above the free
609 limit to the space free list, if not free limit == space size. This adding
610 is necessary to make the descriptor defined, as they are uninitialized
611 above the free limit.
612 @param[in] space_id Space id
613 @param[in] offset Page offset; if equal to the free limit, we
614 try to add new extents to the space free list
615 @param[in] page_size Page size
616 @param[in,out] mtr Mini-transaction
617 @return pointer to the extent descriptor, NULL if the page does not
618 exist in the space or if the offset exceeds the free limit */
619 [[nodiscard]] static xdes_t *xdes_get_descriptor(space_id_t space_id,
620 page_no_t offset,
621 const page_size_t &page_size,
622 mtr_t *mtr) {
623 buf_block_t *block;
624 fsp_header_t *sp_header;
625
626 block = buf_page_get(page_id_t(space_id, 0), page_size, RW_SX_LATCH,
627 UT_LOCATION_HERE, mtr);
628
629 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
630
631 sp_header = FSP_HEADER_OFFSET + buf_block_get_frame(block);
632 return (xdes_get_descriptor_with_space_hdr(sp_header, space_id, offset, mtr));
633 }
634
635 /** Gets pointer to a the extent descriptor if the file address of the
636 descriptor list node is known. The page where the extent descriptor resides
637 is x-locked.
638 @param[in] space Space id
639 @param[in] page_size Page size
640 @param[in] lst_node File address of the list node contained in the
641 descriptor
642 @param[in,out] mtr Mini-transaction
643 @return pointer to the extent descriptor */
644 static inline xdes_t *xdes_lst_get_descriptor(space_id_t space,
645 const page_size_t &page_size,
646 fil_addr_t lst_node, mtr_t *mtr) {
647 xdes_t *descr;
648
649 ut_ad(mtr);
650 ut_ad(mtr_memo_contains(mtr, fil_space_get_latch(space), MTR_MEMO_X_LOCK));
651
652 descr = fut_get_ptr(space, page_size, lst_node, RW_SX_LATCH, mtr) -
653 XDES_FLST_NODE;
654
655 return (descr);
656 }
657
658 /** Returns page offset of the first page in extent described by a descriptor.
659 @return offset of the first page in extent */
660 static inline page_no_t xdes_get_offset(
661 const xdes_t *descr) /*!< in: extent descriptor */
662 {
663 ut_ad(descr);
664
665 return (page_get_page_no(page_align(descr)) +
666 static_cast<page_no_t>(
667 ((page_offset(descr) - XDES_ARR_OFFSET) / XDES_SIZE) *
668 FSP_EXTENT_SIZE));
669 }
670 #endif /* !UNIV_HOTBACKUP */
671
672 /** Inits a file page whose prior contents should be ignored. */
673 static void fsp_init_file_page_low(
674 buf_block_t *block) /*!< in: pointer to a page */
675 {
676 page_t *page = buf_block_get_frame(block);
677 page_zip_des_t *page_zip = buf_block_get_page_zip(block);
678
679 if (!fsp_is_system_temporary(block->page.id.space())) {
680 memset(page, 0, UNIV_PAGE_SIZE);
681 }
682
683 mach_write_to_4(page + FIL_PAGE_OFFSET, block->page.id.page_no());
684 mach_write_to_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
685 block->page.id.space());
686
687 /* Reset FRAME LSN, which otherwise points to the LSN of the last
688 page that used this buffer block. This is needed by CLONE for
689 tracking dirty pages. */
690 memset(page + FIL_PAGE_LSN, 0, 8);
691
692 if (page_zip) {
693 memset(page_zip->data, 0, page_zip_get_size(page_zip));
694 memcpy(page_zip->data + FIL_PAGE_OFFSET, page + FIL_PAGE_OFFSET, 4);
695 memcpy(page_zip->data + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
696 page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, 4);
697 memcpy(page_zip->data + FIL_PAGE_LSN, page + FIL_PAGE_LSN, 8);
698 }
699 }
700
701 #ifndef UNIV_HOTBACKUP
702 #ifdef UNIV_DEBUG
703 /** Assert that the mini-transaction is compatible with
704 updating an allocation bitmap page.
705 @param[in] id Tablespace identifier
706 @param[in] mtr Mini-transaction */
707 static void fsp_space_modify_check(space_id_t id, const mtr_t *mtr) {
708 ut_ad(mtr);
709 switch (mtr->get_log_mode()) {
710 case MTR_LOG_SHORT_INSERTS:
711 /* These modes are only allowed within a non-bitmap page
712 when there is a higher-level redo log record written. */
713 break;
714
715 case MTR_LOG_NONE:
716 /* We allow MTR_LOG_NONE to be set over MTR_LOG_NO_REDO. */
717 if (!mtr_t::s_logging.is_enabled()) {
718 return;
719 }
720 break;
721
722 case MTR_LOG_NO_REDO:
723 #ifdef UNIV_DEBUG
724 {
725 const fil_type_t type = fil_space_get_type(id);
726 ut_a(fsp_is_system_temporary(id) || !mtr_t::s_logging.is_enabled() ||
727 fil_space_get_flags(id) == UINT32_UNDEFINED ||
728 type == FIL_TYPE_TEMPORARY || type == FIL_TYPE_IMPORT ||
729 fil_space_is_redo_skipped(id) || !undo::is_active(id, false));
730 }
731 #endif /* UNIV_DEBUG */
732 return;
733 case MTR_LOG_ALL:
734 /* We must not write redo log for the shared temporary
735 tablespace. */
736 ut_ad(!fsp_is_system_temporary(id));
737 /* If we write redo log, the tablespace must exist. */
738 ut_ad(fil_space_get_type(id) == FIL_TYPE_TABLESPACE);
739 return;
740
741 default:
742 break;
743 }
744
745 ut_d(ut_error);
746 }
747 #endif /* UNIV_DEBUG */
748
749 /** Initialize a file page.
750 @param[in,out] block File page
751 @param[in,out] mtr Mini-transaction */
752 static void fsp_init_file_page(buf_block_t *block, mtr_t *mtr) {
753 fsp_init_file_page_low(block);
754
755 ut_d(fsp_space_modify_check(block->page.id.space(), mtr));
756 mlog_write_initial_log_record(buf_block_get_frame(block),
757 MLOG_INIT_FILE_PAGE2, mtr);
758 }
759 #endif /* !UNIV_HOTBACKUP */
760
761 byte *fsp_parse_init_file_page(byte *ptr, byte *end_ptr [[maybe_unused]],
762 buf_block_t *block) {
763 if (block) {
764 fsp_init_file_page_low(block);
765 }
766
767 return (ptr);
768 }
769
770 /** Initializes the fsp system. */
771 void fsp_init() {
772 /* FSP_EXTENT_SIZE must be a multiple of page & zip size */
773 ut_a(UNIV_PAGE_SIZE > 0);
774 ut_a(0 == (UNIV_PAGE_SIZE % FSP_EXTENT_SIZE));
775
776 static_assert(!(UNIV_PAGE_SIZE_MAX % FSP_EXTENT_SIZE_MAX),
777 "UNIV_PAGE_SIZE_MAX % FSP_EXTENT_SIZE_MAX != 0");
778
779 static_assert(!(UNIV_ZIP_SIZE_MIN % FSP_EXTENT_SIZE_MIN),
780 "UNIV_ZIP_SIZE_MIN % FSP_EXTENT_SIZE_MIN != 0");
781
782 /* Does nothing at the moment */
783 }
784
785 /** Writes the space id and flags to a tablespace header. The flags contain
786 row type, physical/compressed page size, and logical/uncompressed page
787 size of the tablespace. */
788 void fsp_header_init_fields(
789 page_t *page, /*!< in/out: first page in the space */
790 space_id_t space_id, /*!< in: space id */
791 uint32_t flags) /*!< in: tablespace flags
792 (FSP_SPACE_FLAGS) */
793 {
794 ut_a(fsp_flags_is_valid(flags));
795
796 fsp_header_set_field(page, FSP_SPACE_ID, space_id);
797 fsp_header_set_field(page, FSP_SPACE_FLAGS, flags);
798 }
799
800 ulint fsp_header_get_encryption_offset(const page_size_t &page_size) {
801 auto offset = XDES_ARR_OFFSET + XDES_SIZE * xdes_arr_size(page_size);
802 #ifdef UNIV_DEBUG
803 auto left_size =
804 page_size.physical() - FSP_HEADER_OFFSET - offset - FIL_PAGE_DATA_END;
805
806 ut_ad(left_size >= Encryption::INFO_SIZE);
807 #endif
808
809 return offset;
810 }
811
812 #ifndef UNIV_HOTBACKUP
813 /** Write the (un)encryption progress info into the space header.
814 @param[in] space_id Tablespace id
815 @param[in] space_flags Tablespace flags
816 @param[in] progress_info Max pages (un)encrypted
817 @param[in] operation_type Type of operation
818 @param[in] update_operation_type Is operation to be updated
819 @param[in,out] mtr Mini-transaction
820 @return true if success. */
821 bool fsp_header_write_encryption_progress(
822 space_id_t space_id, uint32_t space_flags, ulint progress_info,
823 byte operation_type, bool update_operation_type, mtr_t *mtr) {
824 buf_block_t *block;
825 ulint offset;
826
827 const page_size_t page_size(space_flags);
828
829 /* Save the encryption info to the page 0. */
830 block = buf_page_get(page_id_t(space_id, 0), page_size, RW_SX_LATCH,
831 UT_LOCATION_HERE, mtr);
832
833 if (block == nullptr) {
834 return false;
835 }
836
837 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
838 ut_ad(space_id == page_get_space_id(buf_block_get_frame(block)));
839
840 offset = fsp_header_get_encryption_progress_offset(page_size);
841 ut_ad(offset != 0 && offset < UNIV_PAGE_SIZE);
842
843 page_t *page = buf_block_get_frame(block);
844
845 /* Write operation type if needed */
846 if (update_operation_type) {
847 mlog_write_ulint(page + offset, operation_type, MLOG_1BYTE, mtr);
848 }
849
850 mlog_write_ulint(page + offset + Encryption::OPERATION_INFO_SIZE,
851 progress_info, MLOG_4BYTES, mtr);
852 return (true);
853 }
854
855 /** Get encryption operation type in progress from the first
856 page of a tablespace.
857 @param[in] page first page of a tablespace
858 @param[in] page_size tablespace page size
859 @return operation type
860 */
861 Encryption::Progress fsp_header_encryption_op_type_in_progress(
862 const page_t *page, page_size_t page_size) {
863 auto offset = fsp_header_get_encryption_progress_offset(page_size);
864 ut_ad(offset != 0 && offset < UNIV_PAGE_SIZE);
865
866 auto op = Encryption::Progress::NONE;
867 /* Read operation type (1 byte) */
868 byte operation = mach_read_from_1(page + offset);
869 switch (operation) {
870 case Encryption::ENCRYPT_IN_PROGRESS:
871 op = Encryption::Progress::ENCRYPTION;
872 break;
873 case Encryption::DECRYPT_IN_PROGRESS:
874 op = Encryption::Progress::DECRYPTION;
875 break;
876 default:
877 op = Encryption::Progress::NONE;
878 break;
879 }
880
881 return op;
882 }
883
884 /** Write the encryption info into the space header.
885 @param[in] space_id Tablespace id
886 @param[in] space_flags Tablespace flags
887 @param[in] encrypt_info Buffer for re-encrypt key
888 @param[in] update_fsp_flags If it need to update the space flags
889 @param[in] rotate_encryption If it is called during key rotation
890 @param[in,out] mtr Mini-transaction
891 @return true if success. */
892 bool fsp_header_write_encryption(space_id_t space_id, uint32_t space_flags,
893 byte *encrypt_info, bool update_fsp_flags,
894 bool rotate_encryption, mtr_t *mtr) {
895 buf_block_t *block;
896 ulint offset;
897 page_t *page;
898 uint32_t master_key_id;
899
900 const page_size_t page_size(space_flags);
901
902 /* Save the encryption info to the page 0. */
903 block = buf_page_get(page_id_t(space_id, 0), page_size, RW_SX_LATCH,
904 UT_LOCATION_HERE, mtr);
905 if (block == nullptr) {
906 return (false);
907 }
908
909 /* suspected as a causer of bug#31073853 */
910 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_FLUSH_PHASE);
911
912 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
913 ut_ad(space_id == page_get_space_id(buf_block_get_frame(block)));
914
915 offset = fsp_header_get_encryption_offset(page_size);
916 ut_ad(offset != 0 && offset < UNIV_PAGE_SIZE);
917
918 page = buf_block_get_frame(block);
919
920 /* Write the new fsp flags into the header if needed */
921 if (update_fsp_flags) {
922 mlog_write_ulint(page + FSP_HEADER_OFFSET + FSP_SPACE_FLAGS, space_flags,
923 MLOG_4BYTES, mtr);
924 }
925
926 if (rotate_encryption) {
927 /* If called during recovery, skip all tablespaces which have updated
928 master_key_id. */
929 master_key_id = mach_read_from_4(page + offset + Encryption::MAGIC_SIZE);
930 if (srv_is_being_started &&
931 master_key_id == Encryption::get_master_key_id()) {
932 ut_ad(Encryption::is_encrypted(page + offset));
933 return (true);
934 }
935 }
936
937 /* Write encryption info passed */
938 mlog_write_string(page + offset, encrypt_info, Encryption::INFO_SIZE, mtr);
939
940 return (true);
941 }
942
943 /** Rotate the encryption info in the space header.
944 @param[in] space Tablespace
945 @param[in] encrypt_info Buffer for re-encrypt key.
946 @param[in,out] mtr Mini-transaction
947 @return true if success. */
948 bool fsp_header_rotate_encryption(fil_space_t *space, byte *encrypt_info,
949 mtr_t *mtr) {
950 ut_ad(mtr);
951 ut_ad(space->can_encrypt());
952
953 DBUG_EXECUTE_IF("fsp_header_rotate_encryption_failure", return (false););
954
955 /* Fill encryption info. */
956 if (!Encryption::fill_encryption_info(space->m_encryption_metadata, true,
957 encrypt_info)) {
958 return (false);
959 }
960
961 /* Write encryption info into space header. */
962 return (fsp_header_write_encryption(space->id, space->flags, encrypt_info,
963 false, true, mtr));
964 }
965
966 /** Read the server version number from the DD tablespace header.
967 @param[out] version server version from tablespace header
968 @return false if success. */
969 bool fsp_header_dict_get_server_version(uint *version) {
970 fil_space_t *space = fil_space_acquire(dict_sys_t::s_dict_space_id);
971
972 if (space == nullptr) {
973 return (true);
974 }
975
976 buf_block_t *block;
977 page_t *page;
978 mtr_t mtr;
979
980 const page_size_t page_size(space->flags);
981
982 mtr_start(&mtr);
983 block = buf_page_get(page_id_t(dict_sys_t::s_dict_space_id, 0), page_size,
984 RW_SX_LATCH, UT_LOCATION_HERE, &mtr);
985 page = buf_block_get_frame(block);
986 *version = fsp_header_get_server_version(page);
987
988 mtr_commit(&mtr);
989 fil_space_release(space);
990
991 return (false);
992 }
993
994 bool fsp_header_init(space_id_t space_id, page_no_t size, mtr_t *mtr) {
995 auto space = fil_space_get(space_id);
996 ut_ad(space != nullptr);
997
998 mtr_x_lock_space(space, mtr);
999
1000 const page_id_t page_id(space_id, 0);
1001 const page_size_t page_size(space->flags);
1002
1003 auto block = buf_page_create(page_id, page_size, RW_SX_LATCH, mtr);
1004 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
1005
1006 space->size_in_header = size;
1007 space->free_len = 0;
1008 space->free_limit = 0;
1009 space->autoextend_size_in_bytes = 0;
1010
1011 /* The prior contents of the file page should be ignored */
1012
1013 fsp_init_file_page(block, mtr);
1014
1015 auto page = buf_block_get_frame(block);
1016
1017 /* This page was just created or returned by the buffer pool - it can't be
1018 stale. */
1019 ut_ad(block->page.get_space() != nullptr && !block->page.was_stale());
1020
1021 mlog_write_ulint(page + FIL_PAGE_TYPE, FIL_PAGE_TYPE_FSP_HDR, MLOG_2BYTES,
1022 mtr);
1023
1024 mlog_write_ulint(page + FIL_PAGE_SRV_VERSION, DD_SPACE_CURRENT_SRV_VERSION,
1025 MLOG_4BYTES, mtr);
1026 mlog_write_ulint(page + FIL_PAGE_SPACE_VERSION,
1027 DD_SPACE_CURRENT_SPACE_VERSION, MLOG_4BYTES, mtr);
1028
1029 auto header = FSP_HEADER_OFFSET + page;
1030
1031 mlog_write_ulint(header + FSP_SPACE_ID, space_id, MLOG_4BYTES, mtr);
1032 mlog_write_ulint(header + FSP_NOT_USED, 0, MLOG_4BYTES, mtr);
1033
1034 fsp_header_size_update(header, size, mtr);
1035 mlog_write_ulint(header + FSP_FREE_LIMIT, 0, MLOG_4BYTES, mtr);
1036 mlog_write_ulint(header + FSP_SPACE_FLAGS, space->flags, MLOG_4BYTES, mtr);
1037 mlog_write_ulint(header + FSP_FRAG_N_USED, 0, MLOG_4BYTES, mtr);
1038
1039 flst_init(header + FSP_FREE, mtr);
1040 flst_init(header + FSP_FREE_FRAG, mtr);
1041 flst_init(header + FSP_FULL_FRAG, mtr);
1042 flst_init(header + FSP_SEG_INODES_FULL, mtr);
1043 flst_init(header + FSP_SEG_INODES_FREE, mtr);
1044
1045 mlog_write_ull(header + FSP_SEG_ID, 1, mtr);
1046
1047 fsp_fill_free_list(
1048 !fsp_is_system_tablespace(space_id) && !fsp_is_global_temporary(space_id),
1049 space, header, mtr);
1050
1051 /* For encryption tablespace, we need to save the encryption
1052 info to the page 0. */
1053 if (FSP_FLAGS_GET_ENCRYPTION(space->flags)) {
1054 auto offset = fsp_header_get_encryption_offset(page_size);
1055 byte encryption_info[Encryption::INFO_SIZE];
1056
1057 if (offset == 0) {
1058 return (false);
1059 }
1060 bool master_key_encrypt = true;
1061
1062 /* Generate redo log encryption info that cannot be extracted with master
1063 key during recovery. This is to validate that clone ignores encryption
1064 information in redo log and works fine. Clone needs to ignore it as the
1065 encryption information in redo log is encrypted using donor master key which
1066 is not available in recipient. This is otherwise difficult to test in mtr
1067 test environment where recipient uses same keyring as donor. */
1068 DBUG_EXECUTE_IF("log_redo_with_invalid_master_key",
1069 master_key_encrypt = false;);
1070 if (!Encryption::fill_encryption_info(space->m_encryption_metadata,
1071 master_key_encrypt,
1072 encryption_info)) {
1073 space->m_encryption_metadata = {};
1074 return false;
1075 }
1076
1077 mlog_write_string(page + offset, encryption_info, Encryption::INFO_SIZE,
1078 mtr);
1079
1080 /* Correct the master key stored in page. We only intend to generate
1081 incorrect redo log. */
1082 DBUG_EXECUTE_IF("log_redo_with_invalid_master_key", {
1083 ut_ad(!master_key_encrypt);
1084 Encryption::fill_encryption_info(space->m_encryption_metadata, true,
1085 encryption_info);
1086 memcpy(page + offset, encryption_info, Encryption::INFO_SIZE);
1087 });
1088 }
1089 space->encryption_op_in_progress = Encryption::Progress::NONE;
1090
1091 if (space_id == TRX_SYS_SPACE) {
1092 if (btr_create(DICT_CLUSTERED | DICT_IBUF, 0, DICT_IBUF_ID_MIN + space_id,
1093 dict_ind_redundant, mtr) == FIL_NULL) {
1094 return (false);
1095 }
1096 }
1097
1098 return (true);
1099 }
1100 #endif /* !UNIV_HOTBACKUP */
1101
1102 /** Reads the space id from the first page of a tablespace.
1103 @return space id, ULINT UNDEFINED if error */
1104 space_id_t fsp_header_get_space_id(
1105 const page_t *page) /*!< in: first page of a tablespace */
1106 {
1107 space_id_t fsp_id;
1108 space_id_t id;
1109
1110 fsp_id = fsp_header_get_field(page, FSP_SPACE_ID);
1111
1112 id = mach_read_from_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
1113
1114 DBUG_EXECUTE_IF("fsp_header_get_space_id_failure", id = SPACE_UNKNOWN;);
1115
1116 if (id != fsp_id) {
1117 ib::error(ER_IB_MSG_414) << "Space ID in fsp header is " << fsp_id
1118 << ", but in the page header it is " << id << ".";
1119 return (SPACE_UNKNOWN);
1120 }
1121
1122 return (id);
1123 }
1124
1125 /** Reads the page size from the first page of a tablespace.
1126 @param[in] page first page of a tablespace
1127 @return page size */
1128 page_size_t fsp_header_get_page_size(const page_t *page) {
1129 return (page_size_t(fsp_header_get_flags(page)));
1130 }
1131
1132 /** Reads the encryption key from the first page of a tablespace.
1133 @param[in] fsp_flags tablespace flags
1134 @param[in,out] e_key tablespace key, iv
1135 @param[in] page first page of a tablespace
1136 @return true if success */
1137 bool fsp_header_get_encryption_key(uint32_t fsp_flags, Encryption_key &e_key,
1138 page_t *page) {
1139 ulint offset;
1140 const page_size_t page_size(fsp_flags);
1141
1142 offset = fsp_header_get_encryption_offset(page_size);
1143 if (offset == 0) {
1144 return (false);
1145 }
1146
1147 return (Encryption::decode_encryption_info(page_get_space_id(page), e_key,
1148 page + offset, true));
1149 }
1150
1151 #ifndef UNIV_HOTBACKUP
1152
1153 /** Increases the space size field of a space.
1154 @param[in] space_id Space id
1155 @param[in] size_inc Size increment in pages
1156 @param[in,out] mtr Mini-transaction */
1157 void fsp_header_inc_size(space_id_t space_id, page_no_t size_inc, mtr_t *mtr) {
1158 fil_space_t *space = fil_space_get(space_id);
1159
1160 mtr_x_lock_space(space, mtr);
1161
1162 ut_d(fsp_space_modify_check(space_id, mtr));
1163
1164 fsp_header_t *header;
1165
1166 header = fsp_get_space_header(space_id, page_size_t(space->flags), mtr);
1167
1168 page_no_t size;
1169
1170 size = mach_read_from_4(header + FSP_SIZE);
1171 ut_ad(size == space->size_in_header);
1172
1173 size += size_inc;
1174
1175 fsp_header_size_update(header, size, mtr);
1176 space->size_in_header = size;
1177 }
1178
1179 /** Gets the size of the system tablespace from the tablespace header. If
1180 we do not have an auto-extending data file, this should be equal to
1181 the size of the data files. If there is an auto-extending data file,
1182 this can be smaller.
1183 @return size in pages */
1184 page_no_t fsp_header_get_tablespace_size(void) {
1185 fil_space_t *space = fil_space_get_sys_space();
1186
1187 mtr_t mtr;
1188
1189 mtr_start(&mtr);
1190
1191 mtr_x_lock_space(space, &mtr);
1192
1193 fsp_header_t *header;
1194
1195 header = fsp_get_space_header(TRX_SYS_SPACE, univ_page_size, &mtr);
1196
1197 page_no_t size;
1198
1199 size = mach_read_from_4(header + FSP_SIZE);
1200
1201 ut_ad(space->size_in_header == size);
1202
1203 mtr_commit(&mtr);
1204
1205 return (size);
1206 }
1207
1208 /** Try to extend a single-table tablespace so that a page would fit in the
1209 data file.
1210 @param[in,out] space Tablespace
1211 @param[in] page_no Page number
1212 @param[in,out] header Tablespace header
1213 @param[in,out] mtr Mini-transaction
1214 @return true if success */
1215 [[nodiscard]] static UNIV_COLD bool fsp_try_extend_data_file_with_pages(
1216 fil_space_t *space, page_no_t page_no, fsp_header_t *header, mtr_t *mtr) {
1217 DBUG_TRACE;
1218
1219 ut_ad(!fsp_is_system_tablespace(space->id));
1220 ut_ad(!fsp_is_global_temporary(space->id));
1221 ut_d(fsp_space_modify_check(space->id, mtr));
1222
1223 page_no_t size = mach_read_from_4(header + FSP_SIZE);
1224 ut_ad(size == space->size_in_header);
1225
1226 ut_a(page_no >= size);
1227
1228 bool success = fil_space_extend(space, page_no + 1);
1229
1230 /* The size may be less than we wanted if we ran out of disk space. */
1231 fsp_header_size_update(header, space->size, mtr);
1232
1233 space->size_in_header = space->size;
1234
1235 return success;
1236 }
1237
1238 /* Adjust the amount to extend an undo tablespace. */
1239 static UNIV_COLD void adjust_undo_extend(fil_space_t *space) {
1240 ut_ad(space->m_undo_extend != 0);
1241 ut_ad(fsp_is_undo_tablespace(space->id));
1242
1243 if (space->m_last_extended.elapsed() < 100) {
1244 /* Aggressive Growth: increase the extend amount. */
1245 if (space->m_undo_extend < (16 * UNDO_INITIAL_SIZE_IN_PAGES)) {
1246 space->m_undo_extend *= 2;
1247 }
1248 } else if (space->m_undo_extend > UNDO_INITIAL_SIZE_IN_PAGES) {
1249 /* No longer Aggressive Growth: decrease the extend amount. */
1250 os_offset_t smaller = space->m_undo_extend /= 2;
1251 smaller = std::max(smaller, UNDO_INITIAL_SIZE_IN_PAGES);
1252 space->m_undo_extend = smaller;
1253 }
1254
1255 space->m_last_extended.reset();
1256 }
1257
1258 /** Try to extend the last data file of a tablespace if it is auto-extending.
1259 @param[in,out] space Tablespace
1260 @param[in,out] header Tablespace header
1261 @param[in,out] mtr Mini-transaction
1262 @return whether the tablespace was extended */
1263 static UNIV_COLD ulint fsp_try_extend_data_file(fil_space_t *space,
1264 fsp_header_t *header,
1265 mtr_t *mtr) {
1266 page_no_t size; /* current number of pages
1267 in the datafile */
1268 page_no_t size_increase; /* number of pages to extend
1269 this file */
1270 const char *OUT_OF_SPACE_MSG =
1271 "ran out of space. Please add another file or use"
1272 " 'autoextend' for the last file in setting";
1273 DBUG_TRACE;
1274
1275 ut_d(fsp_space_modify_check(space->id, mtr));
1276
1277 if (space->id == TRX_SYS_SPACE &&
1278 !srv_sys_space.can_auto_extend_last_file()) {
1279 /* We print the error message only once to avoid
1280 spamming the error log. Note that we don't need
1281 to reset the flag to false as dealing with this
1282 error requires server restart. */
1283 if (!srv_sys_space.get_tablespace_full_status()) {
1284 ib::error(ER_IB_MSG_415) << "Tablespace " << srv_sys_space.name() << " "
1285 << OUT_OF_SPACE_MSG << " innodb_data_file_path.";
1286 srv_sys_space.set_tablespace_full_status(true);
1287 }
1288 return false;
1289 } else if (fsp_is_global_temporary(space->id) &&
1290 !srv_tmp_space.can_auto_extend_last_file()) {
1291 /* We print the error message only once to avoid
1292 spamming the error log. Note that we don't need
1293 to reset the flag to false as dealing with this
1294 error requires server restart. */
1295 if (!srv_tmp_space.get_tablespace_full_status()) {
1296 ib::error(ER_IB_MSG_416)
1297 << "Tablespace " << srv_tmp_space.name() << " " << OUT_OF_SPACE_MSG
1298 << " innodb_temp_data_file_path.";
1299 srv_tmp_space.set_tablespace_full_status(true);
1300 }
1301 return false;
1302 }
1303
1304 size = mach_read_from_4(header + FSP_SIZE);
1305 ut_ad(size == space->size_in_header);
1306
1307 const page_size_t page_size(mach_read_from_4(header + FSP_SPACE_FLAGS));
1308
1309 if (space->id == TRX_SYS_SPACE) {
1310 size_increase = srv_sys_space.get_increment();
1311
1312 } else if (fsp_is_global_temporary(space->id)) {
1313 size_increase = srv_tmp_space.get_increment();
1314
1315 } else {
1316 /* Check if the tablespace supports autoextend_size */
1317 page_no_t autoextend_size_pages =
1318 space->autoextend_size_in_bytes / page_size.physical();
1319 if (autoextend_size_pages > 0) {
1320 ut_ad((autoextend_size_pages % fsp_get_extent_size_in_pages(page_size)) ==
1321 0);
1322
1323 /* If the current size is not a multiple of autoextend_size, allocate just
1324 enough to make the file size a multiple of autoextend_size. */
1325 if ((size % autoextend_size_pages) > 0) {
1326 size_increase = autoextend_size_pages - (size % autoextend_size_pages);
1327 } else {
1328 size_increase = autoextend_size_pages;
1329 }
1330 } else {
1331 page_no_t extent_pages = fsp_get_extent_size_in_pages(page_size);
1332 if (size < extent_pages) {
1333 /* Let us first extend the file to extent_size */
1334 if (!fsp_try_extend_data_file_with_pages(space, extent_pages - 1,
1335 header, mtr)) {
1336 return false;
1337 }
1338
1339 size = extent_pages;
1340 }
1341
1342 size_increase = fsp_get_pages_to_extend_ibd(page_size, size);
1343 }
1344
1345 /* There is an additional algorithm for extending an undo tablespace. */
1346 if (space->m_undo_extend != 0) {
1347 adjust_undo_extend(space);
1348
1349 /* Use whichever increases the file size the most. */
1350 size_increase = std::max(size_increase, space->m_undo_extend);
1351 }
1352
1353 DBUG_EXECUTE_IF("fsp_crash_before_space_extend", DBUG_SUICIDE(););
1354 }
1355
1356 if (size_increase == 0) {
1357 return false;
1358 }
1359
1360 if (!fil_space_extend(space, size + size_increase)) {
1361 return false;
1362 }
1363
1364 /* We ignore any fragments of a full megabyte when storing the size
1365 to the space header */
1366
1367 space->size_in_header =
1368 ut_calc_align_down(space->size, (1024 * 1024) / page_size.physical());
1369
1370 fsp_header_size_update(header, space->size_in_header, mtr);
1371
1372 return true;
1373 }
1374
1375 /** Calculate the number of pages to extend a datafile.
1376 We extend single-table and general tablespaces first one extent at a time,
1377 but 4 at a time for bigger tablespaces. It is not enough to extend always
1378 by one extent, because we need to add at least one extent to FSP_FREE.
1379 A single extent descriptor page will track many extents. And the extent
1380 that uses its extent descriptor page is put onto the FSP_FREE_FRAG list.
1381 Extents that do not use their extent descriptor page are added to FSP_FREE.
1382 The physical page size is used to determine how many extents are tracked
1383 on one extent descriptor page. See xdes_calc_descriptor_page().
1384 @param[in] page_size page_size of the datafile
1385 @param[in] size current number of pages in the datafile
1386 @return number of pages to extend the file. */
1387 page_no_t fsp_get_pages_to_extend_ibd(const page_size_t &page_size,
1388 page_no_t size) {
1389 page_no_t size_increase; /* number of pages to extend this file */
1390 page_no_t extent_size; /* one megabyte, in pages */
1391 page_no_t threshold; /* The size of the tablespace (in number
1392 of pages) where we start allocating more
1393 than one extent at a time. */
1394
1395 extent_size = fsp_get_extent_size_in_pages(page_size);
1396
1397 /* The threshold is set at 32MiB except when the physical page
1398 size is small enough that it must be done sooner. */
1399 threshold =
1400 std::min(32 * extent_size, static_cast<page_no_t>(page_size.physical()));
1401
1402 if (size < threshold) {
1403 size_increase = extent_size;
1404 } else {
1405 /* Below in fsp_fill_free_list() we assume
1406 that we add at most FSP_FREE_ADD extents at
1407 a time */
1408 size_increase = FSP_FREE_ADD * extent_size;
1409 }
1410
1411 return (size_increase);
1412 }
1413
1414 /** Initialize a fragment extent and puts it into the free fragment list.
1415 @param[in,out] header Tablespace header
1416 @param[in,out] descr Extent descriptor
1417 @param[in,out] mtr Mini-transaction */
1418 static void fsp_init_xdes_free_frag(fsp_header_t *header, xdes_t *descr,
1419 mtr_t *mtr) {
1420 ulint n_used;
1421
1422 /* The first page in the extent is a extent descriptor page
1423 and the second is an ibuf bitmap page: mark them used */
1424 xdes_set_bit(descr, XDES_FREE_BIT, FSP_XDES_OFFSET, false, mtr);
1425 xdes_set_bit(descr, XDES_FREE_BIT, FSP_IBUF_BITMAP_OFFSET, false, mtr);
1426
1427 xdes_set_segment_id(descr, 0, XDES_FREE_FRAG, mtr);
1428 flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
1429
1430 n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr);
1431 mlog_write_ulint(header + FSP_FRAG_N_USED, n_used + XDES_FRAG_N_USED,
1432 MLOG_4BYTES, mtr);
1433 }
1434
1435 /** Put new extents to the free list if there are free extents above the free
1436 limit. If an extent happens to contain an extent descriptor page, the extent
1437 is put to the FSP_FREE_FRAG list with the page marked as used.
1438 @param[in] init_space True if this is a single-table tablespace
1439 and we are only initializing the first extent and the first bitmap pages;
1440 then we will not allocate more extents
1441 @param[in,out] space Tablespace
1442 @param[in,out] header Tablespace header
1443 @param[in,out] mtr Mini-transaction */
1444 static void fsp_fill_free_list(bool init_space, fil_space_t *space,
1445 fsp_header_t *header, mtr_t *mtr) {
1446 page_no_t limit;
1447 page_no_t size;
1448 uint32_t flags;
1449 xdes_t *descr;
1450 ulint count = 0;
1451 page_no_t i;
1452
1453 ut_ad(page_offset(header) == FSP_HEADER_OFFSET);
1454 ut_d(fsp_space_modify_check(space->id, mtr));
1455
1456 /* Check if we can fill free list from above the free list limit */
1457 size = mach_read_from_4(header + FSP_SIZE);
1458 limit = mach_read_from_4(header + FSP_FREE_LIMIT);
1459 flags = mach_read_from_4(header + FSP_SPACE_FLAGS);
1460
1461 ut_ad(size == space->size_in_header);
1462 ut_ad(limit == space->free_limit);
1463
1464 /* Exclude Encryption flag as it might have been changed In Memory flags but
1465 not on disk. */
1466 ut_ad(!((flags ^ space->flags) & ~(FSP_FLAGS_MASK_ENCRYPTION)));
1467
1468 const page_size_t page_size(flags);
1469
1470 if (size < limit + FSP_EXTENT_SIZE * FSP_FREE_ADD) {
1471 if ((!init_space && !fsp_is_system_tablespace(space->id) &&
1472 !fsp_is_global_temporary(space->id)) ||
1473 (space->id == TRX_SYS_SPACE &&
1474 srv_sys_space.can_auto_extend_last_file()) ||
1475 (fsp_is_global_temporary(space->id) &&
1476 srv_tmp_space.can_auto_extend_last_file())) {
1477 fsp_try_extend_data_file(space, header, mtr);
1478 size = space->size_in_header;
1479 }
1480 }
1481
1482 i = limit;
1483
1484 while ((init_space && i < 1) ||
1485 ((i + FSP_EXTENT_SIZE <= size) && (count < FSP_FREE_ADD))) {
1486 bool init_xdes = (ut_2pow_remainder(i, page_size.physical()) == 0);
1487
1488 space->free_limit = i + FSP_EXTENT_SIZE;
1489 mlog_write_ulint(header + FSP_FREE_LIMIT, i + FSP_EXTENT_SIZE, MLOG_4BYTES,
1490 mtr);
1491
1492 if (init_xdes) {
1493 buf_block_t *block;
1494
1495 /* We are going to initialize a new descriptor page
1496 and a new ibuf bitmap page: the prior contents of the
1497 pages should be ignored. */
1498
1499 if (i > 0) {
1500 const page_id_t page_id(space->id, i);
1501
1502 block = buf_page_create(page_id, page_size, RW_SX_LATCH, mtr);
1503
1504 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
1505
1506 fsp_init_file_page(block, mtr);
1507 mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE,
1508 FIL_PAGE_TYPE_XDES, MLOG_2BYTES, mtr);
1509
1510 ut_a(block->page.get_space() != nullptr && !block->page.was_stale());
1511 }
1512
1513 /* Initialize the ibuf bitmap page in a separate
1514 mini-transaction because it is low in the latching
1515 order, and we must be able to release its latch.
1516 Note: Insert-Buffering is disabled for tables that
1517 reside in the temp-tablespace. */
1518 if (!fsp_is_system_temporary(space->id)) {
1519 mtr_t ibuf_mtr;
1520
1521 mtr_start(&ibuf_mtr);
1522
1523 if (space->purpose == FIL_TYPE_TEMPORARY) {
1524 mtr_set_log_mode(&ibuf_mtr, MTR_LOG_NO_REDO);
1525 }
1526
1527 const page_id_t page_id(space->id, i + FSP_IBUF_BITMAP_OFFSET);
1528
1529 block = buf_page_create(page_id, page_size, RW_SX_LATCH, &ibuf_mtr);
1530
1531 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
1532
1533 fsp_init_file_page(block, &ibuf_mtr);
1534
1535 ut_a(block->page.get_space() != nullptr && !block->page.was_stale());
1536
1537 ibuf_bitmap_page_init(block, &ibuf_mtr);
1538
1539 mtr_commit(&ibuf_mtr);
1540 }
1541 }
1542
1543 buf_block_t *desc_block = nullptr;
1544 descr = xdes_get_descriptor_with_space_hdr(header, space->id, i, mtr,
1545 init_space, &desc_block);
1546 if (desc_block != nullptr) {
1547 buf_block_reset_page_type_on_mismatch(*desc_block, FIL_PAGE_TYPE_XDES,
1548 *mtr);
1549 }
1550 xdes_init(descr, mtr);
1551
1552 if (init_xdes) {
1553 fsp_init_xdes_free_frag(header, descr, mtr);
1554 } else {
1555 flst_add_last(header + FSP_FREE, descr + XDES_FLST_NODE, mtr);
1556 count++;
1557 }
1558
1559 i += FSP_EXTENT_SIZE;
1560 }
1561 ut_a(count < std::numeric_limits<uint32_t>::max());
1562 space->free_len += (uint32_t)count;
1563 }
1564
1565 /** Allocates a new free extent.
1566 @param[in] space_id Tablespace identifier
1567 @param[in] page_size Page size
1568 @param[in] hint Hint of which extent would be desirable: any
1569 page offset in the extent goes; the hint must not be > FSP_FREE_LIMIT
1570 @param[in,out] mtr Mini-transaction
1571 @return extent descriptor, NULL if cannot be allocated */
1572 static xdes_t *fsp_alloc_free_extent(space_id_t space_id,
1573 const page_size_t &page_size,
1574 page_no_t hint, mtr_t *mtr) {
1575 fsp_header_t *header;
1576 fil_addr_t first;
1577 xdes_t *descr;
1578 buf_block_t *desc_block = nullptr;
1579
1580 header = fsp_get_space_header(space_id, page_size, mtr);
1581
1582 descr = xdes_get_descriptor_with_space_hdr(header, space_id, hint, mtr, false,
1583 &desc_block);
1584
1585 fil_space_t *space = fil_space_get(space_id);
1586 ut_a(space != nullptr);
1587
1588 if (desc_block != nullptr) {
1589 buf_block_reset_page_type_on_mismatch(*desc_block, FIL_PAGE_TYPE_XDES,
1590 *mtr);
1591 }
1592
1593 if (descr && (xdes_get_state(descr, mtr) == XDES_FREE)) {
1594 /* Ok, we can take this extent */
1595 } else {
1596 /* Take the first extent in the free list */
1597 first = flst_get_first(header + FSP_FREE, mtr);
1598
1599 if (fil_addr_is_null(first)) {
1600 fsp_fill_free_list(false, space, header, mtr);
1601
1602 first = flst_get_first(header + FSP_FREE, mtr);
1603 }
1604
1605 if (fil_addr_is_null(first)) {
1606 return (nullptr); /* No free extents left */
1607 }
1608
1609 descr = xdes_lst_get_descriptor(space_id, page_size, first, mtr);
1610 }
1611
1612 flst_remove(header + FSP_FREE, descr + XDES_FLST_NODE, mtr);
1613 space->free_len--;
1614
1615 return (descr);
1616 }
1617
1618 /** Allocates a single free page from a space. */
1619 static void fsp_alloc_from_free_frag(
1620 fsp_header_t *header, /*!< in/out: tablespace header */
1621 xdes_t *descr, /*!< in/out: extent descriptor */
1622 page_no_t bit, /*!< in: slot to allocate in the extent */
1623 mtr_t *mtr) /*!< in/out: mini-transaction */
1624 {
1625 ulint frag_n_used;
1626
1627 ut_ad(xdes_get_state(descr, mtr) == XDES_FREE_FRAG);
1628 ut_a(xdes_mtr_get_bit(descr, XDES_FREE_BIT, bit, mtr));
1629 xdes_set_bit(descr, XDES_FREE_BIT, bit, false, mtr);
1630
1631 /* Update the FRAG_N_USED field */
1632 frag_n_used = mach_read_from_4(header + FSP_FRAG_N_USED);
1633 frag_n_used++;
1634 mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used, MLOG_4BYTES, mtr);
1635 if (xdes_is_full(descr, mtr)) {
1636 /* The fragment is full: move it to another list */
1637 flst_remove(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
1638 xdes_set_state(descr, XDES_FULL_FRAG, mtr);
1639
1640 flst_add_last(header + FSP_FULL_FRAG, descr + XDES_FLST_NODE, mtr);
1641 mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used - FSP_EXTENT_SIZE,
1642 MLOG_4BYTES, mtr);
1643 }
1644 }
1645
1646 /** Gets a buffer block for an allocated page.
1647 NOTE: If init_mtr != mtr, the block will only be initialized if it was
1648 not previously x-latched. It is assumed that the block has been
1649 x-latched only by mtr, and freed in mtr in that case.
1650 @param[in] page_id Page id of the allocated page
1651 @param[in] page_size Page size of the allocated page
1652 @param[in] rw_latch RW_SX_LATCH, RW_X_LATCH
1653 @param[in,out] mtr Mini-transaction of the allocation
1654 @param[in,out] init_mtr Mini-transaction for initializing the page
1655 @return block, initialized if init_mtr==mtr
1656 or rw_lock_x_lock_count(&block->lock) == 1 */
1657 static buf_block_t *fsp_page_create(const page_id_t &page_id,
1658 const page_size_t &page_size,
1659 rw_lock_type_t rw_latch, mtr_t *mtr,
1660 mtr_t *init_mtr) {
1661 ut_ad(rw_latch == RW_X_LATCH || rw_latch == RW_SX_LATCH);
1662 buf_block_t *block = buf_page_create(page_id, page_size, rw_latch, init_mtr);
1663
1664 if (init_mtr == mtr ||
1665 (rw_latch == RW_X_LATCH ? rw_lock_get_x_lock_count(&block->lock) == 1
1666 : rw_lock_get_sx_lock_count(&block->lock) == 1)) {
1667 /* Initialize the page, unless it was already
1668 SX-latched in mtr. (In this case, we would want to
1669 allocate another page that has not been freed in mtr.) */
1670 ut_ad(init_mtr == mtr ||
1671 !mtr_memo_contains_flagged(
1672 mtr, block, MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX));
1673
1674 fsp_init_file_page(block, init_mtr);
1675 }
1676
1677 return (block);
1678 }
1679
1680 /** Allocates a single free page from a space.
1681 The page is marked as used.
1682 @param[in] space Space id
1683 @param[in] page_size Page size
1684 @param[in] hint Hint of which page would be desirable
1685 @param[in] rw_latch RW_SX_LATCH, RW_X_LATCH
1686 @param[in,out] mtr Mini-transaction
1687 @param[in,out] init_mtr Mini-transaction in which the page should be
1688 initialized (may be the same as mtr)
1689 @retval NULL if no page could be allocated
1690 @retval block rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
1691 (init_mtr == mtr, or the page was not previously freed in mtr),
1692 returned block is not allocated nor initialized otherwise */
1693 [[nodiscard]] static buf_block_t *fsp_alloc_free_page(
1694 space_id_t space, const page_size_t &page_size, page_no_t hint,
1695 rw_lock_type_t rw_latch, mtr_t *mtr, mtr_t *init_mtr) {
1696 fsp_header_t *header;
1697 fil_addr_t first;
1698 xdes_t *descr;
1699 page_no_t free;
1700 page_no_t page_no;
1701 page_no_t space_size;
1702
1703 ut_ad(mtr);
1704 ut_ad(init_mtr);
1705
1706 ut_d(fsp_space_modify_check(space, mtr));
1707 header = fsp_get_space_header(space, page_size, mtr);
1708
1709 /* Get the hinted descriptor */
1710 descr = xdes_get_descriptor_with_space_hdr(header, space, hint, mtr);
1711
1712 if (descr && (xdes_get_state(descr, mtr) == XDES_FREE_FRAG)) {
1713 /* Ok, we can take this extent */
1714 } else {
1715 /* Else take the first extent in free_frag list */
1716 first = flst_get_first(header + FSP_FREE_FRAG, mtr);
1717
1718 if (fil_addr_is_null(first)) {
1719 /* There are no partially full fragments: allocate
1720 a free extent and add it to the FREE_FRAG list. NOTE
1721 that the allocation may have as a side-effect that an
1722 extent containing a descriptor page is added to the
1723 FREE_FRAG list. But we will allocate our page from the
1724 the free extent anyway. */
1725
1726 descr = fsp_alloc_free_extent(space, page_size, hint, mtr);
1727
1728 if (descr == nullptr) {
1729 /* No free space left */
1730
1731 return (nullptr);
1732 }
1733
1734 xdes_set_state(descr, XDES_FREE_FRAG, mtr);
1735 flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
1736 } else {
1737 descr = xdes_lst_get_descriptor(space, page_size, first, mtr);
1738 }
1739
1740 /* Reset the hint */
1741 hint = 0;
1742 }
1743
1744 /* Now we have in descr an extent with at least one free page. Look
1745 for a free page in the extent. */
1746
1747 free = xdes_find_bit(descr, XDES_FREE_BIT, true, hint % FSP_EXTENT_SIZE, mtr);
1748 if (free == FIL_NULL) {
1749 ut_print_buf(stderr, ((byte *)descr) - 500, 1000);
1750 putc('\n', stderr);
1751
1752 ut_error;
1753 }
1754
1755 page_no = xdes_get_offset(descr) + free;
1756
1757 space_size = mach_read_from_4(header + FSP_SIZE);
1758 ut_ad(space_size == fil_space_get(space)->size_in_header ||
1759 (space == TRX_SYS_SPACE && srv_startup_is_before_trx_rollback_phase));
1760
1761 if (space_size <= page_no) {
1762 /* It must be that we are extending a single-table tablespace
1763 whose size is still < 64 pages */
1764
1765 ut_a(!fsp_is_system_tablespace(space));
1766 ut_a(!fsp_is_global_temporary(space));
1767 if (page_no >= FSP_EXTENT_SIZE) {
1768 ib::error(ER_IB_MSG_417) << "Trying to extend a single-table"
1769 " tablespace "
1770 << space
1771 << " , by single"
1772 " page(s) though the space size "
1773 << space_size << ". Page no " << page_no << ".";
1774 return (nullptr);
1775 }
1776
1777 fil_space_t *fspace = fil_space_get(space);
1778
1779 if (!fsp_try_extend_data_file_with_pages(fspace, page_no, header, mtr)) {
1780 /* No disk space left */
1781 return (nullptr);
1782 }
1783 }
1784
1785 fsp_alloc_from_free_frag(header, descr, free, mtr);
1786 return (fsp_page_create(page_id_t(space, page_no), page_size, rw_latch, mtr,
1787 init_mtr));
1788 }
1789
1790 /** Frees a single page of a space.
1791 The page is marked as free and clean.
1792 @param[in] page_id Page id
1793 @param[in] page_size Page size
1794 @param[in,out] mtr Mini-transaction */
1795 static void fsp_free_page(const page_id_t &page_id,
1796 const page_size_t &page_size, mtr_t *mtr) {
1797 fsp_header_t *header;
1798 xdes_t *descr;
1799 ulint state;
1800 ulint frag_n_used;
1801
1802 ut_ad(mtr);
1803 ut_d(fsp_space_modify_check(page_id.space(), mtr));
1804
1805 /* fprintf(stderr, "Freeing page %lu in space %lu\n", page, space); */
1806
1807 header = fsp_get_space_header(page_id.space(), page_size, mtr);
1808
1809 descr = xdes_get_descriptor_with_space_hdr(header, page_id.space(),
1810 page_id.page_no(), mtr);
1811
1812 state = xdes_get_state(descr, mtr);
1813
1814 if (state != XDES_FREE_FRAG && state != XDES_FULL_FRAG) {
1815 ib::error(ER_IB_MSG_418) << "File space extent descriptor of page "
1816 << page_id << " has state " << state;
1817 fputs("InnoDB: Dump of descriptor: ", stderr);
1818 ut_print_buf(stderr, ((byte *)descr) - 50, 200);
1819 putc('\n', stderr);
1820
1821 if (state == XDES_FREE) {
1822 /* Crash in debug version, so that we get a core dump
1823 of this corruption. */
1824 ut_d(ut_error);
1825 /* We put here some fault tolerance: if the page
1826 is already free, return without doing anything! */
1827
1828 ut_o(return);
1829 }
1830
1831 ut_error;
1832 }
1833
1834 if (xdes_mtr_get_bit(descr, XDES_FREE_BIT,
1835 page_id.page_no() % FSP_EXTENT_SIZE, mtr)) {
1836 ib::error(ER_IB_MSG_419)
1837 << "File space extent descriptor of page " << page_id
1838 << " says it is free. Dump of descriptor: ";
1839 ut_print_buf(stderr, ((byte *)descr) - 50, 200);
1840 putc('\n', stderr);
1841 /* Crash in debug version, so that we get a core dump
1842 of this corruption. */
1843 ut_d(ut_error);
1844
1845 /* We put here some fault tolerance: if the page
1846 is already free, return without doing anything! */
1847
1848 ut_o(return);
1849 }
1850
1851 const page_no_t bit = page_id.page_no() % FSP_EXTENT_SIZE;
1852
1853 xdes_set_bit(descr, XDES_FREE_BIT, bit, true, mtr);
1854 xdes_set_bit(descr, XDES_CLEAN_BIT, bit, true, mtr);
1855
1856 frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr);
1857 if (state == XDES_FULL_FRAG) {
1858 /* The fragment was full: move it to another list */
1859 flst_remove(header + FSP_FULL_FRAG, descr + XDES_FLST_NODE, mtr);
1860 xdes_set_state(descr, XDES_FREE_FRAG, mtr);
1861 flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
1862 mlog_write_ulint(header + FSP_FRAG_N_USED,
1863 frag_n_used + FSP_EXTENT_SIZE - 1, MLOG_4BYTES, mtr);
1864 } else {
1865 ut_a(frag_n_used > 0);
1866 mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used - 1, MLOG_4BYTES,
1867 mtr);
1868 }
1869
1870 if (xdes_is_free(descr, mtr)) {
1871 /* The extent has become free: move it to another list */
1872 flst_remove(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
1873 fsp_free_extent(page_id, page_size, mtr);
1874 }
1875 }
1876
1877 /** Returns an extent to the free list of a space.
1878 @param[in] page_id Page id in the extent
1879 @param[in] page_size Page size
1880 @param[in,out] mtr Mini-transaction */
1881 static void fsp_free_extent(const page_id_t &page_id,
1882 const page_size_t &page_size, mtr_t *mtr) {
1883 fsp_header_t *header;
1884 xdes_t *descr;
1885
1886 ut_ad(mtr);
1887
1888 header = fsp_get_space_header(page_id.space(), page_size, mtr);
1889
1890 descr = xdes_get_descriptor_with_space_hdr(header, page_id.space(),
1891 page_id.page_no(), mtr);
1892
1893 switch (xdes_get_state(descr, mtr)) {
1894 case XDES_FSEG_FRAG:
1895 /* The extent is being returned to the FSP_FREE_FRAG list. */
1896 xdes_init(descr, mtr);
1897 fsp_init_xdes_free_frag(header, descr, mtr);
1898 break;
1899 case XDES_FSEG:
1900 case XDES_FREE_FRAG:
1901 case XDES_FULL_FRAG:
1902
1903 xdes_init(descr, mtr);
1904
1905 flst_add_last(header + FSP_FREE, descr + XDES_FLST_NODE, mtr);
1906
1907 fil_space_t *space;
1908
1909 space = fil_space_get(page_id.space());
1910
1911 ++space->free_len;
1912
1913 break;
1914
1915 case XDES_FREE:
1916 case XDES_NOT_INITED:
1917 ut_error;
1918 }
1919 }
1920
1921 /** Returns the nth inode slot on an inode page.
1922 @param[in] page Segment inode page
1923 @param[in] i Inode index on page
1924 @param[in] page_size Page size
1925 @param[in,out] mtr Mini-transaction
1926 @return segment inode */
1927 static inline fseg_inode_t *fsp_seg_inode_page_get_nth_inode(
1928 page_t *page, page_no_t i, const page_size_t &page_size, mtr_t *mtr) {
1929 ut_ad(i < FSP_SEG_INODES_PER_PAGE(page_size));
1930 ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_SX_FIX));
1931
1932 return (page + FSEG_ARR_OFFSET + FSEG_INODE_SIZE * i);
1933 }
1934
1935 /** Looks for a used segment inode on a segment inode page.
1936 @param[in] page Segment inode page
1937 @param[in] page_size Page size
1938 @param[in,out] mtr Mini-transaction
1939 @return segment inode index, or FIL_NULL if not found */
1940 static page_no_t fsp_seg_inode_page_find_used(page_t *page,
1941 const page_size_t &page_size,
1942 mtr_t *mtr) {
1943 page_no_t i;
1944 fseg_inode_t *inode;
1945
1946 for (i = 0; i < FSP_SEG_INODES_PER_PAGE(page_size); i++) {
1947 inode = fsp_seg_inode_page_get_nth_inode(page, i, page_size, mtr);
1948
1949 if (mach_read_from_8(inode + FSEG_ID)) {
1950 /* This is used */
1951
1952 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
1953 return (i);
1954 }
1955 }
1956
1957 return (FIL_NULL);
1958 }
1959
1960 /** Looks for an unused segment inode on a segment inode page.
1961 @param[in] page Segment inode page
1962 @param[in] i Search forward starting from this index
1963 @param[in] page_size Page size
1964 @param[in,out] mtr Mini-transaction
1965 @return segment inode index, or FIL_NULL if not found */
1966 static page_no_t fsp_seg_inode_page_find_free(page_t *page, page_no_t i,
1967 const page_size_t &page_size,
1968 mtr_t *mtr) {
1969 for (; i < FSP_SEG_INODES_PER_PAGE(page_size); i++) {
1970 fseg_inode_t *inode;
1971
1972 inode = fsp_seg_inode_page_get_nth_inode(page, i, page_size, mtr);
1973
1974 if (!mach_read_from_8(inode + FSEG_ID)) {
1975 /* This is unused */
1976 return (i);
1977 }
1978
1979 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
1980 }
1981
1982 return (FIL_NULL);
1983 }
1984
1985 /** Allocates a new file segment inode page.
1986 @return true if could be allocated */
1987 static bool fsp_alloc_seg_inode_page(
1988 fsp_header_t *space_header, /*!< in: space header */
1989 mtr_t *mtr) /*!< in/out: mini-transaction */
1990 {
1991 fseg_inode_t *inode;
1992 buf_block_t *block;
1993 page_t *page;
1994 space_id_t space;
1995
1996 ut_ad(page_offset(space_header) == FSP_HEADER_OFFSET);
1997
1998 space = page_get_space_id(page_align(space_header));
1999
2000 const page_size_t page_size(mach_read_from_4(FSP_SPACE_FLAGS + space_header));
2001
2002 block = fsp_alloc_free_page(space, page_size, 0, RW_SX_LATCH, mtr, mtr);
2003
2004 if (block == nullptr) {
2005 return false;
2006 }
2007
2008 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
2009 ut_ad(rw_lock_get_sx_lock_count(&block->lock) == 1);
2010
2011 page = buf_block_get_frame(block);
2012
2013 mlog_write_ulint(page + FIL_PAGE_TYPE, FIL_PAGE_INODE, MLOG_2BYTES, mtr);
2014
2015 for (page_no_t i = 0; i < FSP_SEG_INODES_PER_PAGE(page_size); i++) {
2016 inode = fsp_seg_inode_page_get_nth_inode(page, i, page_size, mtr);
2017
2018 mlog_write_ull(inode + FSEG_ID, 0, mtr);
2019 }
2020
2021 flst_add_last(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE,
2022 mtr);
2023
2024 return true;
2025 }
2026
2027 /** Allocates a new file segment inode.
2028 @return segment inode, or NULL if not enough space */
2029 static fseg_inode_t *fsp_alloc_seg_inode(
2030 fsp_header_t *space_header, /*!< in: space header */
2031 mtr_t *mtr) /*!< in/out: mini-transaction */
2032 {
2033 buf_block_t *block;
2034 page_t *page;
2035 fseg_inode_t *inode;
2036 page_no_t n;
2037
2038 ut_ad(page_offset(space_header) == FSP_HEADER_OFFSET);
2039
2040 /* Allocate a new segment inode page if needed. */
2041 if (flst_get_len(space_header + FSP_SEG_INODES_FREE) == 0 &&
2042 !fsp_alloc_seg_inode_page(space_header, mtr)) {
2043 return (nullptr);
2044 }
2045
2046 const page_size_t page_size(mach_read_from_4(FSP_SPACE_FLAGS + space_header));
2047
2048 const page_id_t page_id(
2049 page_get_space_id(page_align(space_header)),
2050 flst_get_first(space_header + FSP_SEG_INODES_FREE, mtr).page);
2051
2052 block = buf_page_get(page_id, page_size, RW_SX_LATCH, UT_LOCATION_HERE, mtr);
2053 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
2054 buf_block_reset_page_type_on_mismatch(*block, FIL_PAGE_INODE, *mtr);
2055
2056 page = buf_block_get_frame(block);
2057
2058 n = fsp_seg_inode_page_find_free(page, 0, page_size, mtr);
2059
2060 ut_a(n != FIL_NULL);
2061
2062 inode = fsp_seg_inode_page_get_nth_inode(page, n, page_size, mtr);
2063
2064 if (FIL_NULL == fsp_seg_inode_page_find_free(page, n + 1, page_size, mtr)) {
2065 /* There are no other unused headers left on the page: move it
2066 to another list */
2067
2068 flst_remove(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE,
2069 mtr);
2070
2071 flst_add_last(space_header + FSP_SEG_INODES_FULL,
2072 page + FSEG_INODE_PAGE_NODE, mtr);
2073 }
2074
2075 ut_ad(!mach_read_from_8(inode + FSEG_ID) ||
2076 mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2077 return (inode);
2078 }
2079
2080 /** Frees a file segment inode.
2081 @param[in] space Space id
2082 @param[in] page_size Page size
2083 @param[in,out] inode Segment inode
2084 @param[in,out] mtr Mini-transaction */
2085 static void fsp_free_seg_inode(space_id_t space, const page_size_t &page_size,
2086 fseg_inode_t *inode, mtr_t *mtr) {
2087 page_t *page;
2088 fsp_header_t *space_header;
2089
2090 ut_d(fsp_space_modify_check(space, mtr));
2091
2092 page = page_align(inode);
2093
2094 space_header = fsp_get_space_header(space, page_size, mtr);
2095
2096 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2097
2098 if (FIL_NULL == fsp_seg_inode_page_find_free(page, 0, page_size, mtr)) {
2099 /* Move the page to another list */
2100
2101 flst_remove(space_header + FSP_SEG_INODES_FULL, page + FSEG_INODE_PAGE_NODE,
2102 mtr);
2103
2104 flst_add_last(space_header + FSP_SEG_INODES_FREE,
2105 page + FSEG_INODE_PAGE_NODE, mtr);
2106 }
2107
2108 mlog_write_ull(inode + FSEG_ID, 0, mtr);
2109 mlog_write_ulint(inode + FSEG_MAGIC_N, 0xfa051ce3, MLOG_4BYTES, mtr);
2110
2111 if (FIL_NULL == fsp_seg_inode_page_find_used(page, page_size, mtr)) {
2112 /* There are no other used headers left on the page: free it */
2113
2114 flst_remove(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE,
2115 mtr);
2116
2117 fsp_free_page(page_id_t(space, page_get_page_no(page)), page_size, mtr);
2118 }
2119 }
2120
2121 /** Returns the file segment inode, page x-latched.
2122 @param[in] header Segment header
2123 @param[in] space Space id
2124 @param[in] page_size Page size
2125 @param[in,out] mtr Mini-transaction
2126 @param[out] block Inode block, or NULL to ignore
2127 @return segment inode, page x-latched; NULL if the inode is free */
2128 static fseg_inode_t *fseg_inode_try_get(const fseg_header_t *header,
2129 space_id_t space,
2130 const page_size_t &page_size,
2131 mtr_t *mtr, buf_block_t **block) {
2132 fil_addr_t inode_addr;
2133 fseg_inode_t *inode;
2134
2135 inode_addr.page = mach_read_from_4(header + FSEG_HDR_PAGE_NO);
2136 inode_addr.boffset = mach_read_from_2(header + FSEG_HDR_OFFSET);
2137 ut_ad(space == mach_read_from_4(header + FSEG_HDR_SPACE));
2138
2139 inode = fut_get_ptr(space, page_size, inode_addr, RW_SX_LATCH, mtr, block);
2140
2141 if (UNIV_UNLIKELY(!mach_read_from_8(inode + FSEG_ID))) {
2142 inode = nullptr;
2143 } else {
2144 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2145 }
2146
2147 return (inode);
2148 }
2149
2150 fseg_inode_t *fseg_inode_get(const fseg_header_t *header, space_id_t space,
2151 const page_size_t &page_size, mtr_t *mtr,
2152 buf_block_t **block) {
2153 fseg_inode_t *inode =
2154 fseg_inode_try_get(header, space, page_size, mtr, block);
2155 ut_a(inode);
2156 return (inode);
2157 }
2158
2159 /** Gets the page number from the nth fragment page slot.
2160 @return page number, FIL_NULL if not in use */
2161 static inline page_no_t fseg_get_nth_frag_page_no(
2162 fseg_inode_t *inode, /*!< in: segment inode */
2163 ulint n, /*!< in: slot index */
2164 mtr_t *mtr [[maybe_unused]])
2165 /*!< in/out: mini-transaction */
2166 {
2167 #ifdef UNIV_DEBUG
2168 const std::size_t n_slots = FSEG_FRAG_ARR_N_SLOTS;
2169 ut_ad(inode && mtr);
2170 ut_ad(n < n_slots);
2171 ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_SX_FIX));
2172 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2173 #endif /* UNIV_DEBUG */
2174 return (mach_read_from_4(inode + FSEG_FRAG_ARR + n * FSEG_FRAG_SLOT_SIZE));
2175 }
2176
2177 /** Sets the page number in the nth fragment page slot. */
2178 static inline void fseg_set_nth_frag_page_no(
2179 fseg_inode_t *inode, /*!< in: segment inode */
2180 ulint n, /*!< in: slot index */
2181 page_no_t page_no, /*!< in: page number to set */
2182 mtr_t *mtr) /*!< in/out: mini-transaction */
2183 {
2184 ut_ad(inode && mtr);
2185 ut_ad(n < FSEG_FRAG_ARR_N_SLOTS);
2186 ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_SX_FIX));
2187 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2188
2189 mlog_write_ulint(inode + FSEG_FRAG_ARR + n * FSEG_FRAG_SLOT_SIZE, page_no,
2190 MLOG_4BYTES, mtr);
2191 }
2192
2193 /** Finds a fragment page slot which is free.
2194 @return slot index; ULINT_UNDEFINED if none found */
2195 static ulint fseg_find_free_frag_page_slot(
2196 fseg_inode_t *inode, /*!< in: segment inode */
2197 mtr_t *mtr) /*!< in/out: mini-transaction */
2198 {
2199 ulint i;
2200 page_no_t page_no;
2201
2202 ut_ad(inode && mtr);
2203
2204 for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) {
2205 page_no = fseg_get_nth_frag_page_no(inode, i, mtr);
2206
2207 if (page_no == FIL_NULL) {
2208 return (i);
2209 }
2210 }
2211
2212 return (ULINT_UNDEFINED);
2213 }
2214
2215 /** Finds a fragment page slot which is used and last in the array.
2216 @return slot index; ULINT_UNDEFINED if none found */
2217 static ulint fseg_find_last_used_frag_page_slot(
2218 fseg_inode_t *inode, /*!< in: segment inode */
2219 mtr_t *mtr) /*!< in/out: mini-transaction */
2220 {
2221 ulint i;
2222 page_no_t page_no;
2223
2224 ut_ad(inode && mtr);
2225
2226 for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) {
2227 page_no =
2228 fseg_get_nth_frag_page_no(inode, FSEG_FRAG_ARR_N_SLOTS - i - 1, mtr);
2229
2230 if (page_no != FIL_NULL) {
2231 return (FSEG_FRAG_ARR_N_SLOTS - i - 1);
2232 }
2233 }
2234
2235 return (ULINT_UNDEFINED);
2236 }
2237
2238 /** Calculates reserved fragment page slots.
2239 @return number of fragment pages */
2240 static ulint fseg_get_n_frag_pages(
2241 fseg_inode_t *inode, /*!< in: segment inode */
2242 mtr_t *mtr) /*!< in/out: mini-transaction */
2243 {
2244 ulint i;
2245 ulint count = 0;
2246
2247 ut_ad(inode && mtr);
2248
2249 for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) {
2250 if (FIL_NULL != fseg_get_nth_frag_page_no(inode, i, mtr)) {
2251 count++;
2252 }
2253 }
2254
2255 return (count);
2256 }
2257
2258 /** Creates a new segment.
2259 @return the block where the segment header is placed, x-latched, NULL
2260 if could not create segment because of lack of space */
2261 buf_block_t *fseg_create_general(
2262 space_id_t space_id, /*!< in: space id */
2263 page_no_t page, /*!< in: page where the segment header is
2264 placed: if this is != 0, the page must belong
2265 to another segment, if this is 0, a new page
2266 will be allocated and it will belong to the
2267 created segment */
2268 ulint byte_offset, /*!< in: byte offset of the created segment header
2269 on the page */
2270 bool has_done_reservation, /*!< in: true if the caller has already
2271 done the reservation for the pages with
2272 fsp_reserve_free_extents (at least 2 extents: one for
2273 the inode and the other for the segment) then there is
2274 no need to do the check for this individual
2275 operation */
2276 mtr_t *mtr) /*!< in/out: mini-transaction */
2277 {
2278 fsp_header_t *space_header;
2279 fseg_inode_t *inode;
2280 ib_id_t seg_id;
2281 buf_block_t *block = nullptr; /* remove warning */
2282 fseg_header_t *header = nullptr; /* remove warning */
2283 ulint n_reserved = 0;
2284 ulint i;
2285
2286 DBUG_TRACE;
2287
2288 ut_ad(byte_offset + FSEG_HEADER_SIZE <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END);
2289 ut_d(fsp_space_modify_check(space_id, mtr));
2290
2291 fil_space_t *space = fil_space_get(space_id);
2292
2293 mtr_x_lock_space(space, mtr);
2294
2295 const page_size_t page_size(space->flags);
2296
2297 if (page != 0) {
2298 block = buf_page_get(page_id_t(space_id, page), page_size, RW_SX_LATCH,
2299 UT_LOCATION_HERE, mtr);
2300
2301 header = byte_offset + buf_block_get_frame(block);
2302
2303 const auto type = space_id == TRX_SYS_SPACE && page == TRX_SYS_PAGE_NO
2304 ? FIL_PAGE_TYPE_TRX_SYS
2305 : FIL_PAGE_TYPE_SYS;
2306
2307 buf_block_reset_page_type_on_mismatch(*block, type, *mtr);
2308 }
2309
2310 if (rw_lock_get_x_lock_count(&space->latch) == 1) {
2311 /* This thread did not own the latch before this call: free
2312 excess pages from the insert buffer free list */
2313
2314 if (space_id == IBUF_SPACE_ID) {
2315 ibuf_free_excess_pages();
2316 }
2317 }
2318
2319 if (!has_done_reservation) {
2320 fsp_reserve_t alloc_type =
2321 (fsp_is_undo_tablespace(space_id) ? FSP_UNDO : FSP_NORMAL);
2322
2323 if (!fsp_reserve_free_extents(&n_reserved, space_id, 2, alloc_type, mtr)) {
2324 return nullptr;
2325 }
2326 }
2327
2328 space_header = fsp_get_space_header(space_id, page_size, mtr);
2329
2330 inode = fsp_alloc_seg_inode(space_header, mtr);
2331
2332 if (inode == nullptr) {
2333 goto funct_exit;
2334 }
2335
2336 /* Read the next segment id from space header and increment the
2337 value in space header */
2338
2339 seg_id = mach_read_from_8(space_header + FSP_SEG_ID);
2340
2341 mlog_write_ull(space_header + FSP_SEG_ID, seg_id + 1, mtr);
2342
2343 mlog_write_ull(inode + FSEG_ID, seg_id, mtr);
2344
2345 { /* Introducing a new scope to localize this object. Otherwise, I have to
2346 declare this object before the goto statement above. */
2347 File_segment_inode fseg_inode(space_id, page_size, inode, mtr);
2348 fseg_inode.write_not_full_n_used(0);
2349 }
2350
2351 flst_init(inode + FSEG_FREE, mtr);
2352 flst_init(inode + FSEG_NOT_FULL, mtr);
2353 flst_init(inode + FSEG_FULL, mtr);
2354
2355 mlog_write_ulint(inode + FSEG_MAGIC_N, FSEG_MAGIC_N_VALUE, MLOG_4BYTES, mtr);
2356 for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) {
2357 fseg_set_nth_frag_page_no(inode, i, FIL_NULL, mtr);
2358 }
2359
2360 if (page == 0) {
2361 block = fseg_alloc_free_page_low(space, page_size, inode, 0, FSP_UP,
2362 RW_SX_LATCH, mtr,
2363 mtr IF_DEBUG(, has_done_reservation));
2364
2365 /* The allocation cannot fail if we have already reserved a
2366 space for the page. */
2367 ut_ad(!has_done_reservation || block != nullptr);
2368
2369 if (block == nullptr) {
2370 fsp_free_seg_inode(space_id, page_size, inode, mtr);
2371
2372 goto funct_exit;
2373 }
2374
2375 ut_ad(rw_lock_get_sx_lock_count(&block->lock) == 1);
2376
2377 header = byte_offset + buf_block_get_frame(block);
2378 mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE,
2379 FIL_PAGE_TYPE_SYS, MLOG_2BYTES, mtr);
2380 }
2381
2382 mlog_write_ulint(header + FSEG_HDR_OFFSET, page_offset(inode), MLOG_2BYTES,
2383 mtr);
2384
2385 mlog_write_ulint(header + FSEG_HDR_PAGE_NO,
2386 page_get_page_no(page_align(inode)), MLOG_4BYTES, mtr);
2387
2388 mlog_write_ulint(header + FSEG_HDR_SPACE, space_id, MLOG_4BYTES, mtr);
2389
2390 funct_exit:
2391 if (!has_done_reservation) {
2392 fil_space_release_free_extents(space_id, n_reserved);
2393 }
2394
2395 return block;
2396 }
2397
2398 /** Creates a new segment.
2399 @return the block where the segment header is placed, x-latched, NULL
2400 if could not create segment because of lack of space */
2401 buf_block_t *fseg_create(
2402 space_id_t space, /*!< in: space id */
2403 page_no_t page, /*!< in: page where the segment header is
2404 placed: if this is != 0, the page must belong
2405 to another segment, if this is 0, a new page
2406 will be allocated and it will belong to the
2407 created segment */
2408 ulint byte_offset, /*!< in: byte offset of the created
2409 segment header on the page */
2410 mtr_t *mtr) /*!< in/out: mini-transaction */
2411 {
2412 return (fseg_create_general(space, page, byte_offset, false, mtr));
2413 }
2414
2415 /** Calculates the number of pages reserved by a segment, and how many
2416 pages are currently used.
2417 @param[in] space_id Unique tablespace identifier
2418 @param[in] page_size Size of each page in the tablespace.
2419 @param[in] inode File segment inode pointer
2420 @param[out] used Number of pages used (not more than reserved)
2421 @param[in,out] mtr Mini-transaction
2422 @return number of reserved pages */
2423 static ulint fseg_n_reserved_pages_low(space_id_t space_id,
2424 const page_size_t &page_size,
2425 fseg_inode_t *inode, ulint *used,
2426 mtr_t *mtr) {
2427 ulint ret;
2428 ut_ad(inode && used && mtr);
2429 ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_SX_FIX));
2430
2431 File_segment_inode fseg_inode(space_id, page_size, inode, mtr);
2432
2433 /* number of used segment pages in the FSEG_NOT_FULL list */
2434 uint32_t n_used_not_full = fseg_inode.read_not_full_n_used();
2435
2436 /* total number of segment pages in the FSEG_NOT_FULL list */
2437 ulint n_total_not_full =
2438 FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_NOT_FULL);
2439
2440 /* n_used can be zero only if n_total is zero. */
2441 ut_ad(n_used_not_full > 0 || n_total_not_full == 0);
2442 ut_ad((n_used_not_full < n_total_not_full) ||
2443 ((n_used_not_full == 0) && (n_total_not_full == 0)));
2444
2445 /* total number of pages in FSEG_FULL list. */
2446 ulint n_total_full = FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_FULL);
2447
2448 /* total number of pages in FSEG_FREE list. */
2449 ulint n_total_free = FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_FREE);
2450
2451 /* Number of fragment pages in the segment. */
2452 ulint n_frags = fseg_get_n_frag_pages(inode, mtr);
2453
2454 *used = n_frags + n_total_full + n_used_not_full;
2455 ret = n_frags + n_total_full + n_total_free + n_total_not_full;
2456
2457 ut_ad(*used <= ret);
2458 ut_ad((*used < ret) || ((n_used_not_full == 0) && (n_total_not_full == 0) &&
2459 (n_total_free == 0)));
2460
2461 return (ret);
2462 }
2463
2464 /** Calculates the number of pages reserved by a segment, and how many pages are
2465 currently used.
2466 @return number of reserved pages */
2467 ulint fseg_n_reserved_pages(
2468 fseg_header_t *header, /*!< in: segment header */
2469 ulint *used, /*!< out: number of pages used (<= reserved) */
2470 mtr_t *mtr) /*!< in/out: mini-transaction */
2471 {
2472 space_id_t space_id;
2473
2474 space_id = page_get_space_id(page_align(header));
2475
2476 fil_space_t *space = fil_space_get(space_id);
2477
2478 mtr_x_lock_space(space, mtr);
2479
2480 const page_size_t page_size(space->flags);
2481
2482 fseg_inode_t *inode;
2483
2484 inode = fseg_inode_get(header, space_id, page_size, mtr);
2485
2486 return (fseg_n_reserved_pages_low(space_id, page_size, inode, used, mtr));
2487 }
2488
2489 /** Tries to fill the free list of a segment with consecutive free extents.
2490 This happens if the segment is big enough to allow extents in the free list,
2491 the free list is empty, and the extents can be allocated consecutively from
2492 the hint onward.
2493 @param[in] inode Segment inode
2494 @param[in] space Space id
2495 @param[in] page_size Page size
2496 @param[in] hint Hint which extent would be good as the first
2497 extent
2498 @param[in,out] mtr Mini-transaction */
2499 static void fseg_fill_free_list(fseg_inode_t *inode, space_id_t space,
2500 const page_size_t &page_size, page_no_t hint,
2501 mtr_t *mtr) {
2502 xdes_t *descr;
2503 page_no_t i;
2504 ib_id_t seg_id;
2505 ulint reserved;
2506 ulint used;
2507
2508 ut_ad(inode && mtr);
2509 ut_ad(!((page_offset(inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
2510 ut_d(fsp_space_modify_check(space, mtr));
2511
2512 reserved = fseg_n_reserved_pages_low(space, page_size, inode, &used, mtr);
2513
2514 if (reserved < FSEG_FREE_LIST_LIMIT * FSP_EXTENT_SIZE) {
2515 /* The segment is too small to allow extents in free list */
2516
2517 return;
2518 }
2519
2520 if (flst_get_len(inode + FSEG_FREE) > 0) {
2521 /* Free list is not empty */
2522
2523 return;
2524 }
2525
2526 for (i = 0; i < FSEG_FREE_LIST_MAX_LEN; i++) {
2527 descr = xdes_get_descriptor(space, hint, page_size, mtr);
2528
2529 if ((descr == nullptr) || (XDES_FREE != xdes_get_state(descr, mtr))) {
2530 /* We cannot allocate the desired extent: stop */
2531
2532 return;
2533 }
2534
2535 descr = fsp_alloc_free_extent(space, page_size, hint, mtr);
2536
2537 seg_id = mach_read_from_8(inode + FSEG_ID);
2538 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2539 xdes_set_segment_id(descr, seg_id, XDES_FSEG, mtr);
2540
2541 flst_add_last(inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr);
2542 hint += FSP_EXTENT_SIZE;
2543 }
2544 }
2545
2546 /** A fragment extent can be leased if it is the special kind that has a
2547 descriptor page and no other pages are being used except the descriptor
2548 and ibuf bitmap pages. The number of used pages will be equal to
2549 XDES_FRAG_N_USED.
2550 @param[in] descr Extent descriptor
2551 @param[in] page_size The page size
2552 @param[in,out] mtr Mini-transaction
2553 @return true if the extent is leasable, false otherwise. */
2554 static inline bool xdes_is_leasable(const xdes_t *descr,
2555 const page_size_t &page_size, mtr_t *mtr) {
2556 ut_ad(descr && mtr);
2557 ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_SX_FIX));
2558
2559 const page_no_t page_no = xdes_get_offset(descr);
2560 const bool has_xdes_page = !ut_2pow_remainder(page_no, page_size.physical());
2561
2562 if (!has_xdes_page) {
2563 return (false);
2564 }
2565 /* Page 0 and 1 must not be free */
2566 if (xdes_mtr_get_bit(descr, XDES_FREE_BIT, 0, mtr) ||
2567 xdes_mtr_get_bit(descr, XDES_FREE_BIT, 1, mtr)) {
2568 return (false);
2569 }
2570
2571 /* All other pages must be free */
2572 for (page_no_t i = 2; i < FSP_EXTENT_SIZE; ++i) {
2573 if (!xdes_mtr_get_bit(descr, XDES_FREE_BIT, i, mtr)) {
2574 return (false);
2575 }
2576 }
2577
2578 return (true);
2579 }
2580
2581 /** Get the extent descriptor of the last fragmented extent from the
2582 free_frag list.
2583 @param[in] header Tablespace header
2584 @param[in] page_size Page size
2585 @param[in,out] mtr Mini-transaction
2586 @return the extent descriptor, or NULL if none */
2587 static xdes_t *fsp_get_last_free_frag_extent(fsp_header_t *header,
2588 const page_size_t &page_size,
2589 mtr_t *mtr) {
2590 space_id_t space;
2591 fil_addr_t node;
2592 xdes_t *descr;
2593
2594 node = flst_get_last(header + FSP_FREE_FRAG, mtr);
2595
2596 if (fil_addr_is_null(node)) {
2597 return (nullptr);
2598 }
2599
2600 space = mach_read_from_4(header + FSEG_HDR_SPACE);
2601 descr = xdes_lst_get_descriptor(space, page_size, node, mtr);
2602 ut_ad(xdes_get_state(descr, mtr) == XDES_FREE_FRAG);
2603
2604 return (descr);
2605 }
2606
2607 /** Allocate an extent from free fragment extent to a segment.
2608 @param[in] space Space id
2609 @param[in,out] inode Segment to which extent is leased
2610 @param[in] page_size Page size
2611 @param[in,out] mtr Mini-transaction
2612 @return extent descriptor or NULL */
2613 static xdes_t *fsp_alloc_xdes_free_frag(space_id_t space, fseg_inode_t *inode,
2614 const page_size_t &page_size,
2615 mtr_t *mtr) {
2616 xdes_t *descr;
2617 ib_id_t seg_id;
2618 ulint n_used;
2619
2620 ut_ad(mtr);
2621 ut_ad(mtr_memo_contains(mtr, fil_space_get_latch(space), MTR_MEMO_X_LOCK));
2622
2623 fsp_header_t *header = fsp_get_space_header(space, page_size, mtr);
2624
2625 /* If available, take an extent from the free_frag list. */
2626 descr = fsp_get_last_free_frag_extent(header, page_size, mtr);
2627 if (!descr) {
2628 return (nullptr);
2629 }
2630
2631 if (!xdes_is_leasable(descr, page_size, mtr)) {
2632 return (nullptr);
2633 }
2634 ut_ad(xdes_get_n_used(descr, mtr) == XDES_FRAG_N_USED);
2635
2636 /* Remove from the FSP_FREE_FRAG list */
2637 flst_remove(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr);
2638 n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr);
2639 mlog_write_ulint(header + FSP_FRAG_N_USED, n_used - XDES_FRAG_N_USED,
2640 MLOG_4BYTES, mtr);
2641
2642 /* Transition the extent (and its ownership) to the segment. */
2643 seg_id = mach_read_from_8(inode + FSEG_ID);
2644 xdes_set_segment_id(descr, seg_id, XDES_FSEG_FRAG, mtr);
2645
2646 /* Add to the end of FSEG_NOT_FULL list. */
2647 flst_add_last(inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
2648
2649 File_segment_inode fseg_inode(space, page_size, inode, mtr);
2650 n_used = fseg_inode.read_not_full_n_used();
2651 fseg_inode.write_not_full_n_used(
2652 static_cast<uint32_t>(n_used + XDES_FRAG_N_USED));
2653
2654 return (descr);
2655 }
2656
2657 /** Allocates a free extent for the segment: looks first in the free list of
2658 the segment, then tries to allocate from the space free list.
2659 NOTE that the extent returned still resides in the segment free list, it is
2660 not yet taken off it!
2661 @param[in] inode Segment inode
2662 @param[in] space Space id
2663 @param[in] page_size Page size
2664 @param[in,out] mtr Mini-transaction
2665 @retval NULL if no page could be allocated
2666 @retval block rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
2667 (init_mtr == mtr, or the page was not previously freed in mtr),
2668 returned block is not allocated nor initialized otherwise */
2669 static xdes_t *fseg_alloc_free_extent(fseg_inode_t *inode, space_id_t space,
2670 const page_size_t &page_size,
2671 mtr_t *mtr) {
2672 xdes_t *descr;
2673 ib_id_t seg_id;
2674 fil_addr_t first;
2675
2676 ut_ad(!((page_offset(inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
2677 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2678 ut_d(fsp_space_modify_check(space, mtr));
2679
2680 if (flst_get_len(inode + FSEG_FREE) > 0) {
2681 /* Segment free list is not empty, allocate from it */
2682
2683 first = flst_get_first(inode + FSEG_FREE, mtr);
2684
2685 descr = xdes_lst_get_descriptor(space, page_size, first, mtr);
2686 } else {
2687 /* Segment free list was empty. */
2688
2689 /* Check if we can allocate an extent from free frag
2690 list of tablespace. */
2691 descr = fsp_alloc_xdes_free_frag(space, inode, page_size, mtr);
2692
2693 if (descr != nullptr) {
2694 return (descr);
2695 }
2696
2697 /* Allocate from space */
2698 descr = fsp_alloc_free_extent(space, page_size, 0, mtr);
2699
2700 if (descr == nullptr) {
2701 return (nullptr);
2702 }
2703
2704 seg_id = mach_read_from_8(inode + FSEG_ID);
2705
2706 xdes_set_segment_id(descr, seg_id, XDES_FSEG, mtr);
2707 flst_add_last(inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr);
2708
2709 /* Try to fill the segment free list */
2710 fseg_fill_free_list(inode, space, page_size,
2711 xdes_get_offset(descr) + FSP_EXTENT_SIZE, mtr);
2712 }
2713
2714 return (descr);
2715 }
2716
2717 static buf_block_t *fseg_alloc_free_page_low(
2718 fil_space_t *space, const page_size_t &page_size, fseg_inode_t *seg_inode,
2719 page_no_t hint, byte direction, rw_lock_type_t rw_latch, mtr_t *mtr,
2720 mtr_t *init_mtr IF_DEBUG(, bool has_done_reservation)) {
2721 fsp_header_t *space_header;
2722 ib_id_t seg_id;
2723 ulint used;
2724 ulint reserved;
2725 xdes_t *descr; /*!< extent of the hinted page */
2726 page_no_t ret_page = FIL_NULL; /*!< the allocated page offset, FIL_NULL
2727 if could not be allocated */
2728 xdes_t *ret_descr = nullptr; /*!< the extent of the allocated page */
2729 ulint n;
2730 const space_id_t space_id = space->id;
2731
2732 ut_ad(mtr);
2733 ut_ad((direction >= FSP_UP) && (direction <= FSP_NO_DIR));
2734 ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
2735 ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
2736 ut_ad(space->purpose == FIL_TYPE_TEMPORARY ||
2737 space->purpose == FIL_TYPE_TABLESPACE);
2738
2739 seg_id = mach_read_from_8(seg_inode + FSEG_ID);
2740
2741 ut_ad(seg_id);
2742 ut_d(fsp_space_modify_check(space_id, mtr));
2743 ut_ad(fil_page_get_type(page_align(seg_inode)) == FIL_PAGE_INODE);
2744
2745 reserved =
2746 fseg_n_reserved_pages_low(space_id, page_size, seg_inode, &used, mtr);
2747
2748 space_header = fsp_get_space_header(space_id, page_size, mtr);
2749
2750 descr = xdes_get_descriptor_with_space_hdr(space_header, space_id, hint, mtr);
2751 if (descr == nullptr) {
2752 /* Hint outside space or too high above free limit: reset
2753 hint */
2754 /* The file space header page is always allocated. */
2755 hint = 0;
2756 descr = xdes_get_descriptor(space_id, hint, page_size, mtr);
2757 }
2758
2759 /* In the big if-else below we look for ret_page and ret_descr */
2760 /*-------------------------------------------------------------*/
2761 if (xdes_in_segment(descr, seg_id, mtr) &&
2762 (xdes_mtr_get_bit(descr, XDES_FREE_BIT, hint % FSP_EXTENT_SIZE, mtr) ==
2763 true)) {
2764 take_hinted_page:
2765 /* 1. We can take the hinted page
2766 =================================*/
2767 ret_descr = descr;
2768 ret_page = hint;
2769 /* Skip the check for extending the tablespace. If the
2770 page hint were not within the size of the tablespace,
2771 we would have got (descr == NULL) above and reset the hint. */
2772 goto got_hinted_page;
2773 /*-----------------------------------------------------------*/
2774 }
2775 if (xdes_get_state(descr, mtr) == XDES_FREE &&
2776 reserved - used < reserved * (fseg_reserve_pct / 100) &&
2777 used >= FSEG_FRAG_LIMIT) {
2778 /* 2. We allocate the free extent from space and can take
2779 =========================================================
2780 the hinted page
2781 ===============*/
2782 ret_descr = fsp_alloc_free_extent(space_id, page_size, hint, mtr);
2783
2784 ut_a(ret_descr == descr);
2785
2786 xdes_set_segment_id(ret_descr, seg_id, XDES_FSEG, mtr);
2787 flst_add_last(seg_inode + FSEG_FREE, ret_descr + XDES_FLST_NODE, mtr);
2788
2789 /* Try to fill the segment free list */
2790 fseg_fill_free_list(seg_inode, space_id, page_size, hint + FSP_EXTENT_SIZE,
2791 mtr);
2792 goto take_hinted_page;
2793 /*-----------------------------------------------------------*/
2794 }
2795 if (direction != FSP_NO_DIR &&
2796 reserved - used < reserved * (fseg_reserve_pct / 100) &&
2797 used >= FSEG_FRAG_LIMIT) {
2798 ret_descr = fseg_alloc_free_extent(seg_inode, space_id, page_size, mtr);
2799 if (ret_descr) {
2800 /* 3. We take any free extent (which was already assigned above
2801 ===============================================================
2802 in the if-condition to ret_descr) and take the lowest or
2803 ========================================================
2804 highest page in it, depending on the direction
2805 ==============================================*/
2806 ret_page = xdes_get_offset(ret_descr);
2807
2808 if (direction == FSP_DOWN) {
2809 ret_page += FSP_EXTENT_SIZE - 1;
2810 } else if (xdes_get_state(ret_descr, mtr) == XDES_FSEG_FRAG) {
2811 ret_page += xdes_find_bit(ret_descr, XDES_FREE_BIT, true, 0, mtr);
2812 }
2813
2814 ut_ad(!has_done_reservation || ret_page != FIL_NULL);
2815 /*-----------------------------------------------------------*/
2816 }
2817 }
2818 if (ret_page == FIL_NULL) {
2819 if (xdes_in_segment(descr, seg_id, mtr) && (!xdes_is_full(descr, mtr))) {
2820 /* 4. We can take the page from the same extent as the
2821 ======================================================
2822 hinted page (and the extent already belongs to the
2823 ==================================================
2824 segment)
2825 ========*/
2826 ret_descr = descr;
2827 ret_page = xdes_get_offset(ret_descr) +
2828 xdes_find_bit(ret_descr, XDES_FREE_BIT, true,
2829 hint % FSP_EXTENT_SIZE, mtr);
2830 ut_ad(!has_done_reservation || ret_page != FIL_NULL);
2831 /*-----------------------------------------------------------*/
2832 } else if (used < reserved) {
2833 /* 5. We take any unused page from the segment
2834 ==============================================*/
2835 fil_addr_t first;
2836
2837 if (flst_get_len(seg_inode + FSEG_NOT_FULL) > 0) {
2838 first = flst_get_first(seg_inode + FSEG_NOT_FULL, mtr);
2839 } else if (flst_get_len(seg_inode + FSEG_FREE) > 0) {
2840 first = flst_get_first(seg_inode + FSEG_FREE, mtr);
2841 } else {
2842 ut_ad(!has_done_reservation);
2843 return (nullptr);
2844 }
2845
2846 ret_descr = xdes_lst_get_descriptor(space_id, page_size, first, mtr);
2847 ret_page = xdes_get_offset(ret_descr) +
2848 xdes_find_bit(ret_descr, XDES_FREE_BIT, true, 0, mtr);
2849 ut_ad(!has_done_reservation || ret_page != FIL_NULL);
2850 /*-----------------------------------------------------------*/
2851 } else if (used < FSEG_FRAG_LIMIT) {
2852 /* 6. We allocate an individual page from the space
2853 ===================================================*/
2854 buf_block_t *block = fsp_alloc_free_page(space_id, page_size, hint,
2855 rw_latch, mtr, init_mtr);
2856
2857 ut_ad(!has_done_reservation || block != nullptr);
2858
2859 if (block != nullptr) {
2860 /* Put the page in the fragment page array of the
2861 segment */
2862 n = fseg_find_free_frag_page_slot(seg_inode, mtr);
2863 ut_a(n != ULINT_UNDEFINED);
2864
2865 fseg_set_nth_frag_page_no(seg_inode, n, block->page.id.page_no(), mtr);
2866 }
2867
2868 /* fsp_alloc_free_page() invoked fsp_init_file_page()
2869 already. */
2870 return (block);
2871 /*-----------------------------------------------------------*/
2872 } else {
2873 /* 7. We allocate a new extent and take its first page
2874 ======================================================*/
2875 ret_descr = fseg_alloc_free_extent(seg_inode, space_id, page_size, mtr);
2876
2877 if (ret_descr == nullptr) {
2878 ret_page = FIL_NULL;
2879 ut_ad(!has_done_reservation);
2880 } else {
2881 const xdes_state_t state = xdes_get_state(ret_descr, mtr);
2882 ret_page = xdes_get_offset(ret_descr);
2883
2884 if (state == XDES_FSEG_FRAG) {
2885 ret_page += xdes_find_bit(ret_descr, XDES_FREE_BIT, true, 0, mtr);
2886 }
2887
2888 ut_ad(!has_done_reservation || ret_page != FIL_NULL);
2889 }
2890 }
2891 }
2892
2893 if (ret_page == FIL_NULL) {
2894 /* Page could not be allocated */
2895
2896 ut_ad(!has_done_reservation);
2897 return (nullptr);
2898 }
2899
2900 if (space->size <= ret_page && !fsp_is_system_or_temp_tablespace(space_id)) {
2901 /* It must be that we are extending a single-table
2902 tablespace whose size is still < 64 pages */
2903
2904 if (ret_page >= FSP_EXTENT_SIZE) {
2905 ib::error(ER_IB_MSG_420)
2906 << "Error (2): trying to extend"
2907 " a single-table tablespace "
2908 << space_id << " by single page(s) though the"
2909 << " space size " << space->size << ". Page no " << ret_page << ".";
2910 ut_ad(!has_done_reservation);
2911 return (nullptr);
2912 }
2913
2914 if (!fsp_try_extend_data_file_with_pages(space, ret_page, space_header,
2915 mtr)) {
2916 /* No disk space left */
2917 ut_ad(!has_done_reservation);
2918 return (nullptr);
2919 }
2920 }
2921
2922 got_hinted_page:
2923 /* ret_descr == NULL if the block was allocated from free_frag
2924 (XDES_FREE_FRAG) */
2925 if (ret_descr != nullptr) {
2926 /* At this point we know the extent and the page offset.
2927 The extent is still in the appropriate list (FSEG_NOT_FULL
2928 or FSEG_FREE), and the page is not yet marked as used. */
2929
2930 ut_ad(xdes_get_descriptor(space_id, ret_page, page_size, mtr) == ret_descr);
2931
2932 ut_ad(xdes_mtr_get_bit(ret_descr, XDES_FREE_BIT, ret_page % FSP_EXTENT_SIZE,
2933 mtr));
2934
2935 fseg_mark_page_used(space_id, page_size, seg_inode, ret_page, ret_descr,
2936 mtr);
2937 }
2938
2939 /* Exclude Encryption flag as it might have been changed In Memory flags but
2940 not on disk. */
2941 ut_ad(!((space->flags ^ mach_read_from_4(FSP_SPACE_FLAGS + space_header)) &
2942 ~(FSP_FLAGS_MASK_ENCRYPTION)));
2943
2944 return (fsp_page_create(page_id_t(space_id, ret_page), page_size, rw_latch,
2945 mtr, init_mtr));
2946 }
2947
2948 /** Allocates a single free page from a segment. This function implements
2949 the intelligent allocation strategy which tries to minimize file space
2950 fragmentation.
2951 @param[in,out] seg_header Segment header
2952 @param[in] hint Hint of which page would be desirable
2953 @param[in,out] direction If the new page is needed because of an index page
2954 split, and records are inserted there in order, into which direction they go
2955 alphabetically: fsp_down, fsp_up, fsp_no_dir
2956 @param[in] has_done_reservation True if the caller has already done the
2957 reservation for the page with fsp_reserve_free_extents, then there is no need to
2958 do the check for this individual page
2959 @param[in,out] mtr Mini-transaction
2960 @param[in,out] init_mtr mtr or another mini-transaction in which the page should
2961 be initialized. if init_mtr!=mtr, but the page is already latched in mtr, do not
2962 initialize the page.
2963 @retval NULL if no page could be allocated
2964 @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
2965 (init_mtr == mtr, or the page was not previously freed in mtr),
2966 returned block is not allocated nor initialized otherwise */
2967 buf_block_t *fseg_alloc_free_page_general(fseg_header_t *seg_header,
2968 page_no_t hint, byte direction,
2969 bool has_done_reservation, mtr_t *mtr,
2970 mtr_t *init_mtr) {
2971 fseg_inode_t *inode;
2972 space_id_t space_id;
2973 buf_block_t *iblock;
2974 buf_block_t *block;
2975 ulint n_reserved = 0;
2976
2977 space_id = page_get_space_id(page_align(seg_header));
2978
2979 fil_space_t *space = fil_space_get(space_id);
2980
2981 mtr_x_lock_space(space, mtr);
2982
2983 const page_size_t page_size(space->flags);
2984
2985 if (rw_lock_get_x_lock_count(&space->latch) == 1) {
2986 /* This thread did not own the latch before this call: free
2987 excess pages from the insert buffer free list */
2988
2989 if (space_id == IBUF_SPACE_ID) {
2990 ibuf_free_excess_pages();
2991 }
2992 }
2993
2994 inode = fseg_inode_get(seg_header, space_id, page_size, mtr, &iblock);
2995 buf_block_reset_page_type_on_mismatch(*iblock, FIL_PAGE_INODE, *mtr);
2996
2997 if (!has_done_reservation &&
2998 !fsp_reserve_free_extents(&n_reserved, space_id, 2, FSP_NORMAL, mtr)) {
2999 return (nullptr);
3000 }
3001
3002 block = fseg_alloc_free_page_low(space, page_size, inode, hint, direction,
3003 RW_X_LATCH, mtr,
3004 init_mtr IF_DEBUG(, has_done_reservation));
3005
3006 /* The allocation cannot fail if we have already reserved a
3007 space for the page. */
3008 ut_ad(!has_done_reservation || block != nullptr);
3009
3010 if (!has_done_reservation) {
3011 fil_space_release_free_extents(space_id, n_reserved);
3012 }
3013
3014 return (block);
3015 }
3016
3017 /** Check that we have at least n_pages frag pages free in the first extent
3018 of a single-table tablespace, and they are also physically initialized to
3019 the data file. That is we have already extended the data file so that those
3020 pages are inside the data file. If not, this function extends the tablespace
3021 with pages.
3022 @param[in,out] space Tablespace
3023 @param[in,out] space_header Tablespace header, x-latched
3024 @param[in] size Size of the tablespace in pages,
3025 must be less than FSP_EXTENT_SIZE
3026 @param[in,out] mtr Mini-transaction
3027 @param[in] n_pages Number of pages to reserve
3028 @return true if there were at least n_pages free pages, or we were able
3029 to extend */
3030 static bool fsp_reserve_free_pages(fil_space_t *space,
3031 fsp_header_t *space_header, page_no_t size,
3032 mtr_t *mtr, page_no_t n_pages) {
3033 xdes_t *descr;
3034
3035 ut_a(!fsp_is_system_tablespace(space->id));
3036 ut_a(!fsp_is_global_temporary(space->id));
3037
3038 const page_size_t page_size(space->flags);
3039
3040 ut_a(size < FSP_EXTENT_SIZE ||
3041 (space->autoextend_size_in_bytes > 0 &&
3042 (size * page_size.physical()) <= space->autoextend_size_in_bytes));
3043
3044 descr = xdes_get_descriptor_with_space_hdr(space_header, space->id, 0, mtr);
3045 page_no_t n_used = xdes_get_n_used(descr, mtr);
3046
3047 ut_a(n_used <= size);
3048
3049 return (size >= n_used + n_pages ||
3050 fsp_try_extend_data_file_with_pages(space, n_used + n_pages - 1,
3051 space_header, mtr));
3052 }
3053
3054 /** Reserves free pages from a tablespace. All mini-transactions which may
3055 use several pages from the tablespace should call this function beforehand
3056 and reserve enough free extents so that they certainly will be able
3057 to do their operation, like a B-tree page split, fully. Reservations
3058 must be released with function fil_space_release_free_extents!
3059
3060 The alloc_type below has the following meaning: FSP_NORMAL means an
3061 operation which will probably result in more space usage, like an
3062 insert in a B-tree; FSP_UNDO means allocation to undo logs: if we are
3063 deleting rows, then this allocation will in the long run result in
3064 less space usage (after a purge); FSP_CLEANING means allocation done
3065 in a physical record delete (like in a purge) or other cleaning operation
3066 which will result in less space usage in the long run. We prefer the latter
3067 two types of allocation: when space is scarce, FSP_NORMAL allocations
3068 will not succeed, but the latter two allocations will succeed, if possible.
3069 The purpose is to avoid dead end where the database is full but the
3070 user cannot free any space because these freeing operations temporarily
3071 reserve some space.
3072
3073 Single-table tablespaces whose size is < FSP_EXTENT_SIZE pages are a special
3074 case. In this function we would liberally reserve several extents for
3075 every page split or merge in a B-tree. But we do not want to waste disk space
3076 if the table only occupies < FSP_EXTENT_SIZE pages. That is why we apply
3077 different rules in that special case, just ensuring that there are n_pages
3078 free pages available.
3079
3080 @param[out] n_reserved Number of extents actually reserved; if we
3081 return true and the tablespace size is <
3082 FSP_EXTENT_SIZE pages, then this can be 0,
3083 otherwise it is n_ext
3084 @param[in] space_id Tablespace identifier
3085 @param[in] n_ext Number of extents to reserve
3086 @param[in] alloc_type Page reservation type (FSP_BLOB, etc)
3087 @param[in,out] mtr Mini-transaction
3088 @param[in] n_pages For small tablespaces (tablespace size is
3089 less than FSP_EXTENT_SIZE), number of free
3090 pages to reserve.
3091 @return true if we were able to make the reservation */
3092 bool fsp_reserve_free_extents(ulint *n_reserved, space_id_t space_id,
3093 ulint n_ext, fsp_reserve_t alloc_type, mtr_t *mtr,
3094 page_no_t n_pages) {
3095 fsp_header_t *space_header;
3096 ulint n_free_list_ext;
3097 page_no_t free_limit;
3098 page_no_t size;
3099 ulint n_free;
3100 ulint n_free_up;
3101 ulint reserve;
3102 DBUG_TRACE;
3103
3104 *n_reserved = n_ext;
3105
3106 fil_space_t *space = fil_space_get(space_id);
3107
3108 mtr_x_lock_space(space, mtr);
3109
3110 const page_size_t page_size(space->flags);
3111
3112 buf_block_t *block = nullptr;
3113 space_header = fsp_get_space_header_block(space_id, page_size, mtr, &block);
3114
3115 ut_ad(block != nullptr);
3116 try_again:
3117 size = mach_read_from_4(space_header + FSP_SIZE);
3118 ut_ad(size == space->size_in_header);
3119
3120 if (space->autoextend_size_in_bytes > 0) {
3121 page_no_t autoextend_size_pages =
3122 space->autoextend_size_in_bytes / page_size.physical();
3123
3124 /* If the tablespace is smaller than the autoextend_size, extend it first
3125 to make the size same as autoextend_size. */
3126 if (size < autoextend_size_pages) {
3127 goto try_to_extend;
3128 }
3129
3130 if (size == autoextend_size_pages) {
3131 /* Get the number of used pages */
3132 xdes_t *descr =
3133 xdes_get_descriptor_with_space_hdr(space_header, space->id, 0, mtr);
3134 page_no_t n_used = xdes_get_n_used(descr, mtr);
3135 if (n_used < autoextend_size_pages &&
3136 n_pages < (autoextend_size_pages - (FSP_EXTENT_SIZE / 2))) {
3137 *n_reserved = 0;
3138 return fsp_reserve_free_pages(space, space_header, size, mtr, n_pages);
3139 }
3140 }
3141 } else if (size < FSP_EXTENT_SIZE && n_pages < FSP_EXTENT_SIZE / 2) {
3142 /* Use different rules for small single-table tablespaces */
3143 *n_reserved = 0;
3144 bool success =
3145 fsp_reserve_free_pages(space, space_header, size, mtr, n_pages);
3146 if (success) {
3147 buf_page_t *page = &block->page;
3148 /* Move the header page to the end of the LRU so that
3149 it gets flushed at the earliest. */
3150 buf_page_make_old(page);
3151 }
3152 return success;
3153 }
3154
3155 n_free_list_ext = flst_get_len(space_header + FSP_FREE);
3156 ut_ad(space->free_len == n_free_list_ext);
3157
3158 free_limit = mtr_read_ulint(space_header + FSP_FREE_LIMIT, MLOG_4BYTES, mtr);
3159 ut_ad(space->free_limit == free_limit);
3160
3161 /* Below we play safe when counting free extents above the free limit:
3162 some of them will contain extent descriptor pages, and therefore
3163 will not be free extents */
3164
3165 if (size >= free_limit) {
3166 n_free_up = (size - free_limit) / FSP_EXTENT_SIZE;
3167 } else {
3168 ut_ad(alloc_type == FSP_BLOB);
3169 n_free_up = 0;
3170 }
3171
3172 if (n_free_up > 0) {
3173 n_free_up--;
3174 n_free_up -= n_free_up / (page_size.physical() / FSP_EXTENT_SIZE);
3175 }
3176
3177 n_free = n_free_list_ext + n_free_up;
3178
3179 switch (alloc_type) {
3180 case FSP_NORMAL:
3181 /* We reserve 1 extent + 0.5 % of the space size to undo logs
3182 and 1 extent + 0.5 % to cleaning operations; NOTE: this source
3183 code is duplicated in the function below! */
3184
3185 reserve = 2 + ((size / FSP_EXTENT_SIZE) * 2) / 200;
3186
3187 if (n_free <= reserve + n_ext) {
3188 goto try_to_extend;
3189 }
3190 break;
3191 case FSP_UNDO:
3192 /* We reserve 0.5 % of the space size to cleaning operations */
3193
3194 reserve = 1 + ((size / FSP_EXTENT_SIZE) * 1) / 200;
3195
3196 if (n_free <= reserve + n_ext) {
3197 goto try_to_extend;
3198 }
3199 break;
3200 case FSP_CLEANING:
3201 case FSP_BLOB:
3202 break;
3203 default:
3204 ut_error;
3205 }
3206
3207 if (fil_space_reserve_free_extents(space_id, n_free, n_ext)) {
3208 return true;
3209 }
3210 try_to_extend:
3211 if (fsp_try_extend_data_file(space, space_header, mtr)) {
3212 buf_page_t *page = &block->page;
3213 /* Move the header page to the end of the LRU so that
3214 it gets flushed at the earliest. */
3215 buf_page_make_old(page);
3216 goto try_again;
3217 }
3218
3219 return false;
3220 }
3221
3222 /** Calculate how many KiB of new data we will be able to insert to the
3223 tablespace without running out of space.
3224 @param[in] space_id tablespace ID
3225 @return available space in KiB
3226 @retval UINTMAX_MAX if unknown */
3227 uintmax_t fsp_get_available_space_in_free_extents(space_id_t space_id) {
3228 fil_space_t *space = fil_space_acquire(space_id);
3229
3230 if (space == nullptr) {
3231 return (UINTMAX_MAX);
3232 }
3233
3234 auto n_free_extents = fsp_get_available_space_in_free_extents(space);
3235
3236 fil_space_release(space);
3237
3238 return (n_free_extents);
3239 }
3240
3241 /** Calculate how many KiB of new data we will be able to insert to the
3242 tablespace without running out of space. Start with a space object that has
3243 been acquired by the caller who holds it for the calculation,
3244 @param[in] space tablespace object from fil_space_acquire()
3245 @return available space in KiB */
3246 uintmax_t fsp_get_available_space_in_free_extents(const fil_space_t *space) {
3247 ut_ad(space->n_pending_ops > 0);
3248
3249 ulint size_in_header = space->size_in_header;
3250 if (size_in_header < FSP_EXTENT_SIZE) {
3251 return (0); /* TODO: count free frag pages and
3252 return a value based on that */
3253 }
3254
3255 /* Below we play safe when counting free extents above the free limit:
3256 some of them will contain extent descriptor pages, and therefore
3257 will not be free extents */
3258 ut_ad(size_in_header >= space->free_limit);
3259 ulint n_free_up = (size_in_header - space->free_limit) / FSP_EXTENT_SIZE;
3260
3261 page_size_t page_size(space->flags);
3262 if (n_free_up > 0) {
3263 n_free_up--;
3264 n_free_up -= n_free_up / (page_size.physical() / FSP_EXTENT_SIZE);
3265 }
3266
3267 /* We reserve 1 extent + 0.5 % of the space size to undo logs
3268 and 1 extent + 0.5 % to cleaning operations; NOTE: this source
3269 code is duplicated in the function above! */
3270
3271 ulint reserve = 2 + ((size_in_header / FSP_EXTENT_SIZE) * 2) / 200;
3272 ulint n_free = space->free_len + n_free_up;
3273
3274 if (reserve > n_free) {
3275 return (0);
3276 }
3277
3278 return (static_cast<uintmax_t>(n_free - reserve) * FSP_EXTENT_SIZE *
3279 (page_size.physical() / 1024));
3280 }
3281
3282 static void fseg_mark_page_used(space_id_t space_id,
3283 const page_size_t &page_size,
3284 fseg_inode_t *seg_inode, page_no_t page,
3285 xdes_t *descr, mtr_t *mtr) {
3286 uint32_t not_full_n_used;
3287
3288 ut_ad(fil_page_get_type(page_align(seg_inode)) == FIL_PAGE_INODE);
3289 ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
3290 ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3291
3292 ut_ad(mach_read_from_8(seg_inode + FSEG_ID) ==
3293 xdes_get_segment_id(descr, mtr));
3294
3295 if (xdes_is_free(descr, mtr)) {
3296 /* We move the extent from the free list to the
3297 NOT_FULL list */
3298 flst_remove(seg_inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr);
3299 flst_add_last(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
3300 }
3301
3302 ut_ad(xdes_mtr_get_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, mtr));
3303
3304 /* We mark the page as used */
3305 xdes_set_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, false, mtr);
3306
3307 File_segment_inode fseg_inode(space_id, page_size, seg_inode, mtr);
3308
3309 not_full_n_used = fseg_inode.read_not_full_n_used();
3310 not_full_n_used++;
3311 fseg_inode.write_not_full_n_used(not_full_n_used);
3312
3313 if (xdes_is_full(descr, mtr)) {
3314 /* We move the extent from the NOT_FULL list to the
3315 FULL list */
3316 flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
3317 flst_add_last(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr);
3318
3319 ut_ad(not_full_n_used >= FSP_EXTENT_SIZE);
3320 fseg_inode.write_not_full_n_used(not_full_n_used - FSP_EXTENT_SIZE);
3321 }
3322 }
3323
3324 /** Frees a single page of a segment.
3325 @param[in] seg_inode Segment inode
3326 @param[in] page_id Page id
3327 @param[in] page_size Page size
3328 @param[in] ahi Whether we may need to drop the adaptive
3329 hash index
3330 @param[in,out] mtr Mini-transaction */
3331 static void fseg_free_page_low(fseg_inode_t *seg_inode,
3332 const page_id_t &page_id,
3333 const page_size_t &page_size, bool ahi,
3334 mtr_t *mtr) {
3335 xdes_t *descr;
3336 uint32_t not_full_n_used;
3337 ib_id_t descr_id;
3338 ib_id_t seg_id;
3339 ulint i;
3340 DBUG_TRACE;
3341
3342 ut_ad(seg_inode != nullptr);
3343 ut_ad(mtr != nullptr);
3344 ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3345 ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
3346 ut_d(fsp_space_modify_check(page_id.space(), mtr));
3347
3348 /* Drop search system page hash index if the page is found in
3349 the pool and is hashed */
3350
3351 if (ahi) {
3352 btr_search_drop_page_hash_when_freed(page_id, page_size);
3353 }
3354
3355 descr =
3356 xdes_get_descriptor(page_id.space(), page_id.page_no(), page_size, mtr);
3357
3358 if (xdes_mtr_get_bit(descr, XDES_FREE_BIT,
3359 page_id.page_no() % FSP_EXTENT_SIZE, mtr)) {
3360 fputs("InnoDB: Dump of the tablespace extent descriptor: ", stderr);
3361 ut_print_buf(stderr, descr, 40);
3362
3363 ib::error(ER_IB_MSG_421) << "InnoDB is trying to free page " << page_id
3364 << " though it is already marked as free in the"
3365 " tablespace! The tablespace free space info is"
3366 " corrupt. You may need to dump your tables and"
3367 " recreate the whole database!";
3368 crash:
3369 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_422) << FORCE_RECOVERY_MSG;
3370 }
3371
3372 xdes_state_t state = xdes_get_state(descr, mtr);
3373
3374 switch (state) {
3375 case XDES_FSEG:
3376 case XDES_FSEG_FRAG:
3377 /* The page belongs to a segment */
3378 break;
3379 case XDES_FREE_FRAG:
3380 case XDES_FULL_FRAG:
3381 /* The page is in the fragment pages of the segment */
3382
3383 for (i = 0;; i++) {
3384 const page_no_t page_no = fseg_get_nth_frag_page_no(seg_inode, i, mtr);
3385 if (page_no == page_id.page_no()) {
3386 fseg_set_nth_frag_page_no(seg_inode, i, FIL_NULL, mtr);
3387 break;
3388 }
3389 }
3390
3391 fsp_free_page(page_id, page_size, mtr);
3392
3393 return;
3394 case XDES_FREE:
3395 case XDES_NOT_INITED:
3396 ut_error;
3397 }
3398
3399 /* If we get here, the page is in some extent of the segment */
3400 File_segment_inode fseg_inode(page_id.space(), page_size, seg_inode, mtr);
3401
3402 descr_id = xdes_get_segment_id(descr);
3403 seg_id = mach_read_from_8(seg_inode + FSEG_ID);
3404
3405 if (UNIV_UNLIKELY(descr_id != seg_id)) {
3406 fputs("InnoDB: Dump of the tablespace extent descriptor: ", stderr);
3407 ut_print_buf(stderr, descr, 40);
3408 fputs("\nInnoDB: Dump of the segment inode: ", stderr);
3409 ut_print_buf(stderr, seg_inode, 40);
3410 putc('\n', stderr);
3411
3412 ib::error(ER_IB_MSG_423)
3413 << "InnoDB is trying to free page " << page_id
3414 << ", which does not belong to segment " << descr_id
3415 << " but belongs to segment " << seg_id << ".";
3416 goto crash;
3417 }
3418
3419 not_full_n_used = fseg_inode.read_not_full_n_used();
3420 if (xdes_is_full(descr, mtr)) {
3421 /* The fragment is full: move it to another list */
3422 flst_remove(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr);
3423 flst_add_last(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
3424 not_full_n_used += FSP_EXTENT_SIZE - 1;
3425 } else {
3426 ut_a(not_full_n_used > 0);
3427 not_full_n_used -= 1;
3428 }
3429
3430 const page_no_t bit = page_id.page_no() % FSP_EXTENT_SIZE;
3431
3432 xdes_set_bit(descr, XDES_FREE_BIT, bit, true, mtr);
3433 xdes_set_bit(descr, XDES_CLEAN_BIT, bit, true, mtr);
3434
3435 page_no_t n_used = xdes_get_n_used(descr, mtr);
3436
3437 ut_ad(state != XDES_FSEG_FRAG || (bit != 0 && bit != 1));
3438 ut_ad(state != XDES_FSEG_FRAG || n_used > 1);
3439 ut_ad(xdes_is_leasable(descr, page_size, mtr) ==
3440 (state == XDES_FSEG_FRAG && n_used == XDES_FRAG_N_USED));
3441
3442 /* A leased fragment extent might have no more pages belonging to
3443 the segment.*/
3444 if (state == XDES_FSEG_FRAG && n_used == XDES_FRAG_N_USED) {
3445 n_used = 0;
3446
3447 ut_ad(not_full_n_used >= XDES_FRAG_N_USED);
3448 not_full_n_used -= XDES_FRAG_N_USED;
3449 }
3450
3451 if (n_used == 0) {
3452 /* The extent has become free: free it to space */
3453 flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
3454 fsp_free_extent(page_id, page_size, mtr);
3455 }
3456
3457 /* Update the FSEG_NOT_FULL_N_USED field after modifying the list. */
3458 fseg_inode.write_not_full_n_used(not_full_n_used);
3459 }
3460
3461 /** Frees a single page of a segment.
3462 @param[in] seg_header Segment header
3463 @param[in] space_id Space id
3464 @param[in] page Page offset
3465 @param[in] ahi Whether we may need to drop the adaptive hash index
3466 @param[in,out] mtr Mini-transaction */
3467 void fseg_free_page(fseg_header_t *seg_header, space_id_t space_id,
3468 page_no_t page, bool ahi, mtr_t *mtr) {
3469 DBUG_TRACE;
3470 fseg_inode_t *seg_inode;
3471 buf_block_t *iblock;
3472
3473 fil_space_t *space = fil_space_get(space_id);
3474
3475 mtr_x_lock_space(space, mtr);
3476
3477 const page_size_t page_size(space->flags);
3478
3479 DBUG_LOG("fseg_free_page", "space_id: " << space_id << ", page_no: " << page);
3480
3481 seg_inode = fseg_inode_get(seg_header, space_id, page_size, mtr, &iblock);
3482 buf_block_reset_page_type_on_mismatch(*iblock, FIL_PAGE_INODE, *mtr);
3483
3484 const page_id_t page_id(space_id, page);
3485
3486 fseg_free_page_low(seg_inode, page_id, page_size, ahi, mtr);
3487
3488 ut_d(buf_page_set_file_page_was_freed(page_id));
3489 }
3490
3491 /** Checks if a single page of a segment is free.
3492 @return true if free */
3493 bool fseg_page_is_free(fseg_header_t *seg_header, /*!< in: segment header */
3494 space_id_t space_id, /*!< in: space id */
3495 page_no_t page) /*!< in: page offset */
3496 {
3497 mtr_t mtr;
3498 xdes_t *descr;
3499 fseg_inode_t *seg_inode;
3500
3501 fil_space_t *space = fil_space_get(space_id);
3502
3503 mtr_start(&mtr);
3504
3505 mtr_x_lock_space(space, &mtr);
3506
3507 const page_size_t page_size(space->flags);
3508
3509 seg_inode = fseg_inode_get(seg_header, space_id, page_size, &mtr);
3510
3511 ut_a(seg_inode);
3512 ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3513 ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE));
3514
3515 descr = xdes_get_descriptor(space_id, page, page_size, &mtr);
3516 ut_a(descr);
3517
3518 auto is_free =
3519 xdes_mtr_get_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, &mtr);
3520
3521 mtr_commit(&mtr);
3522
3523 return (is_free);
3524 }
3525
3526 /** Frees an extent of a segment to the space free list.
3527 @param[in] seg_inode Segment inode
3528 @param[in] space Space id
3529 @param[in] page A page in the extent
3530 @param[in] page_size Page size
3531 @param[in] ahi Whether we may need to drop the adaptive hash
3532 index
3533 @param[in,out] mtr Mini-transaction */
3534 static void fseg_free_extent(fseg_inode_t *seg_inode, space_id_t space,
3535 const page_size_t &page_size, page_no_t page,
3536 bool ahi, mtr_t *mtr) {
3537 page_no_t first_page_in_extent;
3538 xdes_t *descr;
3539 page_no_t i;
3540 File_segment_inode fseg_inode(space, page_size, seg_inode, mtr);
3541
3542 ut_ad(seg_inode != nullptr);
3543 ut_ad(mtr != nullptr);
3544
3545 descr = xdes_get_descriptor(space, page, page_size, mtr);
3546
3547 const xdes_state_t state = xdes_get_state(descr, mtr);
3548 ut_a(state == XDES_FSEG || state == XDES_FSEG_FRAG);
3549
3550 ut_a(!memcmp(descr + XDES_ID, seg_inode + FSEG_ID, 8));
3551 ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3552 ut_d(fsp_space_modify_check(space, mtr));
3553
3554 first_page_in_extent = page - (page % FSP_EXTENT_SIZE);
3555
3556 if (ahi) {
3557 for (i = state == XDES_FSEG ? 0 : XDES_FRAG_N_USED; i < FSP_EXTENT_SIZE;
3558 i++) {
3559 if (!xdes_mtr_get_bit(descr, XDES_FREE_BIT, i, mtr)) {
3560 /* Drop search system page hash index
3561 if the page is found in the pool and
3562 is hashed */
3563
3564 btr_search_drop_page_hash_when_freed(
3565 page_id_t(space, first_page_in_extent + i), page_size);
3566 }
3567 }
3568 }
3569
3570 if (xdes_is_full(descr, mtr)) {
3571 flst_remove(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr);
3572 } else if (xdes_is_free(descr, mtr)) {
3573 flst_remove(seg_inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr);
3574 } else {
3575 flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr);
3576
3577 page_no_t not_full_n_used = fseg_inode.read_not_full_n_used();
3578
3579 page_no_t descr_n_used = xdes_get_n_used(descr, mtr);
3580 ut_a(not_full_n_used >= descr_n_used);
3581 fseg_inode.write_not_full_n_used(not_full_n_used - descr_n_used);
3582 }
3583
3584 fsp_free_extent(page_id_t(space, page), page_size, mtr);
3585
3586 #ifdef UNIV_DEBUG
3587 for (i = state == XDES_FSEG ? 0 : XDES_FRAG_N_USED; i < FSP_EXTENT_SIZE;
3588 i++) {
3589 buf_page_set_file_page_was_freed(
3590 page_id_t(space, first_page_in_extent + i));
3591 }
3592 #endif /* UNIV_DEBUG */
3593 }
3594
3595 /** Frees part of a segment. This function can be used to free a segment by
3596 repeatedly calling this function in different mini-transactions. Doing
3597 the freeing in a single mini-transaction might result in too big a
3598 mini-transaction.
3599 @return true if freeing completed */
3600 bool fseg_free_step(
3601 fseg_header_t *header, /*!< in, own: segment header; NOTE: if the header
3602 resides on the first page of the frag list
3603 of the segment, this pointer becomes obsolete
3604 after the last freeing step */
3605 bool ahi, /*!< in: whether we may need to drop
3606 the adaptive hash index */
3607 mtr_t *mtr) /*!< in/out: mini-transaction */
3608 {
3609 ulint n;
3610 page_no_t page;
3611 xdes_t *descr;
3612 fseg_inode_t *inode;
3613 space_id_t space_id;
3614 page_no_t header_page;
3615
3616 DBUG_TRACE;
3617
3618 space_id = page_get_space_id(page_align(header));
3619 header_page = page_get_page_no(page_align(header));
3620
3621 fil_space_t *space = fil_space_get(space_id);
3622
3623 mtr_x_lock_space(space, mtr);
3624
3625 const page_size_t page_size(space->flags);
3626
3627 descr = xdes_get_descriptor(space_id, header_page, page_size, mtr);
3628
3629 /* Check that the header resides on a page which has not been
3630 freed yet */
3631
3632 ut_a(xdes_mtr_get_bit(descr, XDES_FREE_BIT, header_page % FSP_EXTENT_SIZE,
3633 mtr) == false);
3634 buf_block_t *iblock;
3635
3636 inode = fseg_inode_try_get(header, space_id, page_size, mtr, &iblock);
3637
3638 if (inode == nullptr) {
3639 ib::info(ER_IB_MSG_424)
3640 << "Double free of inode from " << page_id_t(space_id, header_page);
3641 return true;
3642 }
3643
3644 buf_block_reset_page_type_on_mismatch(*iblock, FIL_PAGE_INODE, *mtr);
3645 descr = fseg_get_first_extent(inode, space_id, page_size, mtr);
3646
3647 if (descr != nullptr) {
3648 /* Free the extent held by the segment */
3649 page = xdes_get_offset(descr);
3650
3651 fseg_free_extent(inode, space_id, page_size, page, ahi, mtr);
3652
3653 return false;
3654 }
3655
3656 /* Free a frag page */
3657 n = fseg_find_last_used_frag_page_slot(inode, mtr);
3658
3659 if (n == ULINT_UNDEFINED) {
3660 /* Freeing completed: free the segment inode */
3661 fsp_free_seg_inode(space_id, page_size, inode, mtr);
3662
3663 return true;
3664 }
3665
3666 fseg_free_page_low(
3667 inode, page_id_t(space_id, fseg_get_nth_frag_page_no(inode, n, mtr)),
3668 page_size, ahi, mtr);
3669
3670 n = fseg_find_last_used_frag_page_slot(inode, mtr);
3671
3672 if (n == ULINT_UNDEFINED) {
3673 /* Freeing completed: free the segment inode */
3674 fsp_free_seg_inode(space_id, page_size, inode, mtr);
3675
3676 return true;
3677 }
3678
3679 return false;
3680 }
3681
3682 /** Frees part of a segment. Differs from fseg_free_step because this function
3683 leaves the header page unfreed.
3684 @return true if freeing completed, except the header page */
3685 bool fseg_free_step_not_header(
3686 fseg_header_t *header, /*!< in: segment header which must reside on
3687 the first fragment page of the segment */
3688 bool ahi, /*!< in: whether we may need to drop
3689 the adaptive hash index */
3690 mtr_t *mtr) /*!< in/out: mini-transaction */
3691 {
3692 ulint n;
3693 xdes_t *descr;
3694 fseg_inode_t *inode;
3695 space_id_t space_id;
3696 page_no_t page_no;
3697
3698 space_id = page_get_space_id(page_align(header));
3699
3700 fil_space_t *space = fil_space_get(space_id);
3701
3702 mtr_x_lock_space(space, mtr);
3703
3704 const page_size_t page_size(space->flags);
3705 buf_block_t *iblock;
3706
3707 inode = fseg_inode_get(header, space_id, page_size, mtr, &iblock);
3708 buf_block_reset_page_type_on_mismatch(*iblock, FIL_PAGE_INODE, *mtr);
3709
3710 descr = fseg_get_first_extent(inode, space_id, page_size, mtr);
3711
3712 if (descr != nullptr) {
3713 /* Free the extent held by the segment */
3714 page_no = xdes_get_offset(descr);
3715
3716 fseg_free_extent(inode, space_id, page_size, page_no, ahi, mtr);
3717
3718 return false;
3719 }
3720
3721 /* Free a frag page */
3722
3723 n = fseg_find_last_used_frag_page_slot(inode, mtr);
3724
3725 if (n == ULINT_UNDEFINED) {
3726 ut_error;
3727 }
3728
3729 page_no = fseg_get_nth_frag_page_no(inode, n, mtr);
3730
3731 if (page_no == page_get_page_no(page_align(header))) {
3732 return true;
3733 }
3734
3735 fseg_free_page_low(inode, page_id_t(space_id, page_no), page_size, ahi, mtr);
3736
3737 return false;
3738 }
3739
3740 /** Returns the first extent descriptor for a segment.
3741 We think of the extent lists of the segment catenated in the order
3742 FSEG_FULL -> FSEG_NOT_FULL -> FSEG_FREE.
3743 @param[in] inode Segment inode
3744 @param[in] space_id Space id
3745 @param[in] page_size Page size
3746 @param[in,out] mtr Mini-transaction
3747 @return the first extent descriptor, or NULL if none */
3748 static xdes_t *fseg_get_first_extent(fseg_inode_t *inode, space_id_t space_id,
3749 const page_size_t &page_size, mtr_t *mtr) {
3750 fil_addr_t first;
3751 xdes_t *descr;
3752
3753 ut_ad(inode && mtr);
3754
3755 ut_ad(space_id == page_get_space_id(page_align(inode)));
3756 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3757
3758 first = fil_addr_null;
3759
3760 if (flst_get_len(inode + FSEG_FULL) > 0) {
3761 first = flst_get_first(inode + FSEG_FULL, mtr);
3762
3763 } else if (flst_get_len(inode + FSEG_NOT_FULL) > 0) {
3764 first = flst_get_first(inode + FSEG_NOT_FULL, mtr);
3765
3766 } else if (flst_get_len(inode + FSEG_FREE) > 0) {
3767 first = flst_get_first(inode + FSEG_FREE, mtr);
3768 }
3769
3770 if (first.page == FIL_NULL) {
3771 return (nullptr);
3772 }
3773 descr = xdes_lst_get_descriptor(space_id, page_size, first, mtr);
3774
3775 return (descr);
3776 }
3777
3778 #ifdef UNIV_BTR_PRINT
3779 /** Writes info of a segment. */
3780 static void fseg_print_low(space_id_t space_id, const page_size_t &page_size,
3781 fseg_inode_t *inode, /*!< in: segment inode */
3782 mtr_t *mtr) /*!< in/out: mini-transaction */
3783 {
3784 space_id_t space;
3785 ulint n_used;
3786 ulint n_frag;
3787 ulint n_free;
3788 ulint n_not_full;
3789 ulint n_full;
3790 ulint reserved;
3791 ulint used;
3792 page_no_t page_no;
3793 ib_id_t seg_id;
3794 File_segment_inode fseg_inode(space_id, page_size, inode, mtr);
3795
3796 ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_SX_FIX));
3797 space = page_get_space_id(page_align(inode));
3798 page_no = page_get_page_no(page_align(inode));
3799
3800 reserved = fseg_n_reserved_pages_low(space_id, page_size, inode, &used, mtr);
3801
3802 seg_id = mach_read_from_8(inode + FSEG_ID);
3803
3804 n_used = fseg_inode.read_not_full_n_used();
3805 n_frag = fseg_get_n_frag_pages(inode, mtr);
3806 n_free = flst_get_len(inode + FSEG_FREE);
3807 n_not_full = flst_get_len(inode + FSEG_NOT_FULL);
3808 n_full = flst_get_len(inode + FSEG_FULL);
3809
3810 ib::info(ER_IB_MSG_425) << "SEGMENT id " << seg_id << " space " << space
3811 << ";"
3812 << " page " << page_no << ";"
3813 << " res " << reserved << " used " << used << ";"
3814 << " full ext " << n_full << ";"
3815 << " fragm pages " << n_frag << ";"
3816 << " free extents " << n_free << ";"
3817 << " not full extents " << n_not_full << ": pages "
3818 << n_used;
3819
3820 ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE);
3821 }
3822
3823 /** Writes info of a segment. */
3824 void fseg_print(fseg_header_t *header, /*!< in: segment header */
3825 mtr_t *mtr) /*!< in/out: mini-transaction */
3826 {
3827 fseg_inode_t *inode;
3828 space_id_t space_id;
3829
3830 space_id = page_get_space_id(page_align(header));
3831
3832 fil_space_t *space = fil_space_get();
3833
3834 mtr_x_lock_space(space, mtr);
3835
3836 const page_size_t page_size(space->flags);
3837
3838 inode = fseg_inode_get(header, space_id, page_size, mtr);
3839
3840 fseg_print_low(space_id, page_size, inode, mtr);
3841 }
3842 #endif /* UNIV_BTR_PRINT */
3843
3844 /** Retrieve tablespace dictionary index root page number stored in the
3845 page 0
3846 @param[in] space Tablespace id
3847 @param[in] page_size Page size
3848 @param[in,out] mtr Mini-transaction
3849 @return root page num of the tablespace dictionary index copy */
3850 page_no_t fsp_sdi_get_root_page_num(space_id_t space,
3851 const page_size_t &page_size, mtr_t *mtr) {
3852 ut_ad(mtr != nullptr);
3853
3854 buf_block_t *block = buf_page_get(page_id_t(space, 0), page_size, RW_S_LATCH,
3855 UT_LOCATION_HERE, mtr);
3856 buf_block_dbg_add_level(block, SYNC_FSP_PAGE);
3857
3858 page_t *page = buf_block_get_frame(block);
3859
3860 ulint sdi_offset = fsp_header_get_sdi_offset(page_size);
3861
3862 uint32_t sdi_ver = mach_read_from_4(page + sdi_offset);
3863
3864 if (sdi_ver != SDI_VERSION) {
3865 ib::warn(ER_IB_MSG_426) << "SDI version mismatch. Expected: " << SDI_VERSION
3866 << " Current version: " << sdi_ver;
3867 }
3868 ut_ad(sdi_ver == SDI_VERSION);
3869
3870 page_no_t root = mach_read_from_4(page + sdi_offset + 4);
3871
3872 ut_ad(root > 2);
3873
3874 return (root);
3875 }
3876
3877 /** Write SDI Index root page num to page 0 of tablespace.
3878 @param[in,out] page Page 0 frame
3879 @param[in] page_size Size of page
3880 @param[in] root_page_num Root page number of SDI
3881 @param[in,out] mtr Mini-transaction */
3882 void fsp_sdi_write_root_to_page(page_t *page, const page_size_t &page_size,
3883 page_no_t root_page_num, mtr_t *mtr) {
3884 ut_ad(page_get_page_no(page) == 0);
3885
3886 ulint sdi_offset = fsp_header_get_sdi_offset(page_size);
3887
3888 /* Write SDI version here. */
3889 mlog_write_ulint(page + sdi_offset, SDI_VERSION, MLOG_4BYTES, mtr);
3890
3891 /* Write SDI root page number */
3892 mlog_write_ulint(page + sdi_offset + 4, root_page_num, MLOG_4BYTES, mtr);
3893 }
3894
3895 #ifdef UNIV_DEBUG
3896 /** Print the file segment header to the given output stream.
3897 @param[in] out the output stream into which the object is printed.
3898 @retval the output stream into which the object was printed. */
3899 std::ostream &fseg_header::to_stream(std::ostream &out) const {
3900 const space_id_t space =
3901 mtr_read_ulint(m_header + FSEG_HDR_SPACE, MLOG_4BYTES, m_mtr);
3902
3903 const page_no_t page_no =
3904 mtr_read_ulint(m_header + FSEG_HDR_PAGE_NO, MLOG_4BYTES, m_mtr);
3905
3906 const ulint offset =
3907 mtr_read_ulint(m_header + FSEG_HDR_OFFSET, MLOG_2BYTES, m_mtr);
3908
3909 out << "[fseg_header_t: space=" << space << ", page=" << page_no
3910 << ", offset=" << offset << "]";
3911
3912 return (out);
3913 }
3914 #endif /* UNIV_DEBUG */
3915
3916 /** Determine if extent belongs to a given segment.
3917 @param[in] descr Extent descriptor
3918 @param[in] seg_id Segment identifier
3919 @param[in] mtr Mini-transaction
3920 @return true if extent is part of the segment, false otherwise */
3921 static bool xdes_in_segment(const xdes_t *descr, ib_id_t seg_id, mtr_t *mtr) {
3922 const xdes_state_t state = xdes_get_state(descr, mtr);
3923 return ((state == XDES_FSEG || state == XDES_FSEG_FRAG) &&
3924 xdes_get_segment_id(descr, mtr) == seg_id);
3925 }
3926
3927 #ifdef UNIV_DEBUG
3928 fsp_header_mem_t::fsp_header_mem_t(const fsp_header_t *header, mtr_t *mtr)
3929 : m_space_id(mach_read_from_4(header + FSP_SPACE_ID)),
3930 m_notused(0),
3931 m_fsp_size(mach_read_from_4(header + FSP_SIZE)),
3932 m_free_limit(mach_read_from_4(header + FSP_FREE_LIMIT)),
3933 m_flags(mach_read_from_4(header + FSP_SPACE_FLAGS)),
3934 m_fsp_frag_n_used(mach_read_from_4(header + FSP_FRAG_N_USED)),
3935 m_fsp_free(header + FSP_FREE, mtr),
3936 m_free_frag(header + FSP_FREE_FRAG, mtr),
3937 m_full_frag(header + FSP_FULL_FRAG, mtr),
3938 m_segid(mach_read_from_8(header + FSP_SEG_ID)),
3939 m_inodes_full(header + FSP_SEG_INODES_FULL, mtr),
3940 m_inodes_free(header + FSP_SEG_INODES_FREE, mtr) {}
3941
3942 std::ostream &fsp_header_mem_t::print(std::ostream &out) const {
3943 out << "[fsp_header_t: "
3944 << "m_space_id=" << m_space_id << ", m_fsp_size=" << m_fsp_size
3945 << ", m_free_limit=" << m_free_limit << ", m_flags=" << m_flags
3946 << ", m_fsp_frag_n_used=" << m_fsp_frag_n_used
3947 << ", m_fsp_free=" << m_fsp_free << ", m_free_frag=" << m_free_frag
3948 << ", m_full_frag=" << m_full_frag << ", m_segid=" << m_segid
3949 << ", m_inodes_full=" << m_inodes_full
3950 << ", m_inodes_free=" << m_inodes_free << "]";
3951 return (out);
3952 }
3953
3954 /** Print the extent descriptor page in user-friendly format.
3955 @param[in] out The output file stream
3956 @param[in] xdes The extent descriptor page
3957 @param[in] page_no The page number of xdes page
3958 @param[in] mtr Mini-transaction.
3959 @return None. */
3960 std::ostream &xdes_page_print(std::ostream &out, const page_t *xdes,
3961 page_no_t page_no, mtr_t *mtr) {
3962 out << "[Extent Descriptor Page: page_no=" << page_no << "\n";
3963
3964 if (page_no == 0) {
3965 const fsp_header_t *tmp = xdes + FSP_HEADER_OFFSET;
3966 fsp_header_mem_t header(tmp, mtr);
3967 out << header << "\n";
3968 }
3969
3970 ulint N = UNIV_PAGE_SIZE / FSP_EXTENT_SIZE;
3971
3972 for (ulint i = 0; i < N; ++i) {
3973 const byte *desc = xdes + XDES_ARR_OFFSET + (i * XDES_SIZE);
3974 xdes_mem_t x(desc);
3975
3976 if (x.is_valid()) {
3977 out << x << "\n";
3978 }
3979 }
3980 out << "]\n";
3981 return (out);
3982 }
3983
3984 std::ostream &xdes_mem_t::print(std::ostream &out) const {
3985 ut_ad(m_xdes != nullptr);
3986
3987 const page_no_t page_no = xdes_get_offset(m_xdes);
3988 const ib_id_t seg_id = xdes_get_segment_id(m_xdes);
3989
3990 out << "[xdes_t: segid=" << seg_id << ",page=" << page_no
3991 << ",state=" << state_name() << ",bitmap=[";
3992 for (page_no_t i = 0; i < FSP_EXTENT_SIZE; ++i) {
3993 const bool is_free = xdes_get_bit(m_xdes, XDES_FREE_BIT, i);
3994 out << (is_free ? "." : "+");
3995 }
3996 out << "]]";
3997 return (out);
3998 }
3999
4000 /** Check if the tablespace size information is valid.
4001 @param[in] space_id the tablespace identifier
4002 @return true if valid, false if invalid. */
4003 bool fsp_check_tablespace_size(space_id_t space_id) {
4004 mtr_t mtr;
4005
4006 mtr_start(&mtr);
4007
4008 fil_space_t *space = fil_space_get(space_id);
4009
4010 mtr_x_lock_space(space, &mtr);
4011
4012 const page_size_t page_size(space->flags);
4013
4014 fsp_header_t *space_header = fsp_get_space_header(space_id, page_size, &mtr);
4015
4016 xdes_t *descr =
4017 xdes_get_descriptor_with_space_hdr(space_header, space->id, 0, &mtr);
4018
4019 ulint n_used = xdes_get_n_used(descr, &mtr);
4020 ulint size = mach_read_from_4(space_header + FSP_SIZE);
4021 ut_a(n_used <= size);
4022
4023 mtr_commit(&mtr);
4024
4025 return (true);
4026 }
4027 #endif /* UNIV_DEBUG */
4028
4029 /** Determine if the tablespace has SDI.
4030 @param[in] space_id Tablespace id
4031 @return DB_SUCCESS if SDI is present else DB_ERROR
4032 or DB_TABLESPACE_NOT_FOUND */
4033 dberr_t fsp_has_sdi(space_id_t space_id) {
4034 fil_space_t *space = fil_space_acquire_silent(space_id);
4035 if (space == nullptr) {
4036 DBUG_EXECUTE_IF(
4037 "ib_sdi", ib::warn(ER_IB_MSG_427)
4038 << "Tablespace doesn't exist for space_id: " << space_id;
4039 ib::warn(ER_IB_MSG_428) << "Is the tablespace dropped or discarded";);
4040 return (DB_TABLESPACE_NOT_FOUND);
4041 }
4042
4043 #ifdef UNIV_DEBUG
4044 mtr_t mtr;
4045 mtr.start();
4046 ut_ad(fsp_sdi_get_root_page_num(space_id, page_size_t(space->flags), &mtr) !=
4047 0);
4048 mtr.commit();
4049 #endif /* UNIV_DEBUG */
4050
4051 fil_space_release(space);
4052 DBUG_EXECUTE_IF(
4053 "ib_sdi", if (!FSP_FLAGS_HAS_SDI(space->flags)) {
4054 ib::warn(ER_IB_MSG_429)
4055 << "SDI doesn't exist in tablespace: " << space->name;
4056 });
4057 return (FSP_FLAGS_HAS_SDI(space->flags) ? DB_SUCCESS : DB_ERROR);
4058 }
4059
4060 /** Mark all pages in tablespace dirty
4061 @param[in] thd current thread
4062 @param[in] space_id tablespace id
4063 @param[in] space_flags tablespace flags
4064 @param[in] total_pages total pages in tablespace
4065 @param[in] from_page page number from where to start the operation */
4066 static void mark_all_page_dirty_in_tablespace(THD *thd, space_id_t space_id,
4067 uint32_t space_flags,
4068 page_no_t total_pages,
4069 page_no_t from_page) {
4070 #ifdef HAVE_PSI_STAGE_INTERFACE
4071 Alter_stage_ts progress_monitor;
4072 #endif
4073 page_size_t pageSize(space_flags);
4074 page_no_t current_page = from_page;
4075 mtr_t mtr;
4076
4077 /* Page 0 is never encrypted */
4078 ut_ad(current_page != 0);
4079
4080 #ifdef HAVE_PSI_STAGE_INTERFACE
4081 progress_monitor.init(srv_stage_alter_tablespace_encryption.m_key);
4082 progress_monitor.set_estimate(total_pages - current_page);
4083 #endif
4084
4085 while (current_page < total_pages) {
4086 /* Mark group of PAGE_GROUP_SIZE pages dirty */
4087 mtr_start(&mtr);
4088 page_no_t inner_count = 0;
4089 for (; inner_count < PAGE_GROUP_SIZE && current_page < total_pages;
4090 inner_count++, current_page++) {
4091 /* As we are trying to read each and every page of
4092 tablespace, there might be few pages which are freed.
4093 Take them into consideration. */
4094 buf_block_t *block = buf_page_get_gen(
4095 page_id_t(space_id, current_page), pageSize, RW_X_LATCH, nullptr,
4096 Page_fetch::POSSIBLY_FREED, UT_LOCATION_HERE, &mtr);
4097
4098 if (block == nullptr) {
4099 continue;
4100 }
4101
4102 page_t *page = buf_block_get_frame(block);
4103 page_zip_des_t *page_zip = buf_block_get_page_zip(block);
4104
4105 /* If page is not initialized */
4106 if (page_get_space_id(page) == 0 || page_get_page_no(page) == 0) {
4107 continue;
4108 }
4109
4110 if (page_zip != nullptr &&
4111 fil_page_type_is_index(fil_page_get_type(page))) {
4112 mach_write_to_4(page + FIL_PAGE_SPACE_ID, space_id);
4113 page_zip_write_header(page_zip, page + FIL_PAGE_SPACE_ID, 4, &mtr);
4114 } else {
4115 mlog_write_ulint(page + FIL_PAGE_SPACE_ID, space_id, MLOG_4BYTES, &mtr);
4116 }
4117
4118 DBUG_INJECT_CRASH_WITH_LOG_FLUSH("alter_encrypt_tablespace_inner_page",
4119 current_page - 1);
4120 }
4121 mtr_commit(&mtr);
4122
4123 mtr_start(&mtr);
4124 /* Write (Un)Encryption progress on page 0 */
4125 fsp_header_write_encryption_progress(space_id, space_flags,
4126 current_page - 1, 0, false, &mtr);
4127 mtr_commit(&mtr);
4128
4129 #ifdef HAVE_PSI_STAGE_INTERFACE
4130 /* Update progress stats */
4131 progress_monitor.update_work(inner_count);
4132 #endif
4133
4134 DBUG_EXECUTE_IF("alter_encrypt_tablespace_insert_delay", sleep(1););
4135
4136 DBUG_INJECT_CRASH_WITH_LOG_FLUSH("alter_encrypt_tablespace_page",
4137 current_page - 1);
4138
4139 #ifdef UNIV_DEBUG
4140 if ((current_page - 1) == 5) {
4141 DEBUG_SYNC(thd, "alter_encrypt_tablespace_wait_after_page5");
4142 }
4143 #endif /* UNIV_DEBUG */
4144
4145 DBUG_EXECUTE_IF("flush_each_dirtied_page",
4146 buf_LRU_flush_or_remove_pages(
4147 space_id, BUF_REMOVE_FLUSH_WRITE, nullptr, false););
4148 }
4149
4150 #ifdef HAVE_PSI_STAGE_INTERFACE
4151 /* Confirm that all pages are covered. */
4152 ut_ad(progress_monitor.is_completed());
4153 #endif
4154 }
4155
4156 /** Get the encryption progress by reading header page.
4157 @param[in] space tablespace
4158 @param[out] operation operation which was being performed */
4159 static uint32_t get_encryption_progress(fil_space_t *space, byte &operation) {
4160 mtr_t mtr;
4161
4162 mtr_start(&mtr);
4163 /* Open page 0 */
4164 page_size_t pageSize(space->flags);
4165 page_id_t page_id(space->id, 0);
4166 buf_block_t *block =
4167 buf_page_get_gen(page_id, pageSize, RW_X_LATCH, nullptr,
4168 Page_fetch::NORMAL, UT_LOCATION_HERE, &mtr);
4169
4170 ut_ad(block != nullptr);
4171
4172 page_t *page = buf_block_get_frame(block);
4173
4174 /* Get the offset of Encryption progress information */
4175 ulint offset = fsp_header_get_encryption_progress_offset(pageSize);
4176
4177 /* Read operation type (1 byte) */
4178 operation = mach_read_from_1(page + offset);
4179
4180 /* Read maximum pages (4 byte) */
4181 uint32_t progress =
4182 mach_read_from_4(page + offset + Encryption::OPERATION_INFO_SIZE);
4183 mtr_commit(&mtr);
4184
4185 return progress;
4186 }
4187
4188 /** Initialize space encrypt operation and persist in page-0.
4189 @param[in,out] space innodb tablespace
4190 @return innodb error code */
4191 static dberr_t encrypt_begin_persist(fil_space_t *space) {
4192 DBUG_TRACE;
4193 dberr_t err = DB_SUCCESS;
4194
4195 /* Fill key, iv and prepare encryption_info to be written in page 0 */
4196 Encryption_metadata encryption_metadata;
4197 Encryption::set_or_generate(Encryption::AES, nullptr, nullptr,
4198 encryption_metadata);
4199
4200 /* Prepare encrypted encryption information to be written on page 0. */
4201 byte encryption_info[Encryption::INFO_SIZE];
4202 if (!Encryption::fill_encryption_info(encryption_metadata, true,
4203 encryption_info)) {
4204 ut_d(ut_error);
4205 ut_o(return DB_ERROR);
4206 }
4207
4208 {
4209 /* Write Encryption information and notify clone. Do this before persisting
4210 encryption information because clone needs to know that the table is being
4211 encrypted before the key is persisted in page-0. This is because clone needs
4212 to copy and re-encrypt the key with recipients master key.
4213
4214 There is an existing issue here that other pages could get encrypted and
4215 flushed after this point before page-0 is flushed. It could eventually
4216 cause issue during recovery in case of a crash. It needs to be fixed
4217 separately (may be) by encrypting pages only if space flag is set. Note that
4218 we haven't yet set the space flag to FSP_FLAGS_MASK_ENCRYPTION yet.
4219
4220 Also, we should introduce some concurrency control (atomics) to prevent race
4221 while accessing space encryption related information during IO. */
4222 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL,
4223 space->id, false);
4224 ut_ad(!notifier.failed());
4225
4226 /* Set encryption for tablespace */
4227 rw_lock_x_lock(&space->latch, UT_LOCATION_HERE);
4228 err =
4229 fil_set_encryption(space->id, encryption_metadata.m_type,
4230 encryption_metadata.m_key, encryption_metadata.m_iv);
4231 rw_lock_x_unlock(&space->latch);
4232
4233 if (err != DB_SUCCESS) {
4234 /* purecov: begin deadcode */
4235 ut_d(ut_error);
4236 ut_o(return err);
4237 /* purecov: end */
4238 }
4239 }
4240
4241 /* Write Encryption information and space flags now on page 0
4242 NOTE : Not modifying space->flags as of now, because we want to persist
4243 the changes on disk and then modify in memory flags. */
4244 mtr_t mtr;
4245 mtr_start(&mtr);
4246
4247 if (!fsp_header_write_encryption(space->id,
4248 space->flags | FSP_FLAGS_MASK_ENCRYPTION,
4249 encryption_info, true, false, &mtr)) {
4250 err = DB_ERROR;
4251 ut_d(ut_error);
4252 }
4253
4254 /* Write operation type and progress (0 now) on page 0 */
4255 fsp_header_write_encryption_progress(
4256 space->id, space->flags, 0, Encryption::ENCRYPT_IN_PROGRESS, true, &mtr);
4257
4258 mtr_commit(&mtr);
4259
4260 /* Make sure encryption information is persisted on disk. Following scenario:
4261 [1] Encryption key is written on page 0 but Page 0 is not flushed.
4262 [2] page P is encrypted with K1 and flushed on disk.
4263 [3] checkpoint hasn't reached [1] yet and has REDO for P before [1].
4264 [4] Server crashed. During recovery REDO scan batch REDO [1] is not reached.
4265 [5] Although REDO for P is to be discarded, but to confirm that page LSN is
4266 to be checked, thus P is read from disk. ERROR. We should replace this
4267 expensive call to flush all by an interface that would flush only page-0. */
4268 buf_LRU_flush_or_remove_pages(space->id, BUF_REMOVE_FLUSH_WRITE, nullptr,
4269 false);
4270 return DB_SUCCESS;
4271 }
4272
4273 /** Initialize space encrypt memory flags.
4274 @param[in,out] space innodb tablespace */
4275 static void encrypt_begin_memory(fil_space_t *space) {
4276 DBUG_TRACE;
4277 /* Don't allow operation to change while clone is evaluating the state of the
4278 space during state transition. */
4279 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL_FLAGS,
4280 space->id, false);
4281 ut_ad(!notifier.failed());
4282
4283 /* Set encryption operation in progress flag */
4284 space->encryption_op_in_progress = Encryption::Progress::ENCRYPTION;
4285
4286 /* Update In-mem Encryption flag for tablespace */
4287 fsp_flags_set_encryption(space->flags);
4288 }
4289
4290 /** Force all pages of a space to be loaded and flushed back to disk
4291 @param[in,out] thd server session THD
4292 @param[in,out] space innodb tablespace
4293 @param[in] from_page page number to resume from */
4294 static void process_all_pages(THD *thd, fil_space_t *space,
4295 page_no_t from_page) {
4296 DBUG_TRACE;
4297 /* Mark all pages in tablespace dirty */
4298 mark_all_page_dirty_in_tablespace(thd, space->id, space->flags, space->size,
4299 from_page);
4300
4301 /* As DMLs are allowed in parallel, pass false for 'strict' */
4302 buf_LRU_flush_or_remove_pages(space->id, BUF_REMOVE_FLUSH_WRITE, nullptr,
4303 false);
4304 }
4305
4306 /** Finish space encrypt operation.
4307 @param[in,out] space innodb tablespace */
4308 static void encrypt_end(fil_space_t *space) {
4309 DBUG_TRACE;
4310 /* Crash before resetting progress on page 0 */
4311 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_before_resetting_progress",
4312 log_buffer_flush_to_disk();
4313 DBUG_SUICIDE(););
4314
4315 /* Erase Operation type and encryption progress from page 0 */
4316 mtr_t mtr;
4317 mtr_start(&mtr);
4318
4319 fsp_header_write_encryption_progress(space->id, space->flags, 0, 0, true,
4320 &mtr);
4321 mtr_commit(&mtr);
4322
4323 /* Don't allow operation to change while clone is evaluating the state of the
4324 space during state transition. */
4325 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL_FLAGS,
4326 space->id, false);
4327 ut_ad(!notifier.failed());
4328
4329 /* Reset encryption in progress flag */
4330 space->encryption_op_in_progress = Encryption::Progress::NONE;
4331 }
4332
4333 /** Find out the place to resume the operation.
4334 @param[in,out] space innodb tablespace
4335 @param[out] from_page page number to resume from
4336 @return state to resume from */
4337 static Encryption::Resume_point encrypt_resume_point(fil_space_t *space,
4338 page_no_t &from_page) {
4339 DBUG_TRACE;
4340 bool encryption_flag = FSP_FLAGS_GET_ENCRYPTION(space->flags);
4341 from_page = 1;
4342
4343 if (!encryption_flag) {
4344 /* Encryption is not yet started. */
4345 return Encryption::Resume_point::INIT;
4346 }
4347
4348 /* Read page 0 and get encryption progress */
4349 byte operation;
4350 from_page = get_encryption_progress(space, operation) + 1;
4351
4352 if (operation != Encryption::ENCRYPT_IN_PROGRESS) {
4353 ut_ad(operation != Encryption::DECRYPT_IN_PROGRESS);
4354 ut_ad(space->encryption_op_in_progress == Encryption::Progress::NONE);
4355 /* Encryption is already done. */
4356 return Encryption::Resume_point::DONE;
4357 }
4358
4359 ut_ad(space->encryption_op_in_progress == Encryption::Progress::ENCRYPTION);
4360
4361 if (from_page == space->size) {
4362 return Encryption::Resume_point::END;
4363 }
4364
4365 return Encryption::Resume_point::PROCESS;
4366 }
4367
4368 /** Encrypt all pages of a tablespace.
4369 @param[in,out] thd server session THD
4370 @param[in] space_id Tablespace id
4371 @param[in] resume true if resumed after server restart
4372 @return innodb error code */
4373 static dberr_t encrypt_tablespace(THD *thd, space_id_t space_id, bool resume) {
4374 DBUG_TRACE;
4375
4376 dberr_t err = DB_SUCCESS;
4377 fil_space_t *space = fil_space_get(space_id);
4378
4379 Encryption::Resume_point resume_point = Encryption::Resume_point::INIT;
4380 page_no_t from_page = 1;
4381
4382 if (resume) {
4383 resume_point = encrypt_resume_point(space, from_page);
4384 }
4385
4386 switch (resume_point) {
4387 case Encryption::Resume_point::INIT:
4388 /* Set and persist encryption key information. We also persist
4389 the initialized progress information together in same mtr (atomic).*/
4390 err = encrypt_begin_persist(space);
4391
4392 ut_ad(err == DB_SUCCESS);
4393
4394 if (err != DB_SUCCESS) {
4395 break; /* purecov: deadcode */
4396 }
4397 /* Set encryption flag and initialize progress information. */
4398 encrypt_begin_memory(space);
4399 [[fallthrough]];
4400
4401 case Encryption::Resume_point::PROCESS:
4402 /* Load and flush all pages so that they are all encrypted on disk. */
4403 process_all_pages(thd, space, from_page);
4404 [[fallthrough]];
4405
4406 case Encryption::Resume_point::END:
4407 /* Reset progress information. */
4408 encrypt_end(space);
4409 [[fallthrough]];
4410
4411 case Encryption::Resume_point::DONE:
4412 break;
4413 }
4414
4415 return err;
4416 }
4417
4418 /** Initialize space decrypt operation and persist in page-0.
4419 @param[in,out] space innodb tablespace
4420 @return innodb error code */
4421 static dberr_t decrypt_begin_persist(fil_space_t *space) {
4422 DBUG_TRACE;
4423 /* Write Decryption progress and notify clone. Do this before persisting the
4424 progress information. Clone needs to identify the state before page-0 is
4425 updated. */
4426 {
4427 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL,
4428 space->id, false);
4429 ut_ad(!notifier.failed());
4430 space->encryption_op_in_progress = Encryption::Progress::DECRYPTION;
4431 }
4432
4433 dberr_t err = DB_SUCCESS;
4434
4435 mtr_t mtr;
4436 mtr_start(&mtr);
4437 /* Write operation type and progress (0 now) on page 0 */
4438 if (!fsp_header_write_encryption_progress(space->id, space->flags, 0,
4439 Encryption::DECRYPT_IN_PROGRESS,
4440 true, &mtr)) {
4441 err = DB_ERROR;
4442 ut_d(ut_error);
4443 }
4444
4445 mtr_commit(&mtr);
4446 return err;
4447 }
4448
4449 /** Initialize space decrypt memory flags.
4450 @param[in,out] space innodb tablespace */
4451 static void decrypt_begin_memory(fil_space_t *space) {
4452 DBUG_TRACE;
4453 /* Notify clone before starting decryption. */
4454 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL_FLAGS,
4455 space->id, false);
4456 ut_ad(!notifier.failed());
4457
4458 /* Set encryption operation in progress flag */
4459 space->encryption_op_in_progress = Encryption::Progress::DECRYPTION;
4460
4461 /* Update In-memory Encryption flag for tablespace. We cannot erase Encryption
4462 info in page-0 till all pages are decrypted. */
4463 fsp_flags_unset_encryption(space->flags);
4464 }
4465
4466 /** Finish space decrypt operation.
4467 @param[in,out] space innodb tablespace
4468 @return innodb error code */
4469 static dberr_t decrypt_end(fil_space_t *space) {
4470 DBUG_TRACE;
4471 ut_ad(!FSP_FLAGS_GET_ENCRYPTION(space->flags));
4472
4473 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_before_updating_flags",
4474 log_buffer_flush_to_disk();
4475 DBUG_SUICIDE(););
4476
4477 dberr_t err = DB_SUCCESS;
4478 {
4479 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT_GENERAL_FLAGS,
4480 space->id, false);
4481 ut_ad(!notifier.failed());
4482
4483 /* Reset encryption in progress flag */
4484 space->encryption_op_in_progress = Encryption::Progress::NONE;
4485
4486 rw_lock_x_lock(&space->latch, UT_LOCATION_HERE);
4487 /* Reset In-memory encryption for tablespace */
4488 err = fil_reset_encryption(space->id);
4489 rw_lock_x_unlock(&space->latch);
4490 ut_ad(err == DB_SUCCESS);
4491 }
4492
4493 if (err != DB_SUCCESS) {
4494 return err; /* purecov: inspected */
4495 }
4496
4497 byte encryption_info[Encryption::INFO_SIZE];
4498 memset(encryption_info, 0, Encryption::INFO_SIZE);
4499
4500 /* Erase encryption information in page-0 and update space flag. Also reset
4501 the progress information in same mtr. */
4502 mtr_t mtr;
4503
4504 mtr_start(&mtr);
4505
4506 if (!fsp_header_write_encryption(space->id, space->flags, encryption_info,
4507 true, false, &mtr)) {
4508 err = DB_ERROR; /* purecov: inspected */
4509 }
4510
4511 /* Crash before resetting progress on page 0 */
4512 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_before_resetting_progress",
4513 log_buffer_flush_to_disk();
4514 DBUG_SUICIDE(););
4515
4516 fsp_header_write_encryption_progress(space->id, space->flags, 0, 0, true,
4517 &mtr);
4518 mtr_commit(&mtr);
4519
4520 ut_ad(err == DB_SUCCESS);
4521 return err;
4522 }
4523
4524 /** Find out the place to resume the operation.
4525 @param[in,out] space innodb tablespace
4526 @param[out] from_page page number to resume from
4527 @return state to resume from */
4528 static Encryption::Resume_point decrypt_resume_point(fil_space_t *space,
4529 page_no_t &from_page) {
4530 DBUG_TRACE;
4531 bool encryption_flag = FSP_FLAGS_GET_ENCRYPTION(space->flags);
4532 from_page = 1;
4533
4534 if (!encryption_flag) {
4535 /* Decryption must have finished already. The encryption flag is reset and
4536 persisted at very end. */
4537 ut_ad(space->encryption_op_in_progress == Encryption::Progress::NONE);
4538
4539 return Encryption::Resume_point::DONE;
4540 }
4541
4542 /* Read page 0 and get encryption progress */
4543 byte operation;
4544 from_page = get_encryption_progress(space, operation) + 1;
4545
4546 if (operation != Encryption::DECRYPT_IN_PROGRESS) {
4547 ut_ad(operation != Encryption::ENCRYPT_IN_PROGRESS);
4548 ut_ad(space->encryption_op_in_progress == Encryption::Progress::NONE);
4549 /* Decryption is not started. */
4550 return Encryption::Resume_point::INIT;
4551 }
4552
4553 ut_ad(space->encryption_op_in_progress == Encryption::Progress::DECRYPTION);
4554
4555 if (from_page == space->size) {
4556 return Encryption::Resume_point::END;
4557 }
4558
4559 return Encryption::Resume_point::PROCESS;
4560 }
4561
4562 /** Decrypt all pages of a tablespace.
4563 @param[in,out] thd server session THD
4564 @param[in] space_id Tablespace id
4565 @param[in] resume true if resumed after server restart
4566 @return innodb error code */
4567 static dberr_t decrypt_tablespace(THD *thd, space_id_t space_id, bool resume) {
4568 DBUG_TRACE;
4569
4570 dberr_t err = DB_SUCCESS;
4571 fil_space_t *space = fil_space_get(space_id);
4572
4573 Encryption::Resume_point resume_point = Encryption::Resume_point::INIT;
4574 page_no_t from_page = 1;
4575
4576 if (resume) {
4577 resume_point = decrypt_resume_point(space, from_page);
4578 }
4579
4580 /* While resuming we need to initialize the flags as they
4581 are not yet persisted. */
4582 if (resume_point == Encryption::Resume_point::END) {
4583 /* Set encryption flag and progress information. */
4584 decrypt_begin_memory(space);
4585 }
4586
4587 switch (resume_point) {
4588 case Encryption::Resume_point::INIT:
4589 /* Set and persist encryption progress information. */
4590 err = decrypt_begin_persist(space);
4591
4592 ut_ad(err == DB_SUCCESS);
4593
4594 if (err != DB_SUCCESS) {
4595 break; /* purecov: deadcode */
4596 }
4597 [[fallthrough]];
4598
4599 case Encryption::Resume_point::PROCESS:
4600 /* Set encryption flag and progress information. */
4601 decrypt_begin_memory(space);
4602
4603 /* Load and flush all pages so that they are all encrypted on disk. */
4604 process_all_pages(thd, space, from_page);
4605 [[fallthrough]];
4606
4607 case Encryption::Resume_point::END:
4608 /* Reset and persist encryption key and progress information. */
4609 err = decrypt_end(space);
4610 ut_ad(err == DB_SUCCESS);
4611 [[fallthrough]];
4612
4613 case Encryption::Resume_point::DONE:
4614 break;
4615 }
4616
4617 return err;
4618 }
4619
4620 dberr_t fsp_alter_encrypt_tablespace(THD *thd, space_id_t space_id,
4621 bool to_encrypt, void *dd_space_in) {
4622 DBUG_TRACE;
4623
4624 /* Make an entry in DDL LOG for this tablespace. If an entry for tablespace
4625 exists then remove that entry and insert a new one. */
4626 auto op_type_ddl_log = (to_encrypt) ? Encryption::Progress::ENCRYPTION
4627 : Encryption::Progress::DECRYPTION;
4628
4629 DDL_Record *old_ddl_rec = log_ddl->find_alter_encrypt_record(space_id);
4630
4631 if (DB_SUCCESS != log_ddl->write_alter_encrypt_space_log(
4632 space_id, op_type_ddl_log, old_ddl_rec)) {
4633 ib::error(ER_IB_MSG_1283) << "Couldn't write DDL LOG for " << space_id;
4634 return DB_ERROR;
4635 }
4636
4637 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_after_ddl_entry",
4638 DBUG_SUICIDE(););
4639
4640 bool resume = (old_ddl_rec != nullptr);
4641
4642 dberr_t err = DB_SUCCESS;
4643
4644 if (to_encrypt) {
4645 err = encrypt_tablespace(thd, space_id, resume);
4646
4647 } else {
4648 err = decrypt_tablespace(thd, space_id, resume);
4649 }
4650
4651 /* Update space flags in DD Tablespace object */
4652 dd::Tablespace *dd_space = reinterpret_cast<dd::Tablespace *>(dd_space_in);
4653 ut_ad(dd_space != nullptr);
4654 fil_space_t *space = fil_space_get(space_id);
4655
4656 dd_space->se_private_data().set(dd_space_key_strings[DD_SPACE_FLAGS],
4657 static_cast<uint32>(space->flags));
4658
4659 /* Crash before flushing page 0 on disk */
4660 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_before_flushing_page_0",
4661 log_buffer_flush_to_disk();
4662 DBUG_SUICIDE(););
4663
4664 /* Flush page 0 here because MEB backup needs to read the key from page 0
4665 before redo log is applied. This is not needed for innodb recovery and
4666 ideally we would like to get rid of all such special purpose code. We should
4667 replace this expensive call to flush all by an interface that would flush only
4668 page-0.*/
4669 buf_LRU_flush_or_remove_pages(space_id, BUF_REMOVE_FLUSH_WRITE, nullptr,
4670 false);
4671
4672 /* Crash after flushing page 0 on disk */
4673 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_after_flushing_page_0",
4674 log_buffer_flush_to_disk();
4675 DBUG_SUICIDE(););
4676 return err;
4677 }
4678
4679 #ifdef UNIV_DEBUG
4680 /** Validate tablespace encryption settings. */
4681 static void validate_tablespace_encryption(fil_space_t *space) {
4682 byte buf[Encryption::KEY_LEN];
4683 memset(buf, 0, Encryption::KEY_LEN);
4684
4685 if (FSP_FLAGS_GET_ENCRYPTION(space->flags)) {
4686 ut_ad(memcmp(space->m_encryption_metadata.m_key, buf,
4687 Encryption::KEY_LEN) != 0);
4688 ut_ad(memcmp(space->m_encryption_metadata.m_iv, buf, Encryption::KEY_LEN) !=
4689 0);
4690 ut_ad(space->m_encryption_metadata.m_key_len != 0);
4691 ut_ad(space->m_encryption_metadata.m_type == Encryption::AES);
4692 } else {
4693 ut_ad(memcmp(space->m_encryption_metadata.m_key, buf,
4694 Encryption::KEY_LEN) == 0);
4695 ut_ad(memcmp(space->m_encryption_metadata.m_iv, buf, Encryption::KEY_LEN) ==
4696 0);
4697 ut_ad(space->m_encryption_metadata.m_key_len == 0);
4698 ut_ad(space->m_encryption_metadata.m_type == Encryption::NONE);
4699 ut_ad(!space->can_encrypt());
4700 }
4701 ut_ad(space->encryption_op_in_progress == Encryption::Progress::NONE);
4702 }
4703 #endif
4704
4705 /** Load encryption info from header page.
4706 @param[in] space tablespace
4707 @return false if success, true otherwise. */
4708 static bool load_encryption_from_header(fil_space_t *space) {
4709 byte encryption_key[Encryption::KEY_LEN] = {0};
4710 byte encryption_iv[Encryption::KEY_LEN] = {0};
4711
4712 /* Read and load encryption info from header page */
4713 const page_size_t page_size(space->flags);
4714 mtr_t mtr;
4715 mtr_start(&mtr);
4716 buf_block_t *block = buf_page_get(page_id_t(space->id, 0), page_size,
4717 RW_SX_LATCH, UT_LOCATION_HERE, &mtr);
4718 ut_ad(block != nullptr);
4719 ut_ad(space->id == page_get_space_id(buf_block_get_frame(block)));
4720 page_t *header_page = buf_block_get_frame(block);
4721
4722 Encryption_key e_key{encryption_key, encryption_iv};
4723 bool ret = fsp_header_get_encryption_key(space->flags, e_key, header_page);
4724 mtr_commit(&mtr);
4725
4726 if (!ret) {
4727 /* NOTE : In case when crash happened just after DDL Log entry,
4728 encryption info won't be loaded even now. Which is fine. In that case
4729 flags on page 0 should not indicate tablespace encrypted. */
4730 ut_ad(!FSP_FLAGS_GET_ENCRYPTION(fsp_header_get_flags(header_page)));
4731 if (FSP_FLAGS_GET_ENCRYPTION(fsp_header_get_flags(header_page))) {
4732 return true;
4733 }
4734 } else {
4735 dberr_t err [[maybe_unused]] = fil_set_encryption(
4736 space->id, Encryption::AES, encryption_key, encryption_iv);
4737 ut_ad(err == DB_SUCCESS);
4738 if (err != DB_SUCCESS) {
4739 return true;
4740 }
4741 }
4742
4743 return false;
4744 }
4745
4746 static const std::string enc("ENCRYPTION");
4747 static const std::string dec("DECRYPTION");
4748 static const std::string none("NONE");
4749
4750 static inline const std::string &get_encryption_op_str(
4751 Encryption::Progress op) {
4752 switch (op) {
4753 case Encryption::Progress::ENCRYPTION:
4754 return enc;
4755 break;
4756 case Encryption::Progress::DECRYPTION:
4757 return dec;
4758 break;
4759 default:
4760 ut_d(ut_error);
4761 ut_o(return none);
4762 }
4763 }
4764
4765 /** Resume Encrypt/Decrypt for tablespace(s) post recovery.
4766 If an error occurs while processing any tablespace needing encryption,
4767 post an error for that space and keep going.
4768 @param[in] thd background thread */
4769 static void resume_alter_encrypt_tablespace(THD *thd) {
4770 /* List of shared MDLs taken. One for each tablespace. */
4771 std::list<MDL_ticket *> shared_mdl_list;
4772
4773 /* Take a SHARED MDL to make sure no user thread could run any DDL on the
4774 tablespace. DMLs are allowed though. */
4775 for (auto it : ts_encrypt_ddl_records) {
4776 space_id_t space_id = it->get_space_id();
4777 fil_space_t *space = fil_space_get(space_id);
4778
4779 ut_ad(space != nullptr);
4780
4781 if (space == nullptr) {
4782 continue;
4783 }
4784
4785 /* If encryption was going on, make sure encryption information is
4786 read/loaded from disk. */
4787 if (it->get_encryption_type() == Encryption::Progress::ENCRYPTION &&
4788 !space->can_encrypt()) {
4789 if (load_encryption_from_header(space)) {
4790 ib::error() << "Encryption information can't be read for tablesapce "
4791 << space->name
4792 << ". Skipping resume encryption operation for it.";
4793 continue;
4794 }
4795 }
4796
4797 MDL_ticket *mdl_ticket;
4798 if (dd::acquire_shared_tablespace_mdl(thd, space->name, false, &mdl_ticket,
4799 false)) {
4800 ut_error;
4801 }
4802 shared_mdl_list.push_back(mdl_ticket);
4803 }
4804
4805 /* Let the startup thread proceed now */
4806 mysql_mutex_lock(&resume_encryption_cond_m);
4807 mysql_cond_signal(&resume_encryption_cond);
4808 mysql_mutex_unlock(&resume_encryption_cond_m);
4809
4810 DBUG_EXECUTE_IF("sleep_resume_alter_encrypt", sleep(10000););
4811
4812 /* server_uuid must have been generated by now. */
4813 ut_ad(strlen(server_uuid) == UUID_LENGTH);
4814
4815 #ifdef UNIV_DEBUG
4816 std::vector<space_id_t>::iterator space_it;
4817 #endif
4818
4819 std::list<MDL_ticket *>::iterator mdl_it = shared_mdl_list.begin();
4820 for (auto it : ts_encrypt_ddl_records) {
4821 ut_ad(it->get_encryption_type() != Encryption::Progress::NONE);
4822 ut_ad(mdl_it != shared_mdl_list.end());
4823
4824 space_id_t space_id = it->get_space_id();
4825 fil_space_t *space = fil_space_get(space_id);
4826 ut_ad(space != nullptr);
4827
4828 if (space == nullptr) {
4829 ib::error(ER_IB_MSG_1277)
4830 << "Tablespace is missing for tablespace id" << space_id
4831 << ". Skipping (un)encryption resume operation.";
4832 ut_d(ut_error);
4833 ut_o(continue);
4834 }
4835
4836 ib::info(ER_IB_MSG_RESUME_OP_FOR_SPACE)
4837 << "Resuming " << get_encryption_op_str(it->get_encryption_type())
4838 << " for tablespace " << space->name << ":" << space_id;
4839
4840 /* Call server API to resume operation */
4841 bool res = dd::alter_tablespace_encryption(
4842 thd, space->name,
4843 (it->get_encryption_type() == Encryption::Progress::ENCRYPTION));
4844 if (res) {
4845 ib::error(ER_IB_MSG_1280)
4846 << get_encryption_op_str(it->get_encryption_type())
4847 << " for tablespace " << space->name << ":" << space_id
4848 << " could not be done successfully.";
4849 } else {
4850 ib::info(ER_IB_MSG_1281)
4851 << "Finished " << get_encryption_op_str(it->get_encryption_type())
4852 << " for tablespace " << space->name << ":" << space_id;
4853
4854 /* Validate tablespace In-mem representation */
4855 ut_d(validate_tablespace_encryption(space));
4856 }
4857
4858 #ifdef UNIV_DEBUG
4859 space_it = std::find(flag_mismatch_spaces.begin(),
4860 flag_mismatch_spaces.end(), space_id);
4861 if (space_it != flag_mismatch_spaces.end()) {
4862 flag_mismatch_spaces.erase(space_it);
4863 }
4864 #endif
4865
4866 /* Release MDL on tablespace explicitly */
4867 dd_release_mdl((*mdl_it));
4868 mdl_it = shared_mdl_list.erase(mdl_it);
4869 }
4870
4871 for (auto &record : ts_encrypt_ddl_records) {
4872 ut_ad(!record->get_deletable());
4873 ut::delete_(record);
4874 }
4875 ts_encrypt_ddl_records.clear();
4876
4877 /* All MDLs should have been released and removed from list by now */
4878 ut_ad(shared_mdl_list.empty());
4879 shared_mdl_list.clear();
4880
4881 ut_ad(flag_mismatch_spaces.empty());
4882 return;
4883 }
4884
4885 /* Initiate roll-forward of alter encrypt in background thread */
4886 void fsp_init_resume_alter_encrypt_tablespace() {
4887 THD *thd = create_internal_thd();
4888
4889 resume_alter_encrypt_tablespace(thd);
4890
4891 destroy_internal_thd(thd);
4892 }
4893
4894 void File_segment_inode::write_not_full_n_used(uint32_t n_used) {
4895 #ifdef UNIV_DEBUG
4896 ut_ad(m_mtr != nullptr);
4897 ut_ad(mtr_memo_contains_page_flagged(
4898 m_mtr, m_fseg_inode, MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX));
4899
4900 if (n_used > 0) {
4901 uint32_t old_value = read_not_full_n_used();
4902 if (n_used > old_value) {
4903 uint32_t incr = n_used - old_value;
4904 ut_ad(incr == 1 || incr == XDES_FRAG_N_USED ||
4905 incr == (FSP_EXTENT_SIZE - 1));
4906 } else {
4907 uint32_t decr = old_value - n_used;
4908 ut_ad(decr == FSP_EXTENT_SIZE || decr == 1 ||
4909 decr == (XDES_FRAG_N_USED + 1) ||
4910 (n_used == calculate_not_full_n_used()));
4911 }
4912 }
4913 #endif /* UNIV_DEBUG */
4914
4915 mlog_write_ulint(m_fseg_inode + FSEG_NOT_FULL_N_USED, n_used, MLOG_4BYTES,
4916 m_mtr);
4917
4918 ut_ad(n_used == 0 || verify_not_full_n_used());
4919 }
4920
4921 #ifdef UNIV_DEBUG
4922 bool File_segment_inode::verify_not_full_n_used() {
4923 if (!do_verify()) {
4924 return (true);
4925 }
4926 uint32_t not_full_n_used_1 = read_not_full_n_used();
4927 uint32_t not_full_n_used_2 = calculate_not_full_n_used();
4928 ut_ad(not_full_n_used_1 == not_full_n_used_2);
4929 return (not_full_n_used_1 == not_full_n_used_2);
4930 }
4931
4932 page_no_t File_segment_inode::calculate_not_full_n_used() {
4933 page_no_t n_used = 0;
4934 xdes_t *descr;
4935 fil_addr_t xdes_addr = flst_get_first(m_fseg_inode + FSEG_NOT_FULL, m_mtr);
4936
4937 while (!xdes_addr.is_null()) {
4938 descr = xdes_lst_get_descriptor(m_space_id, m_page_size, xdes_addr, m_mtr);
4939 n_used += xdes_get_n_used(descr, m_mtr);
4940 xdes_addr = flst_get_next_addr(descr + XDES_FLST_NODE, m_mtr);
4941 }
4942
4943 return (n_used);
4944 }
4945 #endif /* UNIV_DEBUG */
4946
4947 uint32_t File_segment_inode::read_not_full_n_used() const {
4948 uint32_t n_used =
4949 mtr_read_ulint(m_fseg_inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, m_mtr);
4950 return (n_used);
4951 }
4952
4953 std::ostream &File_segment_inode::print(std::ostream &out) const {
4954 out << "[File_segment_inode: FSEG_ID=" << get_seg_id()
4955 << ", FSEG_NOT_FULL_N_USED=" << read_not_full_n_used() << "]";
4956
4957 return (out);
4958 }
4959
4960 #endif /* !UNIV_HOTBACKUP */