Debian Codegraph @

storage/innobase/fsp/fsp0file.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2013, 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/fsp0file.cc
29 Tablespace data file implementation
30
31 Created 2013-7-26 by Kevin Lewis
32 *******************************************************/
33
34 #include "ha_prototypes.h"
35
36 #include "dict0dd.h"
37 #include "fil0fil.h"
38 #include "fsp0file.h"
39 #include "fsp0sysspace.h"
40 #include "fsp0types.h"
41 #include "os0file.h"
42 #include "page0page.h"
43 #include "srv0start.h"
44 #include "trx0purge.h"
45 #include "ut0new.h"
46
47 #include <scope_guard.h>
48
49 #ifdef UNIV_HOTBACKUP
50 #include "my_sys.h"
51 #endif /* UNIV_HOTBACKUP */
52
53 /** Initialize the name and flags of this datafile.
54 @param[in] name tablespace name, will be copied
55 @param[in] flags tablespace flags */
56 void Datafile::init(const char *name, uint32_t flags) {
57 ut_ad(m_name == nullptr);
58 ut_ad(name != nullptr);
59
60 m_name = mem_strdup(name);
61 m_flags = flags;
62 m_encryption_key = nullptr;
63 m_encryption_iv = nullptr;
64 }
65
66 /** Release the resources. */
67 void Datafile::shutdown() {
68 close();
69
70 ut::free(m_name);
71 m_name = nullptr;
72
73 free_filepath();
74
75 free_first_page();
76
77 if (m_encryption_key != nullptr) {
78 ut::free(m_encryption_key);
79 m_encryption_key = nullptr;
80 }
81
82 if (m_encryption_iv != nullptr) {
83 ut::free(m_encryption_iv);
84 m_encryption_iv = nullptr;
85 }
86 }
87
88 /** Create/open a data file.
89 @param[in] read_only_mode if true, then readonly mode checks are enforced.
90 @return DB_SUCCESS or error code */
91 dberr_t Datafile::open_or_create(bool read_only_mode) {
92 bool success;
93 ut_a(m_filepath != nullptr);
94 ut_ad(m_handle.m_file == OS_FILE_CLOSED);
95
96 m_handle = os_file_create(innodb_data_file_key, m_filepath, m_open_flags,
97 OS_DATA_FILE, read_only_mode, &success);
98
99 if (!success) {
100 m_last_os_error = os_file_get_last_error(true);
101 ib::error(ER_IB_MSG_390) << "Cannot open datafile '" << m_filepath << "'";
102 return (DB_CANNOT_OPEN_FILE);
103 }
104
105 return (DB_SUCCESS);
106 }
107
108 /** Open a data file in read-only mode to check if it exists so that it
109 can be validated.
110 @param[in] strict whether to issue error messages
111 @return DB_SUCCESS or error code */
112 dberr_t Datafile::open_read_only(bool strict) {
113 bool success = false;
114 ut_ad(m_handle.m_file == OS_FILE_CLOSED);
115
116 /* This function can be called for file objects that do not need
117 to be opened, which is the case when the m_filepath is NULL */
118 if (m_filepath == nullptr) {
119 return (DB_ERROR);
120 }
121
122 set_open_flags(OS_FILE_OPEN);
123 m_handle = os_file_create_simple_no_error_handling(
124 innodb_data_file_key, m_filepath, m_open_flags, OS_FILE_READ_ONLY, true,
125 &success);
126
127 if (success) {
128 m_exists = true;
129 init_file_info();
130
131 return (DB_SUCCESS);
132 }
133
134 if (strict) {
135 m_last_os_error = os_file_get_last_error(true);
136 ib::error(ER_IB_MSG_391) << "Cannot open datafile for read-only: '"
137 << m_filepath << "' OS error: " << m_last_os_error;
138 }
139
140 return (DB_CANNOT_OPEN_FILE);
141 }
142
143 /** Open a data file in read-write mode during start-up so that
144 doublewrite pages can be restored and then it can be validated.
145 @param[in] read_only_mode if true, then readonly mode checks are enforced.
146 @return DB_SUCCESS or error code */
147 dberr_t Datafile::open_read_write(bool read_only_mode) {
148 bool success = false;
149 ut_ad(m_handle.m_file == OS_FILE_CLOSED);
150
151 /* This function can be called for file objects that do not need
152 to be opened, which is the case when the m_filepath is NULL */
153 if (m_filepath == nullptr) {
154 return (DB_ERROR);
155 }
156
157 set_open_flags(OS_FILE_OPEN);
158 m_handle = os_file_create_simple_no_error_handling(
159 innodb_data_file_key, m_filepath, m_open_flags, OS_FILE_READ_WRITE,
160 read_only_mode, &success);
161
162 if (!success) {
163 m_last_os_error = os_file_get_last_error(true);
164 ib::error(ER_IB_MSG_392)
165 << "Cannot open datafile for read-write: '" << m_filepath << "'";
166 return (DB_CANNOT_OPEN_FILE);
167 }
168
169 m_exists = true;
170
171 init_file_info();
172
173 return (DB_SUCCESS);
174 }
175
176 /** Initialize OS specific file info. */
177 void Datafile::init_file_info() {
178 #ifdef _WIN32
179 GetFileInformationByHandle(m_handle.m_file, &m_file_info);
180 #else
181 fstat(m_handle.m_file, &m_file_info);
182 #endif /* WIN32 */
183 }
184
185 /** Close a data file.
186 @return DB_SUCCESS or error code */
187 dberr_t Datafile::close() {
188 if (m_handle.m_file != OS_FILE_CLOSED) {
189 auto success = os_file_close(m_handle);
190 ut_a(success);
191
192 m_handle.m_file = OS_FILE_CLOSED;
193 }
194
195 return DB_SUCCESS;
196 }
197
198 /** Make a full filepath from a directory path and a filename.
199 Prepend the dirpath to filename using the extension given.
200 If dirpath is nullptr, prepend the default datadir to filepath.
201 Store the result in m_filepath.
202 @param[in] dirpath directory path
203 @param[in] filename filename or filepath
204 @param[in] ext filename extension */
205 void Datafile::make_filepath(const char *dirpath, const char *filename,
206 ib_file_suffix ext) {
207 free_filepath();
208
209 std::string path;
210 std::string name;
211
212 if (dirpath != nullptr) {
213 path.assign(dirpath);
214 }
215
216 if (filename != nullptr) {
217 name.assign(filename);
218 }
219
220 m_filepath = Fil_path::make(path, name, ext);
221
222 ut_ad(m_filepath != nullptr);
223
224 set_filename();
225 }
226
227 /** Set the filepath by duplicating the filepath sent in. This is the
228 name of the file with its extension and absolute or relative path.
229 @param[in] filepath filepath to set */
230 void Datafile::set_filepath(const char *filepath) {
231 free_filepath();
232 m_filepath = static_cast<char *>(
233 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, strlen(filepath) + 1));
234 ::strcpy(m_filepath, filepath);
235 set_filename();
236 }
237
238 /** Free the filepath buffer. */
239 void Datafile::free_filepath() {
240 if (m_filepath != nullptr) {
241 ut::free(m_filepath);
242 m_filepath = nullptr;
243 m_filename = nullptr;
244 }
245 }
246
247 /** Do a quick test if the filepath provided looks the same as this filepath
248 byte by byte. If they are two different looking paths to the same file,
249 same_as() will be used to show that after the files are opened.
250 @param[in] other filepath to compare with
251 @retval true if it is the same filename by byte comparison
252 @retval false if it looks different */
253 bool Datafile::same_filepath_as(const char *other) const {
254 return (0 == strcmp(m_filepath, other));
255 }
256
257 /** Test if another opened datafile is the same file as this object.
258 @param[in] other Datafile to compare with
259 @return true if it is the same file, else false */
260 bool Datafile::same_as(const Datafile &other) const {
261 #ifdef _WIN32
262 return (m_file_info.dwVolumeSerialNumber ==
263 other.m_file_info.dwVolumeSerialNumber &&
264 m_file_info.nFileIndexHigh == other.m_file_info.nFileIndexHigh &&
265 m_file_info.nFileIndexLow == other.m_file_info.nFileIndexLow);
266 #else
267 return (m_file_info.st_ino == other.m_file_info.st_ino &&
268 m_file_info.st_dev == other.m_file_info.st_dev);
269 #endif /* WIN32 */
270 }
271
272 /** Allocate and set the datafile or tablespace name in m_name.
273 If a name is provided, use it; else if the datafile is file-per-table,
274 extract a file-per-table tablespace name from m_filepath; else it is a
275 general tablespace, so just call it that for now. The value of m_name
276 will be freed in the destructor.
277 @param[in] name Tablespace Name if known, nullptr if not */
278 void Datafile::set_name(const char *name) {
279 ut::free(m_name);
280
281 if (name != nullptr) {
282 m_name = mem_strdup(name);
283 } else if (fsp_is_file_per_table(m_space_id, m_flags)) {
284 m_name = fil_path_to_space_name(m_filepath);
285 #ifndef UNIV_HOTBACKUP
286 } else if (fsp_is_undo_tablespace(m_space_id)) {
287 m_name = undo::make_space_name(m_space_id);
288 #endif /* !UNIV_HOTBACKUP */
289 } else if (fsp_is_dd_tablespace(m_space_id)) {
290 m_name = mem_strdup(dict_sys_t::s_dd_space_name);
291 } else {
292 #ifndef UNIV_HOTBACKUP
293 /* Give this general tablespace a temporary name. */
294 m_name = static_cast<char *>(ut::malloc_withkey(
295 UT_NEW_THIS_FILE_PSI_KEY, strlen(general_space_name) + 20));
296
297 sprintf(m_name, "%s_" SPACE_ID_PF, general_space_name, m_space_id);
298 #else /* !UNIV_HOTBACKUP */
299 /* Use the absolute path of general tablespaces. Absolute path
300 will help MEB to ignore the dirty records from the redo logs
301 pertaining to the same tablespace but with older space_ids.
302 It will also not cause name clashes with remote tablespaces or
303 tables in schema directory. */
304 size_t len = strlen(m_filepath);
305 m_name = static_cast<char *>(
306 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, len + 1));
307 memcpy(m_name, m_filepath, len);
308 m_name[len] = '\0';
309 #endif /* !UNIV_HOTBACKUP */
310 }
311 }
312
313 dberr_t Datafile::read_first_page() {
314 ut_ad(is_open());
315 /* Align the memory for a possible read from a raw device */
316 m_first_page = static_cast<byte *>(
317 ut::aligned_alloc(UNIV_PAGE_SIZE_MAX, UNIV_PAGE_SIZE));
318
319 IORequest request;
320 dberr_t err = DB_ERROR;
321 size_t page_size = UNIV_PAGE_SIZE_MAX;
322
323 /* Don't want unnecessary complaints about partial reads. */
324
325 request.disable_partial_io_warnings();
326
327 while (page_size >= UNIV_PAGE_SIZE_MIN) {
328 ulint n_read = 0;
329
330 err = os_file_read_no_error_handling(request, m_filename, m_handle,
331 m_first_page, 0, page_size, &n_read);
332
333 if (err == DB_IO_ERROR && n_read >= UNIV_PAGE_SIZE_MIN) {
334 page_size >>= 1;
335
336 } else if (err == DB_SUCCESS) {
337 ut_a(n_read == page_size);
338
339 break;
340
341 } else {
342 ib::error(ER_IB_MSG_393) << "Cannot read first page of '" << m_filepath
343 << "' " << ut_strerr(err);
344 break;
345 }
346 }
347
348 if (err == DB_SUCCESS && m_order == 0) {
349 m_flags = fsp_header_get_flags(m_first_page);
350
351 m_space_id = fsp_header_get_space_id(m_first_page);
352
353 m_server_version = fsp_header_get_server_version(m_first_page);
354
355 m_space_version = fsp_header_get_space_version(m_first_page);
356 }
357
358 return (err);
359 }
360
361 /** Free the first page from memory when it is no longer needed. */
362 void Datafile::free_first_page() {
363 ut::aligned_free(m_first_page);
364 m_first_page = nullptr;
365 }
366
367 /** Validates the datafile and checks that it conforms with the expected
368 space ID and flags. The file should exist and be successfully opened
369 in order for this function to validate it.
370 @param[in] space_id The expected tablespace ID.
371 @param[in] flags The expected tablespace flags.
372 @param[in] for_import if it is for importing
373 @retval DB_SUCCESS if tablespace is valid, DB_ERROR if not.
374 m_is_valid is also set true on success, else false. */
375 dberr_t Datafile::validate_to_dd(space_id_t space_id, uint32_t flags,
376 bool for_import) {
377 dberr_t err;
378
379 if (!is_open()) {
380 return (DB_ERROR);
381 }
382
383 /* Validate this single-table-tablespace with the data dictionary,
384 but do not compare the DATA_DIR flag, in case the tablespace was
385 remotely located. */
386 err = validate_first_page(space_id, nullptr, for_import);
387 if (err != DB_SUCCESS) {
388 return (err);
389 }
390
391 if (m_space_id == space_id && FSP_FLAGS_ARE_NOT_SET(flags) &&
392 fsp_is_dd_tablespace(space_id)) {
393 return (DB_SUCCESS);
394 }
395
396 /* Make sure the datafile we found matched the space ID.
397 If the datafile is a file-per-table tablespace then also match
398 the row format and zip page size. */
399
400 /* We exclude SDI & DATA_DIR space flags because they are not stored
401 in table flags in dictionary */
402
403 if (m_space_id == space_id &&
404 !((m_flags ^ flags) & ~(FSP_FLAGS_MASK_DATA_DIR | FSP_FLAGS_MASK_SHARED |
405 FSP_FLAGS_MASK_SDI))) {
406 /* Datafile matches the tablespace expected. */
407 return (DB_SUCCESS);
408 }
409
410 /* For a shared tablesapce, it is possible that encryption flag updated in
411 the ibd file, but the server crashed before DD flags are updated. Exclude
412 encryption flags for that scenario. */
413 if ((FSP_FLAGS_GET_ENCRYPTION(flags) != FSP_FLAGS_GET_ENCRYPTION(m_flags)) &&
414 fsp_is_shared_tablespace(flags)) {
415 #ifndef UNIV_HOTBACKUP
416 #ifdef UNIV_DEBUG
417 /* Note this tablespace id down and assert that it is in the list of
418 tablespaces for which encryption is being resumed. */
419 flag_mismatch_spaces.push_back(space_id);
420 #endif
421 #endif /* !UNIV_HOTBACKUP */
422
423 if (!((m_flags ^ flags) &
424 ~(FSP_FLAGS_MASK_ENCRYPTION | FSP_FLAGS_MASK_DATA_DIR |
425 FSP_FLAGS_MASK_SHARED | FSP_FLAGS_MASK_SDI))) {
426 return (DB_SUCCESS);
427 }
428 }
429
430 /* else do not use this tablespace. */
431 m_is_valid = false;
432
433 ib::error(ER_IB_MSG_394)
434 << "In file '" << m_filepath
435 << "', tablespace id and"
436 " flags are "
437 << m_space_id << " and " << m_flags
438 << ", but in"
439 " the InnoDB data dictionary they are "
440 << space_id << " and " << flags
441 << ". Have you moved InnoDB .ibd files around without"
442 " using the commands DISCARD TABLESPACE and IMPORT TABLESPACE?"
443 " "
444 << TROUBLESHOOT_DATADICT_MSG;
445
446 return (DB_ERROR);
447 }
448
449 dberr_t Datafile::validate_for_recovery(space_id_t space_id) {
450 dberr_t err;
451
452 ut_ad(!srv_read_only_mode);
453 ut_ad(is_open());
454
455 err = validate_first_page(space_id, nullptr, false);
456
457 switch (err) {
458 case DB_SUCCESS:
459 case DB_TABLESPACE_EXISTS:
460 case DB_TABLESPACE_NOT_FOUND:
461 case DB_INVALID_ENCRYPTION_META:
462 break;
463
464 default:
465 /* For encryption tablespace, we skip the retry step,
466 since it is only because the keyring is not ready. */
467 if (FSP_FLAGS_GET_ENCRYPTION(m_flags) && (err != DB_CORRUPTION)) {
468 return (err);
469 }
470
471 /* Re-open the file in read-write mode Attempt to restore
472 page 0 from doublewrite and read the space ID from a survey
473 of the first few pages. */
474 err = open_read_write(srv_read_only_mode);
475 if (err != DB_SUCCESS) {
476 ib::error(ER_IB_MSG_395) << "Datafile '" << m_filepath
477 << "' could not"
478 " be opened in read-write mode so that the"
479 " doublewrite pages could be restored.";
480 return (err);
481 };
482
483 err = find_space_id();
484 if (err != DB_SUCCESS || m_space_id == 0) {
485 ib::error(ER_IB_MSG_396)
486 << "Datafile '" << m_filepath
487 << "' is"
488 " corrupted. Cannot determine the space ID from"
489 " the first 64 pages.";
490 return (err);
491 }
492
493 err = restore_from_doublewrite(0);
494
495 if (err != DB_SUCCESS) {
496 return (err);
497 }
498
499 /* Free the previously read first page and then re-validate. */
500 free_first_page();
501
502 err = validate_first_page(space_id, nullptr, false);
503 }
504
505 if (err == DB_SUCCESS || err == DB_INVALID_ENCRYPTION_META) {
506 set_name(nullptr);
507 }
508
509 return (err);
510 }
511
512 dberr_t Datafile::validate_first_page(space_id_t space_id, lsn_t *flush_lsn,
513 bool for_import) {
514 char *prev_name;
515 char *prev_filepath;
516 const char *error_txt = nullptr;
517
518 m_is_valid = true;
519 ut_ad(is_open());
520
521 if (m_first_page == nullptr && read_first_page() != DB_SUCCESS) {
522 error_txt = "Cannot read first page";
523 } else {
524 ut_ad(m_first_page);
525
526 if (flush_lsn != nullptr) {
527 *flush_lsn = mach_read_from_8(m_first_page + FIL_PAGE_FILE_FLUSH_LSN);
528 }
529 }
530 /* fil_space_read_name_and_filepath will acquire the fil shard mutex. If there
531 is any other thread that tries to open this file, it will have the fil
532 mutex and will wait for this file to open. It will not succeed on Windows
533 as we don't open the file for shared write. */
534 close();
535
536 if (error_txt == nullptr && m_space_id == TRX_SYS_SPACE && !m_flags) {
537 /* Check if the whole page is blank. */
538
539 const byte *b = m_first_page;
540 ulint nonzero_bytes = UNIV_PAGE_SIZE;
541
542 while (*b == '\0' && --nonzero_bytes != 0) {
543 b++;
544 }
545
546 if (nonzero_bytes == 0) {
547 error_txt = "Header page consists of zero bytes";
548 }
549 }
550
551 const page_size_t page_size(m_flags);
552
553 if (error_txt != nullptr) {
554 /* skip the next few tests */
555 } else if (univ_page_size.logical() != page_size.logical()) {
556 /* Page size must be univ_page_size. */
557
558 ib::error(ER_IB_MSG_397) << "Data file '" << m_filepath
559 << "' uses page size " << page_size.logical()
560 << ", but the innodb_page_size"
561 " start-up parameter is "
562 << univ_page_size.logical();
563
564 free_first_page();
565
566 return (DB_ERROR);
567 } else if (!fsp_flags_is_valid(m_flags) || FSP_FLAGS_GET_TEMPORARY(m_flags)) {
568 /* Tablespace flags must be valid. */
569 error_txt = "Tablespace flags are invalid";
570 } else if (page_get_page_no(m_first_page) != 0) {
571 /* First page must be number 0 */
572 error_txt = "Header page contains inconsistent data";
573
574 } else if (m_space_id == SPACE_UNKNOWN) {
575 /* The space_id can be most anything, except -1. */
576 error_txt = "A bad Space ID was found";
577
578 } else if (m_space_id != 0 && space_id != m_space_id) {
579 /* Tablespace ID mismatch. The file could be in use
580 by another tablespace. */
581
582 #ifndef UNIV_HOTBACKUP
583 ut_d(ib::info(ER_IB_MSG_398)
584 << "Tablespace file '" << filepath() << "' ID mismatch"
585 << ", expected " << space_id << " but found " << m_space_id);
586 #else /* !UNIV_HOTBACKUP */
587 ib::trace_2() << "Tablespace file '" << filepath() << "' ID mismatch"
588 << ", expected " << space_id << " but found " << m_space_id;
589 #endif /* !UNIV_HOTBACKUP */
590
591 return (DB_WRONG_FILE_NAME);
592
593 } else {
594 BlockReporter reporter(false, m_first_page, page_size,
595 fsp_is_checksum_disabled(m_space_id));
596
597 if (reporter.is_corrupted()) {
598 /* Look for checksum and other corruptions. */
599 error_txt = "Checksum mismatch";
600 }
601
602 /** TODO: Enable following after WL#11063: Update
603 server version information in InnoDB tablespaces:
604
605 else if (!for_import
606 && (fsp_header_get_server_version(m_first_page)
607 != DD_SPACE_CURRENT_SRV_VERSION)) {
608 error_txt = "Wrong server version";
609 } else if (!for_import
610 && (fsp_header_get_space_version(m_first_page)
611 != DD_SPACE_CURRENT_SPACE_VERSION)) {
612 error_txt = "Wrong tablespace version";
613 } */
614 }
615
616 if (error_txt != nullptr) {
617 ib::error(ER_IB_MSG_399)
618 << error_txt << " in datafile: " << m_filepath
619 << ", Space ID:" << m_space_id << ", Flags: " << m_flags << ". "
620 << TROUBLESHOOT_DATADICT_MSG;
621 m_is_valid = false;
622
623 free_first_page();
624
625 return (DB_CORRUPTION);
626 }
627
628 /* For encrypted tablespace, check the encryption info in the
629 first page can be decrypt by master key, otherwise, this table
630 can't be open. And for importing, we skip checking it. */
631 if (FSP_FLAGS_GET_ENCRYPTION(m_flags) && !for_import) {
632 m_encryption_key = static_cast<byte *>(
633 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, Encryption::KEY_LEN));
634 m_encryption_iv = static_cast<byte *>(
635 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, Encryption::KEY_LEN));
636 #ifdef UNIV_ENCRYPT_DEBUG
637 fprintf(stderr, "Got from file %u:", m_space_id);
638 #endif
639
640 Encryption_key e_key{m_encryption_key, m_encryption_iv};
641 if (!fsp_header_get_encryption_key(m_flags, e_key, m_first_page)) {
642 ib::error(ER_IB_MSG_401)
643 << "Encryption information in datafile: " << m_filepath
644 << " can't be decrypted, please confirm that"
645 " keyring is loaded.";
646
647 m_is_valid = false;
648 free_first_page();
649 ut::free(m_encryption_key);
650 ut::free(m_encryption_iv);
651 m_encryption_key = nullptr;
652 m_encryption_iv = nullptr;
653 return (DB_INVALID_ENCRYPTION_META);
654 } else {
655 #ifdef UNIV_DEBUG
656 ib::info(ER_IB_MSG_402) << "Read encryption metadata from " << m_filepath
657 << " successfully, encryption"
658 << " of this tablespace enabled.";
659 #endif
660 m_encryption_master_key_id = e_key.m_master_key_id;
661 }
662
663 if (recv_recovery_is_on() &&
664 memcmp(m_encryption_key, m_encryption_iv, Encryption::KEY_LEN) == 0) {
665 ut::free(m_encryption_key);
666 ut::free(m_encryption_iv);
667 m_encryption_key = nullptr;
668 m_encryption_iv = nullptr;
669 }
670 }
671 #ifndef UNIV_HOTBACKUP
672 /* Set encryption operation in progress based on operation type
673 at page 0. */
674 m_encryption_op_in_progress =
675 fsp_header_encryption_op_type_in_progress(m_first_page, page_size);
676 #endif /* UNIV_HOTBACKUP */
677 /* Following call will attempt to acquire a Fil_shard mutex, which can cause
678 a deadlock if done while holding file handle open. */
679 ut_ad(!is_open());
680 if (fil_space_read_name_and_filepath(m_space_id, &prev_name,
681 &prev_filepath)) {
682 if (0 == strcmp(m_filepath, prev_filepath)) {
683 ut::free(prev_name);
684 ut::free(prev_filepath);
685 return (DB_SUCCESS);
686 }
687
688 /* Make sure the space_id has not already been opened. */
689 ib::error(ER_IB_MSG_403) << "Attempted to open a previously opened"
690 " tablespace. Previous tablespace "
691 << prev_name << " at filepath: " << prev_filepath
692 << " uses space ID: " << m_space_id
693 << ". Cannot open filepath: " << m_filepath
694 << " which uses the same space ID.";
695
696 ut::free(prev_name);
697 ut::free(prev_filepath);
698
699 m_is_valid = false;
700
701 free_first_page();
702
703 return (DB_TABLESPACE_EXISTS);
704 }
705
706 return (DB_SUCCESS);
707 }
708
709 /** Determine the space id of the given file descriptor by reading a few
710 pages from the beginning of the .ibd file.
711 @return DB_SUCCESS if space id was successfully identified, else DB_ERROR. */
712 dberr_t Datafile::find_space_id() {
713 os_offset_t file_size;
714
715 ut_ad(m_handle.m_file != OS_FILE_CLOSED);
716
717 file_size = os_file_get_size(m_handle);
718
719 if (file_size == (os_offset_t)-1) {
720 ib::error(ER_IB_MSG_404)
721 << "Could not get file size of datafile '" << m_filepath << "'";
722 return (DB_CORRUPTION);
723 }
724
725 /* Assuming a page size, read the space_id from each page and store it
726 in a map. Find out which space_id is agreed on by majority of the
727 pages. Choose that space_id. */
728 for (uint32_t page_size = UNIV_ZIP_SIZE_MIN; page_size <= UNIV_PAGE_SIZE_MAX;
729 page_size <<= 1) {
730 /* map[space_id] = count of pages */
731 typedef std::map<space_id_t, ulint, std::less<space_id_t>,
732 ut::allocator<std::pair<const space_id_t, ulint>>>
733 Pages;
734
735 Pages verify;
736 ulint page_count = 64;
737 ulint valid_pages = 0;
738
739 /* Adjust the number of pages to analyze based on file size */
740 while ((page_count * page_size) > file_size) {
741 --page_count;
742 }
743
744 ib::info(ER_IB_MSG_405)
745 << "Page size:" << page_size << ". Pages to analyze:" << page_count;
746
747 byte *page = static_cast<byte *>(
748 ut::aligned_alloc(UNIV_PAGE_SIZE_MAX, UNIV_SECTOR_SIZE));
749
750 for (ulint j = 0; j < page_count; ++j) {
751 dberr_t err;
752 ulint n_bytes = j * page_size;
753 IORequest request(IORequest::READ);
754 bool encrypted = false;
755
756 err =
757 os_file_read(request, m_filename, m_handle, page, n_bytes, page_size);
758
759 if (err == DB_IO_DECRYPT_FAIL) {
760 /* At this stage, even if the page decryption failed, we don't have to
761 report error now. Currently, only the space_id will be read from the
762 page header. Since page header is unencrypted, we will ignore the
763 decryption error for now. */
764 encrypted = true;
765
766 } else if (err == DB_IO_DECOMPRESS_FAIL) {
767 /* If the page was compressed on the fly then
768 try and decompress the page */
769
770 n_bytes = os_file_compressed_page_size(page);
771
772 if (n_bytes != ULINT_UNDEFINED) {
773 err = os_file_read(request, m_filename, m_handle, page, page_size,
774 UNIV_PAGE_SIZE_MAX);
775
776 if (err != DB_SUCCESS) {
777 ib::info(ER_IB_MSG_406) << "READ FAIL: "
778 << "page_no:" << j;
779 continue;
780 }
781 }
782
783 } else if (err != DB_SUCCESS) {
784 ib::info(ER_IB_MSG_407) << "READ FAIL: page_no:" << j;
785
786 continue;
787 }
788
789 bool noncompressed_ok = false;
790
791 /* For noncompressed pages, the page size must be
792 equal to univ_page_size.physical(). */
793 if (page_size == univ_page_size.physical()) {
794 BlockReporter reporter(false, page, univ_page_size, false);
795
796 noncompressed_ok = !reporter.is_corrupted();
797 }
798
799 bool compressed_ok = false;
800
801 /* file-per-table tablespaces can be compressed with
802 the same physical and logical page size. General
803 tablespaces must have different physical and logical
804 page sizes in order to be compressed. For this check,
805 assume the page is compressed if univ_page_size.
806 logical() is equal to or less than 16k and the
807 page_size we are checking is equal to or less than
808 univ_page_size.logical(). */
809 if (!encrypted && univ_page_size.logical() <= UNIV_PAGE_SIZE_DEF &&
810 page_size <= univ_page_size.logical()) {
811 const page_size_t compr_page_size(page_size, univ_page_size.logical(),
812 true);
813
814 BlockReporter reporter(false, page, compr_page_size, false);
815
816 compressed_ok = !reporter.is_corrupted();
817 }
818
819 if (noncompressed_ok || compressed_ok || encrypted) {
820 space_id_t space_id = mach_read_from_4(page + FIL_PAGE_SPACE_ID);
821
822 if (space_id > 0) {
823 ib::info(ER_IB_MSG_408)
824 << "VALID: space:" << space_id << " page_no:" << j
825 << " page_size:" << page_size;
826
827 ++valid_pages;
828
829 ++verify[space_id];
830 }
831 }
832 }
833
834 ut::aligned_free(page);
835
836 ib::info(ER_IB_MSG_409) << "Page size: " << page_size
837 << ". Possible space_id count:" << verify.size();
838
839 const ulint pages_corrupted = 3;
840
841 for (ulint missed = 0; missed <= pages_corrupted; ++missed) {
842 for (Pages::const_iterator it = verify.begin(); it != verify.end();
843 ++it) {
844 ib::info(ER_IB_MSG_410)
845 << "space_id:" << it->first
846 << ", Number of pages matched: " << it->second << "/" << valid_pages
847 << " (" << page_size << ")";
848
849 if (it->second == (valid_pages - missed)) {
850 ib::info(ER_IB_MSG_411) << "Chosen space:" << it->first;
851
852 m_space_id = it->first;
853 return (DB_SUCCESS);
854 }
855 }
856 }
857 }
858
859 return (DB_CORRUPTION);
860 }
861
862 /** Finds a given page of the given space id from the double write buffer
863 and copies it to the corresponding .ibd file.
864 @param[in] restore_page_no Page number to restore
865 @return DB_SUCCESS if page was restored from doublewrite, else DB_ERROR */
866 dberr_t Datafile::restore_from_doublewrite(page_no_t restore_page_no) {
867 ut_a(is_open());
868 auto page_id = page_id_t{m_space_id, restore_page_no};
869
870 /* Find if double write buffer contains page_no of given space id. */
871 const byte *page = recv_sys->dblwr->find(page_id);
872
873 bool found = false;
874 lsn_t reduced_lsn = LSN_MAX;
875 std::tie(found, reduced_lsn) = recv_sys->dblwr->find_entry(page_id);
876
877 if (page == nullptr) {
878 /* If the first page of the given user tablespace is not there
879 in the doublewrite buffer, then the recovery is going to fail
880 now. Hence this is treated as an error. */
881
882 if (found && reduced_lsn != LSN_MAX && reduced_lsn != 0) {
883 ib::fatal(UT_LOCATION_HERE, ER_REDUCED_DBLWR_PAGE_FOUND, m_filepath,
884 page_id.space(), page_id.page_no());
885 } else {
886 ib::error(ER_IB_MSG_412)
887 << "Corrupted page " << page_id_t(m_space_id, restore_page_no)
888 << " of datafile '" << m_filepath
889 << "' could not be found in the doublewrite buffer.";
890 }
891 return (DB_CORRUPTION);
892 }
893
894 const lsn_t dblwr_lsn = mach_read_from_8(page + FIL_PAGE_LSN);
895
896 if (found && reduced_lsn != LSN_MAX && reduced_lsn > dblwr_lsn) {
897 ib::fatal(UT_LOCATION_HERE, ER_REDUCED_DBLWR_PAGE_FOUND, m_filepath,
898 page_id.space(), page_id.page_no());
899 }
900
901 const uint32_t flags = fsp_header_get_field(page, FSP_SPACE_FLAGS);
902
903 const page_size_t page_size(flags);
904
905 ut_a(page_get_page_no(page) == restore_page_no);
906
907 ib::info(ER_IB_MSG_413) << "Restoring page "
908 << page_id_t(m_space_id, restore_page_no)
909 << " of datafile '" << m_filepath
910 << "' from the doublewrite buffer. Writing "
911 << page_size.physical() << " bytes into file '"
912 << m_filepath << "'";
913
914 IORequest request(IORequest::WRITE);
915
916 /* Note: The pages are written out as uncompressed because we don't
917 have the compression algorithm information at this point. */
918
919 request.disable_compression();
920
921 return (os_file_write(request, m_filepath, m_handle, page, 0,
922 page_size.physical()));
923 }