Debian Codegraph @

storage/innobase/fil/fil0fil.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
6 it under the terms of the GNU General Public License, version 2.0,
7 as published by the 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,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file fil/fil0fil.cc
29 The tablespace memory cache */
30
31 #include <fil0fil.h>
32 #include "my_config.h"
33
34 #include "detail/fil/open_files_limit.h"
35
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39
40 #include <scope_guard.h>
41 #include "arch0page.h"
42 #include "btr0btr.h"
43 #include "buf0buf.h"
44 #include "buf0flu.h"
45 #include "clone0api.h"
46 #include "dict0boot.h"
47 #include "dict0dd.h"
48 #include "dict0dict.h"
49 #include "fsp0file.h"
50 #include "fsp0fsp.h"
51 #include "fsp0space.h"
52 #include "fsp0sysspace.h"
53 #include "ha_prototypes.h"
54 #include "hash0hash.h"
55 #include "log0buf.h"
56 #include "log0chkp.h"
57 #include "log0recv.h"
58 #include "log0write.h"
59 #include "mach0data.h"
60 #include "mem0mem.h"
61 #include "mtr0log.h"
62 #include "my_dbug.h"
63 #include "os0file.h"
64 #include "page0zip.h"
65 #include "sql/mysqld.h" // lower_case_file_system
66 #include "srv0srv.h"
67 #include "srv0start.h"
68 #include "univ.i" // Using OS_PATH_SEPARATOR
69 #include "ut0new.h"
70
71 #ifndef UNIV_HOTBACKUP
72 #include "buf0lru.h"
73 #include "ibuf0ibuf.h"
74 #include "os0event.h"
75 #include "row0mysql.h"
76 #include "sql_backup_lock.h"
77 #include "sql_class.h"
78 #include "sync0sync.h"
79 #include "trx0purge.h"
80 #else /* !UNIV_HOTBACKUP */
81 #include <cstring>
82 #include "srv0srv.h"
83 #endif /* !UNIV_HOTBACKUP */
84
85 #include "os0thread-create.h"
86
87 #include "current_thd.h"
88 #include "ha_prototypes.h"
89
90 #include <array>
91 #include <fstream>
92 #include <functional>
93 #include <list>
94 #include <mutex>
95 #include <thread>
96 #include <tuple>
97 #include <unordered_map>
98
99 using Dirs = std::vector<std::string>;
100 using Space_id_set = std::set<space_id_t>;
101
102 dberr_t dict_stats_rename_table(const char *old_name, const char *new_name,
103 char *errstr, size_t errstr_sz);
104
105 /** Used for collecting the data in boot_tablespaces() */
106 namespace dd_fil {
107
108 struct Moved {
109 /** DD Object ID */
110 dd::Object_id object_id;
111
112 /** InnoDB tablspace ID */
113 space_id_t space_id;
114
115 /** DD/InnoDB tablespace name */
116 std::string space_name;
117
118 /** Path in DD tablespace */
119 std::string old_path;
120
121 /** Path where it was found during the scan. */
122 std::string new_path;
123
124 /** This tablespace has moved out of data directory but is missing the
125 DD_TABLE_DATA_DIRECTORY flag. This can happen before versions
126 8.0.38/8.4.1/9.0.0 */
127 bool dd_flag_missing;
128 };
129
130 using Tablespaces = std::vector<Moved>;
131 } // namespace dd_fil
132
133 size_t fil_get_scan_threads(size_t num_files) {
134 /* Number of additional threads required to scan all the files.
135 n_threads == 0 means that the main thread itself will do all the
136 work instead of spawning any additional threads. */
137 size_t n_threads = num_files / FIL_SCAN_MAX_TABLESPACES_PER_THREAD;
138
139 /* Return if no additional threads are needed. */
140 if (n_threads == 0) {
141 return 0;
142 }
143
144 /* Number of concurrent threads supported by the host machine. */
145 size_t max_threads =
146 FIL_SCAN_THREADS_PER_CORE * std::thread::hardware_concurrency();
147
148 /* If the number of concurrent threads supported by the host
149 machine could not be calculated, assume the supported threads
150 to be FIL_SCAN_MAX_THREADS. */
151 max_threads = max_threads == 0 ? FIL_SCAN_MAX_THREADS : max_threads;
152
153 /* Restrict the number of threads to the lower of number of threads
154 supported by the host machine or FIL_SCAN_MAX_THREADS. */
155 if (n_threads > max_threads) {
156 n_threads = max_threads;
157 }
158
159 if (n_threads > FIL_SCAN_MAX_THREADS) {
160 n_threads = FIL_SCAN_MAX_THREADS;
161 }
162
163 return n_threads;
164 }
165
166 /* uint16_t is the index into Tablespace_dirs::m_dirs */
167 using Scanned_files = std::vector<std::pair<uint16_t, std::string>>;
168
169 #ifdef UNIV_PFS_IO
170 mysql_pfs_key_t innodb_tablespace_open_file_key;
171 #endif /* UNIV_PFS_IO */
172
173 /** System tablespace. */
174 fil_space_t *fil_space_t::s_sys_space;
175
176 #ifdef UNIV_HOTBACKUP
177 /** Directories in which remote general tablespaces have been found in the
178 target directory during apply log operation */
179 Dir_set rem_gen_ts_dirs;
180
181 /** true in case the apply-log operation is being performed
182 in the data directory */
183 bool replay_in_datadir = false;
184
185 /* Re-define mutex macros to use the Mutex class defined by the MEB
186 source. MEB calls the routines in "fil0fil.cc" in parallel and,
187 therefore, the mutex protecting the critical sections of the tablespace
188 memory cache must be included also in the MEB compilation of this
189 module. */
190 #undef mutex_create
191 #undef mutex_free
192 #undef mutex_enter
193 #undef mutex_exit
194 #undef mutex_own
195 #undef mutex_validate
196
197 #define mutex_create(I, M) new (M) meb::Mutex()
198 #define mutex_free(M) delete (M)
199 #define mutex_enter(M) (M)->lock()
200 #define mutex_exit(M) (M)->unlock()
201 #define mutex_own(M) 1
202 #define mutex_validate(M) 1
203
204 /** Process a MLOG_FILE_CREATE redo record.
205 @param[in] page_id Page id of the redo log record
206 @param[in] flags Tablespace flags
207 @param[in] name Tablespace filename */
208 static void meb_tablespace_redo_create(const page_id_t &page_id, uint32_t flags,
209 const char *name);
210
211 /** Process a MLOG_FILE_RENAME redo record.
212 @param[in] page_id Page id of the redo log record
213 @param[in] from_name Tablespace from filename
214 @param[in] to_name Tablespace to filename */
215 static void meb_tablespace_redo_rename(const page_id_t &page_id,
216 const char *from_name,
217 const char *to_name);
218
219 /** Process a MLOG_FILE_DELETE redo record.
220 @param[in] page_id Page id of the redo log record
221 @param[in] name Tablespace filename */
222 static void meb_tablespace_redo_delete(const page_id_t &page_id,
223 const char *name);
224
225 #endif /* UNIV_HOTBACKUP */
226
227 /*
228 IMPLEMENTATION OF THE TABLESPACE MEMORY CACHE
229 =============================================
230
231 The tablespace cache is responsible for providing fast read/write access to
232 tablespaces. File creation and deletion is done in other modules which know
233 more of the logic of the operation, however.
234
235 Only the system tablespace consists of a list of files. The size of these
236 files does not have to be divisible by the database block size, because
237 we may just leave the last incomplete block unused. When a new file is
238 appended to the tablespace, the maximum size of the file is also specified.
239 At the moment, we think that it is best to extend the file to its maximum
240 size already at the creation of the file, because then we can avoid dynamically
241 extending the file when more space is needed for the tablespace.
242
243 Non system tablespaces contain only a single file.
244
245 A block's position in the tablespace is specified with a 32-bit unsigned
246 integer. The files in the list are thought to be catenated, and the block
247 corresponding to an address n is the nth block in the catenated file (where
248 the first block is named the 0th block, and the incomplete block fragments
249 at the end of files are not taken into account). A tablespace can be extended
250 by appending a new file at the end of the list.
251
252 Our tablespace concept is similar to the one of Oracle.
253
254 To have fast access to a tablespace file, we put the data structures to
255 a hash table. Each tablespace file is given an unique 32-bit identifier,
256 its tablespace ID.
257
258 Some operating systems do not support many open files at the same time, or have
259 a limit set for user or process. Therefore, we put the open files that can be
260 easily closed in an LRU-list. If we need to open another file, we may close the
261 file at the end of the LRU-list. When an I/O-operation is pending on a file, the
262 file cannot be closed - we take the file nodes with pending I/O-operations out
263 of the LRU-list and keep a count of pending operations for each such file node.
264 When an operation completes, we decrement the count and return the file to the
265 LRU-list if the count drops to zero.
266
267 The data structure (Fil_shard) that keeps track of the tablespace ID to
268 fil_space_t* mapping are hashed on the tablespace ID. The tablespace name to
269 fil_space_t* mapping is stored in the same shard. A shard tracks the flushing
270 and open state of a file. When we run out open file handles, we use a ticketing
271 system to serialize the file open, see Fil_shard::reserve_open_slot() and
272 Fil_shard::release_open_slot().
273
274 When updating the global/shared data in Fil_system acquire the mutexes of
275 all shards in ascending order. The shard mutex covers the fil_space_t data
276 members as noted in the fil_space_t and fil_node_t definition. */
277
278 /** Reference to the server data directory. */
279 Fil_path MySQL_datadir_path;
280
281 /** Reference to the server undo directory. */
282 Fil_path MySQL_undo_path;
283
284 /** The undo path is different from any other known directory. */
285 bool MySQL_undo_path_is_unique;
286
287 /** Common InnoDB file extensions */
288 const char *dot_ext[] = {"", ".ibd", ".cfg", ".cfp",
289 ".ibt", ".ibu", ".dblwr", ".bdblwr"};
290
291 /** Number of pending tablespace flushes */
292 std::atomic<std::uint64_t> fil_n_pending_tablespace_flushes = 0;
293
294 /** Number of files currently open */
295 std::atomic_size_t fil_n_files_open{0};
296
297 enum fil_load_status {
298 /** The tablespace file(s) were found and valid. */
299 FIL_LOAD_OK,
300
301 /** The name no longer matches space_id */
302 FIL_LOAD_ID_CHANGED,
303
304 /** The file(s) were not found */
305 FIL_LOAD_NOT_FOUND,
306
307 /** The file(s) were not valid */
308 FIL_LOAD_INVALID,
309
310 /** The tablespace file ID in the first page doesn't match
311 expected value. */
312 FIL_LOAD_MISMATCH,
313
314 /** Doublewrite buffer corruption */
315 FIL_LOAD_DBWLR_CORRUPTION
316 };
317
318 /** File operations for tablespace */
319 enum fil_operation_t {
320
321 /** delete a single-table tablespace */
322 FIL_OPERATION_DELETE,
323
324 /** close a single-table tablespace */
325 FIL_OPERATION_CLOSE
326 };
327
328 /** The null file address */
329 fil_addr_t fil_addr_null = {FIL_NULL, 0};
330
331 #ifndef UNIV_HOTBACKUP
332 /** Maximum number of shards supported. */
333 static const size_t MAX_SHARDS = 68;
334
335 /** Number of undo shards to reserve. */
336 static const size_t UNDO_SHARDS = 4;
337
338 /** The UNDO logs have their own shards (4). */
339 static const size_t UNDO_SHARDS_START = MAX_SHARDS - UNDO_SHARDS;
340 #else /* !UNIV_HOTBACKUP */
341
342 /** Maximum number of shards supported. */
343 static const size_t MAX_SHARDS = 1;
344
345 /** The UNDO logs have their own shards (4). */
346 static const size_t UNDO_SHARDS_START = 0;
347 #endif /* !UNIV_HOTBACKUP */
348
349 /** We want to store the line number from where it was called. */
350 #define mutex_acquire() acquire(__LINE__)
351
352 /** Hash a NUL terminated 'string' */
353 struct Char_Ptr_Hash {
354 /** Hashing function
355 @param[in] ptr NUL terminated string to hash
356 @return the hash */
357 size_t operator()(const char *ptr) const {
358 return static_cast<size_t>(ut::hash_string(ptr));
359 }
360 };
361
362 /** Compare two 'strings' */
363 struct Char_Ptr_Compare {
364 /** Compare two NUL terminated strings
365 @param[in] lhs Left hand side
366 @param[in] rhs Right hand side
367 @return true if the contents match */
368 bool operator()(const char *lhs, const char *rhs) const {
369 return (strcmp(lhs, rhs) == 0);
370 }
371 };
372
373 /** Tablespace files discovered during startup. */
374 class Tablespace_files {
375 public:
376 using Names = std::vector<std::string, ut::allocator<std::string>>;
377 using Paths = std::unordered_map<space_id_t, Names>;
378 using Undo_num2id = std::unordered_map<space_id_t, space_id_t>;
379
380 /** Default constructor
381 @param[in] dir Directory that the files are under */
382 explicit Tablespace_files(const std::string &dir);
383
384 /** Add a space ID to filename mapping.
385 @param[in] space_id Tablespace ID
386 @param[in] name File name.
387 @return number of files that map to the space ID */
388 [[nodiscard]] size_t add(space_id_t space_id, const std::string &name);
389
390 /** Get the file names that map to a space ID
391 @param[in] space_id Tablespace ID
392 @return the filenames that map to space id */
393 [[nodiscard]] Names *find_by_id(space_id_t space_id) {
394 ut_ad(space_id != TRX_SYS_SPACE);
395
396 if (undo::is_reserved(space_id)) {
397 auto it = m_undo_paths.find(space_id);
398
399 if (it != m_undo_paths.end()) {
400 return &it->second;
401 }
402
403 } else {
404 auto it = m_ibd_paths.find(space_id);
405
406 if (it != m_ibd_paths.end()) {
407 return &it->second;
408 }
409 }
410
411 return nullptr;
412 }
413
414 /** Get the file name that maps to an undo space number
415 @param[in] space_num undo tablespace number
416 @param[out] space_id undo tablespace ID
417 @return the file name that maps to the space number */
418 [[nodiscard]] Names *find_by_num(space_id_t space_num, space_id_t &space_id) {
419 ut_ad(space_num > 0 && space_num <= FSP_MAX_UNDO_TABLESPACES);
420 auto it_nums = m_undo_nums.find(space_num);
421 if (it_nums == m_undo_nums.end()) {
422 return (nullptr);
423 }
424 space_id = it_nums->second;
425
426 auto it = m_undo_paths.find(space_id);
427 ut_ad(it != m_undo_paths.end());
428
429 return (&it->second);
430 }
431
432 /** Remove the entry for the space ID.
433 @param[in] space_id Tablespace ID mapping to remove
434 @return true if erase successful */
435 [[nodiscard]] bool erase_path(space_id_t space_id) {
436 ut_ad(space_id != TRX_SYS_SPACE);
437
438 if (undo::is_reserved(space_id)) {
439 auto n_erased = m_undo_nums.erase(undo::id2num(space_id));
440 ut_ad(n_erased == 1);
441
442 n_erased = m_undo_paths.erase(space_id);
443
444 return (n_erased == 1);
445 } else {
446 auto n_erased = m_ibd_paths.erase(space_id);
447
448 return (n_erased == 1);
449 }
450 }
451
452 /** Clear all the tablespace data. */
453 void clear() {
454 m_ibd_paths.clear();
455 m_undo_paths.clear();
456 m_undo_nums.clear();
457 }
458
459 /** @return m_dir */
460 const Fil_path &root() const { return m_dir; }
461
462 /** @return the directory path specified by the user. */
463 const std::string &path() const { return m_dir.path(); }
464
465 private:
466 /* Note: The file names in m_ibd_paths and m_undo_paths are relative
467 to m_real_path. */
468
469 /** Mapping from tablespace ID to data filenames */
470 Paths m_ibd_paths;
471
472 /** Mapping from tablespace ID to Undo files */
473 Paths m_undo_paths;
474
475 /** Mapping from undo space number to space ID */
476 Undo_num2id m_undo_nums;
477
478 /** Top level directory where the above files were found. */
479 Fil_path m_dir;
480 };
481
482 /** Directories scanned during startup and the files discovered. */
483 class Tablespace_dirs {
484 public:
485 using Result = std::pair<std::string, Tablespace_files::Names *>;
486
487 /** Constructor */
488 Tablespace_dirs() : m_dirs(), m_checked() {}
489
490 /** Normalize and save a directory to scan for IBD and IBU datafiles
491 before recovery.
492 @param[in] directory directory to scan for ibd and ibu files
493 @param[in] is_undo_dir true for an undo directory */
494 void set_scan_dir(const std::string &directory, bool is_undo_dir = false);
495
496 /** Normalize and save a list of directories to scan for IBD and IBU
497 datafiles before recovery.
498 @param[in] directories Directories to scan for ibd and ibu files */
499 void set_scan_dirs(const std::string &directories);
500
501 /** Discover tablespaces by reading the header from .ibd files.
502 @return DB_SUCCESS if all goes well */
503 [[nodiscard]] dberr_t scan();
504
505 /** Clear all the tablespace file data but leave the list of
506 scanned directories in place. */
507 void clear() {
508 for (auto &dir : m_dirs) {
509 dir.clear();
510 }
511
512 m_checked = 0;
513 }
514
515 /** Erase a space ID to filename mapping.
516 @param[in] space_id Tablespace ID to erase
517 @return true if successful */
518 [[nodiscard]] bool erase_path(space_id_t space_id) {
519 for (auto &dir : m_dirs) {
520 if (dir.erase_path(space_id)) {
521 return true;
522 }
523 }
524
525 return false;
526 }
527
528 /* Find the first matching space ID -> name mapping.
529 @param[in] space_id Tablespace ID
530 @return directory searched and pointer to names that map to the
531 tablespace ID */
532 [[nodiscard]] Result find_by_id(space_id_t space_id) {
533 for (auto &dir : m_dirs) {
534 const auto names = dir.find_by_id(space_id);
535
536 if (names != nullptr) {
537 return (Result{dir.path(), names});
538 }
539 }
540
541 return (Result{"", nullptr});
542 }
543
544 /* Find the matching space number ->space ID -> name mapping.
545 @param[in] space_num undo tablespace number
546 @param[out] space_id undo tablespace ID
547 @return directory searched and pointer to name that maps to the
548 tablespace number */
549 [[nodiscard]] Result find_by_num(space_id_t space_num, space_id_t &space_id) {
550 for (auto &dir : m_dirs) {
551 const auto names = dir.find_by_num(space_num, space_id);
552
553 if (names != nullptr) {
554 return Result{dir.path(), names};
555 }
556 }
557
558 return Result{"", nullptr};
559 }
560
561 /** Determine if this Fil_path contains the path provided.
562 @param[in] path file or directory path to compare.
563 @return true if this Fil_path contains path */
564 [[nodiscard]] bool contains(const std::string &path) const {
565 const Fil_path descendant{path};
566
567 for (const auto &dir : m_dirs) {
568 if (dir.root().is_same_as(descendant) ||
569 dir.root().is_ancestor(descendant)) {
570 return true;
571 }
572 }
573 return false;
574 }
575
576 /** Get the list of directories that InnoDB knows about.
577 @return the list of directories 'dir1;dir2;....;dirN' */
578 std::string get_dirs() const {
579 std::string dirs;
580
581 ut_ad(!m_dirs.empty());
582
583 for (const auto &dir : m_dirs) {
584 dirs.append(dir.root());
585 dirs.push_back(FIL_PATH_SEPARATOR);
586 }
587
588 dirs.pop_back();
589
590 ut_ad(!dirs.empty());
591
592 return dirs;
593 }
594
595 private:
596 /** Print the duplicate filenames for a tablespace ID to the log
597 @param[in] duplicates Duplicate tablespace IDs*/
598 void print_duplicates(const Space_id_set &duplicates);
599
600 /** first=dir path from the user, second=files found under first. */
601 using Scanned = std::vector<Tablespace_files>;
602
603 /** Report a warning that a path is being ignored and include the reason. */
604 void warn_ignore(std::string path_in, const char *reason);
605
606 /** Add a single path specification to this list of tablespace directories.
607 Convert it to an absolute path. Check if the path is valid. Ignore
608 unreadable, duplicate or invalid directories.
609 @param[in] str Path specification to tokenize
610 @param[in] is_undo_dir true for an undo directory */
611 void add_path(const std::string &str, bool is_undo_dir = false);
612
613 /** Add a delimited list of path specifications to this list of tablespace
614 directories. Convert relative paths to absolute paths. Check if the paths
615 are valid. Ignore unreadable, duplicate or invalid directories.
616 @param[in] str Path specification to tokenize
617 @param[in] delimiters Delimiters */
618 void add_paths(const std::string &str, const std::string &delimiters);
619
620 using Const_iter = Scanned_files::const_iterator;
621
622 /** Check for duplicate tablespace IDs.
623 @param[in] start Start of slice
624 @param[in] end End of slice
625 @param[in] thread_id Thread ID
626 @param[in,out] mutex Mutex protecting the global state
627 @param[in,out] unique To check for duplicates
628 @param[in,out] duplicates Duplicate space IDs found */
629 void duplicate_check(const Const_iter &start, const Const_iter &end,
630 size_t thread_id, std::mutex *mutex,
631 Space_id_set *unique, Space_id_set *duplicates);
632
633 private:
634 /** Directories scanned and the files discovered under them. */
635 Scanned m_dirs;
636
637 /** Number of files checked. */
638 std::atomic_size_t m_checked;
639 };
640
641 /** Determine if space flushing should be disabled, for example when user has
642 explicitly disabled fsync(). */
643 static inline bool fil_disable_space_flushing(const fil_space_t *space) {
644 #ifndef _WIN32
645 if (space->purpose == FIL_TYPE_TABLESPACE &&
646 srv_unix_file_flush_method == SRV_UNIX_O_DIRECT_NO_FSYNC) {
647 return true;
648 }
649 #endif /* !_WIN32 */
650 if (space->purpose == FIL_TYPE_TEMPORARY) {
651 return true;
652 }
653 return false;
654 }
655
656 class Fil_shard {
657 using File_list = UT_LIST_BASE_NODE_T(fil_node_t, LRU);
658 using Space_list = UT_LIST_BASE_NODE_T(fil_space_t, unflushed_spaces);
659 using Spaces = std::unordered_map<space_id_t, fil_space_t *>;
660
661 using Names = std::unordered_map<const char *, fil_space_t *, Char_Ptr_Hash,
662 Char_Ptr_Compare>;
663
664 public:
665 /** Constructor
666 @param[in] shard_id Shard ID */
667 explicit Fil_shard(size_t shard_id);
668
669 /** Destructor */
670 ~Fil_shard() {
671 mutex_destroy(&m_mutex);
672 ut_a(UT_LIST_GET_LEN(m_LRU) == 0);
673 ut_a(UT_LIST_GET_LEN(m_unflushed_spaces) == 0);
674 }
675
676 /** @return the shard ID */
677 size_t id() const { return m_id; }
678
679 /** Acquire the mutex.
680 @param[in] line Line number from where it was called */
681 void acquire(int line) const {
682 #ifndef UNIV_HOTBACKUP
683 m_mutex.enter(srv_n_spin_wait_rounds, srv_spin_wait_delay, __FILE__, line);
684 #else
685 mutex_enter(&m_mutex);
686 #endif /* !UNIV_HOTBACKUP */
687 }
688
689 /** Release the mutex. */
690 void mutex_release() const { mutex_exit(&m_mutex); }
691
692 #ifdef UNIV_DEBUG
693 /** @return true if the mutex is owned. */
694 bool mutex_owned() const { return mutex_own(&m_mutex); }
695 #endif /* UNIV_DEBUG */
696
697 /** Acquire a tablespace to prevent it from being dropped concurrently.
698 The thread must call Fil_shard::fil_space_release() when the operation
699 is done.
700 @param[in] space tablespace to acquire
701 @return true if not space->stop_new_ops */
702 bool space_acquire(fil_space_t *space);
703
704 /** Release a tablespace acquired with Fil_shard::space_acquire().
705 @param[in,out] space tablespace to release */
706 void space_release(fil_space_t *space);
707
708 /** Fetch the fil_space_t instance that maps to space_id. Does not look
709 through system reserved spaces.
710 @param[in] space_id Tablespace ID to lookup
711 @return tablespace instance or nullptr if not found. */
712 [[nodiscard]] fil_space_t *get_space_by_id_from_map(
713 space_id_t space_id) const {
714 ut_ad(mutex_owned());
715
716 auto it = m_spaces.find(space_id);
717
718 if (it == m_spaces.end()) {
719 return nullptr;
720 }
721
722 ut_ad(it->second->magic_n == FIL_SPACE_MAGIC_N);
723 ut_ad(fsp_is_system_temporary(space_id) || it->second->files.size() == 1);
724
725 return it->second;
726 }
727
728 /** Fetch the fil_space_t instance that maps to space_id.
729 @param[in] space_id Tablespace ID to lookup
730 @return tablespace instance or nullptr if not found. */
731 fil_space_t *get_space_by_id(space_id_t space_id) const;
732
733 /** Fetch the fil_space_t instance that maps to the name.
734 @param[in] name Tablespace name to lookup
735 @return tablespace instance or nullptr if not found. */
736 [[nodiscard]] fil_space_t *get_space_by_name(const char *name) const {
737 ut_ad(mutex_owned());
738
739 auto it = m_names.find(name);
740
741 if (it == m_names.end()) {
742 return nullptr;
743 }
744
745 ut_ad(it->second->magic_n == FIL_SPACE_MAGIC_N);
746
747 return it->second;
748 }
749
750 /** Tries to close a file in the shard LRU list.
751 The caller must hold the Fil_shard::m_mutex.
752 @return true if success, false if should retry later */
753 [[nodiscard]] bool close_files_in_LRU();
754
755 /** Remove the file node from the LRU list.
756 @param[in,out] file File for the tablespace */
757 void remove_from_LRU(fil_node_t *file);
758
759 /** Add the file node to the LRU list if required.
760 @param[in,out] file File for the tablespace */
761 void add_to_lru_if_needed(fil_node_t *file);
762
763 /** Open all the system files.
764 @param[in] max_n_open Maximum number of open files allowed
765 @param[in,out] n_open Current number of open files */
766 void open_system_tablespaces(size_t max_n_open, size_t *n_open);
767
768 /** Close a tablespace file.
769 @param[in,out] file Tablespace file to close */
770 void close_file(fil_node_t *file);
771
772 /** Close a tablespace file based on tablespace ID.
773 @param[in] space_id Tablespace ID
774 @return false if space_id was not found. */
775 bool close_file(space_id_t space_id);
776
777 /** Prepare to free a file object from a tablespace
778 memory cache.
779 @param[in,out] file Tablespace file
780 @param[in] space tablespace */
781 void file_close_to_free(fil_node_t *file, fil_space_t *space);
782
783 /** Close all open files. */
784 void close_all_files();
785
786 #ifndef UNIV_HOTBACKUP
787 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
788 /** Check that each fil_space_t::m_n_ref_count in this shard matches the
789 number of pages counted in the buffer pool.
790 @param[in] buffer_pool_references Map of spaces instances to the count
791 of their pages in the buffer pool. */
792 void validate_space_reference_count(Space_References &buffer_pool_references);
793 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
794 #endif /* !UNIV_HOTBACKUP */
795
796 /** Determine if the tablespace needs encryption rotation.
797 @param[in] space tablespace to rotate
798 @return true if the tablespace needs to be rotated, false if not. */
799 bool needs_encryption_rotate(fil_space_t *space);
800
801 /** Rotate the tablespace keys by new master key.
802 @param[in,out] rotate_count A cumulative count of all tablespaces rotated
803 in the Fil_system.
804 @return the number of tablespaces that failed to rotate. */
805 [[nodiscard]] size_t encryption_rotate(size_t *rotate_count);
806
807 /** Detach a space object from the tablespace memory cache and
808 closes the tablespace files but does not delete them.
809 There must not be any pending I/O's or flushes on the files.
810 @param[in,out] space tablespace */
811 void space_detach(fil_space_t *space);
812
813 /** Remove the fil_space_t instance from the maps used to search for it.
814 @param[in] space_id Tablespace ID to remove from maps. */
815 void space_remove_from_lookup_maps(space_id_t space_id) {
816 ut_ad(mutex_owned());
817
818 auto it = m_spaces.find(space_id);
819
820 if (it != m_spaces.end()) {
821 m_names.erase(it->second->name);
822 m_spaces.erase(it);
823 }
824 }
825
826 #ifndef UNIV_HOTBACKUP
827 /** Move the space to the deleted list and remove from the default
828 lookup set.
829 @param[in, out] space Space instance to delete. */
830 void space_prepare_for_delete(fil_space_t *space) noexcept {
831 mutex_acquire();
832
833 space->set_deleted();
834
835 /* Remove access to the fil_space_t instance. */
836 space_remove_from_lookup_maps(space->id);
837
838 m_deleted_spaces.push_back({space->id, space});
839
840 space_detach(space);
841 ut_a(space->files.size() == 1);
842 ut_a(space->files.front().n_pending_ios == 0);
843
844 mutex_release();
845 }
846
847 /** Purge entries from m_deleted_spaces that are no longer referenced by a
848 buffer pool page. This is no longer required to be done during checkpoint -
849 this is done here for historical reasons - it has to be done periodically
850 somewhere. */
851 void purge() {
852 /* Avoid cleaning up old undo files while this is on. */
853 DBUG_EXECUTE_IF("ib_undo_trunc_checkpoint_off", return;);
854
855 mutex_acquire();
856 for (auto it = m_deleted_spaces.begin(); it != m_deleted_spaces.end();) {
857 auto space = it->second;
858
859 if (space->has_no_references()) {
860 ut_a(space->files.size() == 1);
861 ut_a(space->files.front().n_pending_ios == 0);
862
863 space_free_low(space);
864
865 it = m_deleted_spaces.erase(it);
866 } else {
867 ++it;
868 }
869 }
870
871 mutex_release();
872 }
873
874 /** Count how many truncated undo space IDs are still tracked in
875 the buffer pool and the file_system cache.
876 @param[in] undo_num undo tablespace number.
877 @return number of undo tablespaces that are still in memory. */
878 size_t count_undo_deleted(space_id_t undo_num) noexcept {
879 size_t count = 0;
880
881 mutex_acquire();
882
883 for (auto deleted : m_deleted_spaces) {
884 if (undo::id2num(deleted.first) == undo_num) {
885 count++;
886 }
887 }
888
889 mutex_release();
890
891 return count;
892 }
893
894 /** Check if a particular space_id for a page in the buffer pool has
895 been deleted recently. Its space_id will be found in m_deleted_spaces
896 until Fil:shard::checkpoint removes the fil_space_t from Fil_system.
897 @param[in] space_id Tablespace ID to check.
898 @return true if this space_id is in the list of recently deleted spaces. */
899 bool is_deleted(space_id_t space_id) {
900 bool found = false;
901
902 mutex_acquire();
903
904 for (auto deleted : m_deleted_spaces) {
905 if (deleted.first == space_id) {
906 found = true;
907 break;
908 }
909 }
910
911 mutex_release();
912
913 return found;
914 }
915
916 #endif /* !UNIV_HOTBACKUP */
917
918 /** Frees a space object from the tablespace memory cache.
919 Closes a tablespaces' files but does not delete them.
920 There must not be any pending I/O's or flushes on the files.
921 @param[in] space_id Tablespace ID
922 @return fil_space_t instance on success or nullptr */
923 [[nodiscard]] fil_space_t *space_free(space_id_t space_id);
924
925 /** Map the space ID and name to the tablespace instance.
926 @param[in] space Tablespace instance */
927 void space_add(fil_space_t *space);
928
929 /** Prepare to free a file. Remove from the unflushed list
930 if there are no pending flushes.
931 @param[in,out] file File instance to free */
932 void prepare_to_free_file(fil_node_t *file);
933
934 /** If the tablespace is on the unflushed list and there
935 are no pending flushes then remove from the unflushed list.
936 @param[in,out] space Tablespace to remove*/
937 void remove_from_unflushed_list(fil_space_t *space);
938
939 /** Updates the data structures when an I/O operation
940 finishes. Updates the pending I/O's field in the file
941 appropriately.
942 @param[in] file Tablespace file
943 @param[in] type Marks the file as modified type == WRITE */
944 void complete_io(fil_node_t *file, const IORequest &type);
945
946 /** Prepares a file for I/O. Opens the file if it is closed. Updates the
947 pending I/O's field in the file and the system appropriately. Takes the file
948 off the LRU list if it is in the LRU list.
949 @param[in] file Tablespace file for IO
950 @return false if the file can't be opened, otherwise true */
951 [[nodiscard]] bool prepare_file_for_io(fil_node_t *file);
952
953 /** Remap the tablespace to the new name.
954 @param[in] space Tablespace instance, with old name.
955 @param[in] new_name New tablespace name */
956 void update_space_name_map(fil_space_t *space, const char *new_name);
957
958 /** Flush to disk the writes in file spaces possibly cached by the OS
959 (note: spaces of type FIL_TYPE_TEMPORARY are skipped) */
960 void flush_file_spaces();
961
962 /** Try to extend a tablespace if it is smaller than the specified size.
963 @param[in,out] space tablespace
964 @param[in] size desired size in pages
965 @return whether the tablespace is at least as big as requested */
966 [[nodiscard]] bool space_extend(fil_space_t *space, page_no_t size);
967
968 /** Flushes to disk possible writes cached by the OS. If the space does
969 not exist or is being dropped, does not do anything.
970 The caller must own the shard mutex. The mutex might be released and
971 re-acquired before returning.
972
973 @param[in] space_id file space ID (id of tablespace of the database)
974 */
975 void space_flush(space_id_t space_id);
976
977 /** Open a file of a tablespace.
978 The caller must own the shard mutex.
979 @param[in,out] file Tablespace file
980 @return false if the file can't be opened, otherwise true */
981 [[nodiscard]] bool open_file(fil_node_t *file);
982
983 /** Checks if all the file nodes in a space are flushed. The caller must hold
984 the fil_system mutex.
985 @param[in] space Tablespace to check
986 @return true if all are flushed */
987 [[nodiscard]] bool space_is_flushed(const fil_space_t *space);
988
989 /** Open each file of a tablespace if not already open.
990 @param[in] space_id tablespace identifier
991 @retval true if all file nodes were opened
992 @retval false on failure */
993 [[nodiscard]] bool space_open(space_id_t space_id);
994
995 /** Opens the files associated with a tablespace and returns a
996 pointer to the fil_space_t that is in the memory cache associated
997 with a space id.
998 @param[in] space_id Get the tablespace instance or this ID
999 @return file_space_t pointer, nullptr if space not found */
1000 [[nodiscard]] fil_space_t *space_load(space_id_t space_id);
1001
1002 /** Wait for pending operations on a tablespace to stop.
1003 @param[in] space_id Tablespace ID
1004 @param[out] space tablespace instance in memory
1005 @param[out] path tablespace path
1006 @return DB_SUCCESS or DB_TABLESPACE_NOT_FOUND. */
1007 [[nodiscard]] dberr_t wait_for_pending_operations(space_id_t space_id,
1008 fil_space_t *&space,
1009 char **path) const;
1010
1011 /** Rename a single-table tablespace.
1012 The tablespace must exist in the memory cache.
1013 @param[in] space_id Tablespace ID
1014 @param[in] old_path Old file name
1015 @param[in] new_name New tablespace name in the schema/space
1016 @param[in] new_path_in New file name, or nullptr if it
1017 is located in the normal data directory
1018 @return InnoDB error code */
1019 [[nodiscard]] dberr_t space_rename(space_id_t space_id, const char *old_path,
1020 const char *new_name,
1021 const char *new_path_in);
1022
1023 /** Deletes an IBD or IBU tablespace.
1024 The tablespace must be cached in the memory cache. This will delete the
1025 datafile, fil_space_t & fil_node_t entries from the file_system_t cache.
1026 @param[in] space_id Tablespace ID
1027 @param[in] buf_remove Specify the action to take on the pages
1028 for this table in the buffer pool.
1029 @return DB_SUCCESS, DB_TABLESPCE_NOT_FOUND or DB_IO_ERROR */
1030 [[nodiscard]] dberr_t space_delete(space_id_t space_id,
1031 buf_remove_t buf_remove);
1032
1033 /** Truncate the tablespace to needed size.
1034 @param[in] space_id Tablespace ID to truncate
1035 @param[in] size_in_pages Truncate size.
1036 @return true if truncate was successful. */
1037 [[nodiscard]] bool space_truncate(space_id_t space_id,
1038 page_no_t size_in_pages);
1039
1040 /** Create a space memory object and put it to the fil_system hash table.
1041 The tablespace name is independent from the tablespace file-name.
1042 Error messages are issued to the server log.
1043 @param[in] name Tablespace name
1044 @param[in] space_id Tablespace identifier
1045 @param[in] flags Tablespace flags
1046 @param[in] purpose Tablespace purpose
1047 @return pointer to created tablespace, to be filled in with fil_node_create()
1048 @retval nullptr on failure (such as when the same tablespace exists) */
1049 [[nodiscard]] fil_space_t *space_create(const char *name, space_id_t space_id,
1050 uint32_t flags, fil_type_t purpose);
1051
1052 /** Adjust temporary auto-generated names created during
1053 file discovery with correct tablespace names from the DD.
1054 @param[in,out] space Tablespace
1055 @param[in] dd_space_name Tablespace name from the DD
1056 @return true if the tablespace is a general or undo tablespace. */
1057 bool adjust_space_name(fil_space_t *space, const char *dd_space_name);
1058
1059 /** Returns true if a matching tablespace exists in the InnoDB
1060 tablespace memory cache.
1061 @param[in] space_id Tablespace ID
1062 @param[in] name Tablespace name used in fil_space_create().
1063 @param[in] print_err Print detailed error information to the
1064 error log if a matching tablespace is
1065 not found from memory.
1066 @param[in] adjust_space Whether to adjust space id on mismatch
1067 @return true if a matching tablespace exists in the memory cache */
1068 [[nodiscard]] bool space_check_exists(space_id_t space_id, const char *name,
1069 bool print_err, bool adjust_space);
1070
1071 /** Read or write data. This operation could be asynchronous (aio).
1072 @param[in] type IO context
1073 @param[in] sync whether synchronous aio is desired
1074 @param[in] page_id page id
1075 @param[in] page_size page size
1076 @param[in] byte_offset remainder of offset in bytes; in AIO this must
1077 be divisible by the OS block size
1078 @param[in] len how many bytes to read or write; this
1079 must not cross a file boundary; in AIO this must be a block size multiple
1080 @param[in,out] buf buffer where to store read data or from
1081 where to write; in AIO this must be appropriately aligned
1082 @param[in] message message for AIO handler if !sync, else ignored
1083 @return error code
1084 @retval DB_SUCCESS on success
1085 @retval DB_TABLESPACE_DELETED if the tablespace does not exist */
1086 [[nodiscard]] dberr_t do_io(const IORequest &type, bool sync,
1087 const page_id_t &page_id,
1088 const page_size_t &page_size, ulint byte_offset,
1089 ulint len, void *buf, void *message);
1090
1091 /** Iterate through all persistent tablespace files (FIL_TYPE_TABLESPACE)
1092 returning the nodes via callback function f.
1093 @param[in] f Callback
1094 @return any error returned by the callback function. */
1095 [[nodiscard]] dberr_t iterate(Fil_iterator::Function &f);
1096
1097 /** Open an ibd tablespace and add it to the InnoDB data structures.
1098 This is similar to fil_ibd_open() except that it is used while
1099 processing the redo and DDL log, so the data dictionary is not
1100 available and very little validation is done. The tablespace name
1101 is extracted from the dbname/tablename.ibd portion of the filename,
1102 which assumes that the file is a file-per-table tablespace. Any name
1103 will do for now. General tablespace names will be read from the
1104 dictionary after it has been recovered. The tablespace flags are read
1105 at this time from the first page of the file in validate_for_recovery().
1106 @param[in] space_id tablespace ID
1107 @param[in] path path/to/databasename/tablename.ibd
1108 @param[out] space the tablespace, or nullptr on error
1109 @return status of the operation */
1110 [[nodiscard]] fil_load_status ibd_open_for_recovery(space_id_t space_id,
1111 const std::string &path,
1112 fil_space_t *&space);
1113
1114 /** Attach a file to a tablespace
1115 @param[in] name file name of a file that is not open
1116 @param[in] size file size in entire database blocks
1117 @param[in,out] space tablespace from fil_space_create()
1118 @param[in] is_raw whether this is a raw device or partition
1119 @param[in] punch_hole true if supported for this file
1120 @param[in] atomic_write true if the file has atomic write enabled
1121 @param[in] max_pages maximum number of pages in file
1122 @return pointer to the file name
1123 @retval nullptr if error */
1124 [[nodiscard]] fil_node_t *create_node(const char *name, page_no_t size,
1125 fil_space_t *space, bool is_raw,
1126 bool punch_hole, bool atomic_write,
1127 page_no_t max_pages = PAGE_NO_MAX);
1128
1129 #ifdef UNIV_DEBUG
1130 /** Validate a shard. */
1131 void validate() const;
1132 #endif /* UNIV_DEBUG */
1133
1134 #ifdef UNIV_HOTBACKUP
1135 /** Extends all tablespaces to the size stored in the space header.
1136 During the mysqlbackup --apply-log phase we extended the spaces
1137 on-demand so that log records could be applied, but that may have
1138 left spaces still too small compared to the size stored in the space
1139 header. */
1140 void meb_extend_tablespaces_to_stored_len();
1141 #endif /* UNIV_HOTBACKUP */
1142
1143 /** Free a tablespace object on which fil_space_detach() was invoked.
1144 There must not be any pending I/O's or flushes on the files.
1145 @param[in,out] space tablespace */
1146 static void space_free_low(fil_space_t *&space);
1147
1148 private:
1149 /** We keep system tablespace files always open; this is important
1150 in preventing deadlocks in this module, as a page read completion
1151 often performs another read from the insert buffer. The insert buffer
1152 is in tablespace TRX_SYS_SPACE, and we cannot end up waiting in this
1153 function.
1154 @param[in] space_id Tablespace ID to look up
1155 @return tablespace instance */
1156 [[nodiscard]] fil_space_t *get_reserved_space(space_id_t space_id);
1157
1158 /** Prepare for truncating a single-table tablespace.
1159 1) Wait for pending operations on the tablespace to stop;
1160 2) Remove all insert buffer entries for the tablespace;
1161 @param[in] space_id Tablespace ID
1162 @param[out] space Instance that maps to the space ID.
1163 @return DB_SUCCESS or error */
1164 [[nodiscard]] dberr_t space_prepare_for_truncate(space_id_t space_id,
1165 fil_space_t *&space);
1166
1167 /** Note that a write IO has completed.
1168 @param[in,out] file File on which a write was completed */
1169 void write_completed(fil_node_t *file);
1170
1171 /** If the tablespace is not on the unflushed list, add it.
1172 @param[in,out] space Tablespace to add */
1173 void add_to_unflushed_list(fil_space_t *space);
1174
1175 /** Check for pending operations.
1176 @param[in] space tablespace
1177 @param[in] count number of attempts so far
1178 @return 0 if no pending operations else count + 1. */
1179 [[nodiscard]] ulint space_check_pending_operations(fil_space_t *space,
1180 ulint count) const;
1181
1182 /** Check for pending IO.
1183 @param[in] space Tablespace to check
1184 @param[in] file File in space list
1185 @param[in] count number of attempts so far
1186 @return 0 if no pending else count + 1. */
1187 [[nodiscard]] ulint check_pending_io(const fil_space_t *space,
1188 const fil_node_t &file,
1189 ulint count) const;
1190
1191 /** First we open the file in the normal mode, no async I/O here, for
1192 simplicity. Then do some checks, and close the file again. NOTE that we
1193 could not use the simple file read function os_file_read() in Windows
1194 to read from a file opened for async I/O!
1195 @param[in,out] file Get the size of this file
1196 @param[in] read_only_mode true if read only mode set
1197 @return DB_SUCCESS or error */
1198 [[nodiscard]] dberr_t get_file_size(fil_node_t *file, bool read_only_mode);
1199
1200 /** Get the AIO mode.
1201 @param[in] req_type IO request type
1202 @param[in] sync true if Synchronous IO
1203 return the AIO mode */
1204 [[nodiscard]] static AIO_mode get_AIO_mode(const IORequest &req_type,
1205 bool sync);
1206
1207 /** Get the file name for IO and the local offset within that file.
1208 @param[in,out] space Tablespace for IO
1209 @param[in,out] page_no The relative page number in the file
1210 @param[out] file File node if DB_SUCCESS, NULL if not
1211 @retval DB_SUCCESS if the file is found with the page_no
1212 @retval DB_ERROR if the file is not found or does not contain the page.
1213 in this case file == nullptr */
1214 [[nodiscard]] static dberr_t get_file_for_io(fil_space_t *space,
1215 page_no_t *page_no,
1216 fil_node_t *&file);
1217
1218 private:
1219 /** Fil_shard ID */
1220 const size_t m_id;
1221
1222 /** Tablespace instances hashed on the space id */
1223 Spaces m_spaces;
1224
1225 /** Tablespace instances hashed on the space name */
1226 Names m_names;
1227
1228 #ifndef UNIV_HOTBACKUP
1229 using Pair = std::pair<space_id_t, fil_space_t *>;
1230 using Deleted_spaces = std::vector<Pair, ut::allocator<Pair>>;
1231
1232 /** Deleted tablespaces. All pages for these tablespaces in the buffer pool
1233 will be passively deleted. They need not be written. Once the reference count
1234 is zero, this fil_space_t can be deleted from m_deleted_spaces and removed
1235 from memory. All reads and writes must be done under the shard mutex. */
1236 Deleted_spaces m_deleted_spaces;
1237 #endif /* !UNIV_HOTBACKUP */
1238
1239 /** Base node for the LRU list of the most recently used open
1240 files with no pending I/O's; if we start an I/O on the file,
1241 we first remove it from this list, and return it to the start
1242 of the list when the I/O ends; the system tablespace file is
1243 not put to this list: it is opened after the startup, and kept
1244 open until shutdown */
1245
1246 File_list m_LRU;
1247
1248 /** Base node for the list of those tablespaces whose files contain unflushed
1249 writes; those spaces have at least one file where modification_counter >
1250 flush_counter */
1251 Space_list m_unflushed_spaces;
1252
1253 /** When we write to a file we increment this by one */
1254 int64_t m_modification_counter;
1255
1256 /** Mutex protecting this shard. */
1257 #ifndef UNIV_HOTBACKUP
1258 mutable ib_mutex_t m_mutex;
1259 #else
1260 mutable meb::Mutex m_mutex;
1261 #endif /* !UNIV_HOTBACKUP */
1262
1263 // Disable copying
1264 Fil_shard(Fil_shard &&) = delete;
1265 Fil_shard(const Fil_shard &) = delete;
1266 Fil_shard &operator=(Fil_shard &&) = delete;
1267 Fil_shard &operator=(const Fil_shard &) = delete;
1268
1269 friend class Fil_system;
1270 };
1271
1272 /** The tablespace memory cache */
1273 class Fil_system {
1274 public:
1275 using Fil_shards = std::vector<Fil_shard *>;
1276
1277 /** Constructor.
1278 @param[in] n_shards Number of shards to create
1279 @param[in] max_open Maximum number of open files */
1280 Fil_system(size_t n_shards, size_t max_open);
1281
1282 /** Destructor */
1283 ~Fil_system();
1284
1285 /** Acquire a tablespace when it could be dropped concurrently.
1286 Used by background threads that do not necessarily hold proper locks
1287 for concurrency control.
1288 @param[in] space_id Tablespace ID
1289 @param[in] silent Whether to silently ignore missing tablespaces
1290 @return the tablespace, or nullptr if missing or being deleted */
1291 fil_space_t *space_acquire(space_id_t space_id, bool silent);
1292
1293 /** Fetch the file names opened for a space_id during recovery.
1294 @param[in] space_id Tablespace ID to lookup
1295 @return pair of top level directory scanned and names that map
1296 to space_id or nullptr if not found. */
1297 [[nodiscard]] Tablespace_dirs::Result get_scanned_filename_by_space_id(
1298 space_id_t space_id) {
1299 return m_dirs.find_by_id(space_id);
1300 }
1301
1302 /** Fetch the file name opened for an undo space number.
1303 @param[in] space_num undo tablespace numb er to lookup
1304 @param[out] space_id Tablespace ID found
1305 @return pair of top level directory scanned and name that maps
1306 to the space_num or nullptr if not found. */
1307 [[nodiscard]] Tablespace_dirs::Result get_scanned_filename_by_space_num(
1308 space_id_t space_num, space_id_t &space_id) {
1309 return (m_dirs.find_by_num(space_num, space_id));
1310 }
1311
1312 /** Fetch the file name opened for a space_id from the file map.
1313 @param[in] space_id tablespace ID
1314 @param[out] name the scanned filename
1315 @return true if the space_id is found. The name is set to an
1316 empty string if the space_id is not found. */
1317 [[nodiscard]] bool get_file_by_space_id(space_id_t space_id,
1318 std::string &name) {
1319 auto result = get_scanned_filename_by_space_id(space_id);
1320
1321 if (result.second != nullptr) {
1322 /* Duplicates should have been sorted out by now. */
1323 ut_a(result.second->size() == 1);
1324 name = result.first + result.second->front();
1325 return true;
1326 }
1327
1328 name = "";
1329 return false;
1330 }
1331
1332 /** Fetch the file name opened for an undo space number.
1333 @param[in] space_num undo tablespace number
1334 @param[out] space_id tablespace ID
1335 @param[out] name the scanned filename
1336 @return true if the space_id is found. The name is set to an
1337 empty string if the space_id is not found. */
1338 [[nodiscard]] bool get_file_by_space_num(space_id_t space_num,
1339 space_id_t &space_id,
1340 std::string &name) {
1341 auto result = get_scanned_filename_by_space_num(space_num, space_id);
1342
1343 if (result.second != nullptr) {
1344 /* Duplicates should have been sorted out by now. */
1345 ut_a(result.second->size() == 1);
1346 name = result.first + result.second->front();
1347 return true;
1348 }
1349
1350 name = "";
1351 return false;
1352 }
1353
1354 /** Erase a tablespace ID and its mapping from the scanned files.
1355 @param[in] space_id Tablespace ID to erase
1356 @return true if successful */
1357 [[nodiscard]] bool erase_path(space_id_t space_id) {
1358 return m_dirs.erase_path(space_id);
1359 }
1360
1361 /** Add file to old file list. The list is used during 5.7 upgrade failure
1362 to revert back the modified file names. We modify partitioned file names
1363 to lower case.
1364 @param[in] file_path old file name with path */
1365 void add_old_file(const std::string &file_path) {
1366 m_old_paths.push_back(file_path);
1367 }
1368
1369 /** Rename partition files during upgrade.
1370 @param[in] revert if true, revert to old names */
1371 void rename_partition_files(bool revert);
1372
1373 /** Clear all accumulated old files. */
1374 void clear_old_files() { m_old_paths.clear(); }
1375
1376 /** Get the top level directory where this filename was found.
1377 @param[in] path Path to look for.
1378 @return the top level directory under which this file was found. */
1379 [[nodiscard]] const std::string &get_root(const std::string &path) const;
1380
1381 /** Update the DD if any files were moved to a new location.
1382 Free the Tablespace_files instance.
1383 @param[in] read_only_mode true if InnoDB is started in
1384 read only mode.
1385 @return DB_SUCCESS if all OK */
1386 [[nodiscard]] dberr_t prepare_open_for_business(bool read_only_mode);
1387
1388 /** Flush to disk the writes in file spaces possibly cached by the OS
1389 (note: spaces of type FIL_TYPE_TEMPORARY are skipped) */
1390 void flush_file_spaces();
1391
1392 #ifndef UNIV_HOTBACKUP
1393 /** Clean up the shards. */
1394 void purge() {
1395 for (auto shard : m_shards) {
1396 shard->purge();
1397 }
1398 }
1399
1400 /** Count how many truncated undo space IDs are still tracked in
1401 the buffer pool and the file_system cache.
1402 @param[in] undo_num undo tablespace number.
1403 @return number of undo tablespaces that are still in memory. */
1404 size_t count_undo_deleted(space_id_t undo_num) {
1405 size_t count = 0;
1406
1407 for (auto shard : m_shards) {
1408 count += shard->count_undo_deleted(undo_num);
1409 }
1410
1411 return count;
1412 }
1413
1414 /** Check if a particular undo space_id for a page in the buffer pool has
1415 been deleted recently.
1416 Its space_id will be found in Fil_shard::m_deleted_spaces until
1417 Fil:shard::checkpoint removes the fil_space_t from Fil_system.
1418 @param[in] space_id Tablespace ID to check.
1419 @return true if this space_id is in the list of recently deleted spaces. */
1420 bool is_deleted(space_id_t space_id) noexcept {
1421 auto shard = shard_by_id(space_id);
1422
1423 return shard->is_deleted(space_id);
1424 }
1425 #endif /* !UNIV_HOTBACKUP */
1426
1427 /** Fetch the fil_space_t instance that maps to the name.
1428 @param[in] name Tablespace name to lookup
1429 @return tablespace instance or nullptr if not found. */
1430 [[nodiscard]] fil_space_t *get_space_by_name(const char *name) {
1431 for (auto shard : m_shards) {
1432 shard->mutex_acquire();
1433
1434 auto space = shard->get_space_by_name(name);
1435
1436 shard->mutex_release();
1437
1438 if (space != nullptr) {
1439 return space;
1440 }
1441 }
1442
1443 return nullptr;
1444 }
1445
1446 /** Check a space ID against the maximum known tablespace ID.
1447 @param[in] space_id Tablespace ID to check
1448 @return true if it is > than maximum known tablespace ID. */
1449 [[nodiscard]] bool is_greater_than_max_id(space_id_t space_id) const {
1450 ut_ad(mutex_owned_all());
1451
1452 return space_id > m_max_assigned_id;
1453 }
1454
1455 /** Update the maximum known tablespace ID.
1456 @param[in] space Tablespace instance */
1457 void set_maximum_space_id(const fil_space_t *space) {
1458 ut_ad(mutex_owned_all());
1459
1460 if (!m_space_id_reuse_warned) {
1461 m_space_id_reuse_warned = true;
1462
1463 ib::warn(ER_IB_MSG_266) << "Allocated tablespace ID " << space->id
1464 << " for " << space->name << ", old maximum"
1465 << " was " << m_max_assigned_id;
1466 }
1467
1468 m_max_assigned_id = space->id;
1469 }
1470
1471 /** Update the maximum known space ID if it's smaller than max_id.
1472 @param[in] space_id Value to set if it's greater */
1473 void update_maximum_space_id(space_id_t space_id) {
1474 mutex_acquire_all();
1475
1476 if (is_greater_than_max_id(space_id)) {
1477 m_max_assigned_id = space_id;
1478 }
1479
1480 mutex_release_all();
1481 }
1482
1483 /** Assigns a new space id for a new single-table tablespace. This
1484 works simply by incrementing the global counter. If 4 billion ids
1485 is not enough, we may need to recycle ids.
1486 @param[out] space_id Set this to the new tablespace ID
1487 @return true if assigned, false if not */
1488 [[nodiscard]] bool assign_new_space_id(space_id_t *space_id);
1489
1490 /** Allows other threads to advance work while we wait for I/Os to complete.
1491 */
1492 void wait_while_ios_in_progress() const {
1493 #ifndef UNIV_HOTBACKUP
1494 /* Wake the I/O-handler threads to make sure pending I/Os are
1495 performed. */
1496 os_aio_simulated_wake_handler_threads();
1497 #endif /* !UNIV_HOTBACKUP */
1498 /* Give CPU to other threads that keep files opened. */
1499 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1500 }
1501
1502 /** Tries to close a file in all the LRU lists.
1503 The caller must hold the mutex.
1504 @return true if success, false if should retry later */
1505 [[nodiscard]] bool close_file_in_all_LRU();
1506
1507 /** Opens all system tablespace data files in all shards. */
1508 void open_all_system_tablespaces();
1509
1510 /** Close all open files. */
1511 void close_all_files();
1512
1513 /** Returns maximum number of allowed non-LRU files opened for a specified
1514 open files limit. */
1515 static size_t get_limit_for_non_lru_files(size_t open_files_limit);
1516
1517 /** Returns minimum open files limit to be set to allow the specified number
1518 of non-LRU files opened. This is inverse function for the
1519 get_limit_for_non_lru_files. */
1520 size_t get_minimum_limit_for_open_files(
1521 size_t n_files_not_belonging_in_lru) const;
1522
1523 /** Changes the maximum opened files limit.
1524 @param[in,out] new_max_open_files New value for the open files limit. If the
1525 limit cannot be changed, the value is changed to a minimum value recommended.
1526 If there are any concurrent calls to set_open_files_limit in progress, setting
1527 the limit will fail and the new_max_open_files will be set to 0.
1528 @return true if the new limit was set. */
1529 bool set_open_files_limit(size_t &new_max_open_files);
1530
1531 /** Returns maximum number of allowed opened files. */
1532 size_t get_open_files_limit() const { return m_open_files_limit.get_limit(); }
1533
1534 /** Iterate through all persistent tablespace files
1535 (FIL_TYPE_TABLESPACE) returning the nodes via callback function cbk.
1536 @param[in] f Callback
1537 @return any error returned by the callback function. */
1538 [[nodiscard]] dberr_t iterate(Fil_iterator::Function &f);
1539
1540 /** Rotate the tablespace keys by new master key.
1541 @return the number of tablespaces that failed to rotate. */
1542 [[nodiscard]] size_t encryption_rotate();
1543
1544 /** Reencrypt tablespace keys by current master key. */
1545 void encryption_reencrypt(std::vector<space_id_t> &sid_vector);
1546
1547 /** Detach a space object from the tablespace memory cache.
1548 Closes the tablespace files but does not delete them.
1549 There must not be any pending I/O's or flushes on the files.
1550 @param[in,out] space tablespace */
1551 void space_detach(fil_space_t *space);
1552
1553 /** @return the maximum assigned ID so far */
1554 space_id_t get_max_space_id() const { return m_max_assigned_id; }
1555
1556 /** Lookup the tablespace ID.
1557 @param[in] space_id Tablespace ID to lookup
1558 @return true if the space ID is known. */
1559 [[nodiscard]] bool lookup_for_recovery(space_id_t space_id);
1560
1561 /** Open a tablespace that has a redo log record to apply.
1562 @param[in] space_id Tablespace ID
1563 @return DB_SUCCESS if the open was successful */
1564 [[nodiscard]] dberr_t open_for_recovery(space_id_t space_id);
1565
1566 /** This function should be called after recovery has completed.
1567 Check for tablespace files for which we did not see any
1568 MLOG_FILE_DELETE or MLOG_FILE_RENAME record. These could not
1569 be recovered.
1570 @return true if there were some filenames missing for which we had to
1571 ignore redo log records during the apply phase */
1572 [[nodiscard]] bool check_missing_tablespaces();
1573
1574 /** Note that a file has been relocated.
1575 @param[in] object_id Server DD tablespace ID
1576 @param[in] space_id InnoDB tablespace ID
1577 @param[in] space_name Tablespace name
1578 @param[in] old_path Path to the old location
1579 @param[in] new_path Path scanned from disk
1580 @param[in] dd_flag_missing This tablespace is outside default data
1581 directory but missing the
1582 DD_TABLE_DATA_DIRECTORY flag. This can
1583 happen before versions
1584 8.0.37/8.4.1/9.0.0 */
1585 void moved(dd::Object_id object_id, space_id_t space_id,
1586 const char *space_name, const std::string &old_path,
1587 const std::string &new_path, bool dd_flag_missing) {
1588 std::lock_guard guard(m_moved_mutex);
1589 m_moved.push_back(
1590 {object_id, space_id, space_name, old_path, new_path, dd_flag_missing});
1591 }
1592
1593 /** Check if a path is known to InnoDB.
1594 @param[in] path Path to check
1595 @return true if path is known to InnoDB */
1596 bool check_path(const std::string &path) const {
1597 return m_dirs.contains(path);
1598 }
1599
1600 /** Get the list of directories that InnoDB knows about.
1601 @return the list of directories 'dir1;dir2;....;dirN' */
1602 std::string get_dirs() const { return m_dirs.get_dirs(); }
1603
1604 /** Determines if a file belongs to the least-recently-used list.
1605 @param[in] space Tablespace to check
1606 @return true if the file belongs to fil_system->m_LRU mutex. */
1607 [[nodiscard]] static bool space_belongs_in_LRU(const fil_space_t *space);
1608
1609 /** Normalize and save a directory to scan for IBD and IBU datafiles
1610 before recovery.
1611 @param[in] directory Directory to scan
1612 @param[in] is_undo_dir true for an undo directory */
1613 void set_scan_dir(const std::string &directory, bool is_undo_dir) {
1614 m_dirs.set_scan_dir(directory, is_undo_dir);
1615 }
1616
1617 /** Normalize and save a list of directories to scan for IBD and IBU
1618 datafiles before recovery.
1619 @param[in] directories Directories to scan */
1620 void set_scan_dirs(const std::string &directories) {
1621 m_dirs.set_scan_dirs(directories);
1622 }
1623
1624 /** Scan the directories to build the tablespace ID to file name
1625 mapping table. */
1626 dberr_t scan() { return m_dirs.scan(); }
1627
1628 /** Get the tablespace ID from an .ibd and/or an undo tablespace. If the
1629 read failed or the ID is 0 on the first page or there is a mismatch of
1630 space_ids stored in FSP_SPACE_ID and FIL_PAGE_SPACE_ID, then try finding
1631 the ID with Datafile::find_space_id(). This function should only be called
1632 during server startup.
1633 @param[in] filename File name to check
1634 @return s_invalid_space_id if not found, otherwise the space ID */
1635 [[nodiscard]] static space_id_t get_tablespace_id(
1636 const std::string &filename);
1637
1638 /** Fil_shard by space ID.
1639 @param[in] space_id Tablespace ID
1640 @return reference to the shard */
1641 [[nodiscard]] Fil_shard *shard_by_id(space_id_t space_id) const {
1642 #ifndef UNIV_HOTBACKUP
1643 if (fsp_is_undo_tablespace(space_id)) {
1644 const size_t limit = space_id % UNDO_SHARDS;
1645
1646 return m_shards[UNDO_SHARDS_START + limit];
1647 }
1648
1649 ut_ad(m_shards.size() == MAX_SHARDS);
1650
1651 return m_shards[space_id % UNDO_SHARDS_START];
1652 #else /* !UNIV_HOTBACKUP */
1653 ut_ad(m_shards.size() == 1);
1654
1655 return m_shards[0];
1656 #endif /* !UNIV_HOTBACKUP */
1657 }
1658
1659 /** Acquire all the mutexes. */
1660 void mutex_acquire_all() const {
1661 #ifdef UNIV_HOTBACKUP
1662 ut_ad(m_shards.size() == 1);
1663 #endif /* UNIV_HOTBACKUP */
1664
1665 for (auto shard : m_shards) {
1666 shard->mutex_acquire();
1667 }
1668 }
1669
1670 /** Release all the mutexes. */
1671 void mutex_release_all() const {
1672 #ifdef UNIV_HOTBACKUP
1673 ut_ad(m_shards.size() == 1);
1674 #endif /* UNIV_HOTBACKUP */
1675
1676 for (auto shard : m_shards) {
1677 shard->mutex_release();
1678 }
1679 }
1680
1681 #ifdef UNIV_DEBUG
1682
1683 /** Checks the consistency of the tablespace cache.
1684 @return true if ok */
1685 [[nodiscard]] bool validate() const;
1686
1687 /** Check if all mutexes are owned
1688 @return true if all owned. */
1689 [[nodiscard]] bool mutex_owned_all() const {
1690 #ifdef UNIV_HOTBACKUP
1691 ut_ad(m_shards.size() == 1);
1692 #endif /* UNIV_HOTBACKUP */
1693
1694 for (const auto shard : m_shards) {
1695 ut_ad(shard->mutex_owned());
1696 }
1697
1698 return true;
1699 }
1700
1701 #endif /* UNIV_DEBUG */
1702
1703 /** Rename a tablespace. Use the space_id to find the shard.
1704 @param[in] space_id tablespace ID
1705 @param[in] old_name old tablespace name
1706 @param[in] new_name new tablespace name
1707 @return DB_SUCCESS on success */
1708 [[nodiscard]] dberr_t rename_tablespace_name(space_id_t space_id,
1709 const char *old_name,
1710 const char *new_name);
1711
1712 /** Free the data structures required for recovery. */
1713 void free_scanned_files() { m_dirs.clear(); }
1714
1715 #ifdef UNIV_HOTBACKUP
1716 /** Extends all tablespaces to the size stored in the space header.
1717 During the mysqlbackup --apply-log phase we extended the spaces
1718 on-demand so that log records could be applied, but that may have
1719 left spaces still too small compared to the size stored in the space
1720 header. */
1721 void meb_extend_tablespaces_to_stored_len() {
1722 ut_ad(m_shards.size() == 1);
1723
1724 /* We use a single shard for MEB. */
1725 auto shard = shard_by_id(SPACE_UNKNOWN);
1726
1727 shard->mutex_acquire();
1728
1729 shard->meb_extend_tablespaces_to_stored_len();
1730
1731 shard->mutex_release();
1732 }
1733
1734 /** Process a file name passed as an input
1735 Wrapper around meb_name_process()
1736 @param[in,out] name absolute path of tablespace file
1737 @param[in] space_id The tablespace ID
1738 @param[in] deleted true if MLOG_FILE_DELETE */
1739 void meb_name_process(char *name, space_id_t space_id, bool deleted);
1740
1741 #endif /* UNIV_HOTBACKUP */
1742
1743 private:
1744 /** Open an ibd tablespace and add it to the InnoDB data structures.
1745 This is similar to fil_ibd_open() except that it is used while
1746 processing the redo log, so the data dictionary is not available
1747 and very little validation is done. The tablespace name is extracted
1748 from the dbname/tablename.ibd portion of the filename, which assumes
1749 that the file is a file-per-table tablespace. Any name will do for
1750 now. General tablespace names will be read from the dictionary after
1751 it has been recovered. The tablespace flags are read at this time
1752 from the first page of the file in validate_for_recovery().
1753 @param[in] space_id tablespace ID
1754 @param[in] path path/to/databasename/tablename.ibd
1755 @param[out] space the tablespace, or nullptr on error
1756 @return status of the operation */
1757 [[nodiscard]] fil_load_status ibd_open_for_recovery(space_id_t space_id,
1758 const std::string &path,
1759 fil_space_t *&space);
1760
1761 private:
1762 /** Fil_shards managed */
1763 Fil_shards m_shards;
1764
1765 fil::detail::Open_files_limit m_open_files_limit;
1766
1767 /** Maximum space id in the existing tables, or assigned during
1768 the time mysqld has been up; at an InnoDB startup we scan the
1769 data dictionary and set here the maximum of the space id's of
1770 the tables there */
1771 space_id_t m_max_assigned_id;
1772
1773 /** true if fil_space_create() has issued a warning about
1774 potential space_id reuse */
1775 bool m_space_id_reuse_warned;
1776
1777 /** List of tablespaces that have been relocated. We need to
1778 update the DD when it is safe to do so. */
1779 dd_fil::Tablespaces m_moved;
1780
1781 /** Mutex protecting the list of relocated tablespaces */
1782 std::mutex m_moved_mutex;
1783
1784 /** Tablespace directories scanned at startup */
1785 Tablespace_dirs m_dirs;
1786
1787 /** Old file paths during 5.7 upgrade. */
1788 std::vector<std::string> m_old_paths;
1789
1790 /** Next index (modulo number of shards) to try to close a file from the LRU
1791 list to distribute closures evenly between the shards. */
1792 std::atomic_size_t m_next_shard_to_close_from_LRU{};
1793
1794 /** Current number of files that are not belonging in LRU. This includes redo
1795 and temporary tablespaces, but not files that were temporarily removed from
1796 the LRU for I/O. */
1797 std::atomic_size_t m_n_files_not_belonging_in_lru{};
1798
1799 /** Throttles messages about high files not belonging in LRU count, the
1800 warning ER_IB_WARN_MANY_NON_LRU_FILES_OPENED. */
1801 ib::Throttler m_MANY_NON_LRU_FILES_OPENED_throttler{};
1802 /** Throttles messages about long waiting for opened files limit, the warning
1803 ER_IB_MSG_TRYING_TO_OPEN_FILE_FOR_LONG_TIME. */
1804 ib::Throttler m_TRYING_TO_OPEN_FILE_FOR_LONG_TIME_throttler{};
1805 /** Throttles messages about accessing space that was already removed, the
1806 warning ACCESSING_NONEXISTINC_SPACE. */
1807 ib::Throttler m_ACCESSING_NONEXISTINC_SPACE_throttler{};
1808
1809 // Disable copying
1810 Fil_system(Fil_system &&) = delete;
1811 Fil_system(const Fil_system &) = delete;
1812 Fil_system &operator=(const Fil_system &) = delete;
1813
1814 friend class Fil_shard;
1815 };
1816
1817 /** The tablespace memory cache. This variable is nullptr before the module is
1818 initialized. */
1819 static Fil_system *fil_system = nullptr;
1820
1821 #ifdef UNIV_HOTBACKUP
1822 static ulint srv_data_read;
1823 static ulint srv_data_written;
1824 #endif /* UNIV_HOTBACKUP */
1825
1826 static bool is_fast_shutdown() {
1827 #ifndef UNIV_HOTBACKUP
1828 return srv_shutdown_state >= SRV_SHUTDOWN_LAST_PHASE &&
1829 srv_fast_shutdown >= 2;
1830 #else
1831 return false;
1832 #endif
1833 }
1834
1835 bool fil_node_t::can_be_closed() const {
1836 ut_ad(is_open);
1837 /* We need to wait for the pending extension and I/Os to finish. */
1838 if (n_pending_ios != 0) {
1839 return false;
1840 }
1841 if (n_pending_flushes != 0) {
1842 return false;
1843 }
1844 if (is_being_extended) {
1845 return false;
1846 }
1847 #ifndef UNIV_HOTBACKUP
1848 /* The file must be flushed, unless we are in very fast shutdown process. */
1849 if (is_fast_shutdown()) {
1850 return true;
1851 }
1852 #endif
1853 return is_flushed();
1854 }
1855
1856 /** Replay a file rename operation if possible.
1857 @param[in] page_id Space ID and first page number in the file
1858 @param[in] old_name old file name
1859 @param[in] new_name new file name
1860 @return whether the operation was successfully applied (the name did not exist,
1861 or new_name did not exist and name was successfully renamed to new_name) */
1862 [[nodiscard]] static bool fil_op_replay_rename(const page_id_t &page_id,
1863 const std::string &old_name,
1864 const std::string &new_name);
1865
1866 #ifndef UNIV_HOTBACKUP
1867 /** Rename partition file.
1868 @param[in] old_path old file path
1869 @param[in] extn file extension suffix
1870 @param[in] revert if true, rename from new to old file
1871 @param[in] import if called during import */
1872 static void fil_rename_partition_file(const std::string &old_path,
1873 ib_file_suffix extn, bool revert,
1874 bool import);
1875 #endif /* !UNIV_HOTBACKUP */
1876
1877 /** Get modified name for partition file. During upgrade we change all
1878 partition files to have lower case separator and partition name.
1879 @param[in] old_path old file name and path
1880 @param[in] extn file extension suffix
1881 @param[out] new_path modified new name for partitioned file
1882 @return true, iff name needs modification. */
1883 static bool fil_get_partition_file(const std::string &old_path,
1884 ib_file_suffix extn, std::string &new_path);
1885
1886 #ifdef UNIV_DEBUG
1887 /** Try fil_validate() every this many times */
1888 static const size_t FIL_VALIDATE_SKIP = 17;
1889 /** Checks the consistency of the tablespace cache some of the time.
1890 @return true if ok or the check was skipped */
1891 static bool fil_validate_skip() {
1892 /** The fil_validate() call skip counter. Use a signed type
1893 because of the race condition below. */
1894 #ifdef UNIV_HOTBACKUP
1895 static meb::Mutex meb_mutex;
1896
1897 meb_mutex.lock();
1898 #endif /* UNIV_HOTBACKUP */
1899 static int fil_validate_count = FIL_VALIDATE_SKIP;
1900
1901 /* There is a race condition below, but it does not matter,
1902 because this call is only for heuristic purposes. We want to
1903 reduce the call frequency of the costly fil_validate() check
1904 in debug builds. */
1905 --fil_validate_count;
1906
1907 if (fil_validate_count > 0) {
1908 #ifdef UNIV_HOTBACKUP
1909 meb_mutex.unlock();
1910 #endif /* UNIV_HOTBACKUP */
1911 return true;
1912 }
1913
1914 fil_validate_count = FIL_VALIDATE_SKIP;
1915 #ifdef UNIV_HOTBACKUP
1916 meb_mutex.unlock();
1917 #endif /* UNIV_HOTBACKUP */
1918
1919 return fil_validate();
1920 }
1921
1922 /** Validate a shard */
1923 void Fil_shard::validate() const {
1924 mutex_acquire();
1925
1926 for (auto elem : m_spaces) {
1927 page_no_t size = 0;
1928 auto space = elem.second;
1929
1930 for (const auto &file : space->files) {
1931 ut_a(file.is_open || !file.n_pending_ios);
1932 size += file.size;
1933 }
1934
1935 ut_a(space->size == size);
1936 }
1937
1938 UT_LIST_CHECK(m_LRU);
1939
1940 for (auto file : m_LRU) {
1941 ut_a(file->is_open);
1942 ut_a(file->n_pending_ios == 0);
1943 ut_a(fil_system->space_belongs_in_LRU(file->space));
1944 }
1945
1946 mutex_release();
1947 }
1948
1949 /** Checks the consistency of the tablespace cache.
1950 @return true if ok */
1951 bool Fil_system::validate() const {
1952 for (const auto shard : m_shards) {
1953 shard->validate();
1954 }
1955
1956 return true;
1957 }
1958 /** Checks the consistency of the tablespace cache.
1959 @return true if ok */
1960 bool fil_validate() { return fil_system->validate(); }
1961 #endif /* UNIV_DEBUG */
1962
1963 /** Constructor.
1964 @param[in] n_shards Number of shards to create
1965 @param[in] max_open Maximum number of open files */
1966 Fil_system::Fil_system(size_t n_shards, size_t max_open)
1967 : m_shards(),
1968 m_open_files_limit(max_open),
1969 m_max_assigned_id(),
1970 m_space_id_reuse_warned() {
1971 for (size_t i = 0; i < n_shards; ++i) {
1972 auto shard = ut::new_withkey<Fil_shard>(UT_NEW_THIS_FILE_PSI_KEY, i);
1973
1974 m_shards.push_back(shard);
1975 }
1976 }
1977
1978 /** Destructor */
1979 Fil_system::~Fil_system() {
1980 for (auto shard : m_shards) {
1981 ut::delete_(shard);
1982 }
1983
1984 m_shards.clear();
1985 }
1986
1987 /** Determines if a file belongs to the least-recently-used list.
1988 @param[in] space Tablespace to check
1989 @return true if the file belongs to fil_system->m_LRU mutex. */
1990 bool Fil_system::space_belongs_in_LRU(const fil_space_t *space) {
1991 switch (space->purpose) {
1992 case FIL_TYPE_TABLESPACE:
1993 return !fsp_is_system_tablespace(space->id) &&
1994 !fsp_is_undo_tablespace(space->id);
1995
1996 case FIL_TYPE_TEMPORARY:
1997 case FIL_TYPE_IMPORT:
1998 return true;
1999 }
2000
2001 ut_d(ut_error);
2002 ut_o(return false);
2003 }
2004
2005 /** Constructor
2006 @param[in] shard_id Shard ID */
2007 Fil_shard::Fil_shard(size_t shard_id)
2008 : m_id(shard_id),
2009 m_spaces(),
2010 m_names(),
2011 m_LRU(),
2012 m_unflushed_spaces(),
2013 m_modification_counter() {
2014 mutex_create(LATCH_ID_FIL_SHARD, &m_mutex);
2015 }
2016
2017 /** Map the space ID and name to the tablespace instance.
2018 @param[in] space Tablespace instance */
2019 void Fil_shard::space_add(fil_space_t *space) {
2020 ut_ad(mutex_owned());
2021
2022 {
2023 auto it = m_spaces.insert(Spaces::value_type(space->id, space));
2024
2025 ut_a(it.second);
2026 }
2027
2028 {
2029 auto name = space->name;
2030
2031 auto it = m_names.insert(Names::value_type(name, space));
2032
2033 ut_a(it.second);
2034 }
2035 }
2036
2037 void Fil_shard::add_to_lru_if_needed(fil_node_t *file) {
2038 ut_ad(mutex_owned());
2039
2040 if (Fil_system::space_belongs_in_LRU(file->space)) {
2041 UT_LIST_ADD_FIRST(m_LRU, file);
2042 }
2043 }
2044
2045 /** Remove the file node from the LRU list.
2046 @param[in,out] file File for the tablespace */
2047 void Fil_shard::remove_from_LRU(fil_node_t *file) {
2048 ut_ad(mutex_owned());
2049
2050 if (Fil_system::space_belongs_in_LRU(file->space)) {
2051 /* The file is in the LRU list, remove it */
2052 ut_ad(ut_list_exists(m_LRU, file));
2053 UT_LIST_REMOVE(m_LRU, file);
2054 }
2055 }
2056
2057 /** Close a tablespace file based on tablespace ID.
2058 @param[in] space_id Tablespace ID
2059 @return false if space_id was not found. */
2060 bool Fil_shard::close_file(space_id_t space_id) {
2061 mutex_acquire();
2062
2063 auto space = get_space_by_id(space_id);
2064
2065 if (space == nullptr) {
2066 mutex_release();
2067
2068 return false;
2069 }
2070
2071 for (auto &file : space->files) {
2072 while (file.is_open && !file.can_be_closed()) {
2073 mutex_release();
2074
2075 std::this_thread::sleep_for(std::chrono::milliseconds(10));
2076
2077 mutex_acquire();
2078 }
2079
2080 if (file.is_open) {
2081 close_file(&file);
2082 }
2083 }
2084
2085 mutex_release();
2086
2087 return true;
2088 }
2089
2090 /** Remap the tablespace to the new name.
2091 @param[in] space Tablespace instance, with old name.
2092 @param[in] new_name New tablespace name */
2093 void Fil_shard::update_space_name_map(fil_space_t *space,
2094 const char *new_name) {
2095 ut_ad(mutex_owned());
2096
2097 ut_ad(m_spaces.find(space->id) != m_spaces.end());
2098
2099 m_names.erase(space->name);
2100
2101 auto it = m_names.insert(Names::value_type(new_name, space));
2102
2103 ut_a(it.second);
2104 }
2105
2106 /** Check if the basename of a filepath is an undo tablespace name
2107 @param[in] name Tablespace name
2108 @return true if it is an undo tablespace name */
2109 bool Fil_path::is_undo_tablespace_name(const std::string &name) {
2110 if (name.empty()) {
2111 return false;
2112 }
2113
2114 std::string basename = Fil_path::get_basename(name);
2115
2116 const auto end = basename.end();
2117
2118 /* 5 is the minimum length for an explicit undo space name.
2119 It must be at least this long; "_.ibu". */
2120 if (basename.length() <= strlen(DOT_IBU)) {
2121 return false;
2122 }
2123
2124 /* Implicit undo names can come in two formats: undo_000 and undo000.
2125 Check for both. */
2126 size_t u = (*(end - 4) == '_') ? 1 : 0;
2127
2128 if (basename.length() == sizeof("undo000") - 1 + u &&
2129 *(end - 7 - u) == 'u' && /* 'u' */
2130 *(end - 6 - u) == 'n' && /* 'n' */
2131 *(end - 5 - u) == 'd' && /* 'd' */
2132 *(end - 4 - u) == 'o' && /* 'o' */
2133 isdigit(*(end - 3)) && /* 'n' */
2134 isdigit(*(end - 2)) && /* 'n' */
2135 isdigit(*(end - 1))) { /* 'n' */
2136 return true;
2137 }
2138
2139 if (basename.substr(basename.length() - 4, 4) == DOT_IBU) {
2140 return true;
2141 }
2142
2143 return false;
2144 }
2145
2146 /** Add a space ID to filename mapping.
2147 @param[in] space_id Tablespace ID
2148 @param[in] name File name.
2149 @return number of files that map to the space ID */
2150 size_t Tablespace_files::add(space_id_t space_id, const std::string &name) {
2151 ut_a(space_id != TRX_SYS_SPACE);
2152
2153 Names *names;
2154
2155 if (undo::is_reserved(space_id)) {
2156 ut_ad(!Fil_path::has_suffix(IBD, name.c_str()));
2157
2158 /* Use m_undo_nums to allow a reserved undo space ID
2159 to be found quickly. */
2160 space_id_t space_num = undo::id2num(space_id);
2161 m_undo_nums[space_num] = space_id;
2162
2163 names = &m_undo_paths[space_id];
2164
2165 } else {
2166 ut_ad(!Fil_path::has_suffix(IBU, name.c_str()));
2167
2168 if (0 == strncmp(name.c_str(), "undo_", 5)) {
2169 ib::warn(ER_IB_MSG_267) << "Tablespace '" << name << "' naming"
2170 << " format is like an undo tablespace"
2171 << " but its ID " << space_id << " is not"
2172 << " in the undo tablespace range";
2173 }
2174
2175 names = &m_ibd_paths[space_id];
2176 }
2177
2178 names->push_back(name);
2179
2180 return names->size();
2181 }
2182
2183 /** Reads data from a space to a buffer. Remember that the possible incomplete
2184 blocks at the end of file are ignored: they are not taken into account when
2185 calculating the byte offset within a space.
2186 @param[in] page_id page id
2187 @param[in] page_size page size
2188 @param[in] byte_offset remainder of offset in bytes; in aio this
2189 must be divisible by the OS block size
2190 @param[in] len how many bytes to read; this must not cross a
2191 file boundary; in aio this must be a block size multiple
2192 @param[in,out] buf buffer where to store data read; in aio this
2193 must be appropriately aligned
2194 @return DB_SUCCESS, or DB_TABLESPACE_DELETED if we are trying to do
2195 i/o on a tablespace which does not exist */
2196 static dberr_t fil_read(const page_id_t &page_id, const page_size_t &page_size,
2197 ulint byte_offset, ulint len, void *buf) {
2198 return fil_io(IORequestRead, true, page_id, page_size, byte_offset, len, buf,
2199 nullptr);
2200 }
2201
2202 /** Writes data to a space from a buffer. Remember that the possible incomplete
2203 blocks at the end of file are ignored: they are not taken into account when
2204 calculating the byte offset within a space.
2205 @param[in] page_id page id
2206 @param[in] page_size page size
2207 @param[in] byte_offset remainder of offset in bytes; in aio this
2208 must be divisible by the OS block size
2209 @param[in] len how many bytes to write; this must not cross
2210 a file boundary; in aio this must be a block size multiple
2211 @param[in] buf buffer from which to write; in aio this must
2212 be appropriately aligned
2213 @return DB_SUCCESS, or DB_TABLESPACE_DELETED if we are trying to do
2214 I/O on a tablespace which does not exist */
2215 static dberr_t fil_write(const page_id_t &page_id, const page_size_t &page_size,
2216 ulint byte_offset, ulint len, void *buf) {
2217 ut_ad(!srv_read_only_mode);
2218
2219 return fil_io(IORequestWrite, true, page_id, page_size, byte_offset, len, buf,
2220 nullptr);
2221 }
2222
2223 /** Look up a tablespace. The caller should hold an InnoDB table lock or
2224 a MDL that prevents the tablespace from being dropped during the operation,
2225 or the caller should be in single-threaded crash recovery mode (no user
2226 connections that could drop tablespaces). If this is not the case,
2227 fil_space_acquire() and fil_space_release() should be used instead.
2228 @param[in] space_id Tablespace ID
2229 @return tablespace, or nullptr if not found */
2230 fil_space_t *fil_space_get(space_id_t space_id) {
2231 auto shard = fil_system->shard_by_id(space_id);
2232
2233 shard->mutex_acquire();
2234
2235 fil_space_t *space = shard->get_space_by_id(space_id);
2236
2237 shard->mutex_release();
2238
2239 return space;
2240 }
2241
2242 #ifndef UNIV_HOTBACKUP
2243
2244 /** Returns the latch of a file space.
2245 @param[in] space_id Tablespace ID
2246 @return latch protecting storage allocation */
2247 rw_lock_t *fil_space_get_latch(space_id_t space_id) {
2248 auto shard = fil_system->shard_by_id(space_id);
2249
2250 shard->mutex_acquire();
2251
2252 fil_space_t *space = shard->get_space_by_id(space_id);
2253
2254 shard->mutex_release();
2255
2256 return &space->latch;
2257 }
2258
2259 #ifdef UNIV_DEBUG
2260
2261 /** Gets the type of a file space.
2262 @param[in] space_id Tablespace ID
2263 @return file type */
2264 fil_type_t fil_space_get_type(space_id_t space_id) {
2265 auto shard = fil_system->shard_by_id(space_id);
2266
2267 shard->mutex_acquire();
2268
2269 auto space = shard->get_space_by_id(space_id);
2270
2271 shard->mutex_release();
2272
2273 return space->purpose;
2274 }
2275
2276 #endif /* UNIV_DEBUG */
2277
2278 void fil_space_set_imported(space_id_t space_id) {
2279 auto shard = fil_system->shard_by_id(space_id);
2280
2281 shard->mutex_acquire();
2282
2283 fil_space_t *space = shard->get_space_by_id(space_id);
2284
2285 ut_ad(space->purpose == FIL_TYPE_IMPORT);
2286 space->purpose = FIL_TYPE_TABLESPACE;
2287
2288 shard->mutex_release();
2289 }
2290 #endif /* !UNIV_HOTBACKUP */
2291
2292 /** Checks if all the file nodes in a space are flushed. The caller must hold
2293 the fil_system mutex.
2294 @param[in] space Tablespace to check
2295 @return true if all are flushed */
2296 bool Fil_shard::space_is_flushed(const fil_space_t *space) {
2297 ut_ad(mutex_owned());
2298
2299 for (const auto &file : space->files) {
2300 if (!file.is_flushed()) {
2301 ut_ad(!fil_disable_space_flushing(space));
2302 return false;
2303 }
2304 }
2305
2306 return true;
2307 }
2308
2309 #if !defined(NO_FALLOCATE) && defined(UNIV_LINUX)
2310
2311 #include <sys/ioctl.h>
2312
2313 /** FusionIO atomic write control info */
2314 #define DFS_IOCTL_ATOMIC_WRITE_SET _IOW(0x95, 2, uint)
2315
2316 /** Try and enable FusionIO atomic writes.
2317 @param[in] file OS file handle
2318 @return true if successful */
2319 bool fil_fusionio_enable_atomic_write(pfs_os_file_t file) {
2320 if (srv_unix_file_flush_method == SRV_UNIX_O_DIRECT) {
2321 uint atomic = 1;
2322
2323 ut_a(file.m_file != -1);
2324
2325 if (ioctl(file.m_file, DFS_IOCTL_ATOMIC_WRITE_SET, &atomic) != -1) {
2326 return true;
2327 }
2328 }
2329
2330 return false;
2331 }
2332 #endif /* !NO_FALLOCATE && UNIV_LINUX */
2333
2334 /** Attach a file to a tablespace
2335 @param[in] name file name of a file that is not open
2336 @param[in] size file size in entire database blocks
2337 @param[in,out] space tablespace from fil_space_create()
2338 @param[in] is_raw whether this is a raw device or partition
2339 @param[in] punch_hole true if supported for this file
2340 @param[in] atomic_write true if the file has atomic write enabled
2341 @param[in] max_pages maximum number of pages in file
2342 @return pointer to the file name
2343 @retval nullptr if error */
2344 fil_node_t *Fil_shard::create_node(const char *name, page_no_t size,
2345 fil_space_t *space, bool is_raw,
2346 bool punch_hole, bool atomic_write,
2347 page_no_t max_pages) {
2348 ut_ad(name != nullptr);
2349 ut_ad(fil_system != nullptr);
2350
2351 if (space == nullptr) {
2352 return nullptr;
2353 }
2354
2355 fil_node_t file{};
2356
2357 file.name = mem_strdup(name);
2358
2359 ut_a(!is_raw || srv_start_raw_disk_in_use);
2360
2361 file.sync_event = os_event_create();
2362
2363 file.is_raw_disk = is_raw;
2364
2365 file.size = size;
2366
2367 file.flush_size = size;
2368
2369 file.magic_n = FIL_NODE_MAGIC_N;
2370
2371 file.init_size = size;
2372
2373 file.max_size = max_pages;
2374
2375 file.space = space;
2376
2377 os_file_stat_t stat_info = os_file_stat_t();
2378
2379 #ifdef UNIV_DEBUG
2380 dberr_t err =
2381 #endif /* UNIV_DEBUG */
2382
2383 os_file_get_status(
2384 file.name, &stat_info, false,
2385 fsp_is_system_temporary(space->id) ? true : srv_read_only_mode);
2386
2387 ut_ad(err == DB_SUCCESS);
2388
2389 file.block_size = stat_info.block_size;
2390
2391 /* In this debugging mode, we can overcome the limitation of some
2392 OSes like Windows that support Punch Hole but have a hole size
2393 effectively too large. By setting the block size to be half the
2394 page size, we can bypass one of the checks that would normally
2395 turn Page Compression off. This execution mode allows compression
2396 to be tested even when full punch hole support is not available. */
2397 DBUG_EXECUTE_IF(
2398 "ignore_punch_hole",
2399 file.block_size = std::min(static_cast<ulint>(stat_info.block_size),
2400 UNIV_PAGE_SIZE / 2););
2401
2402 if (!IORequest::is_punch_hole_supported() || !punch_hole ||
2403 file.block_size >= srv_page_size) {
2404 fil_no_punch_hole(&file);
2405 } else {
2406 file.punch_hole = punch_hole;
2407 }
2408
2409 file.atomic_write = atomic_write;
2410
2411 mutex_acquire();
2412
2413 space->size += size;
2414
2415 space->files.push_back(file);
2416
2417 mutex_release();
2418
2419 ut_a(space->id == TRX_SYS_SPACE || space->purpose == FIL_TYPE_TEMPORARY ||
2420 space->files.size() == 1);
2421
2422 return &space->files.front();
2423 }
2424
2425 /** Attach a file to a tablespace. File must be closed.
2426 @param[in] name file name (file must be closed)
2427 @param[in] size file size in database blocks, rounded
2428 downwards to an integer
2429 @param[in,out] space space where to append
2430 @param[in] is_raw true if a raw device or a raw disk partition
2431 @param[in] atomic_write true if the file has atomic write enabled
2432 @param[in] max_pages maximum number of pages in file
2433 @return pointer to the file name
2434 @retval nullptr if error */
2435 char *fil_node_create(const char *name, page_no_t size, fil_space_t *space,
2436 bool is_raw, bool atomic_write, page_no_t max_pages) {
2437 auto shard = fil_system->shard_by_id(space->id);
2438
2439 fil_node_t *file;
2440
2441 file = shard->create_node(name, size, space, is_raw,
2442 IORequest::is_punch_hole_supported(), atomic_write,
2443 max_pages);
2444
2445 return file == nullptr ? nullptr : file->name;
2446 }
2447
2448 dberr_t Fil_shard::get_file_size(fil_node_t *file, bool read_only_mode) {
2449 bool success;
2450 fil_space_t *space = file->space;
2451 ut_ad(mutex_owned());
2452
2453 do {
2454 ut_a(!file->is_open);
2455
2456 file->handle = os_file_create_simple_no_error_handling(
2457 innodb_data_file_key, file->name, OS_FILE_OPEN, OS_FILE_READ_ONLY,
2458 read_only_mode, &success);
2459
2460 if (!success) {
2461 /* The following call prints an error message */
2462 os_file_get_last_error(true);
2463
2464 ib::warn(ER_IB_MSG_268) << "Cannot open '" << file->name
2465 << "'."
2466 " Have you deleted .ibd files under a"
2467 " running mysqld server?";
2468
2469 return DB_ERROR;
2470 }
2471
2472 } while (!success);
2473
2474 os_offset_t size_bytes = os_file_get_size(file->handle);
2475
2476 ut_a(size_bytes != (os_offset_t)-1);
2477
2478 #ifdef UNIV_HOTBACKUP
2479 if (space->id == TRX_SYS_SPACE) {
2480 file->size = (ulint)(size_bytes / UNIV_PAGE_SIZE);
2481 space->size += file->size;
2482 os_file_close(file->handle);
2483 return DB_SUCCESS;
2484 }
2485 #endif /* UNIV_HOTBACKUP */
2486
2487 /* Align memory for file I/O if we might have O_DIRECT set */
2488 const ulint buf_size =
2489 recv_recovery_is_on() ? (UNIV_PAGE_SIZE * 2) : UNIV_PAGE_SIZE;
2490 auto page = static_cast<byte *>(ut::aligned_alloc(buf_size, UNIV_PAGE_SIZE));
2491
2492 ut_ad(page == page_align(page));
2493
2494 /* Read the first page of the tablespace */
2495
2496 IORequest request(IORequest::READ);
2497
2498 dberr_t err = os_file_read_first_page(request, file->name, file->handle, page,
2499 buf_size);
2500
2501 ut_a(err == DB_SUCCESS);
2502
2503 os_file_close(file->handle);
2504
2505 uint32_t flags = fsp_header_get_flags(page);
2506 space_id_t space_id = fsp_header_get_space_id(page);
2507
2508 /* To determine if tablespace is from 5.7 or not, we
2509 rely on SDI flag. For IBDs from 5.7, which are opened
2510 during import or during upgrade, their initial size
2511 is lesser than the initial size in 8.0 */
2512 bool has_sdi = FSP_FLAGS_HAS_SDI(flags);
2513
2514 uint8_t expected_size =
2515 has_sdi ? FIL_IBD_FILE_INITIAL_SIZE : FIL_IBD_FILE_INITIAL_SIZE_5_7;
2516
2517 const page_size_t page_size(flags);
2518
2519 ulint min_size = expected_size * page_size.physical();
2520
2521 if (size_bytes < min_size) {
2522 if (has_sdi) {
2523 /** Add some tolerance when the tablespace is upgraded. If an empty
2524 general tablespace is created in 5.7, and then upgraded to 8.0, then
2525 its size changes from FIL_IBD_FILE_INITIAL_SIZE_5_7 pages to
2526 FIL_IBD_FILE_INITIAL_SIZE-1. */
2527
2528 ut_ad(expected_size == FIL_IBD_FILE_INITIAL_SIZE);
2529 ulint upgrade_size = (expected_size - 1) * page_size.physical();
2530
2531 if (size_bytes < upgrade_size) {
2532 ib::error(ER_IB_MSG_269)
2533 << "The size of tablespace file " << file->name << " is only "
2534 << size_bytes << ", should be at least " << upgrade_size << "!";
2535
2536 ut_error;
2537 }
2538
2539 } else {
2540 ib::error(ER_IB_MSG_269)
2541 << "The size of tablespace file " << file->name << " is only "
2542 << size_bytes << ", should be at least " << min_size << "!";
2543
2544 ut_error;
2545 }
2546 }
2547
2548 if (space_id != space->id) {
2549 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_270)
2550 << "Tablespace id is " << space->id
2551 << " in the data dictionary but in file " << file->name << " it is "
2552 << space_id << "!";
2553 }
2554
2555 /* We need to adjust for compressed pages. */
2556 const page_size_t space_page_size(space->flags);
2557
2558 if (!page_size.equals_to(space_page_size)) {
2559 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_271)
2560 << "Tablespace file " << file->name << " has page size " << page_size
2561 << " (flags=" << ib::hex(flags) << ") but the data dictionary expects"
2562 << " page size " << space_page_size
2563 << " (flags=" << ib::hex(space->flags) << ")!";
2564 }
2565
2566 /* Make the SDI flag in space->flags reflect the SDI flag in the header
2567 page. Maybe this space was discarded before a reboot and then replaced
2568 with a 5.7 space that needs to be imported and upgraded. */
2569 fsp_flags_unset_sdi(space->flags);
2570 space->flags |= flags & FSP_FLAGS_MASK_SDI;
2571
2572 /* Data dictionary and tablespace are flushed at different points in
2573 time. If a crash happens in between, they can have different
2574 encryption flags as long as the redo log is not replayed. To avoid a
2575 recovery error due to differing encryption flags, ensure that the
2576 fil_space_t instance has the same setting as the header page. First
2577 clear the encryption flag, then set it from the flags found in the
2578 file. */
2579 if (recv_recovery_is_on()) {
2580 fsp_flags_unset_encryption(space->flags);
2581 space->flags |= flags & FSP_FLAGS_MASK_ENCRYPTION;
2582 }
2583
2584 /* Make sure the space_flags are the same as the header page flags. */
2585 if (space->flags != flags) {
2586 ib::error(ER_IB_MSG_272, ulong{space->flags}, file->name, ulonglong{flags});
2587 ut_error;
2588 }
2589
2590 {
2591 page_no_t size = fsp_header_get_field(page, FSP_SIZE);
2592
2593 page_no_t free_limit;
2594
2595 free_limit = fsp_header_get_field(page, FSP_FREE_LIMIT);
2596
2597 ulint free_len;
2598
2599 free_len = flst_get_len(FSP_HEADER_OFFSET + FSP_FREE + page);
2600
2601 ut_ad(space->free_limit == 0 || space->free_limit == free_limit);
2602
2603 ut_ad(space->free_len == 0 || space->free_len == free_len);
2604
2605 space->size_in_header = size;
2606 space->free_limit = free_limit;
2607
2608 ut_a(free_len < std::numeric_limits<uint32_t>::max());
2609
2610 space->free_len = (uint32_t)free_len;
2611
2612 /* TODO: Get consistent flag from recovered DD. For that, DD should be
2613 recovered already. */
2614 /* Set estimated value for space->compression_type
2615 during recovery process. */
2616
2617 if (recv_recovery_is_on() &&
2618 (Compression::is_compressed_page(page + page_size.physical()) ||
2619 Compression::is_compressed_encrypted_page(page +
2620 page_size.physical()))) {
2621 ut_ad(buf_size >= (UNIV_PAGE_SIZE * 2));
2622 Compression::meta_t header;
2623 Compression::deserialize_header(page + page_size.physical(), &header);
2624 space->compression_type = header.m_algorithm;
2625 }
2626 }
2627
2628 ut::aligned_free(page);
2629
2630 /* For encrypted tablespace, we need to check the
2631 encryption key and iv(initial vector) is read. */
2632 if (FSP_FLAGS_GET_ENCRYPTION(space->flags) && !recv_recovery_is_on() &&
2633 space->m_encryption_metadata.m_type != Encryption::AES) {
2634 ib::error(ER_IB_MSG_273, file->name);
2635
2636 return DB_ERROR;
2637 }
2638
2639 if (file->size == 0) {
2640 ulint extent_size;
2641
2642 extent_size = page_size.physical() * FSP_EXTENT_SIZE;
2643
2644 #ifndef UNIV_HOTBACKUP
2645 /* Truncate the size to a multiple of extent size. */
2646 if (size_bytes >= extent_size) {
2647 size_bytes = ut_2pow_round(size_bytes, extent_size);
2648 }
2649 #else /* !UNIV_HOTBACKUP */
2650
2651 /* After apply-incremental, tablespaces are not
2652 extended to a whole megabyte. Do not cut off
2653 valid data. */
2654
2655 #endif /* !UNIV_HOTBACKUP */
2656
2657 file->size = static_cast<page_no_t>(size_bytes / page_size.physical());
2658
2659 space->size += file->size;
2660 }
2661
2662 return DB_SUCCESS;
2663 }
2664
2665 size_t Fil_system::get_limit_for_non_lru_files(size_t open_files_limit) {
2666 /* Leave at least 10% of the limit for the LRU files, to not make system too
2667 inefficient in an edge case there is a lot of non-LRU files causing LRU
2668 ones to be constantly closed and opened. The absolute minimum would be a
2669 single slot for LRU files, but it may be very inefficient. Let's make two the
2670 hard limit. */
2671 const size_t minimum_limit_left_for_lru_files =
2672 std::max(2LL, std::llround(0.1 * open_files_limit));
2673 return open_files_limit - minimum_limit_left_for_lru_files;
2674 }
2675
2676 size_t Fil_system::get_minimum_limit_for_open_files(
2677 size_t n_files_not_belonging_in_lru) const {
2678 size_t result = 0;
2679 /* Start with the most significant bit and iterate till last one. */
2680 for (size_t current_bit = ~(std::numeric_limits<size_t>::max() >> 1);
2681 current_bit; current_bit >>= 1) {
2682 if (get_limit_for_non_lru_files(result + current_bit - 1) <
2683 n_files_not_belonging_in_lru) {
2684 result += current_bit;
2685 }
2686 }
2687
2688 return result;
2689 }
2690
2691 bool Fil_shard::open_file(fil_node_t *file) {
2692 bool success;
2693 fil_space_t *space = file->space;
2694
2695 ut_ad(mutex_owned());
2696
2697 /* This method is not straightforward. The description is included in comments
2698 to different parts of this function. They are best read one after another
2699 in order. */
2700
2701 ut_a(!file->is_open);
2702 ut_a(file->n_pending_ios == 0);
2703
2704 const auto start_time = std::chrono::steady_clock::now();
2705
2706 /* This method first assures we can open a file. This comes down to assuring a
2707 correct state under locks is present and that opening of this file will not
2708 exceed any limits. Currently we have two limits for open files:
2709 - maximum number of opened files - fil_system->m_open_files_limit,
2710 - maximum number of opened files that can't be closed on request, i.e. are not
2711 part of open files LRU list.
2712
2713 We can ignore the latter iff the file will be part of the LRU.
2714 For each limit we need to comply with, we need to bump the current number of
2715 files within the limit. If the bump succeeds (results in a current number not
2716 larger than the limit value), we have a right to open a file.
2717
2718 When all rights are acquired the `Fil_shard::open_file` opens the file and
2719 returns true. The file opened will naturally count against the limits. After
2720 this happens, the current values of files for the limits are decreased only in
2721 `Fil_shard::close_file`. */
2722
2723 /* We remember if we have already acquired right to open the file against the
2724 total open files limit. */
2725 bool have_right_for_open = false;
2726 /* As well as the right to open the file against limit for files that do not
2727 take part in LRU algorithm. If the file takes part in LRU algorithm, this
2728 is never true. */
2729 bool have_right_for_open_non_lru = false;
2730
2731 /* To acquire a right against a limit, we use this helper function. It
2732 atomically tries to bump the value of supplied reference to a current value
2733 as long as it is below the limit set. Returns true if the right to open is
2734 acquired. */
2735 const auto acquire_right = [](std::atomic<size_t> &counter,
2736 size_t limit) -> bool {
2737 auto current_count = counter.load();
2738 while (limit > current_count) {
2739 if (counter.compare_exchange_weak(current_count, current_count + 1)) {
2740 return true;
2741 }
2742 }
2743 return false;
2744 };
2745
2746 /* At any point we can decide to release any rights that we have acquired so
2747 far. This will make us unable to open the file now. The
2748 `Fil_shard::open_file()` when returning `false` must assure no rights are
2749 left unreleased - this helper function helps to assure that. */
2750 const auto release_rights = [&]() {
2751 if (have_right_for_open) {
2752 fil_n_files_open.fetch_sub(1);
2753 have_right_for_open = false;
2754 }
2755 if (have_right_for_open_non_lru) {
2756 ut_ad(fil_system->m_n_files_not_belonging_in_lru.load() > 0);
2757 fil_system->m_n_files_not_belonging_in_lru.fetch_sub(1);
2758 have_right_for_open_non_lru = false;
2759 }
2760 };
2761
2762 /* Helper function: In case of repeated errors, we will delay printing of
2763 any messages to log by PRINT_INTERVAL_SECS after the method processing
2764 starts and then print one message per PRINT_INTERVAL_SECS. */
2765 const auto should_print_message =
2766 [&start_time](ib::Throttler &throttler) -> bool {
2767 const auto current_time = std::chrono::steady_clock::now();
2768 if (current_time - start_time >= PRINT_INTERVAL) {
2769 return throttler.apply();
2770 }
2771 return false;
2772 };
2773 /* If this is `false`, the file to open will count against the limit for
2774 opened files not taking part in the LRU algorithm. We will need to acquire
2775 a right to open it. */
2776 const bool belongs_to_lru = Fil_system::space_belongs_in_LRU(file->space);
2777
2778 /* We remember the current limit for opened files. If it changes while we are
2779 acquiring the rights, we must ensure we have not caused it to be bumped higher
2780 than the new limit. This double checking works together with double checking
2781 in the `Fil_system::set_open_files_limit` to ensure no race conditions are
2782 possible to leave number of opened files over the limit even in an event of
2783 changing the limit in parallel.
2784
2785 The non-LRU files limit can only change when the main limit for open files is
2786 changed, so we monitor only the main one. */
2787 auto last_open_file_limit = fil_system->get_open_files_limit();
2788
2789 /* This is the main loop. It tries to assure all conditions required to open
2790 the file or causes `open_file` to exit if the file is already opened in
2791 different thread.
2792
2793 At this point, start of each loop and upon exit of the loop (either with
2794 `break` or `return`) the shard's mutex is owned by this thread. However, it
2795 may be released and re-acquired in meantime, for a while, inside this loop. If
2796 we decide to release the mutex, we must execute the loop from begin after
2797 re-acquiring it.
2798
2799 The following is the list of conditions we must fulfill to allow file to be
2800 opened:
2801 1. At any point, if the file becomes open, we just return success. Must be
2802 done under the mutex.
2803
2804 2. At any point, if the space becomes deleted, we just return failure. Must be
2805 done under the mutex.
2806
2807 3. If the file is locked with `space->prevent_file_open`, then release any
2808 rights against the limits acquired so far, and wait till the "lock" is
2809 released. The check must be done under the mutex. But the waiting must be
2810 executed only when we don't own the mutex - it is required by other thread to
2811 release the "lock".
2812
2813 4. Reserve a right within the non-LRU opened files limit. This is conditional
2814 - required only if the file is supposed to not be placed in the opened files
2815 LRU. This is lock-free.
2816
2817 5. Reserve a right within the fil_system->get_open_files_limit(),
2818 unconditionally.
2819
2820 6. Check if the limit value for the opened files have not changed. If it did,
2821 we just release all rights and retry from the beginning.
2822
2823 7. Only then we can proceed with actually opening the file. */
2824 for (;;) {
2825 /* 1. If the file becomes open, we just return success. We own the mutex,
2826 may have some rights already acquired. */
2827 ut_ad(mutex_owned());
2828 if (file->is_open) {
2829 release_rights();
2830 return true;
2831 }
2832
2833 /* 2. If the space becomes deleted, we just return failure. We own the
2834 mutex and may have some rights already acquired.*/
2835 if (space->is_deleted()) {
2836 release_rights();
2837 return false;
2838 }
2839
2840 /* 3. If the file is locked with `space->prevent_file_open`. */
2841 if (space->prevent_file_open) {
2842 /* Someone wants to rename the file. We can't have it opened now.
2843 Give CPU to other thread that renames the file. Release any
2844 rights and the mutex before we go to sleep - we will not need it and
2845 someone else will be able to get these or use the mutex to change the
2846 `space->prevent_file_open`. */
2847 mutex_release();
2848 release_rights();
2849
2850 if (should_print_message(
2851 space->m_prevent_file_open_wait_message_throttler)) {
2852 ib::warn(ER_IB_MSG_278, space->name,
2853 (long long)std::chrono::duration_cast<std::chrono::seconds>(
2854 std::chrono::steady_clock::now() - start_time)
2855 .count());
2856 }
2857
2858 #ifndef UNIV_HOTBACKUP
2859 /* Wake the I/O handler threads to make sure pending I/O's are performed
2860 */
2861 os_aio_simulated_wake_handler_threads();
2862
2863 #endif /* UNIV_HOTBACKUP */
2864
2865 std::this_thread::sleep_for(std::chrono::milliseconds(1));
2866
2867 mutex_acquire();
2868 continue;
2869 }
2870 /* 4. We try to acquire required right for non-LRU file, if it is not taking
2871 part in the LRU algorithm. */
2872 if (!(belongs_to_lru || have_right_for_open_non_lru)) {
2873 have_right_for_open_non_lru =
2874 acquire_right(fil_system->m_n_files_not_belonging_in_lru,
2875 Fil_system::get_limit_for_non_lru_files(
2876 fil_system->get_open_files_limit()));
2877 if (!have_right_for_open_non_lru) {
2878 mutex_release();
2879 if (should_print_message(
2880 fil_system->m_MANY_NON_LRU_FILES_OPENED_throttler)) {
2881 ib::warn(ER_IB_WARN_MANY_NON_LRU_FILES_OPENED,
2882 fil_system->m_n_files_not_belonging_in_lru.load(),
2883 fil_system->get_open_files_limit());
2884 }
2885 /* Give CPU to other threads that keep files opened. */
2886 std::this_thread::sleep_for(std::chrono::milliseconds(1));
2887 mutex_acquire();
2888 continue;
2889 }
2890 }
2891
2892 /* 5. We try to acquire required right to open file. */
2893 if (!have_right_for_open) {
2894 have_right_for_open =
2895 acquire_right(fil_n_files_open, fil_system->get_open_files_limit());
2896 if (!have_right_for_open) {
2897 mutex_release();
2898
2899 if (should_print_message(
2900 fil_system->m_TRYING_TO_OPEN_FILE_FOR_LONG_TIME_throttler)) {
2901 ib::warn warning(
2902 ER_IB_MSG_TRYING_TO_OPEN_FILE_FOR_LONG_TIME,
2903 static_cast<long long>(
2904 std::chrono::duration_cast<std::chrono::seconds>(
2905 std::chrono::steady_clock::now() - start_time)
2906 .count()),
2907 fil_system->get_open_files_limit());
2908 }
2909
2910 /* Flush tablespaces so that we can close modified files in the LRU
2911 list. */
2912 fil_system->flush_file_spaces();
2913
2914 if (!fil_system->close_file_in_all_LRU()) {
2915 fil_system->wait_while_ios_in_progress();
2916 }
2917 mutex_acquire();
2918 continue;
2919 }
2920 }
2921
2922 /* 6. Re-check the open files limit value. This is working in tandem with
2923 double checking the limits in the `set_open_files_limit()`. Either this
2924 thread or one executing `set_open_files_limit()` will spot the limit is
2925 exceeded and rollback to a correct state: either restore limit or release
2926 rights. */
2927 if (last_open_file_limit != fil_system->get_open_files_limit()) {
2928 release_rights();
2929 last_open_file_limit = fil_system->get_open_files_limit();
2930 continue;
2931 }
2932 /* 7. If we have all required rights, and checked under the mutex the
2933 file is not open and can be opened, proceed to opening the file. The file
2934 must be opened before we release the mutex again. */
2935 break;
2936 }
2937
2938 /* We have fulfilled all requirements to actually open the file. */
2939 ut_ad(mutex_owned());
2940 ut_ad(!file->is_open);
2941 ut_ad(!space->prevent_file_open);
2942 ut_ad(belongs_to_lru || have_right_for_open_non_lru);
2943 ut_ad(have_right_for_open);
2944
2945 bool read_only_mode;
2946
2947 read_only_mode = !fsp_is_system_temporary(space->id) && srv_read_only_mode;
2948
2949 if (file->size == 0 ||
2950 (space->size_in_header == 0 && space->purpose == FIL_TYPE_TABLESPACE &&
2951 file == &space->files.front()
2952 #ifndef UNIV_HOTBACKUP
2953 && undo::is_active(space->id, false) &&
2954 srv_startup_is_before_trx_rollback_phase
2955 #endif /* !UNIV_HOTBACKUP */
2956 )) {
2957 /* We don't know the file size yet. */
2958 dberr_t err = get_file_size(file, read_only_mode);
2959
2960 if (err != DB_SUCCESS) {
2961 /* Release the rights acquired as we failed to open it in the end.
2962 */
2963 release_rights();
2964 return false;
2965 }
2966 }
2967
2968 /* Open the file for reading and writing, in Windows normally in the
2969 unbuffered async I/O mode, though global variables may make os_file_create()
2970 to fall back to the normal file I/O mode. */
2971
2972 if (file->is_raw_disk) {
2973 file->handle =
2974 os_file_create(innodb_data_file_key, file->name, OS_FILE_OPEN_RAW,
2975 OS_DATA_FILE, read_only_mode, &success);
2976 } else {
2977 file->handle =
2978 os_file_create(innodb_data_file_key, file->name, OS_FILE_OPEN,
2979 OS_DATA_FILE, read_only_mode, &success);
2980 }
2981
2982 if (success) {
2983 add_to_lru_if_needed(file);
2984 /* The file is ready for IO. */
2985 file->is_open = true;
2986 } else {
2987 /* Release the rights acquired as we failed to open it in the end. */
2988 release_rights();
2989 }
2990
2991 /* We exit with the mutex acquired. The file is assured to remain open only as
2992 long as the mutex is held. Calls, like to `prepare_file_for_io()` are
2993 required to continue to use the file with the mutex released. */
2994 return success;
2995 }
2996
2997 void Fil_shard::close_file(fil_node_t *file) {
2998 ut_ad(mutex_owned());
2999
3000 ut_a(file->can_be_closed());
3001
3002 bool ret = os_file_close(file->handle);
3003
3004 ut_a(ret);
3005
3006 file->handle.m_file = (os_file_t)-1;
3007
3008 file->is_open = false;
3009
3010 auto old_files_open_count = fil_n_files_open.fetch_sub(1);
3011 ut_a(old_files_open_count > 0);
3012
3013 if (!Fil_system::space_belongs_in_LRU(file->space)) {
3014 ut_ad(fil_system->m_n_files_not_belonging_in_lru.load() > 0);
3015
3016 fil_system->m_n_files_not_belonging_in_lru.fetch_sub(1);
3017 }
3018
3019 remove_from_LRU(file);
3020 }
3021
3022 bool Fil_shard::close_files_in_LRU() {
3023 ut_ad(mutex_owned());
3024
3025 for (auto file = UT_LIST_GET_LAST(m_LRU); file != nullptr;
3026 file = UT_LIST_GET_PREV(LRU, file)) {
3027 if (file->can_be_closed()) {
3028 close_file(file);
3029
3030 return true;
3031 }
3032 }
3033
3034 return false;
3035 }
3036
3037 bool Fil_system::close_file_in_all_LRU() {
3038 const auto n_shards = m_shards.size();
3039 const auto index = m_next_shard_to_close_from_LRU++;
3040 for (size_t i = 0; i < n_shards; ++i) {
3041 auto shard = m_shards[(index + i) % n_shards];
3042 shard->mutex_acquire();
3043
3044 bool success = shard->close_files_in_LRU();
3045
3046 shard->mutex_release();
3047
3048 if (success) {
3049 return true;
3050 }
3051 }
3052
3053 return false;
3054 }
3055
3056 fil_space_t *Fil_shard::get_space_by_id(space_id_t space_id) const {
3057 ut_ad(mutex_owned());
3058
3059 if (space_id == TRX_SYS_SPACE) {
3060 return fil_space_t::s_sys_space;
3061 }
3062
3063 return get_space_by_id_from_map(space_id);
3064 }
3065
3066 /** Prepare to free a file. Remove from the unflushed list if there
3067 are no pending flushes.
3068 @param[in,out] file File instance to free */
3069 void Fil_shard::prepare_to_free_file(fil_node_t *file) {
3070 ut_ad(mutex_owned());
3071
3072 fil_space_t *space = file->space;
3073
3074 if (space->is_in_unflushed_spaces && space_is_flushed(space)) {
3075 space->is_in_unflushed_spaces = false;
3076
3077 UT_LIST_REMOVE(m_unflushed_spaces, space);
3078 }
3079 }
3080
3081 /** Prepare to free a file object from a tablespace memory cache.
3082 @param[in,out] file Tablespace file
3083 @param[in] space tablespace */
3084 void Fil_shard::file_close_to_free(fil_node_t *file, fil_space_t *space) {
3085 ut_ad(mutex_owned());
3086 ut_a(file->magic_n == FIL_NODE_MAGIC_N);
3087 ut_a(file->n_pending_ios == 0);
3088 ut_a(!file->is_being_extended);
3089 ut_a(file->space == space);
3090
3091 if (file->is_open) {
3092 /* We fool the assertion in Fil_system::close_file() to think
3093 there are no unflushed modifications in the file */
3094
3095 file->set_flushed();
3096
3097 os_event_set(file->sync_event);
3098
3099 if (fil_disable_space_flushing(space)) {
3100 ut_ad(!space->is_in_unflushed_spaces);
3101 ut_ad(space_is_flushed(space));
3102
3103 } else {
3104 prepare_to_free_file(file);
3105 }
3106
3107 close_file(file);
3108 }
3109 }
3110
3111 void Fil_shard::space_detach(fil_space_t *space) {
3112 ut_ad(mutex_owned());
3113
3114 m_names.erase(space->name);
3115
3116 if (space->is_in_unflushed_spaces) {
3117 ut_ad(!fil_disable_space_flushing(space));
3118
3119 space->is_in_unflushed_spaces = false;
3120
3121 UT_LIST_REMOVE(m_unflushed_spaces, space);
3122 }
3123
3124 ut_a(space->magic_n == FIL_SPACE_MAGIC_N);
3125 ut_a(space->n_pending_flushes == 0);
3126
3127 for (auto &file : space->files) {
3128 file_close_to_free(&file, space);
3129 }
3130 }
3131
3132 /** Free a tablespace object on which fil_space_detach() was invoked.
3133 There must not be any pending I/O's or flushes on the files.
3134 @param[in,out] space tablespace */
3135 void Fil_shard::space_free_low(fil_space_t *&space) {
3136 #ifndef UNIV_HOTBACKUP
3137 {
3138 /* Temporary and undo tablespaces IDs are assigned from a large but
3139 fixed size pool of reserved IDs. Therefore we must ensure that a
3140 fil_space_t instance can't be dropped until all the pages that point
3141 to it are also purged from the buffer pool. */
3142
3143 ut_a(srv_shutdown_state.load() == SRV_SHUTDOWN_LAST_PHASE ||
3144 space->has_no_references());
3145 }
3146 #endif /* !UNIV_HOTBACKUP */
3147
3148 for (auto &file : space->files) {
3149 ut_d(space->size -= file.size);
3150
3151 os_event_destroy(file.sync_event);
3152
3153 ut::free(file.name);
3154 }
3155
3156 call_destructor(&space->files);
3157
3158 ut_ad(space->size == 0);
3159
3160 rw_lock_free(&space->latch);
3161 ut::free(space->name);
3162 ut::free(space);
3163
3164 space = nullptr;
3165 }
3166
3167 /** Frees a space object from the tablespace memory cache.
3168 Closes a tablespaces' files but does not delete them.
3169 There must not be any pending I/O's or flushes on the files.
3170 @param[in] space_id Tablespace ID
3171 @return fil_space_t instance on success or nullptr */
3172 fil_space_t *Fil_shard::space_free(space_id_t space_id) {
3173 mutex_acquire();
3174
3175 fil_space_t *space = get_space_by_id(space_id);
3176
3177 if (space != nullptr) {
3178 space_detach(space);
3179
3180 space_remove_from_lookup_maps(space_id);
3181 }
3182
3183 mutex_release();
3184
3185 return space;
3186 }
3187
3188 /** Frees a space object from the tablespace memory cache.
3189 Closes a tablespaces' files but does not delete them.
3190 There must not be any pending i/o's or flushes on the files.
3191 @param[in] space_id Tablespace ID
3192 @param[in] x_latched Whether the caller holds X-mode space->latch
3193 @return true if success */
3194 static bool fil_space_free(space_id_t space_id, bool x_latched) {
3195 ut_ad(space_id != TRX_SYS_SPACE);
3196
3197 auto shard = fil_system->shard_by_id(space_id);
3198 auto space = shard->space_free(space_id);
3199
3200 if (space == nullptr) {
3201 return false;
3202 }
3203
3204 if (x_latched) {
3205 rw_lock_x_unlock(&space->latch);
3206 }
3207
3208 Fil_shard::space_free_low(space);
3209 ut_a(space == nullptr);
3210
3211 return true;
3212 }
3213
3214 #ifdef UNIV_HOTBACKUP
3215 /** Frees a space object from the tablespace memory cache.
3216 Closes a tablespaces' files but does not delete them.
3217 There must not be any pending i/o's or flushes on the files.
3218 @param[in] space_id Tablespace ID
3219 @return true if success */
3220 bool meb_fil_space_free(space_id_t space_id) {
3221 return fil_space_free(space_id, false);
3222 }
3223 #endif /* UNIV_HOTBACKUP */
3224
3225 /** Create a space memory object and put it to the fil_system hash table.
3226 The tablespace name is independent from the tablespace file-name.
3227 Error messages are issued to the server log.
3228 @param[in] name Tablespace name
3229 @param[in] space_id Tablespace identifier
3230 @param[in] flags Tablespace flags
3231 @param[in] purpose Tablespace purpose
3232 @return pointer to created tablespace, to be filled in with fil_node_create()
3233 @retval nullptr on failure (such as when the same tablespace exists) */
3234 fil_space_t *Fil_shard::space_create(const char *name, space_id_t space_id,
3235 uint32_t flags, fil_type_t purpose) {
3236 ut_ad(mutex_owned());
3237
3238 /* Look for a matching tablespace. */
3239 fil_space_t *space = get_space_by_name(name);
3240
3241 if (space == nullptr) {
3242 space = get_space_by_id(space_id);
3243 }
3244
3245 if (space != nullptr) {
3246 std::ostringstream oss;
3247
3248 for (size_t i = 0; i < space->files.size(); ++i) {
3249 oss << "'" << space->files[i].name << "'";
3250
3251 if (i < space->files.size() - 1) {
3252 oss << ", ";
3253 }
3254 }
3255
3256 ib::info(ER_IB_MSG_281)
3257 << "Trying to add tablespace '" << name << "'"
3258 << " with id " << space_id << " to the tablespace"
3259 << " memory cache, but tablespace"
3260 << " '" << space->name << "'"
3261 << " already exists in the cache with space ID " << space->id
3262 << ". It maps to the following file(s): " << oss.str();
3263
3264 return nullptr;
3265 }
3266
3267 space = static_cast<fil_space_t *>(
3268 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(*space)));
3269 /* This could be just a placement new constructor call if, only if it compiles
3270 OK on SunPro. */
3271 space->initialize();
3272
3273 space->id = space_id;
3274 space->name = mem_strdup(name);
3275
3276 #ifndef UNIV_HOTBACKUP
3277 if (fil_system->is_greater_than_max_id(space_id) && !recv_recovery_on &&
3278 !dict_sys_t::is_reserved(space_id) &&
3279 !fsp_is_system_temporary(space_id)) {
3280 fil_system->set_maximum_space_id(space);
3281 }
3282 #endif /* !UNIV_HOTBACKUP */
3283
3284 space->purpose = purpose;
3285
3286 ut_a(flags < std::numeric_limits<uint32_t>::max());
3287 space->flags = (uint32_t)flags;
3288
3289 space->magic_n = FIL_SPACE_MAGIC_N;
3290
3291 space->m_encryption_metadata.m_type = Encryption::NONE;
3292 space->encryption_op_in_progress = Encryption::Progress::NONE;
3293
3294 rw_lock_create(fil_space_latch_key, &space->latch, LATCH_ID_FIL_SPACE);
3295
3296 #ifndef UNIV_HOTBACKUP
3297 if (space->purpose == FIL_TYPE_TEMPORARY) {
3298 ut_d(space->latch.set_temp_fsp());
3299 }
3300 #endif /* !UNIV_HOTBACKUP */
3301
3302 space_add(space);
3303
3304 return space;
3305 }
3306
3307 /** Create a space memory object and put it to the fil_system hash table.
3308 The tablespace name is independent from the tablespace file-name.
3309 Error messages are issued to the server log.
3310 @param[in] name Tablespace name
3311 @param[in] space_id Tablespace ID
3312 @param[in] flags Tablespace flags
3313 @param[in] purpose Tablespace purpose
3314 @return pointer to created tablespace, to be filled in with fil_node_create()
3315 @retval nullptr on failure (such as when the same tablespace exists) */
3316 fil_space_t *fil_space_create(const char *name, space_id_t space_id,
3317 uint32_t flags, fil_type_t purpose) {
3318 ut_ad(fsp_flags_is_valid(flags));
3319 ut_ad(srv_page_size == UNIV_PAGE_SIZE_ORIG || flags != 0);
3320
3321 DBUG_EXECUTE_IF("fil_space_create_failure", return nullptr;);
3322
3323 fil_system->mutex_acquire_all();
3324
3325 auto shard = fil_system->shard_by_id(space_id);
3326
3327 auto space = shard->space_create(name, space_id, flags, purpose);
3328
3329 if (space == nullptr) {
3330 /* Duplicate error. */
3331 fil_system->mutex_release_all();
3332 return nullptr;
3333 }
3334
3335 /* Cache the system tablespaces, avoid looking them up during IO. */
3336
3337 if (space->id == TRX_SYS_SPACE) {
3338 ut_a(fil_space_t::s_sys_space == nullptr ||
3339 fil_space_t::s_sys_space == space);
3340
3341 fil_space_t::s_sys_space = space;
3342 }
3343
3344 fil_system->mutex_release_all();
3345
3346 return space;
3347 }
3348
3349 /** Assigns a new space id for a new single-table tablespace. This
3350 works simply by incrementing the global counter. If 4 billion ids
3351 is not enough, we may need to recycle ids.
3352 @param[out] space_id Set this to the new tablespace ID
3353 @return true if assigned, false if not */
3354 bool Fil_system::assign_new_space_id(space_id_t *space_id) {
3355 mutex_acquire_all();
3356
3357 space_id_t id = *space_id;
3358
3359 if (id < m_max_assigned_id) {
3360 id = m_max_assigned_id;
3361 }
3362
3363 ++id;
3364
3365 space_id_t reserved_space_id = dict_sys_t::s_reserved_space_id;
3366
3367 if (id > (reserved_space_id / 2) && (id % 1000000UL == 0)) {
3368 ib::warn(ER_IB_MSG_282)
3369 << "You are running out of new single-table"
3370 " tablespace id's. Current counter is "
3371 << id << " and it must not exceed " << reserved_space_id
3372 << "! To reset the counter to zero you have to dump"
3373 " all your tables and recreate the whole InnoDB"
3374 " installation.";
3375 }
3376
3377 bool success = !dict_sys_t::is_reserved(id);
3378
3379 if (success) {
3380 *space_id = m_max_assigned_id = id;
3381
3382 } else {
3383 ib::warn(ER_IB_MSG_283) << "You have run out of single-table tablespace"
3384 " id's! Current counter is "
3385 << id
3386 << ". To reset the counter to zero"
3387 " you have to dump all your tables and"
3388 " recreate the whole InnoDB installation.";
3389
3390 *space_id = SPACE_UNKNOWN;
3391 }
3392
3393 mutex_release_all();
3394
3395 return success;
3396 }
3397
3398 /** Assigns a new space id for a new single-table tablespace. This works
3399 simply by incrementing the global counter. If 4 billion id's is not enough,
3400 we may need to recycle id's.
3401 @param[out] space_id Set this to the new tablespace ID
3402 @return true if assigned, false if not */
3403 bool fil_assign_new_space_id(space_id_t *space_id) {
3404 return fil_system->assign_new_space_id(space_id);
3405 }
3406
3407 /** Open the files associated with a tablespace, make sure the size of
3408 the tablespace is read from the header page, and return a pointer to the
3409 fil_space_t that is in the memory cache associated with the given space id.
3410 @param[in] space_id Get the tablespace instance or this ID
3411 @return file_space_t pointer, nullptr if space not found */
3412 fil_space_t *Fil_shard::space_load(space_id_t space_id) {
3413 ut_ad(mutex_owned());
3414
3415 fil_space_t *space = get_space_by_id(space_id);
3416
3417 if (space == nullptr || space->size != 0) {
3418 return space;
3419 }
3420
3421 switch (space->purpose) {
3422 case FIL_TYPE_IMPORT:
3423 case FIL_TYPE_TEMPORARY:
3424 case FIL_TYPE_TABLESPACE:
3425
3426 ut_a(space_id != TRX_SYS_SPACE);
3427
3428 space = get_space_by_id(space_id);
3429
3430 if (space == nullptr) {
3431 return nullptr;
3432 }
3433
3434 ut_a(1 == space->files.size());
3435
3436 {
3437 auto file = &space->files.front();
3438
3439 /* It must be a single-table tablespace and
3440 we have not opened the file yet; the following
3441 calls will open it and update the size fields */
3442 if (!prepare_file_for_io(file)) {
3443 /* The single-table tablespace can't be opened,
3444 because the ibd file is missing. */
3445
3446 return nullptr;
3447 }
3448
3449 complete_io(file, IORequestRead);
3450 }
3451 }
3452
3453 return space;
3454 }
3455
3456 /** Returns the path from the first fil_node_t found with this space ID.
3457 The caller is responsible for freeing the memory allocated here for the
3458 value returned.
3459 @param[in] space_id Tablespace ID
3460 @return own: A copy of fil_node_t::path, nullptr if space ID is zero
3461 or not found. */
3462 char *fil_space_get_first_path(space_id_t space_id) {
3463 auto shard = fil_system->shard_by_id(space_id);
3464
3465 shard->mutex_acquire();
3466
3467 fil_space_t *space = shard->space_load(space_id);
3468
3469 char *path;
3470
3471 if (space != nullptr) {
3472 path = mem_strdup(space->files.front().name);
3473 } else {
3474 path = nullptr;
3475 }
3476
3477 shard->mutex_release();
3478
3479 return path;
3480 }
3481
3482 /** Returns the size of the space in pages. The tablespace must be cached
3483 in the memory cache.
3484 @param[in] space_id Tablespace ID
3485 @return space size, 0 if space not found */
3486 page_no_t fil_space_get_size(space_id_t space_id) {
3487 auto shard = fil_system->shard_by_id(space_id);
3488
3489 shard->mutex_acquire();
3490
3491 fil_space_t *space = shard->space_load(space_id);
3492
3493 page_no_t size = space ? space->size : 0;
3494
3495 shard->mutex_release();
3496
3497 return size;
3498 }
3499
3500 page_no_t fil_space_get_undo_initial_size(space_id_t space_id) {
3501 auto shard = fil_system->shard_by_id(space_id);
3502
3503 shard->mutex_acquire();
3504
3505 fil_space_t *space = shard->space_load(space_id);
3506
3507 page_no_t size = space ? space->m_undo_initial : 0;
3508
3509 shard->mutex_release();
3510
3511 return size;
3512 }
3513
3514 void fil_space_set_undo_size(space_id_t space_id, bool use_current) {
3515 ut_ad(fsp_is_undo_tablespace(space_id));
3516
3517 auto shard = fil_system->shard_by_id(space_id);
3518
3519 shard->mutex_acquire();
3520
3521 fil_space_t *space = shard->space_load(space_id);
3522
3523 if (space != nullptr) {
3524 space->m_undo_initial =
3525 (use_current ? space->size : UNDO_INITIAL_SIZE_IN_PAGES);
3526 space->m_undo_extend = UNDO_INITIAL_SIZE_IN_PAGES;
3527 }
3528
3529 shard->mutex_release();
3530 }
3531
3532 /** Returns the flags of the space. The tablespace must be cached
3533 in the memory cache.
3534 @param[in] space_id Tablespace ID for which to get the flags
3535 @return flags, ULINT_UNDEFINED if space not found */
3536 uint32_t fil_space_get_flags(space_id_t space_id) {
3537 auto shard = fil_system->shard_by_id(space_id);
3538
3539 shard->mutex_acquire();
3540
3541 fil_space_t *space = shard->space_load(space_id);
3542
3543 uint32_t flags;
3544
3545 flags = (space != nullptr) ? space->flags : UINT32_UNDEFINED;
3546
3547 shard->mutex_release();
3548
3549 return flags;
3550 }
3551
3552 /** Open each file of a tablespace if not already open.
3553 @param[in] space_id tablespace identifier
3554 @retval true if all file nodes were opened
3555 @retval false on failure */
3556 bool Fil_shard::space_open(space_id_t space_id) {
3557 ut_ad(mutex_owned());
3558
3559 fil_space_t *space = get_space_by_id(space_id);
3560
3561 for (auto &file : space->files) {
3562 if (!file.is_open && !open_file(&file)) {
3563 return false;
3564 }
3565 }
3566
3567 return true;
3568 }
3569
3570 /** Open each file of a tablespace if not already open.
3571 @param[in] space_id Tablespace ID
3572 @retval true if all file nodes were opened
3573 @retval false on failure */
3574 bool fil_space_open(space_id_t space_id) {
3575 auto shard = fil_system->shard_by_id(space_id);
3576
3577 shard->mutex_acquire();
3578
3579 bool success = shard->space_open(space_id);
3580
3581 shard->mutex_release();
3582
3583 return success;
3584 }
3585
3586 /** Close each file of a tablespace if open.
3587 @param[in] space_id Tablespace ID */
3588 void fil_space_close(space_id_t space_id) {
3589 if (fil_system == nullptr) {
3590 return;
3591 }
3592
3593 auto shard = fil_system->shard_by_id(space_id);
3594
3595 shard->close_file(space_id);
3596 }
3597
3598 /** Returns the page size of the space and whether it is compressed or not.
3599 The tablespace must be cached in the memory cache.
3600 @param[in] space_id Tablespace ID
3601 @param[out] found true if tablespace was found
3602 @return page size */
3603 const page_size_t fil_space_get_page_size(space_id_t space_id, bool *found) {
3604 const uint32_t flags = fil_space_get_flags(space_id);
3605
3606 if (flags == UINT32_UNDEFINED) {
3607 *found = false;
3608 return univ_page_size;
3609 }
3610
3611 *found = true;
3612
3613 return page_size_t(flags);
3614 }
3615
3616 /** Initializes the tablespace memory cache.
3617 @param[in] max_n_open Maximum number of open files */
3618 void fil_init(ulint max_n_open) {
3619 static_assert((1 << UNIV_PAGE_SIZE_SHIFT_MAX) == UNIV_PAGE_SIZE_MAX,
3620 "(1 << UNIV_PAGE_SIZE_SHIFT_MAX) != UNIV_PAGE_SIZE_MAX");
3621
3622 static_assert((1 << UNIV_PAGE_SIZE_SHIFT_MIN) == UNIV_PAGE_SIZE_MIN,
3623 "(1 << UNIV_PAGE_SIZE_SHIFT_MIN) != UNIV_PAGE_SIZE_MIN");
3624
3625 ut_a(fil_system == nullptr);
3626
3627 ut_a(max_n_open > 0);
3628
3629 fil_system = ut::new_withkey<Fil_system>(UT_NEW_THIS_FILE_PSI_KEY, MAX_SHARDS,
3630 max_n_open);
3631 }
3632
3633 bool fil_open_files_limit_update(size_t &new_max_open_files) {
3634 return fil_system->set_open_files_limit(new_max_open_files);
3635 }
3636
3637 bool Fil_system::set_open_files_limit(size_t &new_max_open_files) {
3638 const auto start_time = std::chrono::steady_clock::now();
3639 {
3640 const auto current_minimum_limit_for_open_files =
3641 get_minimum_limit_for_open_files(m_n_files_not_belonging_in_lru);
3642
3643 if (new_max_open_files < current_minimum_limit_for_open_files) {
3644 /* Use the same value that was used for the check, to not mislead user
3645 with other value than was used in calculations. */
3646 new_max_open_files = current_minimum_limit_for_open_files;
3647 return false;
3648 }
3649 }
3650 /* We impose our new limit to not allow new file openings to cross new limits
3651 (including non-LRU limit). */
3652 if (!m_open_files_limit.set_desired_limit(new_max_open_files)) {
3653 new_max_open_files = 0;
3654 return false;
3655 }
3656
3657 /* We read the m_n_files_not_belonging_in_lru again after the
3658 m_open_files_limit write is issued. */
3659 const auto current_minimum_limit_for_open_files =
3660 get_minimum_limit_for_open_files(m_n_files_not_belonging_in_lru);
3661
3662 if (new_max_open_files < current_minimum_limit_for_open_files) {
3663 /* The limit was already exceeded while we were setting the
3664 m_open_files_limit.get_limit(). We rollback from the limit change. There is
3665 a counterpart check in the `Fil_shard::open_file` to rollback the limit
3666 reservation if this case is encountered there. */
3667 m_open_files_limit.revert_desired_limit();
3668
3669 /* Use the same value that was used for the check, to not mislead user with
3670 other value than was used in calculations. */
3671 new_max_open_files = current_minimum_limit_for_open_files;
3672 return false;
3673 }
3674
3675 const auto set_new_limit_timeout = std::chrono::seconds(5);
3676
3677 for (;;) {
3678 auto current_n_files_open = fil_n_files_open.load();
3679 if ((size_t)new_max_open_files >= current_n_files_open) {
3680 break;
3681 }
3682 if (std::chrono::steady_clock::now() - start_time > set_new_limit_timeout) {
3683 /* Timeout, let's rollback the limit change and recommend a new limit. */
3684 m_open_files_limit.revert_desired_limit();
3685
3686 /* Use the same value that was used for the check, to not mislead user
3687 with other value than was used in calculations. */
3688 new_max_open_files = current_n_files_open;
3689 return false;
3690 }
3691 fil_system->flush_file_spaces();
3692
3693 if (fil_system->close_file_in_all_LRU()) {
3694 /* We closed some file, loop again to re-evaluate situation. */
3695 continue;
3696 }
3697 wait_while_ios_in_progress();
3698 }
3699
3700 #ifndef UNIV_HOTBACKUP
3701 /* Set the new limit in system variable. */
3702 innobase_set_open_files_limit(new_max_open_files);
3703 m_open_files_limit.commit_desired_limit();
3704 #endif
3705
3706 return true;
3707 }
3708
3709 /** Open all the system files.
3710 @param[in] max_n_open Maximum number of open files allowed
3711 @param[in,out] n_open Current number of open files */
3712 void Fil_shard::open_system_tablespaces(size_t max_n_open, size_t *n_open) {
3713 mutex_acquire();
3714
3715 for (auto elem : m_spaces) {
3716 auto space = elem.second;
3717
3718 if (Fil_system::space_belongs_in_LRU(space)) {
3719 continue;
3720 }
3721
3722 for (auto &file : space->files) {
3723 if (!file.is_open) {
3724 if (!open_file(&file)) {
3725 /* This func is called during server's startup. If some file of log
3726 or system tablespace is missing, the server can't start
3727 successfully. So we should assert for it. */
3728 ut_error;
3729 }
3730
3731 ++*n_open;
3732 }
3733
3734 if (max_n_open < 10 + *n_open) {
3735 ib::warn(ER_IB_MSG_284, *n_open, max_n_open);
3736 }
3737 }
3738 }
3739
3740 mutex_release();
3741 }
3742
3743 /** Opens all system tablespace data files in all shards. */
3744 void Fil_system::open_all_system_tablespaces() {
3745 size_t n_open = 0;
3746
3747 for (auto shard : m_shards) {
3748 shard->open_system_tablespaces(get_open_files_limit(), &n_open);
3749 }
3750 }
3751
3752 /** Opens all system tablespace data files. They stay open until the
3753 database server shutdown. This should be called at a server startup
3754 after the space objects for the log and the system tablespace have
3755 been created. The purpose of this operation is to make sure we never
3756 run out of file descriptors if we need to read from the insert buffer
3757 or to write to the log. */
3758 void fil_open_system_tablespace_files() {
3759 fil_system->open_all_system_tablespaces();
3760 }
3761
3762 #ifndef UNIV_HOTBACKUP
3763 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3764 static void fil_validate_space_reference_count(
3765 fil_space_t *space, Space_References &buffer_pool_references) {
3766 const auto space_reference_count = space->get_reference_count();
3767
3768 if (space_reference_count != buffer_pool_references[space]) {
3769 ib::error() << "Space id=" << space->id << " reference count is "
3770 << space_reference_count
3771 << ", while references count found in buffer pool is "
3772 << buffer_pool_references[space] << ". fast_shutdown is "
3773 << srv_fast_shutdown;
3774 }
3775 }
3776
3777 void Fil_shard::validate_space_reference_count(
3778 Space_References &buffer_pool_references) {
3779 ut_ad(!mutex_owned());
3780
3781 mutex_acquire();
3782
3783 for (auto &e : m_spaces) {
3784 fil_validate_space_reference_count(e.second, buffer_pool_references);
3785 }
3786
3787 for (auto &e : m_deleted_spaces) {
3788 fil_validate_space_reference_count(e.second, buffer_pool_references);
3789 }
3790
3791 mutex_release();
3792 }
3793 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3794 #endif /* !UNIV_HOTBACKUP */
3795
3796 void Fil_shard::close_all_files() {
3797 ut_ad(mutex_owned());
3798
3799 /* Iterates over a specified container of pair */
3800 auto iterate_all_spaces_files = [this](auto &spaces, auto preprocess_space,
3801 auto postprocess_space) {
3802 for (auto &e : spaces) {
3803 auto &space = e.second;
3804 if (space == nullptr) {
3805 continue;
3806 }
3807
3808 preprocess_space(space);
3809
3810 for (auto &file : space->files) {
3811 if (file.is_open && !file.can_be_closed()) {
3812 mutex_release();
3813 std::this_thread::sleep_for(std::chrono::milliseconds{1});
3814 mutex_acquire();
3815 /* Files or spaces could have changed when we did not hold the
3816 mutex, restart the loop. */
3817 return false;
3818 }
3819 if (file.is_open) {
3820 close_file(&file);
3821 }
3822 }
3823
3824 postprocess_space(space);
3825
3826 space_free_low(space);
3827
3828 ut_a(space == nullptr);
3829 }
3830 return true;
3831 };
3832
3833 for (;;) {
3834 if (!iterate_all_spaces_files(
3835 m_spaces,
3836 [](auto space) {
3837 ut_a(space->id == TRX_SYS_SPACE ||
3838 space->purpose == FIL_TYPE_TEMPORARY ||
3839 space->files.size() == 1);
3840 },
3841 [this](auto space) { space_detach(space); })) {
3842 continue;
3843 }
3844
3845 m_spaces.clear();
3846
3847 #ifndef UNIV_HOTBACKUP
3848 if (!iterate_all_spaces_files(
3849 m_deleted_spaces,
3850 [](auto space) {
3851 ut_a(space->id != TRX_SYS_SPACE &&
3852 space->id != dict_sys_t::s_dict_space_id);
3853
3854 ut_a(space->files.size() <= 1);
3855 },
3856 [](auto) {})) {
3857 continue;
3858 }
3859
3860 m_deleted_spaces.clear();
3861 #endif /* !UNIV_HOTBACKUP */
3862 break;
3863 }
3864 }
3865
3866 /** Close all open files. */
3867 void Fil_system::close_all_files() {
3868 #ifndef UNIV_HOTBACKUP
3869 #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
3870 bool should_validate_space_reference_count = srv_fast_shutdown == 0;
3871 DBUG_EXECUTE_IF("buf_disable_space_reference_count_check",
3872 should_validate_space_reference_count = false;);
3873
3874 if (should_validate_space_reference_count) {
3875 auto buffer_pool_references = buf_LRU_count_space_references();
3876 for (auto shard : m_shards) {
3877 shard->validate_space_reference_count(buffer_pool_references);
3878 }
3879 }
3880 #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
3881 #endif /* !UNIV_HOTBACKUP */
3882
3883 for (auto shard : m_shards) {
3884 shard->mutex_acquire();
3885
3886 shard->close_all_files();
3887
3888 shard->mutex_release();
3889 }
3890
3891 #ifndef UNIV_HOTBACKUP
3892 /* Revert to old names if downgrading after upgrade failure. */
3893 if (srv_downgrade_partition_files) {
3894 rename_partition_files(true);
3895 }
3896
3897 clear_old_files();
3898 #endif /* !UNIV_HOTBACKUP */
3899 }
3900
3901 /** Closes all open files. There must not be any pending i/o's or not flushed
3902 modifications in the files. */
3903 void fil_close_all_files() { fil_system->close_all_files(); }
3904
3905 /** Iterate through all persistent tablespace files (FIL_TYPE_TABLESPACE)
3906 returning the nodes via callback function cbk.
3907 @param[in] f Callback
3908 @return any error returned by the callback function. */
3909 dberr_t Fil_shard::iterate(Fil_iterator::Function &f) {
3910 mutex_acquire();
3911
3912 for (auto &elem : m_spaces) {
3913 auto space = elem.second;
3914
3915 if (space->purpose != FIL_TYPE_TABLESPACE) {
3916 continue;
3917 }
3918
3919 for (auto &file : space->files) {
3920 /* Note: The callback can release the mutex. */
3921
3922 dberr_t err = f(&file);
3923
3924 if (err != DB_SUCCESS) {
3925 mutex_release();
3926
3927 return err;
3928 }
3929 }
3930 }
3931
3932 mutex_release();
3933
3934 return DB_SUCCESS;
3935 }
3936
3937 dberr_t Fil_system::iterate(Fil_iterator::Function &f) {
3938 for (auto shard : m_shards) {
3939 dberr_t err = shard->iterate(f);
3940
3941 if (err != DB_SUCCESS) {
3942 return err;
3943 }
3944 }
3945
3946 return DB_SUCCESS;
3947 }
3948
3949 dberr_t Fil_iterator::iterate(Function &&f) { return fil_system->iterate(f); }
3950
3951 /** Sets the max tablespace id counter if the given number is bigger than the
3952 previous value.
3953 @param[in] max_id Maximum known tablespace ID */
3954 void fil_set_max_space_id_if_bigger(space_id_t max_id) {
3955 if (dict_sys_t::is_reserved(max_id)) {
3956 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_285, ulong{max_id});
3957 }
3958
3959 fil_system->update_maximum_space_id(max_id);
3960 }
3961
3962 /** Write the flushed LSN to the page header of the first page in the
3963 system tablespace.
3964 @param[in] lsn Flushed LSN
3965 @return DB_SUCCESS or error number */
3966 dberr_t fil_write_flushed_lsn(lsn_t lsn) {
3967 dberr_t err;
3968
3969 auto buf =
3970 static_cast<byte *>(ut::aligned_alloc(UNIV_PAGE_SIZE, UNIV_PAGE_SIZE));
3971
3972 const page_id_t page_id(TRX_SYS_SPACE, 0);
3973
3974 err = fil_read(page_id, univ_page_size, 0, univ_page_size.physical(), buf);
3975
3976 if (err == DB_SUCCESS) {
3977 mach_write_to_8(buf + FIL_PAGE_FILE_FLUSH_LSN, lsn);
3978
3979 err = fil_write(page_id, univ_page_size, 0, univ_page_size.physical(), buf);
3980
3981 fil_system->flush_file_spaces();
3982 }
3983
3984 ut::aligned_free(buf);
3985
3986 return err;
3987 }
3988
3989 /** Acquire a tablespace when it could be dropped concurrently.
3990 Used by background threads that do not necessarily hold proper locks
3991 for concurrency control.
3992 @param[in] space_id Tablespace ID
3993 @param[in] silent Whether to silently ignore missing tablespaces
3994 @return the tablespace, or nullptr if missing or being deleted */
3995 fil_space_t *Fil_system::space_acquire(space_id_t space_id, bool silent) {
3996 auto shard = fil_system->shard_by_id(space_id);
3997
3998 shard->mutex_acquire();
3999
4000 fil_space_t *space = shard->get_space_by_id(space_id);
4001
4002 if (space == nullptr) {
4003 if (!silent && m_ACCESSING_NONEXISTINC_SPACE_throttler.apply()) {
4004 ib::warn(ER_IB_WARN_ACCESSING_NONEXISTINC_SPACE, ulong{space_id});
4005 }
4006 } else if (!shard->space_acquire(space)) {
4007 space = nullptr;
4008 }
4009
4010 shard->mutex_release();
4011
4012 return space;
4013 }
4014
4015 inline bool Fil_shard::space_acquire(fil_space_t *space) {
4016 ut_ad(mutex_owned());
4017 ut_ad(space != nullptr);
4018
4019 if (space->stop_new_ops) {
4020 return false;
4021 }
4022
4023 ++space->n_pending_ops;
4024
4025 return true;
4026 }
4027
4028 /** Acquire a tablespace when it could be dropped concurrently.
4029 Used by background threads that do not necessarily hold proper locks
4030 for concurrency control.
4031 @param[in] space_id Tablespace ID
4032 @return the tablespace, or nullptr if missing or being deleted */
4033 fil_space_t *fil_space_acquire(space_id_t space_id) {
4034 return fil_system->space_acquire(space_id, false);
4035 }
4036
4037 /** Acquire a tablespace that may not exist.
4038 Used by background threads that do not necessarily hold proper locks
4039 for concurrency control.
4040 @param[in] space_id Tablespace ID
4041 @return the tablespace, or nullptr if missing or being deleted */
4042 fil_space_t *fil_space_acquire_silent(space_id_t space_id) {
4043 return fil_system->space_acquire(space_id, true);
4044 }
4045
4046 /** Release a tablespace acquired with fil_space_acquire().
4047 @param[in,out] space Tablespace to release */
4048 void fil_space_release(fil_space_t *space) {
4049 auto shard = fil_system->shard_by_id(space->id);
4050
4051 shard->mutex_acquire();
4052 shard->space_release(space);
4053 shard->mutex_release();
4054 }
4055
4056 /** Release a tablespace acquired with Fil_shard::space_acquire().
4057 @param[in,out] space tablespace to release */
4058 void Fil_shard::space_release(fil_space_t *space) {
4059 ut_ad(space->magic_n == FIL_SPACE_MAGIC_N);
4060 ut_ad(space->n_pending_ops > 0);
4061
4062 --space->n_pending_ops;
4063 }
4064
4065 /** Check for pending operations.
4066 @param[in] space tablespace
4067 @param[in] count number of attempts so far
4068 @return 0 if no pending operations else count + 1. */
4069 ulint Fil_shard::space_check_pending_operations(fil_space_t *space,
4070 ulint count) const {
4071 ut_ad(mutex_owned());
4072
4073 if (space != nullptr && space->n_pending_ops > 0) {
4074 if (count > 5000) {
4075 ib::warn(ER_IB_MSG_287, space->name, ulong{space->n_pending_ops});
4076 }
4077
4078 return count + 1;
4079 }
4080
4081 return 0;
4082 }
4083
4084 /** Check for pending IO.
4085 @param[in] space Tablespace to check
4086 @param[in] file File in space list
4087 @param[in] count number of attempts so far
4088 @return 0 if no pending else count + 1. */
4089 ulint Fil_shard::check_pending_io(const fil_space_t *space,
4090 const fil_node_t &file, ulint count) const {
4091 ut_ad(mutex_owned());
4092 ut_a(space->n_pending_ops == 0);
4093
4094 ut_a(space->id == TRX_SYS_SPACE || space->purpose == FIL_TYPE_TEMPORARY ||
4095 space->files.size() == 1);
4096
4097 if (space->n_pending_flushes > 0 || file.n_pending_ios > 0) {
4098 if (count > 1000) {
4099 ib::warn(ER_IB_MSG_288, space->name, ulong{space->n_pending_flushes},
4100 size_t{file.n_pending_ios});
4101 }
4102
4103 return count + 1;
4104 }
4105
4106 return 0;
4107 }
4108
4109 dberr_t Fil_shard::wait_for_pending_operations(space_id_t space_id,
4110 fil_space_t *&space,
4111 char **path) const {
4112 ut_ad(!fsp_is_system_tablespace(space_id));
4113 ut_ad(!fsp_is_global_temporary(space_id));
4114
4115 space = nullptr;
4116
4117 mutex_acquire();
4118
4119 fil_space_t *sp = get_space_by_id(space_id);
4120
4121 if (sp != nullptr) {
4122 sp->stop_new_ops = true;
4123 }
4124
4125 mutex_release();
4126
4127 /* Check for pending operations. */
4128
4129 ulint count = 0;
4130
4131 do {
4132 mutex_acquire();
4133
4134 sp = get_space_by_id(space_id);
4135
4136 count = space_check_pending_operations(sp, count);
4137
4138 mutex_release();
4139
4140 if (count > 0) {
4141 std::this_thread::sleep_for(std::chrono::milliseconds(20));
4142 }
4143
4144 } while (count > 0);
4145
4146 /* Check for pending IO. */
4147
4148 *path = nullptr;
4149
4150 do {
4151 mutex_acquire();
4152
4153 sp = get_space_by_id(space_id);
4154
4155 if (sp == nullptr) {
4156 mutex_release();
4157
4158 return DB_TABLESPACE_NOT_FOUND;
4159 }
4160
4161 ut_a(sp->files.size() == 1);
4162 const fil_node_t &file = sp->files.front();
4163
4164 count = check_pending_io(sp, file, count);
4165
4166 if (count == 0) {
4167 *path = mem_strdup(file.name);
4168 }
4169
4170 mutex_release();
4171
4172 if (count > 0) {
4173 std::this_thread::sleep_for(std::chrono::milliseconds(20));
4174 }
4175
4176 } while (count > 0);
4177
4178 ut_ad(sp != nullptr);
4179
4180 space = sp;
4181
4182 return DB_SUCCESS;
4183 }
4184
4185 std::string Fil_path::get_existing_path(const std::string &path,
4186 std::string &ghost) {
4187 std::string existing_path{path};
4188
4189 /* This is only called for non-existing paths. */
4190 while (!os_file_exists(existing_path.c_str())) {
4191 /* Some part of this path does not exist.
4192 If the last char is a separator, strip it off. */
4193 trim_separator(existing_path);
4194
4195 auto sep = existing_path.find_last_of(SEPARATOR);
4196 if (sep == std::string::npos) {
4197 /* If no separator is found, it must be relative to the current dir. */
4198 if (existing_path == ".") {
4199 /* This probably cannot happen, but break here to ensure that the
4200 loop always has a way out. */
4201 break;
4202 }
4203 ghost.assign(path);
4204 existing_path.assign(".");
4205 existing_path.push_back(OS_SEPARATOR);
4206 } else {
4207 ghost.assign(path.substr(sep + 1, path.length()));
4208 existing_path.resize(sep + 1);
4209 }
4210 }
4211
4212 return existing_path;
4213 }
4214
4215 std::string Fil_path::get_real_path(const std::string &path, bool force) {
4216 bool path_exists;
4217 os_file_type_t path_type;
4218 char abspath[OS_FILE_MAX_PATH];
4219 std::string in_path{path};
4220 std::string real_path;
4221
4222 if (path.empty()) {
4223 return std::string("");
4224 }
4225
4226 /* We do not need a separator at the end in order to determine what
4227 kind of object it is. So take it off. If it is there and the last
4228 part is actually a file, the correct real path will be returned. */
4229 if (in_path.length() > 1 && is_separator(in_path.back())) {
4230 trim_separator(in_path);
4231 }
4232
4233 /* Before we make an absolute path, check if this path exists,
4234 and if so, what type it is. */
4235 os_file_status(in_path.c_str(), &path_exists, &path_type);
4236
4237 int ret = my_realpath(abspath, in_path.c_str(), MYF(0));
4238
4239 if (ret == 0) {
4240 real_path.assign(abspath);
4241 } else {
4242 /* This often happens on non-Windows platforms when the path does not
4243 fully exist yet. */
4244
4245 if (path_exists) {
4246 /* my_realpath() failed for some reason other than the path does not
4247 exist. */
4248 if (force) {
4249 /* Use the given path and make it comparable. */
4250 real_path.assign(in_path);
4251 } else {
4252 /* Return null and make a note of it. Another attempt will be made
4253 later when Fil_path::get_real_path() is called with force=true. */
4254 ib::info(ER_IB_MSG_289) << "my_realpath('" << path
4255 << "') failed for path type " << path_type;
4256 return (std::string(""));
4257 }
4258 } else {
4259 /* The path does not exist. Try my_realpath() again with the
4260 existing portion of the path. */
4261 std::string ghost;
4262 std::string dir = get_existing_path(in_path, ghost);
4263
4264 ret = my_realpath(abspath, dir.c_str(), MYF(0));
4265 ut_ad(ret == 0);
4266
4267 /* Concatenate the absolute path with the non-existing sub-path.
4268 NOTE: If this path existed, my_realpath() would put a separator
4269 at the end if it is a directory. But since the ghost portion
4270 does not yet exist, we don't know if it is a dir or a file, so
4271 we cannot attach a trailing separator for a directory. So we
4272 trim them off in Fil_path::is_same_as() and is_ancestor(). */
4273 real_path.assign(abspath);
4274 append_separator(real_path);
4275 real_path.append(ghost);
4276 }
4277 }
4278
4279 if (lower_case_file_system) {
4280 Fil_path::to_lower(real_path);
4281 }
4282
4283 /* Try to consistently end a directory name with a separator.
4284 On Windows, my_realpath() usually puts a separator at the end
4285 of a directory path (it does not do that for the path ".").
4286 On non-Windows it never does.
4287 So if the separator is missing, decide whether to append it. */
4288 ut_ad(!real_path.empty());
4289 if (!is_separator(real_path.back())) {
4290 bool add_sep = true;
4291 switch (path_type) {
4292 case OS_FILE_TYPE_DIR:
4293 case OS_FILE_TYPE_BLOCK:
4294 break;
4295 case OS_FILE_TYPE_FILE:
4296 case OS_FILE_TYPE_LINK:
4297 add_sep = false;
4298 break;
4299 case OS_FILE_TYPE_FAILED:
4300 case OS_FILE_TYPE_MISSING:
4301 case OS_FILE_TYPE_NAME_TOO_LONG:
4302 case OS_FILE_PERMISSION_ERROR:
4303 case OS_FILE_TYPE_UNKNOWN:
4304 /* This filepath is missing or cannot be identified for some other
4305 reason. If it ends in a three letter extension, assume it is a file
4306 name and do not add the trailing separator. Otherwise, assume it is
4307 intended to be a directory.*/
4308 size_t s = real_path.size();
4309 if (s > 4 && real_path[s - 4] == '.' && real_path[s - 3] != '.' &&
4310 real_path[s - 2] != '.' && real_path[s - 1] != '.' &&
4311 !is_separator(real_path[s - 3]) &&
4312 !is_separator(real_path[s - 2])) {
4313 add_sep = false;
4314 }
4315 }
4316
4317 if (add_sep) {
4318 append_separator(real_path);
4319 }
4320 }
4321
4322 return real_path;
4323 }
4324
4325 std::string Fil_path::get_basename(const std::string &filepath) {
4326 auto sep = filepath.find_last_of(SEPARATOR);
4327
4328 return (sep == std::string::npos)
4329 ? filepath
4330 : filepath.substr(sep + 1, filepath.length() - sep);
4331 }
4332
4333 /** Constructor
4334 @param[in] dir Directory that the files are under */
4335 Tablespace_files::Tablespace_files(const std::string &dir)
4336 : m_ibd_paths(), m_undo_paths(), m_dir(dir) {
4337 ut_ad(Fil_path::is_separator(dir.back()));
4338 }
4339
4340 /** Closes a single-table tablespace. The tablespace must be cached in the
4341 memory cache. Free all pages used by the tablespace.
4342 @param[in] space_id Tablespace ID
4343 @return DB_SUCCESS or error */
4344 dberr_t fil_close_tablespace(space_id_t space_id) {
4345 ut_ad(!fsp_is_undo_tablespace(space_id));
4346 ut_ad(!fsp_is_system_or_temp_tablespace(space_id));
4347
4348 auto shard = fil_system->shard_by_id(space_id);
4349
4350 char *path{};
4351 fil_space_t *space{};
4352
4353 auto err = shard->wait_for_pending_operations(space_id, space, &path);
4354
4355 if (err != DB_SUCCESS) {
4356 return err;
4357 }
4358
4359 ut_a(path != nullptr);
4360
4361 #ifndef UNIV_HOTBACKUP
4362 shard->space_prepare_for_delete(space);
4363 #else
4364 rw_lock_x_lock(&space->latch, UT_LOCATION_HERE);
4365
4366 /* If the free is successful, the X lock will be released before
4367 the space memory data structure is freed. */
4368
4369 if (!fil_space_free(space_id, true)) {
4370 rw_lock_x_unlock(&space->latch);
4371 err = DB_TABLESPACE_NOT_FOUND;
4372 } else {
4373 err = DB_SUCCESS;
4374 }
4375 #endif /* !UNIV_HOTBACKUP */
4376
4377 /* Delete any generated files, otherwise if we drop the database the
4378 remove directory will fail. */
4379
4380 auto cfg_name = Fil_path::make_cfg(path);
4381
4382 if (cfg_name != nullptr) {
4383 os_file_delete_if_exists(innodb_data_file_key, cfg_name, nullptr);
4384
4385 ut::free(cfg_name);
4386 }
4387
4388 auto cfp_name = Fil_path::make_cfp(path);
4389
4390 if (cfp_name != nullptr) {
4391 os_file_delete_if_exists(innodb_data_file_key, cfp_name, nullptr);
4392
4393 ut::free(cfp_name);
4394 }
4395
4396 ut::free(path);
4397
4398 return err;
4399 }
4400
4401 #ifndef UNIV_HOTBACKUP
4402 /** Write a log record about an operation on a tablespace file.
4403 @param[in] type MLOG_FILE_OPEN or MLOG_FILE_DELETE
4404 or MLOG_FILE_CREATE or MLOG_FILE_RENAME
4405 @param[in] space_id Tablespace identifier
4406 @param[in] path File path
4407 @param[in] new_path If type is MLOG_FILE_RENAME, the new name
4408 @param[in] flags If type is MLOG_FILE_CREATE, the space flags
4409 @param[in,out] mtr Mini-transaction */
4410 static void fil_op_write_log(mlog_id_t type, space_id_t space_id,
4411 const char *path, const char *new_path,
4412 uint32_t flags, mtr_t *mtr) {
4413 ut_ad(space_id != TRX_SYS_SPACE);
4414
4415 byte *log_ptr = nullptr;
4416
4417 if (!mlog_open(mtr, 11 + 4 + 2 + 1, log_ptr)) {
4418 /* Logging in mtr is switched off during crash recovery:
4419 in that case mlog_open returns nullptr */
4420 return;
4421 }
4422
4423 log_ptr = mlog_write_initial_log_record_low(type, space_id, 0, log_ptr, mtr);
4424
4425 if (type == MLOG_FILE_CREATE) {
4426 mach_write_to_4(log_ptr, flags);
4427 log_ptr += 4;
4428 }
4429
4430 /* Let us store the strings as null-terminated for easier readability
4431 and handling */
4432
4433 ulint len = strlen(path) + 1;
4434
4435 mach_write_to_2(log_ptr, len);
4436 log_ptr += 2;
4437
4438 mlog_close(mtr, log_ptr);
4439
4440 mlog_catenate_string(mtr, reinterpret_cast<const byte *>(path), len);
4441
4442 switch (type) {
4443 case MLOG_FILE_RENAME:
4444
4445 ut_ad(strchr(new_path, Fil_path::OS_SEPARATOR) != nullptr);
4446
4447 len = strlen(new_path) + 1;
4448
4449 ut_a(mlog_open(mtr, 2 + len, log_ptr));
4450
4451 mach_write_to_2(log_ptr, len);
4452
4453 log_ptr += 2;
4454
4455 mlog_close(mtr, log_ptr);
4456
4457 mlog_catenate_string(mtr, reinterpret_cast<const byte *>(new_path), len);
4458 break;
4459 case MLOG_FILE_DELETE:
4460 case MLOG_FILE_CREATE:
4461 break;
4462 default:
4463 ut_d(ut_error);
4464 }
4465 }
4466
4467 bool fil_system_get_file_by_space_id(space_id_t space_id, std::string &name) {
4468 ut_a(dict_sys_t::is_reserved(space_id) || srv_is_upgrade_mode);
4469
4470 return fil_system->get_file_by_space_id(space_id, name);
4471 }
4472
4473 bool fil_system_get_file_by_space_num(space_id_t space_num,
4474 space_id_t &space_id, std::string &name) {
4475 return fil_system->get_file_by_space_num(space_num, space_id, name);
4476 }
4477
4478 #endif /* !UNIV_HOTBACKUP */
4479
4480 dberr_t Fil_shard::space_delete(space_id_t space_id, buf_remove_t buf_remove) {
4481 char *path = nullptr;
4482 fil_space_t *space = nullptr;
4483
4484 ut_ad(!fsp_is_system_tablespace(space_id));
4485 ut_ad(!fsp_is_global_temporary(space_id));
4486
4487 dberr_t err = wait_for_pending_operations(space_id, space, &path);
4488
4489 if (err != DB_SUCCESS) {
4490 ut_a(err == DB_TABLESPACE_NOT_FOUND);
4491 return err;
4492 }
4493
4494 ut_a(path != nullptr);
4495 ut_a(space != nullptr);
4496
4497 #ifndef UNIV_HOTBACKUP
4498 /* IMPORTANT: Because we have set space::stop_new_ops there
4499 can't be any new ibuf merges, reads or flushes. We are here
4500 because file::n_pending was zero above. However, it is still
4501 possible to have pending read and write requests:
4502
4503 A read request can happen because the reader thread has
4504 gone through the ::stop_new_ops check in buf_page_init_for_read()
4505 before the flag was set and has not yet incremented ::n_pending
4506 when we checked it above.
4507
4508 A write request can be issued any time because we don't check
4509 the ::stop_new_ops flag when queueing a block for write.
4510
4511 We deal with pending write requests in the following function
4512 where we'd minimally evict all dirty pages belonging to this
4513 space from the flush_list. Note that if a block is IO-fixed
4514 we'll wait for IO to complete.
4515
4516 For buf_remove == BUF_REMOVE_NONE we mark the fil_space_t instance
4517 as deleted by bumping up the file_space_t::m_version. All pages
4518 that are less than this version number will be discarded. We wait
4519 for any pending IO to complete after that.
4520
4521 To deal with potential read requests, we will check the
4522 ::stop_new_ops flag in fil_io(). */
4523
4524 if (buf_remove != BUF_REMOVE_NONE) {
4525 buf_LRU_flush_or_remove_pages(space_id, buf_remove, nullptr);
4526 }
4527
4528 /* Ensure that we write redo log for the operation also within the Clone
4529 notifier block. This is needed because we don't have any mechanism today
4530 to avoid checkpoint crossing the redo log before the actual operation
4531 is complete. Make sure we are not holding shard mutex. */
4532 ut_ad(!mutex_owned());
4533 Clone_notify notifier(Clone_notify::Type::SPACE_DROP, space_id, false);
4534
4535 if (notifier.failed()) {
4536 /* Currently post DDL operations are never rolled back. */
4537 /* purecov: begin deadcode */
4538 ut::free(path);
4539 ut_d(ut_error);
4540 ut_o(return DB_ERROR);
4541 /* purecov: end */
4542 }
4543 #endif /* !UNIV_HOTBACKUP */
4544
4545 /* If it is a delete then also delete any generated files, otherwise
4546 when we drop the database the remove directory will fail. */
4547 if (space->purpose != FIL_TYPE_TEMPORARY) {
4548 #ifdef UNIV_HOTBACKUP
4549 /* When replaying the operation in MySQL Enterprise
4550 Backup, we do not try to write any log record. */
4551 #else /* UNIV_HOTBACKUP */
4552 /* Before deleting the file, write a log record about it, so that
4553 InnoDB crash recovery will expect the file to be gone. */
4554 mtr_t mtr;
4555
4556 mtr.start();
4557
4558 fil_op_write_log(MLOG_FILE_DELETE, space_id, path, nullptr, 0, &mtr);
4559
4560 mtr.commit();
4561
4562 /* Even if we got killed shortly after deleting the
4563 tablespace file, the record must have already been
4564 written to the redo log. */
4565 log_write_up_to(*log_sys, mtr.commit_lsn(), true);
4566
4567 DBUG_EXECUTE_IF("space_delete_crash", DBUG_SUICIDE(););
4568 #endif /* UNIV_HOTBACKUP */
4569
4570 char *cfg_name = Fil_path::make_cfg(path);
4571
4572 if (cfg_name != nullptr) {
4573 os_file_delete_if_exists(innodb_data_file_key, cfg_name, nullptr);
4574
4575 ut::free(cfg_name);
4576 }
4577
4578 char *cfp_name = Fil_path::make_cfp(path);
4579
4580 if (cfp_name != nullptr) {
4581 os_file_delete_if_exists(innodb_data_file_key, cfp_name, nullptr);
4582
4583 ut::free(cfp_name);
4584 }
4585 }
4586
4587 mutex_acquire();
4588
4589 /* Double check the sanity of pending ops after reacquiring
4590 the fil_system::mutex. */
4591 if (const fil_space_t *s = get_space_by_id(space_id)) {
4592 ut_a(s == space);
4593
4594 space->set_deleted();
4595
4596 #ifndef UNIV_HOTBACKUP
4597 ut_a(space->files.size() == 1);
4598 auto &file = space->files.front();
4599
4600 /* Wait for any pending writes. */
4601 while (file.n_pending_ios > 0 || file.n_pending_flushes > 0 ||
4602 file.is_being_extended) {
4603 /* Release and reacquire the mutex because we want the IO to complete. */
4604 mutex_release();
4605
4606 std::this_thread::yield();
4607
4608 mutex_acquire();
4609 }
4610
4611 m_deleted_spaces.push_back({space->id, space});
4612 #endif /* !UNIV_HOTBACKUP */
4613
4614 space_detach(space);
4615
4616 ut_a(space->files.size() == 1);
4617 ut_a(space->files.front().n_pending_ios == 0);
4618 space_remove_from_lookup_maps(space_id);
4619
4620 mutex_release();
4621
4622 #ifdef UNIV_HOTBACKUP
4623 /* For usage inside MEB we don't support lazy stale page eviction, we just
4624 do what fil_shard::purge() does directly here. */
4625 space_free_low(space);
4626 #endif /* UNIV_HOTBACKUP */
4627
4628 if (!os_file_delete(innodb_data_file_key, path) &&
4629 !os_file_delete_if_exists(innodb_data_file_key, path, nullptr)) {
4630 /* Note: This is because we have removed the
4631 tablespace instance from the cache. */
4632
4633 err = DB_IO_ERROR;
4634 }
4635 } else {
4636 mutex_release();
4637
4638 err = DB_TABLESPACE_NOT_FOUND;
4639 }
4640
4641 ut::free(path);
4642 return err;
4643 }
4644
4645 dberr_t fil_delete_tablespace(space_id_t space_id, buf_remove_t buf_remove) {
4646 auto shard = fil_system->shard_by_id(space_id);
4647
4648 return shard->space_delete(space_id, buf_remove);
4649 }
4650
4651 dberr_t Fil_shard::space_prepare_for_truncate(space_id_t space_id,
4652 fil_space_t *&space) {
4653 ut_ad(space_id != TRX_SYS_SPACE);
4654 ut_ad(!fsp_is_system_tablespace(space_id));
4655 ut_ad(!fsp_is_global_temporary(space_id));
4656
4657 char *path{};
4658 auto err = wait_for_pending_operations(space_id, space, &path);
4659
4660 ut::free(path);
4661
4662 return err;
4663 }
4664
4665 bool Fil_shard::space_truncate(space_id_t space_id, page_no_t size_in_pages) {
4666 #ifndef UNIV_HOTBACKUP
4667 fil_space_t *space{};
4668
4669 /* Step-1: Prepare tablespace for truncate. This involves
4670 stopping all the new operations + IO on that tablespace. Any future attempts
4671 to flush will be ignored and pages discarded. */
4672 if (space_prepare_for_truncate(space_id, space) != DB_SUCCESS) {
4673 return false;
4674 }
4675
4676 mutex_acquire();
4677
4678 /* Step-2: Mark the tablespace pages in the buffer pool as stale by bumping
4679 the version number of the space. Those stale pages will be ignored and freed
4680 lazily later. This includes AHI, for which entries will be removed on
4681 buf_page_free_stale*() -> buf_LRU_free_page ->
4682 btr_search_drop_page_hash_index() */
4683 space->bump_version();
4684
4685 /* Step-3: Truncate the tablespace and accordingly update
4686 the fil_space_t handler that is used to access this tablespace. */
4687 ut_a(space->files.size() == 1);
4688
4689 auto &file = space->files.front();
4690
4691 if (!file.is_open) {
4692 if (!open_file(&file)) {
4693 mutex_release();
4694 return false;
4695 }
4696 }
4697
4698 space->size = file.size = size_in_pages;
4699
4700 bool success = os_file_truncate(file.name, file.handle, 0);
4701
4702 if (success) {
4703 os_offset_t size = size_in_pages * UNIV_PAGE_SIZE;
4704
4705 success = os_file_set_size(file.name, file.handle, 0, size, true);
4706
4707 if (success) {
4708 space->stop_new_ops = false;
4709 }
4710 }
4711
4712 mutex_release();
4713
4714 return success;
4715 #else
4716 /* Truncating a tablespace is not supported for MEB. */
4717 ut_error;
4718 #endif
4719 }
4720
4721 /** Truncate the tablespace to needed size.
4722 @param[in] space_id Tablespace ID to truncate
4723 @param[in] size_in_pages Truncate size.
4724 @return true if truncate was successful. */
4725 bool fil_truncate_tablespace(space_id_t space_id, page_no_t size_in_pages) {
4726 auto shard = fil_system->shard_by_id(space_id);
4727
4728 return shard->space_truncate(space_id, size_in_pages);
4729 }
4730
4731 #ifdef UNIV_DEBUG
4732 /** Increase redo skipped count for a tablespace.
4733 @param[in] space_id Tablespace ID */
4734 void fil_space_inc_redo_skipped_count(space_id_t space_id) {
4735 auto shard = fil_system->shard_by_id(space_id);
4736
4737 shard->mutex_acquire();
4738
4739 fil_space_t *space = shard->get_space_by_id(space_id);
4740
4741 ut_a(space != nullptr);
4742
4743 ++space->redo_skipped_count;
4744
4745 shard->mutex_release();
4746 }
4747
4748 /** Decrease redo skipped count for a tablespace.
4749 @param[in] space_id Tablespace ID */
4750 void fil_space_dec_redo_skipped_count(space_id_t space_id) {
4751 auto shard = fil_system->shard_by_id(space_id);
4752
4753 shard->mutex_acquire();
4754
4755 fil_space_t *space = shard->get_space_by_id(space_id);
4756
4757 ut_a(space != nullptr);
4758 ut_a(space->redo_skipped_count > 0);
4759
4760 --space->redo_skipped_count;
4761
4762 shard->mutex_release();
4763 }
4764
4765 /** Check whether a single-table tablespace is redo skipped.
4766 @param[in] space_id Tablespace ID
4767 @return true if redo skipped */
4768 bool fil_space_is_redo_skipped(space_id_t space_id) {
4769 auto shard = fil_system->shard_by_id(space_id);
4770
4771 shard->mutex_acquire();
4772
4773 fil_space_t *space = shard->get_space_by_id(space_id);
4774
4775 ut_a(space != nullptr);
4776
4777 bool is_redo_skipped = space->redo_skipped_count > 0;
4778
4779 shard->mutex_release();
4780
4781 return is_redo_skipped;
4782 }
4783 #endif /* UNIV_DEBUG */
4784
4785 #ifndef UNIV_HOTBACKUP
4786
4787 /** Discards a single-table tablespace. The tablespace must be cached in the
4788 memory cache. Discarding is like deleting a tablespace, but
4789
4790 1. We do not drop the table from the data dictionary;
4791
4792 2. We remove all insert buffer entries for the tablespace immediately;
4793 in DROP TABLE they are only removed gradually in the background;
4794
4795 3. When the user does IMPORT TABLESPACE, the tablespace will have the
4796 same id as it originally had.
4797
4798 4. Free all the pages in use by the tablespace if rename=true.
4799 @param[in] space_id Tablespace ID
4800 @return DB_SUCCESS or error */
4801 dberr_t fil_discard_tablespace(space_id_t space_id) {
4802 dberr_t err;
4803
4804 err = fil_delete_tablespace(space_id, BUF_REMOVE_NONE);
4805
4806 switch (err) {
4807 case DB_SUCCESS:
4808 break;
4809
4810 case DB_IO_ERROR:
4811
4812 ib::warn(ER_IB_MSG_291, ulong{space_id}, ut_strerr(err));
4813 break;
4814
4815 case DB_TABLESPACE_NOT_FOUND:
4816
4817 ib::warn(ER_IB_MSG_292, ulong{space_id}, ut_strerr(err));
4818 break;
4819
4820 default:
4821 ut_error;
4822 }
4823
4824 return err;
4825 }
4826
4827 /** Write redo log for renaming a file.
4828 @param[in] space_id Tablespace id
4829 @param[in] old_name Tablespace file name
4830 @param[in] new_name Tablespace file name after renaming
4831 @param[in,out] mtr Mini-transaction */
4832 static void fil_name_write_rename(space_id_t space_id, const char *old_name,
4833 const char *new_name, mtr_t *mtr) {
4834 ut_ad(!fsp_is_system_or_temp_tablespace(space_id));
4835 ut_ad(!fsp_is_undo_tablespace(space_id));
4836
4837 /* Note: A checkpoint can take place here. */
4838
4839 DBUG_EXECUTE_IF("ib_crash_rename_log_1", DBUG_SUICIDE(););
4840
4841 static const auto type = MLOG_FILE_RENAME;
4842
4843 fil_op_write_log(type, space_id, old_name, new_name, 0, mtr);
4844
4845 DBUG_EXECUTE_IF("ib_crash_rename_log_2", DBUG_SUICIDE(););
4846
4847 /* Note: A checkpoint can take place here too before we
4848 have physically renamed the file. */
4849 }
4850
4851 #ifdef UNIV_LINUX
4852 /* Write a redo log record for adding pages to a tablespace
4853 @param[in] space_id Space ID
4854 @param[in] offset Offset from where the file
4855 is extended
4856 @param[in] size Number of bytes by which the file
4857 is extended starting from the offset
4858 @param[in,out] mtr Mini-transaction */
4859 static void fil_op_write_space_extend(space_id_t space_id, os_offset_t offset,
4860 os_offset_t size, mtr_t *mtr) {
4861 byte *log_ptr;
4862
4863 if (!mlog_open(mtr, 7 + 8 + 8, log_ptr)) {
4864 /* Logging in mtr is switched off during crash recovery:
4865 in that case mlog_open returns nullptr */
4866 return;
4867 }
4868
4869 #ifdef UNIV_DEBUG
4870 byte *start_log = log_ptr;
4871 #endif /* UNIV_DEBUG */
4872
4873 log_ptr = mlog_write_initial_log_record_low(MLOG_FILE_EXTEND, space_id, 0,
4874 log_ptr, mtr);
4875
4876 ut_ad(size > 0);
4877
4878 /* Write the starting offset in the file */
4879 mach_write_to_8(log_ptr, offset);
4880 log_ptr += 8;
4881
4882 /* Write the size by which file needs to be extended from
4883 the given offset */
4884 mach_write_to_8(log_ptr, size);
4885 log_ptr += 8;
4886
4887 ut_ad(log_ptr <= start_log + 23);
4888
4889 mlog_close(mtr, log_ptr);
4890
4891 DBUG_EXECUTE_IF(
4892 "ib_redo_log_system_tablespace_expansion", if (space_id == 0) {
4893 /* info message requires increasing the log level of the test,
4894 and the test happens to produce the huge logs. Therefore, produce a
4895 warning that doesn't require increasing the log level */
4896 ib::warn() << "System tablespace expansion is redo logged.";
4897 });
4898 }
4899 #endif
4900 #endif /* !UNIV_HOTBACKUP */
4901
4902 /** Allocate and build a file name from a path, a table or tablespace name
4903 and a suffix.
4904 @param[in] path_in nullptr or the directory path or the full path
4905 and filename
4906 @param[in] name_in nullptr if path is full, or Table/Tablespace
4907 name
4908 @param[in] ext the file extension to use
4909 @param[in] trim whether last name on the path should be trimmed
4910 @return own: file name; must be freed by ut::free() */
4911 char *Fil_path::make(const std::string &path_in, const std::string &name_in,
4912 ib_file_suffix ext, bool trim) {
4913 /* The path should be a directory and should not contain the
4914 basename of the file. If the path is empty, we will use the
4915 default path, */
4916
4917 ut_ad(!path_in.empty() || !name_in.empty());
4918
4919 std::string path;
4920
4921 if (path_in.empty()) {
4922 if (is_absolute_path(name_in)) {
4923 path = "";
4924 } else {
4925 path.assign(MySQL_datadir_path);
4926 }
4927 } else {
4928 path.assign(path_in);
4929 }
4930
4931 std::string name;
4932
4933 if (!name_in.empty()) {
4934 name.assign(name_in);
4935 }
4936
4937 /* Do not prepend the datadir path (which must be DOT_SLASH)
4938 if the name is an absolute path or a relative path like
4939 DOT_SLASH or DOT_DOT_SLASH. */
4940 if (is_absolute_path(name) || has_prefix(name, DOT_SLASH) ||
4941 has_prefix(name, DOT_DOT_SLASH)) {
4942 path.clear();
4943 }
4944
4945 std::string filepath;
4946
4947 if (!path.empty()) {
4948 filepath.assign(path);
4949 }
4950
4951 if (trim) {
4952 /* Find the offset of the last DIR separator and set it to
4953 null in order to strip off the old basename from this path. */
4954 auto pos = filepath.find_last_of(SEPARATOR);
4955
4956 if (pos != std::string::npos) {
4957 filepath.resize(pos);
4958 }
4959 }
4960
4961 if (!name.empty()) {
4962 append_separator(filepath);
4963
4964 filepath.append(name);
4965 }
4966
4967 /* Make sure that the specified suffix is at the end. */
4968 if (ext != NO_EXT) {
4969 const auto suffix = dot_ext[ext];
4970 size_t len = strlen(suffix);
4971
4972 /* This assumes that the suffix starts with '.'. If the
4973 first char of the suffix is found in the filepath at the
4974 same length as the suffix from the end, then we will assume
4975 that there is a previous suffix that needs to be replaced. */
4976
4977 ut_ad(*suffix == '.');
4978
4979 if (filepath.length() > len && *(filepath.end() - len) == *suffix) {
4980 filepath.replace(filepath.end() - len, filepath.end(), suffix);
4981 } else {
4982 filepath.append(suffix);
4983 }
4984 }
4985
4986 normalize(filepath);
4987
4988 return mem_strdup(filepath.c_str());
4989 }
4990
4991 bool Fil_path::parse_file_path(const std::string &file_path,
4992 ib_file_suffix extn, std::string &dict_name) {
4993 dict_name.assign(file_path);
4994 if (!Fil_path::truncate_suffix(extn, dict_name)) {
4995 dict_name.clear();
4996 return false;
4997 }
4998
4999 /* Extract table name */
5000 auto table_pos = dict_name.find_last_of(SEPARATOR);
5001 if (table_pos == std::string::npos) {
5002 dict_name.clear();
5003 return false;
5004 }
5005 std::string table_name = dict_name.substr(table_pos + 1);
5006 dict_name.resize(table_pos);
5007
5008 /* Extract schema name */
5009 auto schema_pos = dict_name.find_last_of(SEPARATOR);
5010 if (schema_pos == std::string::npos) {
5011 dict_name.clear();
5012 return false;
5013 }
5014 std::string schema_name = dict_name.substr(schema_pos + 1);
5015
5016 /* Build dictionary table name schema/table form. */
5017 dict_name.assign(schema_name);
5018 dict_name.push_back(DB_SEPARATOR);
5019 dict_name.append(table_name);
5020 return true;
5021 }
5022
5023 std::string Fil_path::make_new_path(const std::string &path_in,
5024 const std::string &name_in,
5025 ib_file_suffix extn) {
5026 ut_a(Fil_path::has_suffix(extn, path_in));
5027 ut_a(!Fil_path::has_suffix(extn, name_in));
5028
5029 std::string path(path_in);
5030
5031 auto pos = path.find_last_of(SEPARATOR);
5032
5033 ut_a(pos != std::string::npos);
5034
5035 path.resize(pos);
5036
5037 pos = path.find_last_of(SEPARATOR);
5038
5039 ut_a(pos != std::string::npos);
5040
5041 path.resize(pos + 1);
5042
5043 path.append(name_in + dot_ext[extn]);
5044
5045 normalize(path);
5046
5047 return path;
5048 }
5049
5050 /** This function reduces a null-terminated full remote path name
5051 into the path that is sent by MySQL for DATA DIRECTORY clause.
5052 It replaces the 'databasename/tablename.ibd' found at the end of the
5053 path with just 'tablename'.
5054
5055 Since the result is always smaller than the path sent in, no new
5056 memory is allocated. The caller should allocate memory for the path
5057 sent in. This function manipulates that path in place. If the path
5058 format is not as expected, set data_dir_path to "" and return.
5059
5060 The result is used to inform a SHOW CREATE TABLE command.
5061 @param[in,out] data_dir_path Full path/data_dir_path */
5062 void Fil_path::make_data_dir_path(char *data_dir_path) {
5063 /* Replace the period before the extension with a null byte. */
5064 ut_ad(has_suffix(IBD, data_dir_path));
5065 char *dot = strrchr((char *)data_dir_path, '.');
5066 *dot = '\0';
5067
5068 /* The tablename starts after the last slash. */
5069 char *base_slash = strrchr((char *)data_dir_path, OS_PATH_SEPARATOR);
5070 ut_ad(base_slash != nullptr);
5071
5072 *base_slash = '\0';
5073
5074 std::string base_name{base_slash + 1};
5075
5076 /* The database name starts after the next to last slash. */
5077 char *db_slash = strrchr((char *)data_dir_path, OS_SEPARATOR);
5078 ut_ad(db_slash != nullptr);
5079 char *db_name = db_slash + 1;
5080
5081 /* Overwrite the db_name with the base_name. */
5082 memmove(db_name, base_name.c_str(), base_name.length());
5083 db_name[base_name.length()] = '\0';
5084 }
5085
5086 /** Test if a tablespace file can be renamed to a new filepath by checking
5087 if that the old filepath exists and the new filepath does not exist.
5088 @param[in] space_id Tablespace ID
5089 @param[in] old_path Old filepath
5090 @param[in] new_path New filepath
5091 @param[in] is_discarded Whether the tablespace is discarded
5092 @return innodb error code */
5093 dberr_t fil_rename_tablespace_check(space_id_t space_id, const char *old_path,
5094 const char *new_path, bool is_discarded) {
5095 bool exists;
5096 os_file_type_t ftype;
5097
5098 if (!is_discarded && os_file_status(old_path, &exists, &ftype) && !exists) {
5099 ib::error(ER_IB_MSG_293, old_path, new_path, ulong{space_id});
5100 return DB_TABLESPACE_NOT_FOUND;
5101 }
5102
5103 if (!os_file_status(new_path, &exists, &ftype) || exists) {
5104 ib::error(ER_IB_MSG_294, old_path, new_path, ulong{space_id});
5105 return DB_TABLESPACE_EXISTS;
5106 }
5107
5108 return DB_SUCCESS;
5109 }
5110
5111 /** Rename a single-table tablespace.
5112 The tablespace must exist in the memory cache.
5113 @param[in] space_id Tablespace ID
5114 @param[in] old_path Old file name
5115 @param[in] new_name New tablespace name in the schema/space
5116 @param[in] new_path_in New file name, or nullptr if it is located
5117 in the normal data directory
5118 @return InnoDB error code */
5119 dberr_t Fil_shard::space_rename(space_id_t space_id, const char *old_path,
5120 const char *new_name, const char *new_path_in) {
5121 fil_space_t *space;
5122 ulint count = 0;
5123 fil_node_t *file = nullptr;
5124 bool write_ddl_log = true;
5125 auto start_time = std::chrono::steady_clock::now();
5126
5127 #ifdef UNIV_DEBUG
5128 static uint32_t crash_injection_rename_tablespace_counter = 1;
5129 #endif /* UNIV_DEBUG */
5130
5131 ut_a(space_id != TRX_SYS_SPACE);
5132 ut_ad(strchr(new_name, '/') != nullptr);
5133
5134 for (;;) {
5135 bool retry = false;
5136 bool flush = false;
5137
5138 ++count;
5139
5140 if (!(count % 1000)) {
5141 ib::warn(ER_IB_MSG_295, old_path, ulong{space_id}, ulonglong{count});
5142 }
5143
5144 /* The name map and space ID map are in the same shard. */
5145 mutex_acquire();
5146
5147 space = get_space_by_id(space_id);
5148
5149 DBUG_EXECUTE_IF("fil_rename_tablespace_failure_1", space = nullptr;);
5150
5151 if (space == nullptr) {
5152 ib::error(ER_IB_MSG_296, ulong{space_id}, old_path);
5153
5154 mutex_release();
5155
5156 return DB_ERROR;
5157
5158 } else if (space->prevent_file_open) {
5159 /* Some other thread has stopped the IO. We need to
5160 wait for the other thread to complete its operation. */
5161 mutex_release();
5162
5163 if (std::chrono::steady_clock::now() - start_time >= PRINT_INTERVAL) {
5164 ib::warn(ER_IB_MSG_297);
5165
5166 start_time = std::chrono::steady_clock::now();
5167 }
5168
5169 std::this_thread::sleep_for(std::chrono::seconds(1));
5170
5171 continue;
5172
5173 } else if (count > 25000) {
5174 mutex_release();
5175
5176 return DB_ERROR;
5177
5178 } else if (space != get_space_by_name(space->name)) {
5179 ib::error(ER_IB_MSG_298, space->name);
5180
5181 mutex_release();
5182
5183 return DB_ERROR;
5184
5185 } else {
5186 auto new_space = get_space_by_name(new_name);
5187
5188 if (new_space != nullptr) {
5189 if (new_space == space) {
5190 mutex_release();
5191
5192 return DB_SUCCESS;
5193 }
5194
5195 ut_a(new_space->id == space->id);
5196 }
5197 }
5198
5199 ut_a(space->files.size() == 1);
5200
5201 #ifndef UNIV_HOTBACKUP
5202 /* Don't write DDL log during recovery when log_ddl is
5203 not initialized. */
5204
5205 if (write_ddl_log && log_ddl != nullptr) {
5206 /* Write ddl log when space->prevent_file_open is true
5207 can cause deadlock:
5208 a. buffer flush thread waits for rename thread to set
5209 prevent_file_open to false;
5210 b. rename thread waits for buffer flush thread to flush
5211 a page and release page lock. The page is ready for
5212 flush in double write buffer. */
5213
5214 ut_ad(!space->prevent_file_open);
5215
5216 file = &space->files.front();
5217
5218 char *new_file_name = new_path_in == nullptr
5219 ? Fil_path::make_ibd_from_table_name(new_name)
5220 : mem_strdup(new_path_in);
5221
5222 char *old_file_name = file->name;
5223
5224 ut_ad(strchr(old_file_name, OS_PATH_SEPARATOR) != nullptr);
5225
5226 ut_ad(strchr(new_file_name, OS_PATH_SEPARATOR) != nullptr);
5227
5228 mutex_release();
5229
5230 /* Rename ddl log is for rollback, so we exchange
5231 old file name with new file name. */
5232 dberr_t err = log_ddl->write_rename_space_log(space_id, new_file_name,
5233 old_file_name);
5234 ut::free(new_file_name);
5235 if (err != DB_SUCCESS) {
5236 return err;
5237 }
5238
5239 write_ddl_log = false;
5240 continue;
5241 }
5242 #endif /* !UNIV_HOTBACKUP */
5243
5244 /* We temporarily close the .ibd file because we do
5245 not trust that operating systems can rename an open
5246 file. For the closing we have to wait until there
5247 are no pending I/O's or flushes on the file. */
5248
5249 space->prevent_file_open = true;
5250
5251 file = &space->files.front();
5252
5253 if (file->n_pending_ios > 0 || file->n_pending_flushes > 0 ||
5254 file->is_being_extended) {
5255 /* There are pending I/O's or flushes or the
5256 file is currently being extended, sleep for
5257 a while and retry */
5258
5259 retry = true;
5260
5261 space->prevent_file_open = false;
5262
5263 } else if (!file->is_flushed()) {
5264 /* Flush the space */
5265
5266 retry = flush = true;
5267
5268 space->prevent_file_open = false;
5269
5270 } else if (file->is_open) {
5271 close_file(file);
5272 }
5273
5274 if (!retry) {
5275 ut_ad(space->prevent_file_open);
5276 }
5277
5278 mutex_release();
5279
5280 if (!retry) {
5281 break;
5282 }
5283
5284 std::this_thread::sleep_for(std::chrono::milliseconds(100));
5285
5286 if (flush) {
5287 mutex_acquire();
5288
5289 space_flush(space->id);
5290
5291 mutex_release();
5292 }
5293 }
5294
5295 #ifndef UNIV_HOTBACKUP
5296 /* Make sure we re not holding shard mutex. */
5297 ut_ad(!mutex_owned());
5298 Clone_notify notifier(Clone_notify::Type::SPACE_RENAME, space_id, false);
5299
5300 if (notifier.failed()) {
5301 mutex_acquire();
5302 space->prevent_file_open = false;
5303 mutex_release();
5304
5305 return DB_ERROR;
5306 }
5307 #endif /* !UNIV_HOTBACKUP */
5308
5309 char *new_file_name;
5310
5311 if (new_path_in == nullptr) {
5312 new_file_name = Fil_path::make_ibd_from_table_name(new_name);
5313 } else {
5314 new_file_name = mem_strdup(new_path_in);
5315 }
5316
5317 char *old_file_name = file->name;
5318 char *old_space_name = space->name;
5319 char *new_space_name = mem_strdup(new_name);
5320
5321 #ifndef UNIV_HOTBACKUP
5322 if (!recv_recovery_on) {
5323 mtr_t mtr;
5324
5325 mtr.start();
5326
5327 fil_name_write_rename(space_id, old_file_name, new_file_name, &mtr);
5328
5329 mtr.commit();
5330 }
5331 #endif /* !UNIV_HOTBACKUP */
5332
5333 ut_ad(strchr(old_file_name, OS_PATH_SEPARATOR) != nullptr);
5334 ut_ad(strchr(new_file_name, OS_PATH_SEPARATOR) != nullptr);
5335
5336 mutex_acquire();
5337
5338 ut_ad(space->prevent_file_open);
5339
5340 /* We already checked these. */
5341 ut_ad(space == get_space_by_name(old_space_name));
5342 ut_ad(get_space_by_name(new_space_name) == nullptr);
5343
5344 bool success;
5345
5346 DBUG_EXECUTE_IF("fil_rename_tablespace_failure_2", goto skip_rename;);
5347
5348 DBUG_INJECT_CRASH("ddl_crash_before_rename_tablespace",
5349 crash_injection_rename_tablespace_counter++);
5350
5351 file = &space->files.front();
5352 ut_ad(!file->is_open);
5353
5354 success = os_file_rename(innodb_data_file_key, old_file_name, new_file_name);
5355
5356 DBUG_EXECUTE_IF("fil_rename_tablespace_failure_2", skip_rename
5357 : success = false;);
5358
5359 DBUG_INJECT_CRASH("ddl_crash_after_rename_tablespace",
5360 crash_injection_rename_tablespace_counter++);
5361
5362 if (success) {
5363 file->name = new_file_name;
5364
5365 update_space_name_map(space, new_space_name);
5366
5367 space->name = new_space_name;
5368
5369 } else {
5370 /* Because nothing was renamed, we must free the new
5371 names, not the old ones. */
5372 old_file_name = new_file_name;
5373 old_space_name = new_space_name;
5374 }
5375
5376 ut_ad(space->prevent_file_open);
5377 space->prevent_file_open = false;
5378
5379 mutex_release();
5380
5381 ut::free(old_file_name);
5382 ut::free(old_space_name);
5383
5384 return success ? DB_SUCCESS : DB_ERROR;
5385 }
5386
5387 /** Rename a single-table tablespace.
5388 The tablespace must exist in the memory cache.
5389 @param[in] space_id Tablespace ID
5390 @param[in] old_path Old file name
5391 @param[in] new_name New tablespace name in the schema/name format
5392 @param[in] new_path_in New file name, or nullptr if it is located in
5393 the normal data directory
5394 @return InnoDB error code */
5395 dberr_t fil_rename_tablespace(space_id_t space_id, const char *old_path,
5396 const char *new_name, const char *new_path_in) {
5397 auto shard = fil_system->shard_by_id(space_id);
5398
5399 dberr_t err = shard->space_rename(space_id, old_path, new_name, new_path_in);
5400
5401 return err;
5402 }
5403
5404 /** Rename a tablespace. Use the space_id to find the shard.
5405 @param[in] space_id tablespace ID
5406 @param[in] old_name old tablespace name
5407 @param[in] new_name new tablespace name
5408 @return DB_SUCCESS on success */
5409 dberr_t Fil_system::rename_tablespace_name(space_id_t space_id,
5410 const char *old_name,
5411 const char *new_name) {
5412 auto old_shard = fil_system->shard_by_id(space_id);
5413
5414 old_shard->mutex_acquire();
5415
5416 auto old_space = old_shard->get_space_by_id(space_id);
5417
5418 if (old_space == nullptr) {
5419 old_shard->mutex_release();
5420
5421 ib::error(ER_IB_MSG_299, old_name);
5422
5423 return DB_TABLESPACE_NOT_FOUND;
5424 }
5425
5426 ut_ad(old_space == old_shard->get_space_by_name(old_name));
5427 old_shard->mutex_release();
5428
5429 Fil_shard *new_shard{};
5430 fil_space_t *new_space{};
5431
5432 mutex_acquire_all();
5433
5434 for (auto shard : m_shards) {
5435 new_space = shard->get_space_by_name(new_name);
5436
5437 if (new_space != nullptr) {
5438 new_shard = shard;
5439 break;
5440 }
5441 }
5442
5443 if (new_space != nullptr) {
5444 mutex_release_all();
5445
5446 if (new_space->id != old_space->id) {
5447 ib::error(ER_IB_MSG_300, new_name);
5448
5449 return DB_TABLESPACE_EXISTS;
5450 } else {
5451 ut_a(new_shard == old_shard);
5452 }
5453
5454 return DB_SUCCESS;
5455 }
5456
5457 auto new_space_name = mem_strdup(new_name);
5458 auto old_space_name = old_space->name;
5459
5460 old_shard->update_space_name_map(old_space, new_space_name);
5461
5462 old_space->name = new_space_name;
5463
5464 mutex_release_all();
5465
5466 ut::free(old_space_name);
5467
5468 return DB_SUCCESS;
5469 }
5470
5471 dberr_t fil_rename_tablespace_by_id(space_id_t space_id, const char *old_name,
5472 const char *new_name) {
5473 return fil_system->rename_tablespace_name(space_id, old_name, new_name);
5474 }
5475
5476 dberr_t fil_write_initial_pages(pfs_os_file_t file, const char *path,
5477 fil_type_t type [[maybe_unused]],
5478 page_no_t size, const byte *encrypt_info,
5479 space_id_t space_id, uint32_t &space_flags,
5480 bool &atomic_write, bool &punch_hole) {
5481 bool success = false;
5482 atomic_write = false;
5483 punch_hole = false;
5484
5485 const page_size_t page_size(space_flags);
5486 const auto sz = ulonglong{size * page_size.physical()};
5487
5488 #if !defined(NO_FALLOCATE) && defined(UNIV_LINUX)
5489 {
5490 int ret = 0;
5491 #ifdef UNIV_DEBUG
5492 DBUG_EXECUTE_IF("fil_create_temp_tablespace_fail_fallocate", ret = -1;);
5493 if (ret == 0)
5494 #endif /* UNIV_DEBUG */
5495 {
5496 ret = posix_fallocate(file.m_file, 0, sz);
5497 }
5498
5499 if (ret == 0) {
5500 success = true;
5501 if (type == FIL_TYPE_TEMPORARY ||
5502 fil_fusionio_enable_atomic_write(file)) {
5503 atomic_write = true;
5504 }
5505 } else {
5506 /* If posix_fallocate() fails for any reason, issue only a warning
5507 and then fall back to os_file_set_size() */
5508 ib::warn(ER_IB_MSG_303, path, sz, ret, strerror(errno));
5509 }
5510 }
5511 #endif /* !NO_FALLOCATE && UNIV_LINUX */
5512
5513 if (!success || (tbsp_extend_and_initialize && !atomic_write)) {
5514 success = os_file_set_size(path, file, 0, sz, true);
5515
5516 if (success) {
5517 /* explicit initialization is needed as same as fil_space_extend(),
5518 instead of punch_hole. */
5519 dberr_t err =
5520 os_file_write_zeros(file, path, page_size.physical(), 0, sz);
5521 if (err != DB_SUCCESS) {
5522 ib::warn(ER_IB_MSG_320) << "Error while writing " << sz << " zeroes to "
5523 << path << " starting at offset " << 0;
5524 }
5525 }
5526 }
5527
5528 if (!success) {
5529 return DB_OUT_OF_DISK_SPACE;
5530 }
5531
5532 /* Note: We are actually punching a hole, previous contents will
5533 be lost after this call, if it succeeds. In this case the file
5534 should be full of NULs. */
5535
5536 punch_hole = os_is_sparse_file_supported(file);
5537
5538 /* Should not make large punch hole as initialization of large file,
5539 for crash-recovery safeness around disk-full. */
5540
5541 /* We have to write the space id to the file immediately and flush the
5542 file to disk. This is because in crash recovery we must be aware what
5543 tablespaces exist and what are their space id's, so that we can apply
5544 the log records to the right file. It may take quite a while until
5545 buffer pool flush algorithms write anything to the file and flush it to
5546 disk. If we would not write here anything, the file would be filled
5547 with zeros from the call of os_file_set_size(), until a buffer pool
5548 flush would write to it. */
5549
5550 /* Align the memory for file i/o if we might have O_DIRECT set */
5551 auto page = static_cast<byte *>(
5552 ut::aligned_zalloc(2 * page_size.logical(), page_size.logical()));
5553
5554 /* Add the UNIV_PAGE_SIZE to the table flags and write them to the
5555 tablespace header. */
5556 space_flags = fsp_flags_set_page_size(space_flags, page_size);
5557 fsp_header_init_fields(page, space_id, space_flags);
5558 mach_write_to_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, space_id);
5559
5560 mach_write_to_4(page + FIL_PAGE_SRV_VERSION, DD_SPACE_CURRENT_SRV_VERSION);
5561 mach_write_to_4(page + FIL_PAGE_SPACE_VERSION,
5562 DD_SPACE_CURRENT_SPACE_VERSION);
5563
5564 if (encrypt_info != nullptr) {
5565 auto key_offset = fsp_header_get_encryption_offset(page_size);
5566 memcpy(page + key_offset, encrypt_info, Encryption::INFO_SIZE);
5567 }
5568
5569 IORequest request(IORequest::WRITE);
5570 dberr_t err = DB_SUCCESS;
5571
5572 if (!page_size.is_compressed()) {
5573 buf_flush_init_for_writing(nullptr, page, nullptr, 0,
5574 fsp_is_checksum_disabled(space_id),
5575 true /* skip_lsn_check */);
5576
5577 err = os_file_write(request, path, file, page, 0, page_size.physical());
5578
5579 ut_ad(err != DB_IO_NO_PUNCH_HOLE);
5580
5581 } else {
5582 page_zip_des_t page_zip;
5583
5584 page_zip_set_size(&page_zip, page_size.physical());
5585 page_zip.data = page + page_size.logical();
5586 ut_d(page_zip.m_start = 0);
5587 page_zip.m_end = 0;
5588 page_zip.n_blobs = 0;
5589 page_zip.m_nonempty = false;
5590
5591 buf_flush_init_for_writing(nullptr, page, &page_zip, 0,
5592 fsp_is_checksum_disabled(space_id),
5593 true /* skip_lsn_check */);
5594
5595 err = os_file_write(request, path, file, page_zip.data, 0,
5596 page_size.physical());
5597
5598 ut_a(err != DB_IO_NO_PUNCH_HOLE);
5599
5600 punch_hole = false;
5601 }
5602
5603 ut::aligned_free(page);
5604 return err;
5605 }
5606
5607 /** Create a tablespace (an IBD or IBT) file
5608 @param[in] space_id Tablespace ID
5609 @param[in] name Tablespace name in dbname/tablename format.
5610 For general tablespaces, the 'dbname/' part
5611 may be missing.
5612 @param[in] path Path and filename of the datafile to create.
5613 @param[in] flags Tablespace flags
5614 @param[in] size Initial size of the tablespace file in pages,
5615 must be >= FIL_IBD_FILE_INITIAL_SIZE
5616 @param[in] type FIL_TYPE_TABLESPACE or FIL_TYPE_TEMPORARY
5617 @return DB_SUCCESS or error code */
5618 static dberr_t fil_create_tablespace(space_id_t space_id, const char *name,
5619 const char *path, uint32_t flags,
5620 page_no_t size, fil_type_t type) {
5621 ut_ad(!fsp_is_system_tablespace(space_id));
5622 ut_ad(!fsp_is_global_temporary(space_id));
5623 ut_a(fsp_flags_is_valid(flags));
5624 ut_a(type == FIL_TYPE_TEMPORARY || type == FIL_TYPE_TABLESPACE);
5625
5626 bool has_shared_space = FSP_FLAGS_GET_SHARED(flags);
5627 /* Create the subdirectories in the path, if they are
5628 not there already. */
5629 if (!has_shared_space) {
5630 auto err = os_file_create_subdirs_if_needed(path);
5631
5632 if (err != DB_SUCCESS) {
5633 return err; /* purecov: inspected */
5634 }
5635 }
5636
5637 bool success = false;
5638
5639 auto file = os_file_create(
5640 type == FIL_TYPE_TEMPORARY ? innodb_temp_file_key : innodb_data_file_key,
5641 path, OS_FILE_CREATE | OS_FILE_ON_ERROR_NO_EXIT, OS_DATA_FILE,
5642 srv_read_only_mode && (type != FIL_TYPE_TEMPORARY), &success);
5643
5644 if (!success) {
5645 /* purecov: begin inspected */
5646 /* The following call will print an error message */
5647 ulint error = os_file_get_last_error(true);
5648
5649 ib::error(ER_IB_MSG_301, path);
5650
5651 switch (error) {
5652 case OS_FILE_ALREADY_EXISTS:
5653 #ifndef UNIV_HOTBACKUP
5654 ib::error(ER_IB_MSG_UNEXPECTED_FILE_EXISTS, path, path);
5655 return DB_TABLESPACE_EXISTS;
5656 #else /* !UNIV_HOTBACKUP */
5657 return DB_SUCCESS; /* Already existing file not an error here. */
5658 #endif /* !UNIV_HOTBACKUP */
5659
5660 case OS_FILE_NAME_TOO_LONG:
5661 ib::error(ER_IB_MSG_TOO_LONG_PATH, path);
5662 return DB_TOO_LONG_PATH;
5663
5664 case OS_FILE_DISK_FULL:
5665 return DB_OUT_OF_DISK_SPACE;
5666
5667 default:
5668 return DB_ERROR;
5669 }
5670 /* purecov: end */
5671 }
5672
5673 bool atomic_write = false;
5674 bool punch_hole = false;
5675
5676 auto err = fil_write_initial_pages(file, path, type, size, nullptr, space_id,
5677 flags, atomic_write, punch_hole);
5678 if (err != DB_SUCCESS) {
5679 ib::error(ER_IB_MSG_304, path);
5680
5681 os_file_close(file);
5682 os_file_delete(innodb_data_file_key, path);
5683
5684 return err;
5685 }
5686
5687 success = os_file_flush(file);
5688
5689 if (!success) {
5690 ib::error(ER_IB_MSG_305, path);
5691
5692 os_file_close(file);
5693 os_file_delete(innodb_data_file_key, path);
5694 return DB_ERROR;
5695 }
5696
5697 #ifndef UNIV_HOTBACKUP
5698 /* Notifier block covers space creation and initialization. */
5699 Clone_notify notifier(Clone_notify::Type::SPACE_CREATE, space_id, false);
5700
5701 if (notifier.failed()) {
5702 os_file_close(file);
5703 return DB_ERROR;
5704 }
5705 #endif /* !UNIV_HOTBACKUP */
5706
5707 auto space = fil_space_create(name, space_id, flags, type);
5708
5709 if (space == nullptr) {
5710 os_file_close(file);
5711 os_file_delete(innodb_data_file_key, path);
5712 return DB_ERROR;
5713 }
5714
5715 DEBUG_SYNC_C("fil_ibd_created_space");
5716
5717 auto shard = fil_system->shard_by_id(space_id);
5718
5719 fil_node_t *file_node =
5720 shard->create_node(path, size, space, false, punch_hole, atomic_write);
5721
5722 err = (file_node == nullptr) ? DB_ERROR : DB_SUCCESS;
5723
5724 #ifndef UNIV_HOTBACKUP
5725 /* Temporary tablespace creation need not be redo logged */
5726 if (err == DB_SUCCESS && type != FIL_TYPE_TEMPORARY) {
5727 ut_a(space->files.size() == 1);
5728 const auto &file = space->files.front();
5729
5730 mtr_t mtr;
5731
5732 mtr_start(&mtr);
5733
5734 fil_op_write_log(MLOG_FILE_CREATE, space_id, file.name, nullptr,
5735 space->flags, &mtr);
5736
5737 mtr_commit(&mtr);
5738
5739 DBUG_EXECUTE_IF("fil_ibd_create_log", log_make_latest_checkpoint(););
5740 }
5741
5742 #endif /* !UNIV_HOTBACKUP */
5743
5744 /* For encryption tablespace, initial encryption information. */
5745 if (space != nullptr && FSP_FLAGS_GET_ENCRYPTION(space->flags)) {
5746 err = fil_set_encryption(space->id, Encryption::AES, nullptr, nullptr);
5747
5748 ut_ad(err == DB_SUCCESS);
5749 }
5750
5751 space->encryption_op_in_progress = Encryption::Progress::NONE;
5752
5753 os_file_close(file);
5754 if (err != DB_SUCCESS) {
5755 os_file_delete(innodb_data_file_key, path);
5756 }
5757
5758 return err;
5759 }
5760
5761 dberr_t fil_ibd_create(space_id_t space_id, const char *name, const char *path,
5762 uint32_t flags, page_no_t size) {
5763 ut_a(size >= FIL_IBD_FILE_INITIAL_SIZE);
5764 ut_ad(!srv_read_only_mode);
5765 return fil_create_tablespace(space_id, name, path, flags, size,
5766 FIL_TYPE_TABLESPACE);
5767 }
5768
5769 dberr_t fil_ibt_create(space_id_t space_id, const char *name, const char *path,
5770 uint32_t flags, page_no_t size) {
5771 ut_a(size >= FIL_IBT_FILE_INITIAL_SIZE);
5772 return fil_create_tablespace(space_id, name, path, flags, size,
5773 FIL_TYPE_TEMPORARY);
5774 }
5775
5776 #ifndef UNIV_HOTBACKUP
5777 dberr_t fil_ibd_open(bool validate, fil_type_t purpose, space_id_t space_id,
5778 uint32_t flags, const char *space_name,
5779 const char *path_in, bool strict, bool old_space) {
5780 Datafile df;
5781 bool is_encrypted = FSP_FLAGS_GET_ENCRYPTION(flags);
5782 bool for_import = (purpose == FIL_TYPE_IMPORT);
5783
5784 if (!fsp_flags_is_valid(flags)) {
5785 return DB_CORRUPTION;
5786 }
5787
5788 /* Check if the file is already open. The space can be loaded
5789 via fil_space_get_first_path() on startup. This is a problem
5790 for partitioning code. It's a convoluted call graph via the DD.
5791 On Windows this can lead to a sharing violation when we attempt
5792 to open it again. */
5793
5794 auto shard = fil_system->shard_by_id(space_id);
5795
5796 shard->mutex_acquire();
5797
5798 auto space = shard->get_space_by_id(space_id);
5799
5800 shard->mutex_release();
5801
5802 df.init(space_name, flags);
5803
5804 if (path_in == nullptr) {
5805 df.make_filepath(nullptr, space_name, IBD);
5806 } else {
5807 df.set_filepath(path_in);
5808 }
5809
5810 /* Attempt to open the tablespace. */
5811 if (df.open_read_only(strict) == DB_SUCCESS) {
5812 ut_ad(df.is_open());
5813 } else {
5814 ut_ad(!df.is_open());
5815 return DB_CANNOT_OPEN_FILE;
5816 }
5817
5818 #if !defined(NO_FALLOCATE) && defined(UNIV_LINUX)
5819 const bool atomic_write =
5820 !dblwr::is_enabled() && fil_fusionio_enable_atomic_write(df.handle());
5821 #else
5822 const bool atomic_write = false;
5823 #endif /* !NO_FALLOCATE && UNIV_LINUX */
5824
5825 dberr_t err;
5826
5827 if ((validate || is_encrypted) &&
5828 (err = df.validate_to_dd(space_id, flags, for_import)) != DB_SUCCESS) {
5829 /* We don't reply the rename via the redo log anymore.
5830 Therefore we can get a space ID mismatch when validating
5831 the files during bootstrap. */
5832
5833 if (!is_encrypted && err != DB_WRONG_FILE_NAME) {
5834 /* The following call prints an error message.
5835 For encrypted tablespace we skip print, since it should
5836 be keyring plugin issues. */
5837
5838 os_file_get_last_error(true);
5839
5840 ib::error(ER_IB_MSG_306, space_name, TROUBLESHOOT_DATADICT_MSG);
5841 }
5842
5843 return err;
5844 }
5845
5846 if (validate && !old_space && !for_import) {
5847 if (df.server_version() / 100 > DD_SPACE_CURRENT_SRV_VERSION / 100) {
5848 ib::error(ER_INVALID_SERVER_DOWNGRADE_NOT_PATCH,
5849 static_cast<uint32_t>(df.server_version()),
5850 DD_SPACE_CURRENT_SRV_VERSION);
5851 /* Server version is lower than the tablespace server version.
5852 We don't support downgrade except for patches, so report error.
5853 If the major/minor version is the same, and only the patch
5854 version is lower, then this is a patch downgrade. This will be
5855 checked in more detail while bootstrapping the SQL layer. */
5856 return DB_SERVER_VERSION_LOW;
5857 }
5858 ut_ad(df.space_version() == DD_SPACE_CURRENT_SPACE_VERSION);
5859 }
5860
5861 /* We are done validating. If the tablespace is already open,
5862 return success. */
5863 if (space != nullptr) {
5864 return DB_SUCCESS;
5865 }
5866
5867 /* We pass UNINITIALIZED flags while we try to open DD tablespace. In that
5868 case, set the flags now based on what is read from disk.*/
5869 if (FSP_FLAGS_ARE_NOT_SET(flags) && fsp_is_dd_tablespace(space_id)) {
5870 flags = df.flags();
5871 is_encrypted = FSP_FLAGS_GET_ENCRYPTION(flags);
5872 }
5873
5874 space = fil_space_create(space_name, space_id, flags, purpose);
5875
5876 if (space == nullptr) {
5877 return DB_ERROR;
5878 }
5879
5880 /* We do not measure the size of the file, that is why
5881 we pass the 0 below */
5882
5883 const fil_node_t *file =
5884 shard->create_node(df.filepath(), 0, space, false,
5885 IORequest::is_punch_hole_supported(), atomic_write);
5886
5887 if (file == nullptr) {
5888 return DB_ERROR;
5889 }
5890
5891 /* Set encryption operation in progress */
5892 space->encryption_op_in_progress = df.m_encryption_op_in_progress;
5893
5894 /* It's possible during Encryption processing, space flag for encryption
5895 has been updated in ibd file but server crashed before DD flags are
5896 updated. Thus, consider ibd setting for encryption. */
5897 if (FSP_FLAGS_GET_ENCRYPTION(df.flags())) {
5898 fsp_flags_set_encryption(space->flags);
5899 } else {
5900 fsp_flags_unset_encryption(space->flags);
5901 }
5902
5903 /* For encryption tablespace, initialize encryption information.*/
5904 if ((is_encrypted || FSP_FLAGS_GET_ENCRYPTION(space->flags)) && !for_import) {
5905 dberr_t err;
5906 byte *iv = df.m_encryption_iv;
5907 byte *key = df.m_encryption_key;
5908
5909 err = fil_set_encryption(space->id, Encryption::AES, key, iv);
5910
5911 if (err != DB_SUCCESS) {
5912 return DB_ERROR;
5913 }
5914
5915 /* If tablespace is encrypted with default master key and server has already
5916 started, rotate it now. */
5917 if (df.m_encryption_master_key_id == Encryption::DEFAULT_MASTER_KEY_ID &&
5918 /* There is no dependency on master thread but we are trying to check if
5919 server is in initial phase or not. */
5920 srv_master_thread_is_active()) {
5921 /* Reencrypt tablespace key */
5922 std::vector<space_id_t> sid;
5923 sid.push_back(space->id);
5924 fil_encryption_reencrypt(sid);
5925 }
5926 }
5927
5928 return DB_SUCCESS;
5929 }
5930
5931 #else /* !UNIV_HOTBACKUP */
5932
5933 /** Allocates a file name for an old version of a single-table tablespace.
5934 The string must be freed by caller with ut::free()!
5935 @param[in] name Original file name
5936 @return own: file name */
5937 static char *meb_make_ibbackup_old_name(const char *name) {
5938 char *path;
5939 ulint len = strlen(name);
5940 static const char suffix[] = "_ibbackup_old_vers_";
5941
5942 path = static_cast<char *>(
5943 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, len + 15 + sizeof(suffix)));
5944
5945 memcpy(path, name, len);
5946 memcpy(path + len, suffix, sizeof(suffix) - 1);
5947
5948 meb_sprintf_timestamp_without_extra_chars(path + len + sizeof(suffix) - 1);
5949
5950 return path;
5951 }
5952 #endif /* UNIV_HOTBACKUP */
5953
5954 /** Looks for a pre-existing fil_space_t with the given tablespace ID
5955 and, if found, returns the name and filepath in newly allocated buffers
5956 that the caller must free.
5957 @param[in] space_id The tablespace ID to search for.
5958 @param[out] name Name of the tablespace found.
5959 @param[out] filepath The filepath of the first datafile for the
5960 tablespace.
5961 @return true if tablespace is found, false if not. */
5962 bool fil_space_read_name_and_filepath(space_id_t space_id, char **name,
5963 char **filepath) {
5964 bool success = false;
5965
5966 *name = nullptr;
5967 *filepath = nullptr;
5968
5969 auto shard = fil_system->shard_by_id(space_id);
5970
5971 shard->mutex_acquire();
5972
5973 fil_space_t *space = shard->get_space_by_id(space_id);
5974
5975 if (space != nullptr) {
5976 *name = mem_strdup(space->name);
5977
5978 ut_a(space->files.size() == 1);
5979 *filepath = mem_strdup(space->files.front().name);
5980
5981 success = true;
5982 }
5983
5984 shard->mutex_release();
5985
5986 return success;
5987 }
5988
5989 /** Convert a file name to a tablespace name. Strip the file name
5990 prefix and suffix, leaving only databasename/tablename.
5991 @param[in] filename directory/databasename/tablename.ibd
5992 @return database/tablename string, to be freed with ut::free() */
5993 char *fil_path_to_space_name(const char *filename) {
5994 std::string path{filename};
5995 auto pos = path.find_last_of(Fil_path::SEPARATOR);
5996
5997 ut_a(pos != std::string::npos && !Fil_path::is_separator(path.back()));
5998
5999 std::string db_name = path.substr(0, pos);
6000 std::string space_name = path.substr(pos + 1, path.length());
6001
6002 /* If it is a path such as a/b/c.ibd, ignore everything before 'b'. */
6003 pos = db_name.find_last_of(Fil_path::SEPARATOR);
6004
6005 if (pos != std::string::npos) {
6006 db_name = db_name.substr(pos + 1);
6007 }
6008
6009 char *name;
6010
6011 if (Fil_path::has_suffix(IBD, space_name)) {
6012 /* fil_space_t::name always uses '/' . */
6013
6014 path = db_name;
6015 path.push_back('/');
6016
6017 /* Strip the ".ibd" suffix. */
6018 path.append(space_name.substr(0, space_name.length() - 4));
6019
6020 name = mem_strdupl(path.c_str(), path.length());
6021
6022 } else {
6023 /* Must have an "undo" prefix. */
6024 ut_ad(space_name.find("undo") == 0);
6025
6026 name = mem_strdupl(space_name.c_str(), space_name.length());
6027 }
6028
6029 return name;
6030 }
6031
6032 /** Open an ibd tablespace and add it to the InnoDB data structures.
6033 This is similar to fil_ibd_open() except that it is used while processing
6034 the redo and DDL log, so the data dictionary is not available and very little
6035 validation is done. The tablespace name is extracted from the
6036 dbname/tablename.ibd portion of the filename, which assumes that the file
6037 is a file-per-table tablespace. Any name will do for now. General
6038 tablespace names will be read from the dictionary after it has been
6039 recovered. The tablespace flags are read at this time from the first page
6040 of the file in validate_for_recovery().
6041 @param[in] space_id tablespace ID
6042 @param[in] path path/to/databasename/tablename.ibd
6043 @param[out] space the tablespace, or nullptr on error
6044 @return status of the operation */
6045 fil_load_status Fil_shard::ibd_open_for_recovery(space_id_t space_id,
6046 const std::string &path,
6047 fil_space_t *&space) {
6048 /* If the a space is already in the file system cache with this
6049 space ID, then there is nothing to do. */
6050
6051 mutex_acquire();
6052
6053 space = get_space_by_id(space_id);
6054
6055 mutex_release();
6056
6057 const char *filename = path.c_str();
6058
6059 if (space != nullptr) {
6060 ut_a(space->files.size() == 1);
6061
6062 const auto &file = space->files.front();
6063
6064 /* Compare the real paths. */
6065 if (Fil_path::is_same_as(filename, file.name)) {
6066 return FIL_LOAD_OK;
6067 }
6068
6069 #ifdef UNIV_HOTBACKUP
6070 ib::trace_2() << "Ignoring data file '" << filename << "' with space ID "
6071 << space->id << ". Another data file called '" << file.name
6072 << "' exists with the same space ID";
6073 #else /* UNIV_HOTBACKUP */
6074 ib::info(ER_IB_MSG_307, filename, ulong{space->id}, file.name);
6075 #endif /* UNIV_HOTBACKUP */
6076
6077 space = nullptr;
6078
6079 return FIL_LOAD_ID_CHANGED;
6080 }
6081
6082 Datafile df;
6083
6084 df.set_filepath(filename);
6085
6086 if (df.open_read_only(false) != DB_SUCCESS) {
6087 return FIL_LOAD_NOT_FOUND;
6088 }
6089
6090 ut_ad(df.is_open());
6091
6092 /* Get and test the file size. */
6093 os_offset_t size = os_file_get_size(df.handle());
6094
6095 /* Read and validate the first page of the tablespace. Assign a tablespace
6096 name based on the tablespace type. This will close the file, but will leave
6097 the flags and names to be queried. */
6098 dberr_t err = df.validate_for_recovery(space_id);
6099
6100 ut_a(err == DB_SUCCESS || err == DB_INVALID_ENCRYPTION_META ||
6101 err == DB_CORRUPTION);
6102
6103 if (err == DB_CORRUPTION) {
6104 return FIL_LOAD_DBWLR_CORRUPTION;
6105 }
6106
6107 if (err == DB_INVALID_ENCRYPTION_META) {
6108 bool success = fil_system->erase_path(space_id);
6109 ut_a(success);
6110 return FIL_LOAD_NOT_FOUND;
6111 }
6112
6113 ut_a(df.space_id() == space_id);
6114
6115 /* Every .ibd file is created >= 4 pages in size.
6116 Smaller files cannot be OK. */
6117 os_offset_t minimum_size;
6118
6119 /* Every .ibd file is created >= FIL_IBD_FILE_INITIAL_SIZE
6120 pages in size. Smaller files cannot be OK. */
6121 {
6122 const page_size_t page_size(df.flags());
6123
6124 minimum_size = FIL_IBD_FILE_INITIAL_SIZE * page_size.physical();
6125 }
6126
6127 if (size == static_cast<os_offset_t>(-1)) {
6128 /* The following call prints an error message */
6129 os_file_get_last_error(true);
6130
6131 ib::error(ER_IB_MSG_308) << "Could not measure the size of"
6132 " single-table tablespace file '"
6133 << df.filepath() << "'";
6134
6135 } else if (size < minimum_size) {
6136 #ifndef UNIV_HOTBACKUP
6137 ib::error(ER_IB_MSG_309)
6138 << "The size of tablespace file '" << df.filepath() << "' is only "
6139 << size << ", should be at least " << minimum_size << "!";
6140 #else
6141 /* In MEB, we work around this error. */
6142 df.set_space_id(SPACE_UNKNOWN);
6143 df.set_flags(0);
6144 #endif /* !UNIV_HOTBACKUP */
6145 }
6146
6147 ut_ad(space == nullptr);
6148
6149 #ifdef UNIV_HOTBACKUP
6150 if (df.space_id() == SPACE_UNKNOWN || df.space_id() == 0) {
6151 char *new_path;
6152
6153 ib::info(ER_IB_MSG_310)
6154 << "Renaming tablespace file '" << df.filepath() << "' with space ID "
6155 << df.space_id() << " to " << df.name()
6156 << "_ibbackup_old_vers_<timestamp>"
6157 " because its size "
6158 << df.size()
6159 << " is too small"
6160 " (< 4 pages 16 kB each), or the space id in the"
6161 " file header is not sensible. This can happen in"
6162 " an mysqlbackup run, and is not dangerous.";
6163 df.close();
6164
6165 new_path = meb_make_ibbackup_old_name(df.filepath());
6166
6167 bool success =
6168 os_file_rename(innodb_data_file_key, df.filepath(), new_path);
6169
6170 ut_a(success);
6171
6172 ut::free(new_path);
6173
6174 return FIL_LOAD_ID_CHANGED;
6175 }
6176
6177 /* A backup may contain the same space several times, if the space got
6178 renamed at a sensitive time. Since it is enough to have one version of
6179 the space, we rename the file if a space with the same space id
6180 already exists in the tablespace memory cache. We rather rename the
6181 file than delete it, because if there is a bug, we do not want to
6182 destroy valuable data. */
6183
6184 mutex_acquire();
6185
6186 space = get_space_by_id(space_id);
6187
6188 mutex_release();
6189
6190 if (space != nullptr) {
6191 ib::info(ER_IB_MSG_311)
6192 << "Renaming data file '" << df.filepath() << "' with space ID "
6193 << space_id << " to " << df.name()
6194 << "_ibbackup_old_vers_<timestamp> because space " << space->name
6195 << " with the same id was scanned"
6196 " earlier. This can happen if you have renamed tables"
6197 " during an mysqlbackup run.";
6198
6199 df.close();
6200
6201 char *new_path = meb_make_ibbackup_old_name(df.filepath());
6202
6203 bool success =
6204 os_file_rename(innodb_data_file_key, df.filepath(), new_path);
6205
6206 ut_a(success);
6207
6208 ut::free(new_path);
6209 return FIL_LOAD_OK;
6210 }
6211 #endif /* UNIV_HOTBACKUP */
6212 std::string tablespace_name(df.name());
6213
6214 /* During the apply-log operation, MEB already has translated the
6215 file name, so file name to space name conversion is not required. */
6216 #ifndef UNIV_HOTBACKUP
6217 dict_name::convert_to_space(tablespace_name);
6218 #endif /* !UNIV_HOTBACKUP */
6219
6220 fil_system->mutex_acquire_all();
6221
6222 space = space_create(tablespace_name.c_str(), space_id, df.flags(),
6223 FIL_TYPE_TABLESPACE);
6224
6225 fil_system->mutex_release_all();
6226
6227 if (space == nullptr) {
6228 return FIL_LOAD_INVALID;
6229 }
6230
6231 ut_ad(space->id == df.space_id());
6232 ut_ad(space->id == space_id);
6233
6234 /* We do not use the size information we have about the file, because
6235 the rounding formula for extents and pages is somewhat complex; we
6236 let create_node() do that task. */
6237
6238 const fil_node_t *file;
6239
6240 file = create_node(df.filepath(), 0, space, false, true, false);
6241
6242 ut_a(file != nullptr);
6243
6244 /* For encryption tablespace, initial encryption information. */
6245 if (FSP_FLAGS_GET_ENCRYPTION(space->flags) &&
6246 df.m_encryption_key != nullptr) {
6247 dberr_t err = fil_set_encryption(space->id, Encryption::AES,
6248 df.m_encryption_key, df.m_encryption_iv);
6249
6250 if (err != DB_SUCCESS) {
6251 ib::error(ER_IB_MSG_312, space->name);
6252 }
6253 }
6254
6255 /* Set encryption operation in progress */
6256 space->encryption_op_in_progress = df.m_encryption_op_in_progress;
6257 space->m_header_page_flush_lsn = df.get_flush_lsn();
6258
6259 return FIL_LOAD_OK;
6260 }
6261
6262 /** Open an ibd tablespace and add it to the InnoDB data structures.
6263 This is similar to fil_ibd_open() except that it is used while processing
6264 the redo log, so the data dictionary is not available and very little
6265 validation is done. The tablespace name is extracted from the
6266 dbname/tablename.ibd portion of the filename, which assumes that the file
6267 is a file-per-table tablespace. Any name will do for now. General
6268 tablespace names will be read from the dictionary after it has been
6269 recovered. The tablespace flags are read at this time from the first page
6270 of the file in validate_for_recovery().
6271 @param[in] space_id tablespace ID
6272 @param[in] path path/to/databasename/tablename.ibd
6273 @param[out] space the tablespace, or nullptr on error
6274 @return status of the operation */
6275 fil_load_status Fil_system::ibd_open_for_recovery(space_id_t space_id,
6276 const std::string &path,
6277 fil_space_t *&space) {
6278 /* System tablespace open should never come here. It should be
6279 opened explicitly using the config path. */
6280 ut_a(space_id != TRX_SYS_SPACE);
6281
6282 #ifndef UNIV_HOTBACKUP
6283 /* Do not attempt to open or load for recovery any undo tablespace that
6284 is currently being truncated. */
6285 if (fsp_is_undo_tablespace(space_id) &&
6286 undo::is_active_truncate_log_present(undo::id2num(space_id))) {
6287 return FIL_LOAD_NOT_FOUND;
6288 }
6289 #endif /* !UNIV_HOTBACKUP */
6290
6291 auto shard = shard_by_id(space_id);
6292
6293 return shard->ibd_open_for_recovery(space_id, path, space);
6294 }
6295
6296 #ifndef UNIV_HOTBACKUP
6297
6298 /** Report that a tablespace for a table was not found.
6299 @param[in] name Table name
6300 @param[in] space_id Table's space ID */
6301 static void fil_report_missing_tablespace(const char *name,
6302 space_id_t space_id) {
6303 ib::error(ER_IB_MSG_313)
6304 << "Table " << name << " in the InnoDB data dictionary has tablespace id "
6305 << space_id << ", but a tablespace with that id or name does not exist."
6306 << " Have you deleted or moved .ibd files?";
6307 }
6308
6309 bool Fil_shard::adjust_space_name(fil_space_t *space,
6310 const char *dd_space_name) {
6311 if (!strcmp(space->name, dd_space_name)) {
6312 return true;
6313 }
6314
6315 bool replace_general =
6316 FSP_FLAGS_GET_SHARED(space->flags) &&
6317 0 == strncmp(space->name, general_space_name, strlen(general_space_name));
6318 bool replace_undo =
6319 fsp_is_undo_tablespace(space->id) &&
6320 0 == strncmp(space->name, undo_space_name, strlen(undo_space_name));
6321
6322 /* Update the auto-generated fil_space_t::name */
6323 if (replace_general || replace_undo) {
6324 char *old_space_name = space->name;
6325 char *new_space_name = mem_strdup(dd_space_name);
6326
6327 update_space_name_map(space, new_space_name);
6328
6329 space->name = new_space_name;
6330
6331 ut::free(old_space_name);
6332 }
6333
6334 /* Update the undo::Tablespace::name. Since the fil_shard mutex is held by
6335 the caller, it would be a sync order violation to get undo::spaces->s_lock.
6336 It is OK to skip this s_lock since this occurs during boot_tablespaces()
6337 which is still single threaded. */
6338 if (replace_undo) {
6339 space_id_t space_num = undo::id2num(space->id);
6340 undo::Tablespace *undo_space = undo::spaces->find(space_num);
6341 undo_space->set_space_name(dd_space_name);
6342 }
6343
6344 return (replace_general || replace_undo);
6345 }
6346
6347 bool Fil_shard::space_check_exists(space_id_t space_id, const char *name,
6348 bool print_err, bool adjust_space) {
6349 fil_space_t *fnamespace = nullptr;
6350
6351 mutex_acquire();
6352
6353 /* Look if there is a space with the same id */
6354 fil_space_t *space = get_space_by_id(space_id);
6355
6356 /* name is nullptr when replaying a DELETE ddl log. */
6357 if (name == nullptr) {
6358 mutex_release();
6359 return (space != nullptr);
6360 }
6361
6362 if (space != nullptr) {
6363 /* No need to check a general tablespace name if the DD
6364 is not yet available. */
6365 if (!srv_sys_tablespaces_open && FSP_FLAGS_GET_SHARED(space->flags)) {
6366 mutex_release();
6367 return true;
6368 }
6369
6370 /* Sometimes the name has been auto-generated when the
6371 datafile is discovered and needs to be adjusted to that
6372 of the DD. This happens for general and undo tablespaces. */
6373 if (srv_sys_tablespaces_open && adjust_space &&
6374 adjust_space_name(space, name)) {
6375 mutex_release();
6376 return true;
6377 }
6378
6379 /* If this space has the expected name, use it. */
6380 fnamespace = get_space_by_name(name);
6381
6382 if (space == fnamespace) {
6383 /* Found */
6384 mutex_release();
6385 return true;
6386 }
6387 }
6388
6389 /* Info from "fnamespace" comes from the ibd file itself, it can
6390 be different from data obtained from System tables since file
6391 operations are not transactional. If adjust_space is set, and the
6392 mismatching space are between a user table and its temp table, we
6393 shall adjust the ibd file name according to system table info */
6394 if (adjust_space && space != nullptr &&
6395 row_is_mysql_tmp_table_name(space->name) &&
6396 !row_is_mysql_tmp_table_name(name)) {
6397 /* Atomic DDL's "ddl_log" will adjust the tablespace name. */
6398 mutex_release();
6399
6400 return true;
6401
6402 } else if (!print_err) {
6403 ;
6404
6405 } else if (space == nullptr) {
6406 if (fnamespace == nullptr) {
6407 if (print_err) {
6408 fil_report_missing_tablespace(name, space_id);
6409 }
6410
6411 } else {
6412 ib::error(ER_IB_MSG_314)
6413 << "Table " << name << " in InnoDB data dictionary has tablespace id "
6414 << space_id << ", but a tablespace with that id does not exist."
6415 << " But there is a tablespace of name " << fnamespace->name
6416 << " and id " << fnamespace->id
6417 << ". Have you deleted or moved .ibd files?";
6418 }
6419
6420 ib::warn(ER_IB_MSG_315) << TROUBLESHOOT_DATADICT_MSG;
6421
6422 } else if (0 != strcmp(space->name, name)) {
6423 ib::error(ER_IB_MSG_316)
6424 << "Table " << name << " in InnoDB data dictionary"
6425 << " has tablespace id " << space_id
6426 << ", but the tablespace with that id has name " << space->name
6427 << ". Have you deleted or moved .ibd files?";
6428
6429 if (fnamespace != nullptr) {
6430 ib::error(ER_IB_MSG_317)
6431 << "There is a tablespace with the name " << fnamespace->name
6432 << ", but its id is " << fnamespace->id << ".";
6433 }
6434
6435 ib::warn(ER_IB_MSG_318) << TROUBLESHOOT_DATADICT_MSG;
6436 }
6437
6438 mutex_release();
6439
6440 return false;
6441 }
6442
6443 bool fil_space_exists_in_mem(space_id_t space_id, const char *name,
6444 bool print_err, bool adjust_space) {
6445 auto shard = fil_system->shard_by_id(space_id);
6446
6447 return shard->space_check_exists(space_id, name, print_err, adjust_space);
6448 }
6449 #endif /* !UNIV_HOTBACKUP */
6450
6451 /** Returns the space ID based on the tablespace name.
6452 The tablespace must be found in the tablespace memory cache.
6453 This call is made from external to this module, so the mutex is not owned.
6454 @param[in] name Tablespace name
6455 @return space ID if tablespace found, SPACE_UNKNOWN if space not. */
6456 space_id_t fil_space_get_id_by_name(const char *name) {
6457 auto space = fil_system->get_space_by_name(name);
6458
6459 return (space == nullptr) ? SPACE_UNKNOWN : space->id;
6460 }
6461
6462 /** Fill the pages with NULs
6463 @param[in] file Tablespace file
6464 @param[in] page_size physical page size
6465 @param[in] start Offset from the start of the file in bytes
6466 @param[in] len Length in bytes
6467 @return DB_SUCCESS or error code */
6468 static dberr_t fil_write_zeros(const fil_node_t *file, ulint page_size,
6469 os_offset_t start, os_offset_t len) {
6470 ut_a(len > 0);
6471
6472 /* Extend at most 1M at a time */
6473 os_offset_t n_bytes = std::min(static_cast<os_offset_t>(1024 * 1024), len);
6474
6475 byte *buf = reinterpret_cast<byte *>(ut::aligned_zalloc(n_bytes, page_size));
6476
6477 os_offset_t offset = start;
6478 dberr_t err = DB_SUCCESS;
6479 const os_offset_t end = start + len;
6480 IORequest request(IORequest::WRITE);
6481
6482 while (offset < end) {
6483 err =
6484 os_file_write(request, file->name, file->handle, buf, offset, n_bytes);
6485
6486 if (err != DB_SUCCESS) {
6487 break;
6488 }
6489
6490 offset += n_bytes;
6491
6492 n_bytes = std::min(n_bytes, end - offset);
6493
6494 DBUG_EXECUTE_IF("ib_crash_during_tablespace_extension", DBUG_SUICIDE(););
6495 }
6496
6497 ut::aligned_free(buf);
6498
6499 return err;
6500 }
6501
6502 /** Try to extend a tablespace if it is smaller than the specified size.
6503 @param[in,out] space tablespace
6504 @param[in] size desired size in pages
6505 @return whether the tablespace is at least as big as requested */
6506 bool Fil_shard::space_extend(fil_space_t *space, page_no_t size) {
6507 /* In read-only mode we allow write to shared temporary tablespace
6508 as intrinsic table created by Optimizer reside in this tablespace. */
6509 ut_ad(!srv_read_only_mode || fsp_is_system_temporary(space->id));
6510
6511 #ifndef UNIV_HOTBACKUP
6512 DBUG_EXECUTE_IF("fil_space_print_xdes_pages",
6513 space->print_xdes_pages("xdes_pages.log"););
6514 #endif /* !UNIV_HOTBACKUP */
6515
6516 fil_node_t *file;
6517 bool success = true;
6518
6519 #ifdef UNIV_HOTBACKUP
6520 page_no_t prev_size = 0;
6521 #endif /* UNIV_HOTBACKUP */
6522
6523 for (;;) {
6524 mutex_acquire();
6525 space = get_space_by_id(space->id);
6526
6527 /* Note:If the file is being opened for the first time then
6528 we don't have the file physical size. There is no guarantee
6529 that the file has been opened at this stage. */
6530
6531 if (size < space->size) {
6532 /* Space already big enough */
6533 mutex_release();
6534
6535 return true;
6536 }
6537
6538 file = &space->files.back();
6539
6540 if (!file->is_being_extended) {
6541 /* Mark this file as undergoing extension. This flag
6542 is used to synchronize threads to execute space extension in order. */
6543
6544 file->is_being_extended = true;
6545
6546 break;
6547 }
6548
6549 /* Another thread is currently using the file. Wait
6550 for it to finish. It'd have been better to use an event
6551 driven mechanism but the entire module is peppered with
6552 polling code. */
6553
6554 mutex_release();
6555
6556 if (!tbsp_extend_and_initialize) {
6557 std::this_thread::sleep_for(std::chrono::microseconds(20));
6558 } else {
6559 std::this_thread::sleep_for(std::chrono::milliseconds(100));
6560 }
6561 }
6562
6563 if (!prepare_file_for_io(file)) {
6564 /* The tablespace data file, such as .ibd file, is missing */
6565 ut_a(file->is_being_extended);
6566 file->is_being_extended = false;
6567
6568 mutex_release();
6569
6570 return false;
6571 }
6572
6573 ut_a(file->is_open);
6574
6575 const page_size_t page_size(space->flags);
6576 const size_t phy_page_size = page_size.physical();
6577
6578 #ifdef UNIV_HOTBACKUP
6579 prev_size = space->size;
6580
6581 ib::trace_1() << "Extending space id : " << space->id
6582 << ", space name : " << space->name
6583 << ", space size : " << space->size
6584 << " pages, page size : " << phy_page_size
6585 << ", to size : " << size;
6586 #endif /* UNIV_HOTBACKUP */
6587
6588 if (size <= space->size) {
6589 ut_a(file->is_being_extended);
6590 file->is_being_extended = false;
6591
6592 complete_io(file, IORequestRead);
6593
6594 mutex_release();
6595
6596 return true;
6597 }
6598
6599 /* At this point it is safe to release the shard mutex. No
6600 other thread can rename, delete or close the file because
6601 we have set the file->in_use flag. */
6602
6603 mutex_release();
6604
6605 page_no_t pages_added;
6606 os_offset_t node_start = os_file_get_size(file->handle);
6607
6608 ut_a(node_start != (os_offset_t)-1);
6609
6610 /* File first page number */
6611 page_no_t node_first_page = space->size - file->size;
6612
6613 /* Number of physical pages in the file */
6614 page_no_t n_node_physical_pages =
6615 static_cast<page_no_t>(node_start / phy_page_size);
6616
6617 /* Number of pages to extend in the file */
6618 page_no_t n_node_extend;
6619
6620 n_node_extend = size - (node_first_page + file->size);
6621
6622 /* If we already have enough physical pages to satisfy the
6623 extend request on the file then ignore it */
6624 if (file->size + n_node_extend > n_node_physical_pages) {
6625 DBUG_EXECUTE_IF("ib_crash_during_tablespace_extension", DBUG_SUICIDE(););
6626
6627 os_offset_t len;
6628 dberr_t err = DB_SUCCESS;
6629
6630 len = ((file->size + n_node_extend) * phy_page_size) - node_start;
6631
6632 ut_ad(len > 0);
6633
6634 #if !defined(UNIV_HOTBACKUP) && defined(UNIV_LINUX)
6635 /* Do not write redo log, during replay and, for temporary tablespaces
6636 because they are reinitialized during startup hence they need not be
6637 recovered during replay. */
6638 if (!recv_recovery_is_on() && space->purpose != FIL_TYPE_TEMPORARY) {
6639 /* Write the redo log record for extending the space */
6640 mtr_t mtr;
6641 mtr_start(&mtr);
6642
6643 ut_ad(node_start > 0);
6644 ut_ad(len > 0);
6645
6646 /* The posix_fallocate() reserves the desired space and updates
6647 the file metadata in the filesystem. On successful execution, any
6648 subsequent attempt to access this newly allocated space will see
6649 it as initialized because of the updated filesystem metadata.
6650
6651 However, the posix_fallocate() call used to allocate space seems
6652 to have an atomicity issue where it can fail after reserving the
6653 space, but before updating the file metadata in the filesystem.
6654
6655 Offset is required to be written in the redo log record to find
6656 out the position in the file where it was extended during space
6657 extend operation. The offset value written in the redo log can
6658 be directly used to find the starting point for initializing
6659 the file during recovery. In case posix_fallocate() crashes as
6660 described above, it will be difficult to find out the old size
6661 of the file and hence it will be difficult to find out the exact
6662 region which needs to be initialized by writing 0's. */
6663
6664 fil_op_write_space_extend(space->id, node_start, len, &mtr);
6665
6666 mtr_commit(&mtr);
6667
6668 DBUG_INJECT_CRASH_WITH_LOG_FLUSH("ib_crash_after_writing_redo_extend", 1);
6669
6670 /* NOTE: Though against for the Write-Ahead-Log principal,
6671 log_write_up_to() is not needed here, because no file shrinks and
6672 duplicate extending is allowed. And log_write_up_to() here helps
6673 nothing for fallocate() inconsistency. */
6674 }
6675 #endif /* !UNIV_HOTBACKUP && UNIV_LINUX */
6676
6677 #if !defined(NO_FALLOCATE) && defined(UNIV_LINUX)
6678 /* This is required by FusionIO HW/Firmware */
6679
6680 int ret = posix_fallocate(file->handle.m_file, node_start, len);
6681
6682 DBUG_EXECUTE_IF("ib_posix_fallocate_fail_eintr", ret = EINTR;);
6683
6684 DBUG_EXECUTE_IF("ib_posix_fallocate_fail_einval", ret = EINVAL;);
6685
6686 if (ret != 0) {
6687 /* We already pass the valid offset and len in, if EINVAL
6688 is returned, it could only mean that the file system doesn't
6689 support fallocate(), currently one known case is ext3 with O_DIRECT.
6690
6691 Also because above call could be interrupted, in this case,
6692 simply go to plan B by writing zeroes.
6693
6694 Both error messages for above two scenarios are skipped in case
6695 of flooding error messages, because they can be ignored by users. */
6696 if (ret != EINTR && ret != EINVAL) {
6697 ib::error(ER_IB_MSG_319)
6698 << "posix_fallocate(): Failed to preallocate"
6699 " data for file "
6700 << file->name << ", desired size " << len
6701 << " bytes."
6702 " Operating system error number "
6703 << ret
6704 << ". Check"
6705 " that the disk is not full or a disk quota"
6706 " exceeded. Make sure the file system supports"
6707 " this function. Refer to your operating system"
6708 " documentation for operating system error code"
6709 " information.";
6710 }
6711
6712 err = DB_IO_ERROR;
6713 }
6714 #endif /* NO_FALLOCATE || !UNIV_LINUX */
6715
6716 if ((tbsp_extend_and_initialize && !file->atomic_write) ||
6717 err == DB_IO_ERROR) {
6718 err = fil_write_zeros(file, phy_page_size, node_start, len);
6719
6720 if (err != DB_SUCCESS) {
6721 ib::warn(ER_IB_MSG_320)
6722 << "Error while writing " << len << " zeroes to " << file->name
6723 << " starting at offset " << node_start;
6724 }
6725 }
6726
6727 /* Check how many pages actually added */
6728 os_offset_t end = os_file_get_size(file->handle);
6729 ut_a(end != static_cast<os_offset_t>(-1) && end >= node_start);
6730
6731 success = (end == node_start + len);
6732 os_has_said_disk_full = !success;
6733
6734 pages_added = static_cast<page_no_t>(end / phy_page_size);
6735
6736 ut_a(pages_added >= file->size);
6737 pages_added -= file->size;
6738
6739 } else {
6740 success = true;
6741 pages_added = n_node_extend;
6742 os_has_said_disk_full = false;
6743 }
6744
6745 mutex_acquire();
6746
6747 file->size += pages_added;
6748 space->size += pages_added;
6749
6750 ut_a(file->is_being_extended);
6751 file->is_being_extended = false;
6752
6753 complete_io(file, IORequestWrite);
6754
6755 #ifndef UNIV_HOTBACKUP
6756 /* Keep the last data file size info up to date, rounded to
6757 full megabytes */
6758 page_no_t pages_per_mb =
6759 static_cast<page_no_t>((1024 * 1024) / phy_page_size);
6760
6761 page_no_t size_in_pages = ((file->size / pages_per_mb) * pages_per_mb);
6762
6763 if (space->id == TRX_SYS_SPACE) {
6764 srv_sys_space.set_last_file_size(size_in_pages);
6765 } else if (fsp_is_system_temporary(space->id)) {
6766 srv_tmp_space.set_last_file_size(size_in_pages);
6767 }
6768 #else /* !UNIV_HOTBACKUP */
6769 ib::trace_2() << "Extended space : " << space->name << " from " << prev_size
6770 << " pages to " << space->size << " pages "
6771 << ", desired space size : " << size << " pages";
6772 #endif /* !UNIV_HOTBACKUP */
6773
6774 space_flush(space->id);
6775
6776 mutex_release();
6777
6778 DBUG_EXECUTE_IF("fil_crash_after_extend", DBUG_SUICIDE(););
6779 return success;
6780 }
6781
6782 /** Try to extend a tablespace if it is smaller than the specified size.
6783 @param[in,out] space Tablespace ID
6784 @param[in] size desired size in pages
6785 @return whether the tablespace is at least as big as requested */
6786 bool fil_space_extend(fil_space_t *space, page_no_t size) {
6787 auto shard = fil_system->shard_by_id(space->id);
6788
6789 return shard->space_extend(space, size);
6790 }
6791
6792 #ifdef UNIV_HOTBACKUP
6793 /** Extends all tablespaces to the size stored in the space header. During the
6794 mysqlbackup --apply-log phase we extended the spaces on-demand so that log
6795 records could be applied, but that may have left spaces still too small
6796 compared to the size stored in the space header. */
6797 void Fil_shard::meb_extend_tablespaces_to_stored_len() {
6798 ut_ad(mutex_owned());
6799
6800 byte *buf = static_cast<byte *>(
6801 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, UNIV_PAGE_SIZE));
6802
6803 ut_a(buf != nullptr);
6804
6805 for (auto &elem : m_spaces) {
6806 auto space = elem.second;
6807
6808 ut_a(space->purpose == FIL_TYPE_TABLESPACE);
6809
6810 /* No need to protect with a mutex, because this is
6811 a single-threaded operation */
6812
6813 mutex_release();
6814
6815 dberr_t error;
6816
6817 const page_size_t page_size(space->flags);
6818
6819 error = fil_read(page_id_t(space->id, 0), page_size, 0,
6820 page_size.physical(), buf);
6821
6822 ut_a(error == DB_SUCCESS);
6823
6824 ulint size_in_header;
6825
6826 size_in_header = fsp_header_get_field(buf, FSP_SIZE);
6827
6828 bool success;
6829
6830 success = space_extend(space, size_in_header);
6831
6832 if (!success) {
6833 ib::error(ER_IB_MSG_321)
6834 << "Could not extend the tablespace of " << space->name
6835 << " to the size stored in"
6836 " header, "
6837 << size_in_header
6838 << " pages;"
6839 " size after extension "
6840 << 0
6841 << " pages. Check that you have free disk"
6842 " space and retry!";
6843
6844 ut_a(success);
6845 }
6846
6847 mutex_acquire();
6848 }
6849
6850 ut::free(buf);
6851 }
6852
6853 /** Extends all tablespaces to the size stored in the space header. During the
6854 mysqlbackup --apply-log phase we extended the spaces on-demand so that log
6855 records could be applied, but that may have left spaces still too small
6856 compared to the size stored in the space header. */
6857 void meb_extend_tablespaces_to_stored_len() {
6858 fil_system->meb_extend_tablespaces_to_stored_len();
6859 }
6860
6861 bool meb_is_redo_log_only_restore = false;
6862
6863 /** Determine if file is intermediate / temporary. These files are
6864 created during reorganize partition, rename tables, add / drop columns etc.
6865 @param[in] filepath absolute / relative or simply file name
6866 @retvalue true if it is intermediate file
6867 @retvalue false if it is normal file */
6868 bool meb_is_intermediate_file(const std::string &filepath) {
6869 std::string file_name = filepath;
6870
6871 {
6872 /** If its redo only restore, apply log needs to got through the
6873 intermediate steps to apply a ddl.
6874 Some of these operation might result in intermediate files.
6875 */
6876 if (meb_is_redo_log_only_restore) return false;
6877 /* extract file name from relative or absolute file name */
6878 auto pos = file_name.rfind(OS_PATH_SEPARATOR);
6879
6880 if (pos != std::string::npos) {
6881 ++pos;
6882 file_name = file_name.substr(pos);
6883 }
6884 }
6885
6886 transform(file_name.begin(), file_name.end(), file_name.begin(), ::tolower);
6887
6888 if (file_name[0] != '#') {
6889 auto pos = file_name.rfind("#tmp#.ibd");
6890 if (pos != std::string::npos) {
6891 return true;
6892 } else {
6893 return false; /* normal file name */
6894 }
6895 }
6896
6897 static std::vector<std::string> prefixes = {"#sql-", "#sql2-", "#tmp#",
6898 "#ren#"};
6899
6900 /* search for the unsupported patterns */
6901 for (const auto &prefix : prefixes) {
6902 if (Fil_path::has_prefix(file_name, prefix)) {
6903 return true;
6904 }
6905 }
6906
6907 return false;
6908 }
6909
6910 /** Return the space ID based of the remote general tablespace name.
6911 This is a wrapper over fil_space_get_id_by_name() method. it means,
6912 the tablespace must be found in the tablespace memory cache.
6913 This method extracts the tablespace name from input parameters and checks if
6914 it has been loaded in memory cache through either any of the remote general
6915 tablespaces directories identified at the time memory cache created.
6916 @param[in, out] tablespace Tablespace name
6917 @return space ID if tablespace found, SPACE_UNKNOWN if not found. */
6918 space_id_t meb_fil_space_get_rem_gen_ts_id_by_name(std::string &tablespace) {
6919 space_id_t space_id = SPACE_UNKNOWN;
6920
6921 for (auto newpath : rem_gen_ts_dirs) {
6922 auto pos = tablespace.rfind(OS_PATH_SEPARATOR);
6923
6924 if (pos == std::string::npos) {
6925 break;
6926 }
6927
6928 newpath += tablespace.substr(pos);
6929
6930 space_id = fil_space_get_id_by_name(newpath.c_str());
6931
6932 if (space_id != SPACE_UNKNOWN) {
6933 tablespace = newpath;
6934 break;
6935 }
6936 }
6937
6938 return space_id;
6939 }
6940
6941 /** Tablespace item during recovery */
6942 struct MEB_file_name {
6943 /** Constructor */
6944 MEB_file_name(std::string name, bool deleted)
6945 : m_name(name), m_space(), m_deleted(deleted) {}
6946
6947 /** Tablespace file name (MLOG_FILE_NAME) */
6948 std::string m_name;
6949
6950 /** Tablespace object (NULL if not valid or not found) */
6951 fil_space_t *m_space;
6952
6953 /** Whether the tablespace has been deleted */
6954 bool m_deleted;
6955 };
6956
6957 /** Map of dirty tablespaces during recovery */
6958 using MEB_recv_spaces =
6959 std::map<space_id_t, MEB_file_name, std::less<space_id_t>,
6960 ut::allocator<std::pair<const space_id_t, MEB_file_name>>>;
6961
6962 static MEB_recv_spaces recv_spaces;
6963
6964 /** Checks if MEB has loaded this space for reovery.
6965 @param[in] space_id Tablespace ID
6966 @return true if the space_id is loaded */
6967 bool meb_is_space_loaded(const space_id_t space_id) {
6968 return (recv_spaces.find(space_id) != recv_spaces.end());
6969 }
6970
6971 /** Set the keys for an encrypted tablespace.
6972 @param[in] space Tablespace for which to set the key */
6973 static void meb_set_encryption_key(const fil_space_t *space) {
6974 ut_ad(FSP_FLAGS_GET_ENCRYPTION(space->flags));
6975
6976 for (auto &key : *recv_sys->keys) {
6977 if (key.space_id != space->id) {
6978 continue;
6979 }
6980
6981 dberr_t err;
6982
6983 err = fil_set_encryption(space->id, Encryption::AES, key.ptr, key.iv);
6984
6985 if (err != DB_SUCCESS) {
6986 ib::error(ER_IB_MSG_322) << "Can't set encryption information"
6987 << " for tablespace" << space->name << "!";
6988 }
6989
6990 ut::free(key.iv);
6991 ut::free(key.ptr);
6992
6993 key.iv = nullptr;
6994 key.ptr = nullptr;
6995 key.space_id = 0;
6996 }
6997 }
6998
6999 /** Process a file name passed as an input
7000 Wrapper around meb_name_process()
7001 @param[in,out] name absolute path of tablespace file
7002 @param[in] space_id The tablespace ID
7003 @param[in] deleted true if MLOG_FILE_DELETE */
7004 void Fil_system::meb_name_process(char *name, space_id_t space_id,
7005 bool deleted) {
7006 ut_ad(space_id != TRX_SYS_SPACE);
7007
7008 /* We will also insert space=nullptr into the map, so that
7009 further checks can ensure that a MLOG_FILE_NAME record was
7010 scanned before applying any page records for the space_id. */
7011
7012 Fil_path::normalize(name);
7013
7014 size_t len = std::strlen(name);
7015
7016 MEB_file_name fname(std::string(name, len - 1), deleted);
7017
7018 auto p = recv_spaces.insert(std::make_pair(space_id, fname));
7019
7020 ut_ad(p.first->first == space_id);
7021
7022 MEB_file_name &f = p.first->second;
7023
7024 if (deleted) {
7025 /* Got MLOG_FILE_DELETE */
7026
7027 if (!p.second && !f.m_deleted) {
7028 f.m_deleted = true;
7029
7030 if (f.m_space != nullptr) {
7031 f.m_space = nullptr;
7032 }
7033 }
7034
7035 ut_ad(f.m_space == nullptr);
7036
7037 } else if (p.second || f.m_name != fname.m_name) {
7038 fil_space_t *space;
7039
7040 /* Check if the tablespace file exists and contains
7041 the space_id. If not, ignore the file after displaying
7042 a note. Abort if there are multiple files with the
7043 same space_id. */
7044
7045 switch (ibd_open_for_recovery(space_id, name, space)) {
7046 case FIL_LOAD_OK:
7047 ut_ad(space != nullptr);
7048
7049 /* For encrypted tablespace, set key and iv. */
7050 if (FSP_FLAGS_GET_ENCRYPTION(space->flags) &&
7051 recv_sys->keys != nullptr) {
7052 meb_set_encryption_key(space);
7053 }
7054
7055 if (f.m_space == nullptr || f.m_space == space) {
7056 f.m_name = fname.m_name;
7057 f.m_space = space;
7058 f.m_deleted = false;
7059
7060 } else {
7061 ib::error(ER_IB_MSG_323)
7062 << "Tablespace " << space_id << " has been found in two places: '"
7063 << f.m_name << "' and '" << name
7064 << "'."
7065 " You must delete one of them.";
7066
7067 recv_sys->found_corrupt_fs = true;
7068 }
7069 break;
7070
7071 case FIL_LOAD_ID_CHANGED:
7072 ut_ad(space == nullptr);
7073
7074 ib::trace_1() << "Ignoring file " << name << " for space-id mismatch "
7075 << space_id;
7076 break;
7077
7078 case FIL_LOAD_NOT_FOUND:
7079 /* No matching tablespace was found; maybe it
7080 was renamed, and we will find a subsequent
7081 MLOG_FILE_* record. */
7082 ut_ad(space == nullptr);
7083 break;
7084
7085 case FIL_LOAD_INVALID:
7086 ut_ad(space == nullptr);
7087
7088 ib::warn(ER_IB_MSG_324) << "Invalid tablespace " << name;
7089 break;
7090
7091 case FIL_LOAD_MISMATCH:
7092 ut_ad(space == nullptr);
7093 break;
7094 case FIL_LOAD_DBWLR_CORRUPTION:
7095 ut_ad(space == nullptr);
7096 break;
7097 }
7098 }
7099 }
7100
7101 /** Process a file name passed as an input
7102 Wrapper around meb_name_process()
7103 @param[in] name absolute path of tablespace file
7104 @param[in] space_id the tablespace ID */
7105 void meb_fil_name_process(const char *name, space_id_t space_id) {
7106 char *file_name = static_cast<char *>(mem_strdup(name));
7107
7108 fil_system->meb_name_process(file_name, space_id, false);
7109
7110 ut::free(file_name);
7111 }
7112
7113 /** Test, if a file path name contains a back-link ("../").
7114 We assume a path to a file. So we don't check for a trailing "/..".
7115 @param[in] path path to check
7116 @return whether the path contains a back-link.
7117 */
7118 static bool meb_has_back_link(const std::string &path) {
7119 #ifdef _WIN32
7120 static const std::string DOT_DOT_SLASH = "..\\";
7121 static const std::string SLASH_DOT_DOT_SLASH = "\\..\\";
7122 #else
7123 static const std::string DOT_DOT_SLASH = "../";
7124 static const std::string SLASH_DOT_DOT_SLASH = "/../";
7125 #endif /* _WIN32 */
7126 return ((0 == path.compare(0, 3, DOT_DOT_SLASH)) ||
7127 (std::string::npos != path.find(SLASH_DOT_DOT_SLASH)));
7128 }
7129
7130 /** Parse a file name retrieved from a MLOG_FILE_* record,
7131 and return the absolute file path corresponds to backup dir
7132 as well as in the form of database/tablespace
7133 @param[in] name path emitted by the redo log
7134 @param[in] flags flags emitted by the redo log
7135 @param[in] space_id space_id emitted by the redo log
7136 @param[out] absolute_path absolute path of tablespace
7137 corresponds to target dir
7138 @param[out] tablespace_name name in the form of database/table */
7139 static void meb_make_abs_file_path(const std::string &name, uint32_t flags,
7140 space_id_t space_id,
7141 std::string &absolute_path,
7142 std::string &tablespace_name) {
7143 Datafile df;
7144 std::string file_name = name;
7145
7146 /* If the tablespace path name is absolute or has back-links ("../"),
7147 we assume, that it is located outside of datadir. */
7148 if (Fil_path::is_absolute_path(file_name.c_str()) ||
7149 (meb_has_back_link(file_name) && !replay_in_datadir)) {
7150 if (replay_in_datadir) {
7151 /* This is an apply-log in the restored datadir. Take the path as is. */
7152 df.set_filepath(file_name.c_str());
7153 } else {
7154 /* This is an apply-log in backup_dir/datadir. Get the file inside. */
7155 auto pos = file_name.rfind(OS_PATH_SEPARATOR);
7156
7157 /* if it is file per tablespace, then include the schema
7158 directory as well */
7159 if (fsp_is_file_per_table(space_id, flags) && pos != std::string::npos) {
7160 pos = file_name.rfind(OS_PATH_SEPARATOR, pos - 1);
7161 }
7162
7163 if (pos == std::string::npos) {
7164 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_325)
7165 << "Could not extract the tablespace"
7166 << " file name from the in the path : " << name;
7167 }
7168
7169 ++pos;
7170
7171 file_name = file_name.substr(pos);
7172
7173 df.make_filepath(MySQL_datadir_path, file_name.c_str(), IBD);
7174 }
7175
7176 } else {
7177 /* This is an apply-log with a relative path, either in the restored
7178 datadir, or in backup_dir/datadir. If in the restored datadir, the
7179 path might start with "../" to reach outside of datadir. */
7180 auto pos = file_name.find(OS_PATH_SEPARATOR);
7181
7182 /* Remove the cur dir from the path as this will cause the
7183 path name mismatch when we try to find out the space_id based
7184 on tablespace name */
7185
7186 if (file_name.substr(0, pos) == ".") {
7187 ++pos;
7188 file_name = file_name.substr(pos);
7189 }
7190
7191 /* make_filepath() does not prepend the directory, if the file name
7192 starts with "../". Prepend it unconditionally here. */
7193 file_name.insert(0, 1, OS_PATH_SEPARATOR);
7194 file_name.insert(0, MySQL_datadir_path);
7195
7196 df.make_filepath(nullptr, file_name.c_str(), IBD);
7197 }
7198
7199 df.set_flags(flags);
7200 df.set_space_id(space_id);
7201 df.set_name(nullptr);
7202
7203 absolute_path = df.filepath();
7204
7205 tablespace_name = df.name();
7206 }
7207
7208 /** Process a MLOG_FILE_CREATE redo record.
7209 @param[in] page_id Page id of the redo log record
7210 @param[in] flags Tablespace flags
7211 @param[in] name Tablespace filename */
7212 static void meb_tablespace_redo_create(const page_id_t &page_id, uint32_t flags,
7213 const char *name) {
7214 std::string abs_file_path;
7215 std::string tablespace_name;
7216
7217 meb_make_abs_file_path(name, flags, page_id.space(), abs_file_path,
7218 tablespace_name);
7219
7220 if (meb_is_intermediate_file(abs_file_path.c_str()) ||
7221 fil_space_get(page_id.space()) ||
7222 fil_space_get_id_by_name(tablespace_name.c_str()) != SPACE_UNKNOWN ||
7223 meb_fil_space_get_rem_gen_ts_id_by_name(tablespace_name) !=
7224 SPACE_UNKNOWN) {
7225 /* Don't create table while :-
7226 1. scanning the redo logs during backup
7227 2. apply-log on a partial backup
7228 3. if it is intermediate file
7229 4. tablespace is already loaded in memory
7230 5. tablespace is a remote general tablespace which is
7231 already loaded for recovery/apply-log from different
7232 directory path */
7233
7234 ib::trace_1() << "Ignoring the log record. No need to "
7235 << "create the tablespace : " << abs_file_path;
7236 } else {
7237 auto it = recv_spaces.find(page_id.space());
7238
7239 if (it == recv_spaces.end() || it->second.m_name != abs_file_path) {
7240 ib::trace_1() << "Creating the tablespace : " << abs_file_path
7241 << ", space_id : " << page_id.space();
7242
7243 dberr_t ret = fil_ibd_create(page_id.space(), tablespace_name.c_str(),
7244 abs_file_path.c_str(), flags,
7245 FIL_IBD_FILE_INITIAL_SIZE);
7246
7247 if (ret != DB_SUCCESS) {
7248 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_326)
7249 << "Could not create the tablespace : " << abs_file_path
7250 << " with space Id : " << page_id.space();
7251 }
7252 }
7253 }
7254 }
7255
7256 /** Process a MLOG_FILE_RENAME redo record.
7257 @param[in] page_id Page id of the redo log record
7258 @param[in] from_name Tablespace from filename
7259 @param[in] to_name Tablespace to filename */
7260 static void meb_tablespace_redo_rename(const page_id_t &page_id,
7261 const char *from_name,
7262 const char *to_name) {
7263 std::string abs_to_path;
7264 std::string abs_from_path;
7265 std::string tablespace_name;
7266
7267 meb_make_abs_file_path(from_name, 0, page_id.space(), abs_from_path,
7268 tablespace_name);
7269
7270 meb_make_abs_file_path(to_name, 0, page_id.space(), abs_to_path,
7271 tablespace_name);
7272
7273 char *new_name = nullptr;
7274
7275 if (meb_is_intermediate_file(from_name) ||
7276 meb_is_intermediate_file(to_name) ||
7277 fil_space_get_id_by_name(tablespace_name.c_str()) != SPACE_UNKNOWN ||
7278 meb_fil_space_get_rem_gen_ts_id_by_name(tablespace_name) !=
7279 SPACE_UNKNOWN ||
7280 fil_space_get(page_id.space()) == nullptr) {
7281 /* Don't rename table while :
7282 1. Scanning the redo logs during backup
7283 2. Apply-log on a partial backup
7284 3. Either of old or new tables are intermediate table
7285 4. The new name is already loaded for recovery/apply-log
7286 5. The new name is a remote general tablespace which is
7287 already loaded for recovery/apply-log from different
7288 directory path
7289 6. Tablespace is not yet loaded in memory.
7290 This will prevent unintended renames during recovery. */
7291
7292 ib::trace_1() << "Ignoring the log record. "
7293 << "No need to rename tablespace";
7294
7295 return;
7296
7297 } else {
7298 ib::trace_1() << "Renaming space id : " << page_id.space()
7299 << ", old tablespace name : " << from_name
7300 << " to new tablespace name : " << to_name;
7301
7302 new_name = static_cast<char *>(mem_strdup(abs_to_path.c_str()));
7303 }
7304
7305 meb_fil_name_process(from_name, page_id.space());
7306 meb_fil_name_process(new_name, page_id.space());
7307
7308 if (!fil_op_replay_rename(page_id, abs_from_path.c_str(),
7309 abs_to_path.c_str())) {
7310 recv_sys->found_corrupt_fs = true;
7311 }
7312
7313 meb_fil_name_process(to_name, page_id.space());
7314
7315 ut::free(new_name);
7316 }
7317
7318 /** Process a MLOG_FILE_DELETE redo record.
7319 @param[in] page_id Page id of the redo log record
7320 @param[in] name Tablespace filename */
7321 static void meb_tablespace_redo_delete(const page_id_t &page_id,
7322 const char *name) {
7323 std::string abs_file_path;
7324 std::string tablespace_name;
7325
7326 meb_make_abs_file_path(name, 0, page_id.space(), abs_file_path,
7327 tablespace_name);
7328
7329 char *file_name = static_cast<char *>(mem_strdup(name));
7330
7331 fil_system->meb_name_process(file_name, page_id.space(), true);
7332
7333 if (fil_space_get(page_id.space())) {
7334 ib::trace_1() << "Deleting the tablespace : " << abs_file_path
7335 << ", space_id : " << page_id.space();
7336 dberr_t err =
7337 fil_delete_tablespace(page_id.space(), BUF_REMOVE_FLUSH_NO_WRITE);
7338
7339 ut_a(err == DB_SUCCESS);
7340 }
7341
7342 ut::free(file_name);
7343 }
7344
7345 #endif /* UNIV_HOTBACKUP */
7346
7347 /*========== RESERVE FREE EXTENTS (for a B-tree split, for example) ===*/
7348
7349 /** Tries to reserve free extents in a file space.
7350 @param[in] space_id Tablespace ID
7351 @param[in] n_free_now Number of free extents now
7352 @param[in] n_to_reserve How many one wants to reserve
7353 @return true if succeed */
7354 bool fil_space_reserve_free_extents(space_id_t space_id, ulint n_free_now,
7355 ulint n_to_reserve) {
7356 auto shard = fil_system->shard_by_id(space_id);
7357
7358 shard->mutex_acquire();
7359
7360 fil_space_t *space = shard->get_space_by_id(space_id);
7361
7362 bool success;
7363
7364 if (space->n_reserved_extents + n_to_reserve > n_free_now) {
7365 success = false;
7366 } else {
7367 ut_a(n_to_reserve < std::numeric_limits<uint32_t>::max());
7368 space->n_reserved_extents += (uint32_t)n_to_reserve;
7369 success = true;
7370 }
7371
7372 shard->mutex_release();
7373
7374 return success;
7375 }
7376
7377 /** Releases free extents in a file space.
7378 @param[in] space_id Tablespace ID
7379 @param[in] n_reserved How many were reserved */
7380 void fil_space_release_free_extents(space_id_t space_id, ulint n_reserved) {
7381 auto shard = fil_system->shard_by_id(space_id);
7382
7383 shard->mutex_acquire();
7384
7385 fil_space_t *space = shard->get_space_by_id(space_id);
7386
7387 ut_a(n_reserved < std::numeric_limits<uint32_t>::max());
7388 ut_a(space->n_reserved_extents >= n_reserved);
7389
7390 space->n_reserved_extents -= (uint32_t)n_reserved;
7391
7392 shard->mutex_release();
7393 }
7394
7395 /** Gets the number of reserved extents. If the database is silent, this number
7396 should be zero.
7397 @param[in] space_id Tablespace ID
7398 @return the number of reserved extents */
7399 ulint fil_space_get_n_reserved_extents(space_id_t space_id) {
7400 auto shard = fil_system->shard_by_id(space_id);
7401
7402 shard->mutex_acquire();
7403
7404 fil_space_t *space = shard->get_space_by_id(space_id);
7405
7406 ulint n = space->n_reserved_extents;
7407
7408 shard->mutex_release();
7409
7410 return n;
7411 }
7412
7413 /*============================ FILE I/O ================================*/
7414
7415 bool Fil_shard::prepare_file_for_io(fil_node_t *file) {
7416 ut_ad(mutex_owned());
7417
7418 fil_space_t *space = file->space;
7419
7420 if (space->is_deleted()) {
7421 return false;
7422 }
7423
7424 if (!file->is_open) {
7425 ut_a(file->n_pending_ios == 0);
7426
7427 if (!open_file(file)) {
7428 return false;
7429 }
7430 }
7431 if (file->n_pending_ios == 0) {
7432 remove_from_LRU(file);
7433 }
7434
7435 ++file->n_pending_ios;
7436
7437 /* The file can't be in the LRU list. */
7438 ut_ad(!ut_list_exists(m_LRU, file));
7439
7440 return true;
7441 }
7442
7443 /** If the tablespace is not on the unflushed list, add it.
7444 @param[in,out] space Tablespace to add */
7445 void Fil_shard::add_to_unflushed_list(fil_space_t *space) {
7446 ut_ad(mutex_owned());
7447 ut_a(space->purpose != FIL_TYPE_TEMPORARY);
7448
7449 if (!space->is_in_unflushed_spaces) {
7450 space->is_in_unflushed_spaces = true;
7451
7452 UT_LIST_ADD_FIRST(m_unflushed_spaces, space);
7453 }
7454 }
7455
7456 /** Note that a write IO has completed.
7457 @param[in,out] file File on which a write was completed */
7458 void Fil_shard::write_completed(fil_node_t *file) {
7459 ut_ad(mutex_owned());
7460
7461 ++m_modification_counter;
7462
7463 file->modification_counter = m_modification_counter;
7464
7465 if (fil_disable_space_flushing(file->space)) {
7466 /* We don't need to keep track of not flushed changes as either:
7467 - user has explicitly disabled buffering,
7468 - or it is FIL_TYPE_TEMPORARY space and we don't ever flush these. */
7469 ut_ad(!file->space->is_in_unflushed_spaces);
7470
7471 file->set_flushed();
7472
7473 } else {
7474 add_to_unflushed_list(file->space);
7475 }
7476 }
7477
7478 /** Updates the data structures when an I/O operation finishes. Updates the
7479 pending I/O's field in the file appropriately.
7480 @param[in] file Tablespace file
7481 @param[in] type Marks the file as modified type == WRITE */
7482 void Fil_shard::complete_io(fil_node_t *file, const IORequest &type) {
7483 ut_ad(mutex_owned());
7484
7485 ut_a(file->n_pending_ios > 0);
7486
7487 --file->n_pending_ios;
7488
7489 ut_ad(type.validate());
7490
7491 if (type.is_write()) {
7492 ut_ad(!srv_read_only_mode || fsp_is_system_temporary(file->space->id));
7493
7494 write_completed(file);
7495 }
7496
7497 if (file->n_pending_ios == 0) {
7498 /* The file must be put back to the LRU list */
7499 add_to_lru_if_needed(file);
7500 }
7501 }
7502
7503 /** Report information about an invalid page access.
7504 @param[in] block_offset Block offset
7505 @param[in] space_id Tablespace ID
7506 @param[in] space_name Tablespace name
7507 @param[in] byte_offset Byte offset
7508 @param[in] len I/O length
7509 @param[in] is_read I/O type
7510 @param[in] line Line called from */
7511 static void fil_report_invalid_page_access_low(page_no_t block_offset,
7512 space_id_t space_id,
7513 const char *space_name,
7514 ulint byte_offset, ulint len,
7515 bool is_read, int line) {
7516 ib::error(ER_IB_MSG_328)
7517 << "Trying to access page number " << block_offset
7518 << " in"
7519 " space "
7520 << space_id << ", space name " << space_name
7521 << ","
7522 " which is outside the tablespace bounds. Byte offset "
7523 << byte_offset << ", len " << len << ", i/o type "
7524 << (is_read ? "read" : "write")
7525 << ". If you get this error at mysqld startup, please check"
7526 " that your my.cnf matches the ibdata files that you have in"
7527 " the MySQL server.";
7528
7529 ib::error(ER_IB_MSG_329) << "Server exits"
7530 #ifdef UNIV_DEBUG
7531 << " at "
7532 << "fil0fil.cc"
7533 << "[" << line << "]"
7534 #endif /* UNIV_DEBUG */
7535 << ".";
7536
7537 ut_error;
7538 }
7539
7540 #define fil_report_invalid_page_access(b, s, n, o, l, t) \
7541 fil_report_invalid_page_access_low((b), (s), (n), (o), (l), (t), __LINE__)
7542
7543 /** Set encryption information for IORequest.
7544 @param[in,out] req_type IO request
7545 @param[in] page_id page id
7546 @param[in] space table space */
7547 void fil_io_set_encryption(IORequest &req_type, const page_id_t &page_id,
7548 fil_space_t *space) {
7549 ut_a(!req_type.is_log());
7550 /* Don't encrypt page 0 of all tablespaces except redo log
7551 tablespace, all pages from the system tablespace. */
7552 if ((space->encryption_op_in_progress == Encryption::Progress::DECRYPTION &&
7553 req_type.is_write()) ||
7554 !space->can_encrypt() || page_id.page_no() == 0) {
7555 req_type.clear_encrypted();
7556 return;
7557 }
7558
7559 /* For writing undo log, if encryption for undo log is disabled,
7560 skip set encryption. */
7561 if (fsp_is_undo_tablespace(space->id) && !srv_undo_log_encrypt &&
7562 req_type.is_write()) {
7563 req_type.clear_encrypted();
7564 return;
7565 }
7566
7567 if (req_type.get_encrypted_block() != nullptr) {
7568 /* Already encrypted. */
7569 req_type.clear_encrypted();
7570 return;
7571 }
7572 req_type.get_encryption_info().set(space->m_encryption_metadata);
7573 ut_ad(space->m_encryption_metadata.m_type == Encryption::AES);
7574 }
7575
7576 AIO_mode Fil_shard::get_AIO_mode(const IORequest &, bool sync) {
7577 #ifndef UNIV_HOTBACKUP
7578 if (sync) {
7579 return AIO_mode::SYNC;
7580
7581 } else {
7582 return AIO_mode::NORMAL;
7583 }
7584 #else /* !UNIV_HOTBACKUP */
7585 ut_a(sync);
7586 return AIO_mode::SYNC;
7587 #endif /* !UNIV_HOTBACKUP */
7588 }
7589
7590 dberr_t Fil_shard::get_file_for_io(fil_space_t *space, page_no_t *page_no,
7591 fil_node_t *&file) {
7592 file = space->get_file_node(page_no);
7593 return (file == nullptr) ? DB_ERROR : DB_SUCCESS;
7594 }
7595
7596 dberr_t Fil_shard::do_io(const IORequest &type, bool sync,
7597 const page_id_t &page_id, const page_size_t &page_size,
7598 ulint byte_offset, ulint len, void *buf,
7599 void *message) {
7600 IORequest req_type(type);
7601
7602 ut_ad(req_type.validate());
7603 ut_a(!req_type.is_log());
7604
7605 ut_ad(len > 0);
7606 ut_ad(byte_offset < UNIV_PAGE_SIZE);
7607 ut_ad(!page_size.is_compressed() || byte_offset == 0);
7608 ut_ad(UNIV_PAGE_SIZE == (ulong)(1 << UNIV_PAGE_SIZE_SHIFT));
7609
7610 ut_ad(fil_validate_skip());
7611
7612 #ifndef UNIV_HOTBACKUP
7613 /* ibuf bitmap pages must be read in the sync AIO mode: */
7614 ut_ad(recv_no_ibuf_operations || req_type.is_write() ||
7615 !ibuf_bitmap_page(page_id, page_size) || sync);
7616
7617 auto aio_mode = get_AIO_mode(req_type, sync);
7618
7619 if (req_type.is_read()) {
7620 ut_ad(type.get_original_size() == 0);
7621 srv_stats.data_read.add(len);
7622
7623 if (aio_mode == AIO_mode::NORMAL && !recv_no_ibuf_operations &&
7624 ibuf_page(page_id, page_size, UT_LOCATION_HERE, nullptr)) {
7625 /* Reduce probability of deadlock bugs
7626 in connection with ibuf: do not let the
7627 ibuf I/O handler sleep */
7628
7629 req_type.clear_do_not_wake();
7630
7631 aio_mode = AIO_mode::IBUF;
7632 }
7633
7634 #ifdef UNIV_DEBUG
7635 mutex_acquire();
7636 /* Should never attempt to read from a deleted tablespace, unless we
7637 are also importing the tablespace. By the time we get here in the final
7638 phase of import the state has changed. Therefore we check if there is
7639 an active fil_space_t instance with the same ID. */
7640 for (auto pair : m_deleted_spaces) {
7641 if (pair.first == page_id.space()) {
7642 auto space = get_space_by_id(page_id.space());
7643 if (space != nullptr) {
7644 ut_a(pair.second != space);
7645 }
7646 }
7647 }
7648 mutex_release();
7649 #endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
7650
7651 } else if (req_type.is_write()) {
7652 ut_ad(!srv_read_only_mode || fsp_is_system_temporary(page_id.space()));
7653
7654 srv_stats.data_written.add(len);
7655 }
7656 #else /* !UNIV_HOTBACKUP */
7657 ut_a(sync);
7658 auto aio_mode = AIO_mode::SYNC;
7659 #endif /* !UNIV_HOTBACKUP */
7660
7661 /* Reserve the mutex and make sure that we can open at
7662 least one file while holding it, if the file is not already open */
7663
7664 auto bpage = static_cast<buf_page_t *>(message);
7665
7666 mutex_acquire();
7667 auto space = get_space_by_id(page_id.space());
7668
7669 /* If we are deleting a tablespace we don't allow async read
7670 operations on that. However, we do allow write operations and
7671 sync read operations. */
7672 if (space == nullptr ||
7673 (req_type.is_read() && !sync && space->stop_new_ops)) {
7674 #ifndef UNIV_HOTBACKUP
7675 const auto is_page_stale = bpage != nullptr && bpage->is_stale();
7676 #endif /* !UNIV_HOTBACKUP */
7677
7678 mutex_release();
7679
7680 if (space == nullptr) {
7681 #ifndef UNIV_HOTBACKUP
7682 if (req_type.is_write() && is_page_stale) {
7683 ut_a(bpage->get_space()->id == page_id.space());
7684 return DB_PAGE_IS_STALE;
7685 }
7686 #endif /* !UNIV_HOTBACKUP */
7687
7688 if (!req_type.ignore_missing()) {
7689 #ifndef UNIV_HOTBACKUP
7690 /* Don't have any record of this tablespace. print a warning. */
7691 if (!Fil_shard::is_deleted(page_id.space())) {
7692 #endif /* !UNIV_HOTBACKUP */
7693 if (space == nullptr) {
7694 ib::error(ER_IB_MSG_330)
7695 << "Trying to do I/O on a tablespace"
7696 << " which does not exist. I/O type: "
7697 << (req_type.is_read() ? "read" : "write")
7698 << ", page: " << page_id << ", I/O length: " << len << " bytes";
7699 } else {
7700 ib::error(ER_IB_MSG_331)
7701 << "Trying to do async read on a tablespace which is being"
7702 << " deleted. Tablespace name: \"" << space->name << "\","
7703 << " page: " << page_id << ", read length: " << len << " bytes";
7704 }
7705 #ifndef UNIV_HOTBACKUP
7706 }
7707 #endif /* !UNIV_HOTBACKUP */
7708 }
7709 }
7710
7711 return DB_TABLESPACE_DELETED;
7712 }
7713
7714 #ifndef UNIV_HOTBACKUP
7715 if (bpage != nullptr) {
7716 ut_a(bpage->get_space()->id == page_id.space());
7717
7718 if (req_type.is_write() && bpage->is_stale()) {
7719 mutex_release();
7720 return DB_PAGE_IS_STALE;
7721 }
7722 ut_a(bpage->get_space() == space);
7723 }
7724 #endif /* !UNIV_HOTBACKUP */
7725
7726 fil_node_t *file;
7727 auto page_no = page_id.page_no();
7728 auto err = get_file_for_io(space, &page_no, file);
7729
7730 if (file == nullptr) {
7731 ut_ad(err == DB_ERROR);
7732
7733 if (req_type.ignore_missing()) {
7734 mutex_release();
7735
7736 return DB_ERROR;
7737 }
7738
7739 #ifndef UNIV_HOTBACKUP
7740 if (req_type.is_write() && bpage != nullptr && bpage->is_stale()) {
7741 ut_a(bpage->get_space()->id == page_id.space());
7742
7743 mutex_release();
7744 return DB_PAGE_IS_STALE;
7745 }
7746 #endif /* !UNIV_HOTBACKUP */
7747
7748 /* This is a hard error. */
7749 fil_report_invalid_page_access(page_id.page_no(), page_id.space(),
7750 space->name, byte_offset, len,
7751 req_type.is_read());
7752 }
7753
7754 if (!prepare_file_for_io(file)) {
7755 #ifndef UNIV_HOTBACKUP
7756 if (space->is_deleted()) {
7757 mutex_release();
7758
7759 if (!sync) {
7760 ut_d(bpage->take_io_responsibility());
7761 buf_page_io_complete(bpage, false);
7762 }
7763
7764 return DB_TABLESPACE_DELETED;
7765 }
7766 #endif /* !UNIV_HOTBACKUP */
7767
7768 if (fsp_is_ibd_tablespace(space->id)) {
7769 mutex_release();
7770
7771 if (!req_type.ignore_missing()) {
7772 ib::error(ER_IB_MSG_332)
7773 << "Trying to do I/O to a tablespace"
7774 " which exists without an .ibd data"
7775 << " file. I/O type: " << (req_type.is_read() ? "read" : "write")
7776 << ", page: " << page_id_t(page_id.space(), page_no)
7777 << ", I/O length: " << len << " bytes";
7778 }
7779
7780 return DB_TABLESPACE_DELETED;
7781 }
7782
7783 /* Could not open a file to perform IO and this is not a IBD file,
7784 which could have become deleted meanwhile. This is a fatal error.
7785 Note: any log information should be emitted inside prepare_file_for_io()
7786 called few lines earlier. That's because the specific reason for this
7787 problem is known only inside there. */
7788 ut_error;
7789 }
7790
7791 /* Check that at least the start offset is within the bounds of a
7792 single-table tablespace, including rollback tablespaces. */
7793 if (file->size <= page_no && space->id != TRX_SYS_SPACE) {
7794 #ifndef UNIV_HOTBACKUP
7795 if (req_type.is_write() && bpage != nullptr && bpage->is_stale()) {
7796 ut_a(bpage->get_space()->id == page_id.space());
7797 return DB_PAGE_IS_STALE;
7798 }
7799 #endif /* !UNIV_HOTBACKUP */
7800
7801 if (req_type.ignore_missing()) {
7802 /* If we can tolerate the non-existent pages, we
7803 should return with DB_ERROR and let caller decide
7804 what to do. */
7805
7806 complete_io(file, req_type);
7807
7808 mutex_release();
7809
7810 return DB_ERROR;
7811 }
7812
7813 /* This is a hard error. */
7814 fil_report_invalid_page_access(page_id.page_no(), page_id.space(),
7815 space->name, byte_offset, len,
7816 req_type.is_read());
7817 }
7818
7819 mutex_release();
7820
7821 DEBUG_SYNC_C("innodb_fil_do_io_prepared_io_with_no_mutex");
7822
7823 ut_a(page_size.is_compressed() ||
7824 page_size.physical() == page_size.logical());
7825
7826 auto offset = (os_offset_t)page_no * page_size.physical();
7827
7828 offset += byte_offset;
7829
7830 ut_a(file->size - page_no >=
7831 (byte_offset +
7832 std::max(static_cast<uint32_t>(len), type.get_original_size()) +
7833 (page_size.physical() - 1)) /
7834 page_size.physical());
7835
7836 ut_a(len % OS_FILE_LOG_BLOCK_SIZE == 0);
7837 ut_a(byte_offset % OS_FILE_LOG_BLOCK_SIZE == 0);
7838
7839 /* Don't compress the log, page 0 of all tablespaces, tables compressed with
7840 the old compression scheme and all pages from the system tablespace. */
7841 if (req_type.is_write() && !page_size.is_compressed() &&
7842 page_id.page_no() > 0 && IORequest::is_punch_hole_supported() &&
7843 file->punch_hole) {
7844 req_type.set_punch_hole();
7845
7846 req_type.compression_algorithm(space->compression_type);
7847
7848 } else {
7849 req_type.clear_compressed();
7850 }
7851
7852 /* Set encryption information. */
7853 fil_io_set_encryption(req_type, page_id, space);
7854
7855 req_type.block_size(file->block_size);
7856
7857 #ifdef UNIV_HOTBACKUP
7858 /* In mysqlbackup do normal I/O, not AIO */
7859 if (req_type.is_read()) {
7860 err = os_file_read(req_type, file->name, file->handle, buf, offset, len);
7861
7862 } else {
7863 ut_ad(!srv_read_only_mode || fsp_is_system_temporary(page_id.space()));
7864
7865 err = os_file_write(req_type, file->name, file->handle, buf, offset, len);
7866 }
7867 #else /* UNIV_HOTBACKUP */
7868 /* Queue the aio request */
7869 err = os_aio(
7870 req_type, aio_mode, file->name, file->handle, buf, offset, len,
7871 fsp_is_system_temporary(page_id.space()) ? false : srv_read_only_mode,
7872 file, message);
7873
7874 #endif /* UNIV_HOTBACKUP */
7875
7876 if (err == DB_IO_NO_PUNCH_HOLE) {
7877 err = DB_SUCCESS;
7878
7879 if (file->punch_hole) {
7880 ib::warn(ER_IB_MSG_333) << "Punch hole failed for '" << file->name << "'";
7881 }
7882
7883 fil_no_punch_hole(file);
7884 }
7885
7886 /* We an try to recover the page from the double write buffer if
7887 the decompression fails or the page is corrupt. */
7888
7889 ut_a(req_type.is_dblwr() || err == DB_SUCCESS);
7890
7891 if (sync) {
7892 /* The i/o operation is already completed when we return from
7893 os_aio: */
7894
7895 mutex_acquire();
7896
7897 complete_io(file, req_type);
7898
7899 mutex_release();
7900
7901 ut_ad(fil_validate_skip());
7902 }
7903
7904 return err;
7905 }
7906
7907 #ifndef UNIV_HOTBACKUP
7908 /** Waits for an AIO operation to complete. This function is used to write the
7909 handler for completed requests. The aio array of pending requests is divided
7910 into segments (see os0file.cc for more info). The thread specifies which
7911 segment it wants to wait for.
7912 @param[in] segment The number of the segment in the AIO array
7913 to wait for */
7914 void fil_aio_wait(ulint segment) {
7915 void *m2;
7916 fil_node_t *m1;
7917 IORequest type;
7918
7919 ut_ad(fil_validate_skip());
7920
7921 auto err = os_aio_handler(segment, &m1, &m2, &type);
7922 ut_a(err == DB_SUCCESS);
7923
7924 auto file = reinterpret_cast<fil_node_t *>(m1);
7925
7926 if (file == nullptr) {
7927 ut_ad(srv_shutdown_state.load() == SRV_SHUTDOWN_EXIT_THREADS);
7928 return;
7929 }
7930
7931 ut_a(!type.is_dblwr());
7932
7933 srv_set_io_thread_op_info(segment, "complete io for file");
7934
7935 auto shard = fil_system->shard_by_id(file->space->id);
7936
7937 shard->mutex_acquire();
7938
7939 shard->complete_io(file, type);
7940
7941 shard->mutex_release();
7942
7943 ut_ad(fil_validate_skip());
7944
7945 /* Do the i/o handling */
7946 /* IMPORTANT: since i/o handling for reads will read also the insert
7947 buffer in tablespace 0, you have to be very careful not to introduce
7948 deadlocks in the i/o system. We keep tablespace 0 data files always
7949 open, and use a special i/o thread to serve insert buffer requests. */
7950
7951 switch (file->space->purpose) {
7952 case FIL_TYPE_IMPORT:
7953 case FIL_TYPE_TEMPORARY:
7954 case FIL_TYPE_TABLESPACE:
7955 srv_set_io_thread_op_info(segment, "complete io for buf page");
7956
7957 /* async single page writes from the dblwr buffer don't have
7958 access to the page */
7959 if (m2 != nullptr) {
7960 auto bpage = static_cast<buf_page_t *>(m2);
7961 ut_d(bpage->take_io_responsibility());
7962 buf_page_io_complete(bpage, false);
7963 }
7964 return;
7965 }
7966
7967 ut_d(ut_error);
7968 }
7969 #endif /* !UNIV_HOTBACKUP */
7970
7971 dberr_t fil_io(const IORequest &type, bool sync, const page_id_t &page_id,
7972 const page_size_t &page_size, ulint byte_offset, ulint len,
7973 void *buf, void *message) {
7974 auto shard = fil_system->shard_by_id(page_id.space());
7975 #ifdef UNIV_DEBUG
7976 if (!sync) {
7977 /* In case of async io we transfer the io responsibility to the thread which
7978 will perform the io completion routine. */
7979 static_cast<buf_page_t *>(message)->release_io_responsibility();
7980 }
7981 #endif
7982
7983 auto const err = shard->do_io(type, sync, page_id, page_size, byte_offset,
7984 len, buf, message);
7985 #ifdef UNIV_DEBUG
7986 /* If the error prevented async io, then we haven't actually transferred the
7987 io responsibility at all, so we revert the debug io responsibility info. */
7988 auto bpage = static_cast<buf_page_t *>(message);
7989
7990 /* When space is deleted, we could have marked the io complete. */
7991 if (err != DB_SUCCESS && !sync && bpage->was_io_fixed()) {
7992 bpage->take_io_responsibility();
7993 }
7994 #endif
7995 return err;
7996 }
7997
7998 /** If the tablespace is on the unflushed list and there are no pending
7999 flushes then remove from the unflushed list.
8000 @param[in,out] space Tablespace to remove */
8001 void Fil_shard::remove_from_unflushed_list(fil_space_t *space) {
8002 ut_ad(mutex_owned());
8003
8004 if (space->is_in_unflushed_spaces && space_is_flushed(space)) {
8005 space->is_in_unflushed_spaces = false;
8006
8007 UT_LIST_REMOVE(m_unflushed_spaces, space);
8008 }
8009 }
8010
8011 void Fil_shard::space_flush(space_id_t space_id) {
8012 ut_ad(mutex_owned());
8013
8014 fil_space_t *space = get_space_by_id(space_id);
8015
8016 if (space == nullptr || space->purpose == FIL_TYPE_TEMPORARY ||
8017 space->stop_new_ops) {
8018 return;
8019 }
8020
8021 const bool disable_flush = fil_disable_space_flushing(space);
8022
8023 if (disable_flush) {
8024 /* No need to flush. User has explicitly disabled
8025 buffering. However, flush should be called if the file
8026 size changes to keep OÐ… metadata in sync. */
8027 ut_ad(!space->is_in_unflushed_spaces);
8028 ut_ad(space_is_flushed(space));
8029
8030 /* Flush only if the file size changes */
8031 bool no_flush = true;
8032 for (const auto &file : space->files) {
8033 #ifdef UNIV_DEBUG
8034 ut_ad(file.is_flushed());
8035 #endif /* UNIV_DEBUG */
8036 if (file.flush_size != file.size) {
8037 /* Found at least one file whose size has changed */
8038 no_flush = false;
8039 break;
8040 }
8041 }
8042
8043 if (no_flush) {
8044 /* Nothing to flush. Just return */
8045 return;
8046 }
8047 }
8048
8049 /* Prevent dropping of the space while we are flushing */
8050 ++space->n_pending_flushes;
8051
8052 for (auto &file : space->files) {
8053 int64_t old_mod_counter = file.modification_counter;
8054
8055 if (!file.is_open) {
8056 continue;
8057 }
8058
8059 /* Skip flushing if the file size has not changed since
8060 last flush was done and the flush mode is O_DIRECT_NO_FSYNC */
8061 if (disable_flush && (file.flush_size == file.size)) {
8062 ut_ad(old_mod_counter <= file.flush_counter);
8063 continue;
8064 }
8065
8066 /* If we are here and the flush mode is O_DIRECT_NO_FSYNC, then
8067 it means that the file size has changed and hence, it should be
8068 flushed, irrespective of the mod_counter and flush counter values,
8069 which are always same in case of O_DIRECT_NO_FSYNC to avoid flush
8070 on every write operation.
8071 For other flush modes, if the flush_counter is same or ahead of
8072 the mod_counter, skip the flush. */
8073 if (!disable_flush && (old_mod_counter <= file.flush_counter)) {
8074 continue;
8075 }
8076
8077 switch (space->purpose) {
8078 case FIL_TYPE_TEMPORARY:
8079 ut_error; // we already checked for this
8080
8081 case FIL_TYPE_TABLESPACE:
8082 case FIL_TYPE_IMPORT:
8083 fil_n_pending_tablespace_flushes.fetch_add(1);
8084 break;
8085 }
8086
8087 bool skip_flush = is_fast_shutdown();
8088 #ifdef _WIN32
8089 if (file.is_raw_disk) {
8090 skip_flush |= true;
8091 }
8092 #endif /* _WIN32 */
8093
8094 while (file.n_pending_flushes > 0 && !skip_flush) {
8095 /* We want to avoid calling os_file_flush() on
8096 the file twice at the same time, because we do
8097 not know what bugs OS's may contain in file
8098 I/O */
8099
8100 int64_t sig_count = os_event_reset(file.sync_event);
8101
8102 mutex_release();
8103
8104 os_event_wait_low(file.sync_event, sig_count);
8105
8106 mutex_acquire();
8107
8108 if (file.flush_counter >= old_mod_counter) {
8109 skip_flush |= true;
8110 }
8111 skip_flush |= is_fast_shutdown();
8112 }
8113
8114 if (!skip_flush) {
8115 ut_a(file.is_open);
8116 ++file.n_pending_flushes;
8117
8118 mutex_release();
8119
8120 os_file_flush(file.handle);
8121
8122 file.flush_size = file.size;
8123
8124 mutex_acquire();
8125
8126 os_event_set(file.sync_event);
8127
8128 --file.n_pending_flushes;
8129 }
8130
8131 if (file.flush_counter < old_mod_counter) {
8132 file.flush_counter = old_mod_counter;
8133
8134 remove_from_unflushed_list(space);
8135 }
8136
8137 switch (space->purpose) {
8138 case FIL_TYPE_TEMPORARY:
8139 ut_error; // we already checked for this
8140
8141 case FIL_TYPE_TABLESPACE:
8142 case FIL_TYPE_IMPORT:
8143 fil_n_pending_tablespace_flushes.fetch_sub(1);
8144 continue;
8145 }
8146
8147 ut_d(ut_error);
8148 }
8149
8150 --space->n_pending_flushes;
8151 }
8152
8153 void fil_flush(space_id_t space_id) {
8154 auto shard = fil_system->shard_by_id(space_id);
8155
8156 shard->mutex_acquire();
8157
8158 /* Note: Will release and reacquire the Fil_shard::mutex. */
8159 shard->space_flush(space_id);
8160
8161 shard->mutex_release();
8162 }
8163
8164 void Fil_shard::flush_file_spaces() {
8165 Space_ids space_ids;
8166
8167 mutex_acquire();
8168
8169 for (auto space : m_unflushed_spaces) {
8170 if ((to_int(space->purpose) & FIL_TYPE_TABLESPACE) &&
8171 !space->stop_new_ops) {
8172 space_ids.push_back(space->id);
8173 }
8174 }
8175
8176 mutex_release();
8177
8178 /* Flush the spaces. It will not hurt to call fil_flush() on
8179 a non-existing space id. */
8180 for (auto space_id : space_ids) {
8181 mutex_acquire();
8182
8183 space_flush(space_id);
8184
8185 mutex_release();
8186 }
8187 }
8188
8189 void Fil_system::flush_file_spaces() {
8190 for (auto shard : m_shards) {
8191 shard->flush_file_spaces();
8192 }
8193 }
8194
8195 void fil_flush_file_spaces() { fil_system->flush_file_spaces(); }
8196
8197 /** Returns true if file address is undefined.
8198 @param[in] addr File address to check
8199 @return true if undefined */
8200 bool fil_addr_is_null(const fil_addr_t &addr) {
8201 return (addr.page == FIL_NULL);
8202 }
8203
8204 /** Get the predecessor of a file page.
8205 @param[in] page File page
8206 @return FIL_PAGE_PREV */
8207 page_no_t fil_page_get_prev(const byte *page) {
8208 return mach_read_from_4(page + FIL_PAGE_PREV);
8209 }
8210
8211 /** Get the successor of a file page.
8212 @param[in] page File page
8213 @return FIL_PAGE_NEXT */
8214 page_no_t fil_page_get_next(const byte *page) {
8215 return mach_read_from_4(page + FIL_PAGE_NEXT);
8216 }
8217
8218 /** Sets the file page type.
8219 @param[in,out] page File page
8220 @param[in] type File page type to set */
8221 void fil_page_set_type(byte *page, ulint type) {
8222 mach_write_to_2(page + FIL_PAGE_TYPE, type);
8223 }
8224
8225 /** Reset the page type.
8226 Data files created before MySQL 5.1 may contain garbage in FIL_PAGE_TYPE.
8227 In MySQL 3.23.53, only undo log pages and index pages were tagged.
8228 Any other pages were written with uninitialized bytes in FIL_PAGE_TYPE.
8229 @param[in] page_id Page number
8230 @param[in,out] page Page with invalid FIL_PAGE_TYPE
8231 @param[in] type Expected page type
8232 @param[in,out] mtr Mini-transaction */
8233 void fil_page_reset_type(const page_id_t &page_id, byte *page, ulint type,
8234 mtr_t *mtr) {
8235 ib::info(ER_IB_MSG_334) << "Resetting invalid page " << page_id << " type "
8236 << fil_page_get_type(page) << " to " << type << ".";
8237 mlog_write_ulint(page + FIL_PAGE_TYPE, type, MLOG_2BYTES, mtr);
8238 }
8239
8240 /** Closes the tablespace memory cache. */
8241 void fil_close() {
8242 if (fil_system == nullptr) {
8243 return;
8244 }
8245
8246 ut::delete_(fil_system);
8247
8248 fil_system = nullptr;
8249 }
8250
8251 #ifndef UNIV_HOTBACKUP
8252 /** Initializes the buffer control block used by fil_tablespace_iterate.
8253 @param[in] block Pointer to the control block
8254 @param[in] frame Pointer to buffer frame */
8255 static void fil_buf_block_init(buf_block_t *block, byte *frame) {
8256 UNIV_MEM_DESC(frame, UNIV_PAGE_SIZE);
8257
8258 block->frame = frame;
8259
8260 block->page.init_io_fix();
8261 /* There are assertions that check for this. */
8262 block->page.buf_fix_count.store(1);
8263 block->page.state = BUF_BLOCK_READY_FOR_USE;
8264
8265 page_zip_des_init(&block->page.zip);
8266 }
8267
8268 struct Fil_page_iterator {
8269 /** File handle */
8270 pfs_os_file_t m_file;
8271
8272 /** File path name */
8273 const char *m_filepath;
8274
8275 /** From where to start */
8276 os_offset_t m_start;
8277
8278 /** Where to stop */
8279 os_offset_t m_end;
8280
8281 /* File size in bytes */
8282 os_offset_t m_file_size;
8283
8284 /** Page size */
8285 size_t m_page_size;
8286
8287 /** Number of pages to use for I/O */
8288 size_t m_n_io_buffers;
8289
8290 /** Buffer to use for IO */
8291 byte *m_io_buffer;
8292
8293 /** Encryption metadata */
8294 const Encryption_metadata &m_encryption_metadata;
8295
8296 /** FS Block Size */
8297 size_t block_size;
8298
8299 /** Compression algorithm to be used if the table needs to be compressed. */
8300 Compression::Type m_compression_type{};
8301 };
8302
8303 /** TODO: This can be made parallel trivially by chunking up the file
8304 and creating a callback per thread. Main benefit will be to use multiple
8305 CPUs for checksums and compressed tables. We have to do compressed tables
8306 block by block right now. Secondly we need to decompress/compress and copy
8307 too much of data. These are CPU intensive.
8308
8309 Iterate over all the pages in the tablespace.
8310 @param[in] iter Tablespace iterator
8311 @param[in,out] block Block to use for IO
8312 @param[in] callback Callback to inspect and update page contents
8313 @retval DB_SUCCESS or error code */
8314 static dberr_t fil_iterate(const Fil_page_iterator &iter, buf_block_t *block,
8315 PageCallback &callback) {
8316 os_offset_t offset;
8317 size_t n_bytes;
8318 page_no_t page_no = 0;
8319 space_id_t space_id = callback.get_space_id();
8320
8321 n_bytes = iter.m_n_io_buffers * iter.m_page_size;
8322
8323 ut_ad(!srv_read_only_mode);
8324
8325 /* For old style compressed tables we do a lot of useless copying
8326 for non-index pages. Unfortunately, it is required by
8327 buf_zip_decompress() */
8328
8329 ulint read_type = IORequest::READ;
8330 ulint write_type = IORequest::WRITE;
8331
8332 for (offset = iter.m_start; offset < iter.m_end; offset += n_bytes) {
8333 byte *io_buffer = iter.m_io_buffer;
8334
8335 block->frame = io_buffer;
8336
8337 if (callback.get_page_size().is_compressed()) {
8338 page_zip_des_init(&block->page.zip);
8339 page_zip_set_size(&block->page.zip, iter.m_page_size);
8340
8341 block->page.size.copy_from(
8342 page_size_t(static_cast<uint32_t>(iter.m_page_size),
8343 static_cast<uint32_t>(univ_page_size.logical()), true));
8344
8345 block->page.zip.data = block->frame + UNIV_PAGE_SIZE;
8346 ut_d(block->page.zip.m_external = true);
8347 ut_ad(iter.m_page_size == callback.get_page_size().physical());
8348
8349 /* Zip IO is done in the compressed page buffer. */
8350 io_buffer = block->page.zip.data;
8351 } else {
8352 io_buffer = iter.m_io_buffer;
8353 }
8354
8355 /* We have to read the exact number of bytes. Otherwise the
8356 InnoDB IO functions croak on failed reads. */
8357
8358 n_bytes = static_cast<ulint>(
8359 std::min(static_cast<os_offset_t>(n_bytes), iter.m_end - offset));
8360
8361 ut_ad(n_bytes > 0);
8362 ut_ad(!(n_bytes % iter.m_page_size));
8363
8364 dberr_t err;
8365 IORequest read_request(read_type);
8366 read_request.block_size(iter.block_size);
8367
8368 /* For encrypted table, set encryption information. */
8369 if (iter.m_encryption_metadata.can_encrypt() && offset != 0) {
8370 read_request.get_encryption_info().set(iter.m_encryption_metadata);
8371 }
8372
8373 err = os_file_read(read_request, iter.m_filepath, iter.m_file, io_buffer,
8374 offset, (ulint)n_bytes);
8375
8376 if (err != DB_SUCCESS) {
8377 ib::error(ER_IB_MSG_335) << "os_file_read() failed";
8378
8379 return err;
8380 }
8381
8382 size_t n_pages_read;
8383 bool updated = false;
8384 os_offset_t page_off = offset;
8385
8386 n_pages_read = (ulint)n_bytes / iter.m_page_size;
8387
8388 for (size_t i = 0; i < n_pages_read; ++i) {
8389 buf_block_set_file_page(block, page_id_t(space_id, page_no++));
8390
8391 /* We are going to modify the page. Add to page tracking system. */
8392 arch_page_sys->track_page(&block->page, LSN_MAX, LSN_MAX, true);
8393
8394 if ((err = callback(page_off, block)) != DB_SUCCESS) {
8395 return err;
8396
8397 } else if (!updated) {
8398 updated = buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE;
8399 }
8400
8401 buf_block_set_state(block, BUF_BLOCK_NOT_USED);
8402 buf_block_set_state(block, BUF_BLOCK_READY_FOR_USE);
8403
8404 page_off += iter.m_page_size;
8405 block->frame += iter.m_page_size;
8406 }
8407
8408 IORequest write_request(write_type);
8409 write_request.block_size(iter.block_size);
8410
8411 /* For encrypted table, set encryption information. */
8412 if (iter.m_encryption_metadata.can_encrypt() && offset != 0) {
8413 write_request.get_encryption_info().set(iter.m_encryption_metadata);
8414 }
8415
8416 /* For compressed table, set compressed information.
8417 @note os_file_compress_page() function expects that the page size is a
8418 multiple of OS punch hole size so we make sure it's true before turning
8419 on compression. */
8420 if (iter.m_compression_type != Compression::Type::NONE &&
8421 IORequest::is_punch_hole_supported() &&
8422 !(srv_page_size % iter.block_size)) {
8423 write_request.compression_algorithm(iter.m_compression_type);
8424
8425 /* In the case of import since we're doing compression for the first time
8426 we would like to ignore any optimisations to not do punch hole. So force
8427 the punch hole. */
8428 write_request.disable_punch_hole_optimisation();
8429 }
8430
8431 /* A page was updated in the set, write back to disk. */
8432
8433 if (updated && (err = os_file_write(write_request, iter.m_filepath,
8434 iter.m_file, io_buffer, offset,
8435 (ulint)n_bytes)) != DB_SUCCESS) {
8436 /* This is not a hard error */
8437 if (err == DB_IO_NO_PUNCH_HOLE) {
8438 err = DB_SUCCESS;
8439 write_type &= ~IORequest::PUNCH_HOLE;
8440
8441 } else {
8442 ib::error(ER_IB_MSG_336) << "os_file_write() failed";
8443
8444 return err;
8445 }
8446 }
8447 }
8448
8449 return DB_SUCCESS;
8450 }
8451
8452 void fil_adjust_name_import(dict_table_t *table [[maybe_unused]],
8453 const char *path,
8454 ib_file_suffix extn [[maybe_unused]]) {
8455 /* Try to open with current name first. */
8456 if (os_file_exists(path)) {
8457 return;
8458 }
8459
8460 /* On failure we need to check if file exists in different letter case
8461 for partitioned table. */
8462
8463 /* Safe check. Never needed on Windows. */
8464 #ifndef _WIN32
8465 /* Needed only for case sensitive file system. */
8466 if (lower_case_file_system) {
8467 return;
8468 }
8469
8470 /* Only needed for partition file. */
8471 if (!dict_name::is_partition(table->name.m_name)) {
8472 return;
8473 }
8474
8475 /* Get Import directory path. */
8476 std::string import_dir(path);
8477 Fil_path::normalize(import_dir);
8478
8479 auto pos = import_dir.find_last_of(Fil_path::SEPARATOR);
8480 if (pos == std::string::npos) {
8481 import_dir.assign(Fil_path::DOT_SLASH);
8482
8483 } else {
8484 import_dir.resize(pos + 1);
8485 ut_ad(Fil_path::is_separator(import_dir.back()));
8486 }
8487
8488 /* Walk through all files under the directory and match the import file
8489 after adjusting case. This is a safe check to allow files exported from
8490 earlier versions where the case for partition name and separator could
8491 be different. */
8492 bool found_path = false;
8493 std::string saved_path;
8494
8495 Dir_Walker::walk(import_dir, false, [&](const std::string &file_path) {
8496 /* Skip entry if already found. */
8497 if (found_path) {
8498 return;
8499 }
8500 /* Check only for partition files. */
8501 if (!dict_name::is_partition(file_path)) {
8502 return;
8503 }
8504
8505 /* Extract table name from path. */
8506 std::string table_name;
8507 if (!Fil_path::parse_file_path(file_path, extn, table_name)) {
8508 /* Not a valid file-per-table path */
8509 return;
8510 }
8511
8512 /* Check if the file name would match after correcting the case. */
8513 dict_name::rebuild(table_name);
8514 if (table_name.compare(table->name.m_name) != 0) {
8515 return;
8516 }
8517
8518 saved_path.assign(file_path);
8519 found_path = true;
8520 });
8521
8522 /* Check and rename the import file name. */
8523 if (found_path) {
8524 fil_rename_partition_file(saved_path, extn, false, true);
8525 }
8526 #endif /* !WIN32 */
8527
8528 return;
8529 }
8530
8531 dberr_t fil_tablespace_iterate(const Encryption_metadata &encryption_metadata,
8532 dict_table_t *table, ulint n_io_buffers,
8533 Compression::Type compression_type,
8534 PageCallback &callback) {
8535 dberr_t err;
8536 pfs_os_file_t file;
8537 char *filepath;
8538 bool success;
8539
8540 ut_a(n_io_buffers > 0);
8541 ut_ad(!srv_read_only_mode);
8542
8543 DBUG_EXECUTE_IF("ib_import_trigger_corruption_1", return DB_CORRUPTION;);
8544
8545 /* Make sure the data_dir_path is set. */
8546 dd_get_and_save_data_dir_path<dd::Table>(table, nullptr, false);
8547
8548 std::string path = dict_table_get_datadir(table);
8549
8550 filepath = Fil_path::make(path, table->name.m_name, IBD, true);
8551
8552 if (filepath == nullptr) {
8553 return DB_OUT_OF_MEMORY;
8554 }
8555
8556 /* Adjust filename for partition file if in different letter case. */
8557 fil_adjust_name_import(table, filepath, IBD);
8558
8559 file = os_file_create_simple_no_error_handling(
8560 innodb_data_file_key, filepath, OS_FILE_OPEN, OS_FILE_READ_WRITE,
8561 srv_read_only_mode, &success);
8562
8563 DBUG_EXECUTE_IF("fil_tablespace_iterate_failure", {
8564 static bool once;
8565
8566 if (!once || ut::random_from_interval_fast(0, 10) == 5) {
8567 once = true;
8568 success = false;
8569 os_file_close(file);
8570 }
8571 });
8572
8573 if (!success) {
8574 /* The following call prints an error message */
8575 os_file_get_last_error(true);
8576
8577 ib::error(ER_IB_MSG_337) << "Trying to import a tablespace, but could not"
8578 " open the tablespace file "
8579 << filepath;
8580
8581 ut::free(filepath);
8582
8583 return DB_TABLESPACE_NOT_FOUND;
8584
8585 } else {
8586 err = DB_SUCCESS;
8587 }
8588
8589 /* Set File System Block Size */
8590 size_t block_size;
8591 {
8592 os_file_stat_t stat_info;
8593
8594 ut_d(dberr_t err =) os_file_get_status(filepath, &stat_info, false, false);
8595 ut_ad(err == DB_SUCCESS);
8596
8597 block_size = stat_info.block_size;
8598 }
8599
8600 callback.set_file(filepath, file);
8601
8602 os_offset_t file_size = os_file_get_size(file);
8603 ut_a(file_size != (os_offset_t)-1);
8604
8605 /* The block we will use for every physical page */
8606 buf_block_t *block;
8607
8608 block = reinterpret_cast<buf_block_t *>(
8609 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(*block)));
8610
8611 mutex_create(LATCH_ID_BUF_BLOCK_MUTEX, &block->mutex);
8612
8613 /* Allocate a page to read in the tablespace header, so that we
8614 can determine the page size and zip size (if it is compressed).
8615 We allocate an extra page in case it is a compressed table. One
8616 page is to ensure alignment. */
8617
8618 byte *page = static_cast<byte *>(
8619 ut::aligned_alloc(2 * UNIV_PAGE_SIZE, UNIV_PAGE_SIZE));
8620
8621 fil_buf_block_init(block, page);
8622
8623 /* Read the first page and determine the page and zip size. */
8624
8625 IORequest request(IORequest::READ);
8626
8627 err = os_file_read_first_page(request, path.c_str(), file, page,
8628 UNIV_PAGE_SIZE);
8629
8630 if (err != DB_SUCCESS) {
8631 err = DB_IO_ERROR;
8632
8633 } else if ((err = callback.init(file_size, block)) == DB_SUCCESS) {
8634 Fil_page_iterator iter{
8635 /* .m_file = */ file,
8636 /* .m_filepath = */ filepath,
8637 /* .m_start = */ 0,
8638 /* .m_end = */ file_size,
8639 /* .m_file_size = */ file_size,
8640 /* .m_page_size = */ callback.get_page_size().physical(),
8641 /* .m_n_io_buffers = */ n_io_buffers,
8642 /* .m_io_buffer = */ nullptr,
8643 /* .m_encryption_metadata = */ encryption_metadata,
8644 /* .block_size = */ block_size,
8645 /* .m_compression_type = */ compression_type,
8646 };
8647 /* Check encryption is matched or not. */
8648 ulint space_flags = callback.get_space_flags();
8649
8650 if (FSP_FLAGS_GET_ENCRYPTION(space_flags)) {
8651 if (!dd_is_table_in_encrypted_tablespace(table)) {
8652 ib::error(ER_IB_MSG_338) << "Table is not in an encrypted tablespace,"
8653 " but the data file intended for import"
8654 " is an encrypted tablespace";
8655
8656 err = DB_IO_NO_ENCRYPT_TABLESPACE;
8657 } else {
8658 /* encryption_key must have been populated while reading CFP file. */
8659 ut_ad(encryption_metadata.can_encrypt());
8660
8661 if (!encryption_metadata.can_encrypt()) {
8662 err = DB_ERROR;
8663 }
8664 }
8665 }
8666
8667 if (err == DB_SUCCESS) {
8668 /* Compressed pages can't be optimised for block IO
8669 for now. We do the IMPORT page by page. */
8670
8671 if (callback.get_page_size().is_compressed()) {
8672 iter.m_n_io_buffers = 1;
8673 ut_a(iter.m_page_size == callback.get_page_size().physical());
8674 }
8675
8676 /** Add an extra page for compressed page scratch
8677 area. */
8678 iter.m_io_buffer = static_cast<byte *>(ut::aligned_alloc(
8679 (1 + iter.m_n_io_buffers) * UNIV_PAGE_SIZE, UNIV_PAGE_SIZE));
8680
8681 err = fil_iterate(iter, block, callback);
8682
8683 ut::aligned_free(iter.m_io_buffer);
8684 }
8685 }
8686
8687 if (err == DB_SUCCESS) {
8688 ib::info(ER_IB_MSG_339) << "Sync to disk";
8689
8690 if (!os_file_flush(file)) {
8691 ib::info(ER_IB_MSG_340) << "os_file_flush() failed!";
8692 err = DB_IO_ERROR;
8693 } else {
8694 ib::info(ER_IB_MSG_341) << "Sync to disk - done!";
8695 }
8696 }
8697
8698 os_file_close(file);
8699
8700 ut::aligned_free(page);
8701 ut::free(filepath);
8702
8703 mutex_free(&block->mutex);
8704
8705 ut::free(block);
8706
8707 return err;
8708 }
8709 #endif /* !UNIV_HOTBACKUP */
8710
8711 /** Set the tablespace table size.
8712 @param[in] page a page belonging to the tablespace */
8713 void PageCallback::set_page_size(const buf_frame_t *page) UNIV_NOTHROW {
8714 m_page_size.copy_from(fsp_header_get_page_size(page));
8715 }
8716
8717 /** Delete the tablespace file and any related files like .cfg.
8718 This should not be called for temporary tables.
8719 @param[in] path File path of the IBD tablespace
8720 @return true on success */
8721 bool fil_delete_file(const char *path) {
8722 bool success = true;
8723
8724 /* Force a delete of any stale .ibd files that are lying around. */
8725 success = os_file_delete_if_exists(innodb_data_file_key, path, nullptr);
8726
8727 char *cfg_filepath = Fil_path::make_cfg(path);
8728
8729 if (cfg_filepath != nullptr) {
8730 os_file_delete_if_exists(innodb_data_file_key, cfg_filepath, nullptr);
8731
8732 ut::free(cfg_filepath);
8733 }
8734
8735 char *cfp_filepath = Fil_path::make_cfp(path);
8736
8737 if (cfp_filepath != nullptr) {
8738 os_file_delete_if_exists(innodb_data_file_key, cfp_filepath, nullptr);
8739
8740 ut::free(cfp_filepath);
8741 }
8742
8743 return success;
8744 }
8745
8746 #ifndef UNIV_HOTBACKUP
8747 dberr_t fil_rename_precheck(const dict_table_t *old_table,
8748 const dict_table_t *new_table,
8749 const char *tmp_name) {
8750 bool old_is_file_per_table = dict_table_is_file_per_table(old_table);
8751 bool new_is_file_per_table = dict_table_is_file_per_table(new_table);
8752
8753 /* If neither table is file-per-table, there will be no renaming of files. */
8754 if (!old_is_file_per_table && !new_is_file_per_table) {
8755 return DB_SUCCESS;
8756 }
8757
8758 auto fetch_path = [](std::string &path, const dict_table_t *source_table,
8759 bool fpt) -> dberr_t {
8760 char *path_ptr{};
8761
8762 /* It is possible that the file could be present in a directory outside of
8763 the data directory (possible because of innodb_directories option), so
8764 fetch the path accordingly.
8765
8766 We are only interested in fetching the right path for file-per-table
8767 tablespaces as during file_rename_tablespace_check the source table should
8768 always exist and we do the rename for only source tables which are
8769 file-per-table tablspaces. */
8770 if (fpt && !dict_table_is_discarded(source_table)) {
8771 path_ptr = fil_space_get_first_path(source_table->space);
8772
8773 if (path_ptr == nullptr) {
8774 return DB_TABLESPACE_NOT_FOUND;
8775 }
8776 } else {
8777 auto dir = dict_table_get_datadir(source_table);
8778
8779 path_ptr =
8780 Fil_path::make(dir, source_table->name.m_name, IBD, !dir.empty());
8781
8782 if (path_ptr == nullptr) {
8783 return DB_OUT_OF_MEMORY;
8784 }
8785 }
8786
8787 path.assign(path_ptr);
8788 ut::free(path_ptr);
8789
8790 return DB_SUCCESS;
8791 };
8792
8793 std::string old_path;
8794
8795 auto err = fetch_path(old_path, old_table, old_is_file_per_table);
8796
8797 if (err != DB_SUCCESS) {
8798 return err;
8799 }
8800
8801 if (old_is_file_per_table) {
8802 std::string tmp_path =
8803 Fil_path::make_new_path(old_path.c_str(), tmp_name, IBD);
8804
8805 /* Temp filepath must not exist. */
8806 err = fil_rename_tablespace_check(old_table->space, old_path.c_str(),
8807 tmp_path.c_str(),
8808 dict_table_is_discarded(old_table));
8809
8810 if (err != DB_SUCCESS) {
8811 return err;
8812 }
8813 }
8814
8815 if (new_is_file_per_table) {
8816 std::string new_path;
8817
8818 err = fetch_path(new_path, new_table, new_is_file_per_table);
8819
8820 if (err != DB_SUCCESS) {
8821 return err;
8822 }
8823
8824 /* Destination filepath must not exist unless this ALTER TABLE starts and
8825 ends with a file_per-table tablespace. */
8826 if (!old_is_file_per_table) {
8827 err = fil_rename_tablespace_check(new_table->space, new_path.c_str(),
8828 old_path.c_str(),
8829 dict_table_is_discarded(new_table));
8830 }
8831 }
8832
8833 return err;
8834 }
8835 #endif /* !UNIV_HOTBACKUP */
8836
8837 /** Note that the file system where the file resides doesn't support PUNCH HOLE.
8838 Called from AIO handlers when IO returns DB_IO_NO_PUNCH_HOLE
8839 @param[in,out] file file to set */
8840 void fil_no_punch_hole(fil_node_t *file) { file->punch_hole = false; }
8841
8842 dberr_t fil_set_compression(space_id_t space_id, const char *algorithm) {
8843 dberr_t err;
8844 Compression compression;
8845
8846 if (algorithm == nullptr || strlen(algorithm) == 0) {
8847 #ifndef UNIV_DEBUG
8848 compression.m_type = Compression::NONE;
8849 #else /* UNIV_DEBUG */
8850 /* This is a Debug tool for setting compression on all
8851 compressible tables not otherwise specified. */
8852 switch (srv_debug_compress) {
8853 case Compression::LZ4:
8854 case Compression::ZLIB:
8855 case Compression::NONE:
8856
8857 compression.m_type = static_cast<Compression::Type>(srv_debug_compress);
8858 break;
8859
8860 default:
8861 compression.m_type = Compression::NONE;
8862 }
8863
8864 #endif /* UNIV_DEBUG */
8865
8866 err = DB_SUCCESS;
8867
8868 } else {
8869 err = Compression::check(algorithm, &compression);
8870 }
8871
8872 fil_space_t *space = fil_space_get(space_id);
8873
8874 if (space == nullptr) {
8875 return DB_NOT_FOUND;
8876 }
8877
8878 const page_size_t page_size(space->flags);
8879
8880 if (!fsp_is_file_per_table(space_id, space->flags) ||
8881 fsp_is_system_temporary(space_id) || page_size.is_compressed()) {
8882 return DB_IO_NO_PUNCH_HOLE_TABLESPACE;
8883 }
8884
8885 space->compression_type = compression.m_type;
8886
8887 if (space->compression_type != Compression::NONE) {
8888 if (!space->files.front().punch_hole) {
8889 return DB_IO_NO_PUNCH_HOLE_FS;
8890 }
8891 }
8892
8893 return err;
8894 }
8895
8896 /** Get the compression algorithm for a tablespace.
8897 @param[in] space_id Space ID to check
8898 @return the compression algorithm */
8899 Compression::Type fil_get_compression(space_id_t space_id) {
8900 fil_space_t *space = fil_space_get(space_id);
8901
8902 return space == nullptr ? Compression::NONE : space->compression_type;
8903 }
8904
8905 /** Set the autoextend_size attribute for the tablespace
8906 @param[in] space_id Space ID of tablespace for which to set
8907 @param[in] autoextend_size Value of autoextend_size attribute
8908 @return DB_SUCCESS or error code */
8909 dberr_t fil_set_autoextend_size(space_id_t space_id, uint64_t autoextend_size) {
8910 ut_ad(space_id != TRX_SYS_SPACE);
8911
8912 fil_space_t *space = fil_space_acquire(space_id);
8913
8914 if (space == nullptr) {
8915 return DB_NOT_FOUND;
8916 }
8917
8918 rw_lock_x_lock(&space->latch, UT_LOCATION_HERE);
8919
8920 space->autoextend_size_in_bytes = autoextend_size;
8921
8922 rw_lock_x_unlock(&space->latch);
8923
8924 fil_space_release(space);
8925
8926 return DB_SUCCESS;
8927 }
8928
8929 /** Set the encryption type for the tablespace
8930 @param[in] space_id Space ID of tablespace for which to set
8931 @param[in] algorithm Encryption algorithm
8932 @param[in] key Encryption key
8933 @param[in] iv Encryption iv
8934 @return DB_SUCCESS or error code */
8935 dberr_t fil_set_encryption(space_id_t space_id, Encryption::Type algorithm,
8936 byte *key, byte *iv) {
8937 ut_ad(space_id != TRX_SYS_SPACE);
8938
8939 if (fsp_is_system_or_temp_tablespace(space_id)) {
8940 return DB_IO_NO_ENCRYPT_TABLESPACE;
8941 }
8942
8943 auto shard = fil_system->shard_by_id(space_id);
8944
8945 shard->mutex_acquire();
8946
8947 fil_space_t *space = shard->get_space_by_id(space_id);
8948
8949 if (space == nullptr) {
8950 shard->mutex_release();
8951 return DB_NOT_FOUND;
8952 }
8953
8954 Encryption::set_or_generate(algorithm, key, iv, space->m_encryption_metadata);
8955
8956 shard->mutex_release();
8957
8958 return DB_SUCCESS;
8959 }
8960
8961 /** Reset the encryption type for the tablespace
8962 @param[in] space_id Space ID of tablespace for which to set
8963 @return DB_SUCCESS or error code */
8964 dberr_t fil_reset_encryption(space_id_t space_id) {
8965 ut_ad(space_id != TRX_SYS_SPACE);
8966
8967 if (fsp_is_system_or_temp_tablespace(space_id)) {
8968 return DB_IO_NO_ENCRYPT_TABLESPACE;
8969 }
8970
8971 auto shard = fil_system->shard_by_id(space_id);
8972
8973 shard->mutex_acquire();
8974
8975 fil_space_t *space = shard->get_space_by_id(space_id);
8976
8977 if (space == nullptr) {
8978 shard->mutex_release();
8979 return DB_NOT_FOUND;
8980 }
8981
8982 space->m_encryption_metadata = {};
8983
8984 shard->mutex_release();
8985
8986 return DB_SUCCESS;
8987 }
8988
8989 #ifndef UNIV_HOTBACKUP
8990 bool Fil_shard::needs_encryption_rotate(fil_space_t *space) {
8991 /* We only rotate if encryption is already set. */
8992 if (!space->can_encrypt()) {
8993 return false;
8994 }
8995
8996 /* Deleted spaces do not need rotation. Their pages are being
8997 deleted from the buffer pool. */
8998 if (space->is_deleted()) {
8999 return false;
9000 }
9001
9002 /* Skip unencypted tablespaces. */
9003 if (fsp_is_system_or_temp_tablespace(space->id)) {
9004 return false;
9005 }
9006
9007 DBUG_EXECUTE_IF(
9008 "ib_encryption_rotate_skip",
9009 ib::info(ER_IB_MSG_INJECT_FAILURE, "ib_encryption_rotate_skip");
9010 return false;);
9011
9012 return true;
9013 }
9014
9015 size_t Fil_shard::encryption_rotate(size_t *rotate_count) {
9016 /* If there are no tablespaces to rotate, return true. */
9017 size_t fail_count = 0;
9018 byte encrypt_info[Encryption::INFO_SIZE];
9019 using Spaces_to_rotate = std::vector<fil_space_t *>;
9020 Spaces_to_rotate spaces2rotate;
9021
9022 /* Use the shard mutex to collect a list of the spaces to rotate. */
9023 mutex_acquire();
9024
9025 for (auto &elem : m_spaces) {
9026 auto space = elem.second;
9027
9028 if (!needs_encryption_rotate(space)) {
9029 continue;
9030 }
9031
9032 spaces2rotate.push_back(space);
9033 }
9034
9035 mutex_release();
9036
9037 /* We can now be assured that each fil_space_t collected above will not be
9038 deleted below (outside the shard mutex protection) because:
9039 1. The caller, Rotate_innodb_master_key::execute(), holds an exclusive
9040 backup lock which blocks any other concurrent DDL or MDL on this space.
9041 2. Only a thread with an MDL on the space name can mark a fil_space_t as
9042 deleted or actually delete it. This includes background threads like
9043 the purge thread doing undo truncation as well as any client DDL.
9044 3. We assured above using the shard mutex that the space is not deleted. */
9045
9046 for (auto &space : spaces2rotate) {
9047 /* Rotate this encrypted tablespace. */
9048 mtr_t mtr;
9049 mtr_start(&mtr);
9050 memset(encrypt_info, 0, Encryption::INFO_SIZE);
9051 bool rotate_ok = fsp_header_rotate_encryption(space, encrypt_info, &mtr);
9052 ut_ad(rotate_ok);
9053 mtr_commit(&mtr);
9054
9055 if (rotate_ok) {
9056 ++(*rotate_count);
9057 } else {
9058 ++fail_count;
9059 }
9060 }
9061
9062 /* This crash forces encryption rotate to complete at startup. */
9063 DBUG_EXECUTE_IF(
9064 "ib_encryption_rotate_crash",
9065 ib::info(ER_IB_MSG_INJECT_FAILURE, "ib_encryption_rotate_crash");
9066 DBUG_SUICIDE(););
9067
9068 return fail_count;
9069 }
9070
9071 size_t Fil_system::encryption_rotate() {
9072 size_t fail_count = 0;
9073 size_t rotate_count = 0;
9074
9075 for (auto shard : m_shards) {
9076 fail_count += shard->encryption_rotate(&rotate_count);
9077 }
9078
9079 if (rotate_count > 0) {
9080 ib::info(ER_IB_MSG_MASTER_KEY_ROTATED, static_cast<int>(rotate_count));
9081 }
9082
9083 return fail_count;
9084 }
9085
9086 void Fil_system::encryption_reencrypt(
9087 std::vector<space_id_t> &space_id_vector) {
9088 /* If there are no tablespaces to reencrypt, return true. */
9089 if (space_id_vector.empty()) {
9090 return;
9091 }
9092
9093 size_t fail_count = 0;
9094 byte encrypt_info[Encryption::INFO_SIZE];
9095
9096 /* This operation is done either post recovery or when the first time
9097 tablespace is loaded. */
9098
9099 for (auto &space_id : space_id_vector) {
9100 fil_space_t *space = fil_space_get(space_id);
9101 ut_ad(space != nullptr);
9102 ut_ad(FSP_FLAGS_GET_ENCRYPTION(space->flags));
9103
9104 /* Rotate this encrypted tablespace. */
9105 mtr_t mtr;
9106 mtr_start(&mtr);
9107 memset(encrypt_info, 0, Encryption::INFO_SIZE);
9108 bool rotate_ok = fsp_header_rotate_encryption(space, encrypt_info, &mtr);
9109 ut_ad(rotate_ok);
9110 mtr_commit(&mtr);
9111
9112 if (rotate_ok) {
9113 if (fsp_is_ibd_tablespace(space_id)) {
9114 if (fsp_is_file_per_table(space_id, space->flags)) {
9115 ib::info(ER_IB_MSG_REENCRYPTED_TABLESPACE_KEY, space->name);
9116 } else {
9117 ib::info(ER_IB_MSG_REENCRYPTED_GENERAL_TABLESPACE_KEY, space->name);
9118 }
9119 }
9120 } else {
9121 ++fail_count;
9122 }
9123 }
9124
9125 /* The operation should finish successfully for all tablespaces */
9126 ut_a(fail_count == 0);
9127 }
9128
9129 size_t fil_encryption_rotate() { return (fil_system->encryption_rotate()); }
9130
9131 void fil_encryption_reencrypt(std::vector<space_id_t> &sid_vector) {
9132 fil_system->encryption_reencrypt(sid_vector);
9133 }
9134 #endif /* !UNIV_HOTBACKUP */
9135
9136 /** Constructor
9137 @param[in] path pathname (may also include the file basename)
9138 @param[in] normalize_path If false, it's the callers responsibility to
9139 ensure that the path is normalized. */
9140 Fil_path::Fil_path(const std::string &path, bool normalize_path)
9141 : m_path(path) {
9142 if (normalize_path) {
9143 normalize(m_path);
9144 }
9145
9146 m_abs_path = get_real_path(m_path, false);
9147 }
9148
9149 /** Constructor
9150 @param[in] path Path, not necessarily NUL terminated
9151 @param[in] normalize_path If false, it's the callers responsibility to
9152 ensure that the path is normalized. */
9153 Fil_path::Fil_path(const char *path, bool normalize_path) : m_path(path) {
9154 if (normalize_path) {
9155 normalize(m_path);
9156 }
9157
9158 m_abs_path = get_real_path(m_path, false);
9159 }
9160
9161 /** Constructor
9162 @param[in] path Path, not necessarily NUL terminated
9163 @param[in] len Length of path
9164 @param[in] normalize_path If false, it's the callers responsibility to
9165 ensure that the path is normalized. */
9166 Fil_path::Fil_path(const char *path, size_t len, bool normalize_path)
9167 : m_path(path, len) {
9168 if (normalize_path) {
9169 normalize(m_path);
9170 }
9171
9172 m_abs_path = get_real_path(m_path, false);
9173 }
9174
9175 /** Default constructor. */
9176 Fil_path::Fil_path() : m_path(), m_abs_path() { /* No op */
9177 }
9178
9179 bool Fil_path::is_same_as(const Fil_path &other) const {
9180 if (path().empty() || other.path().empty()) {
9181 return false;
9182 }
9183
9184 std::string first = abs_path();
9185 trim_separator(first);
9186
9187 std::string second = other.abs_path();
9188 trim_separator(second);
9189
9190 return (first == second);
9191 }
9192
9193 bool Fil_path::is_same_as(const std::string &other) const {
9194 if (path().empty() || other.empty()) {
9195 return false;
9196 }
9197
9198 Fil_path other_path(other);
9199
9200 return is_same_as(other_path);
9201 }
9202
9203 Fil_path Fil_path::get_abs_directory() const {
9204 std::string dir_path = split(abs_path()).first;
9205 Fil_path directory{dir_path};
9206 return directory;
9207 }
9208
9209 bool Fil_path::is_dir_same_as(const Fil_path &other) const {
9210 return get_abs_directory().is_same_as(other.get_abs_directory());
9211 }
9212
9213 std::pair<std::string, std::string> Fil_path::split(const std::string &path) {
9214 const auto n = path.rfind(OS_PATH_SEPARATOR);
9215 ut_ad(n != std::string::npos);
9216 return {path.substr(0, n), path.substr(n)};
9217 }
9218
9219 bool Fil_path::is_ancestor(const Fil_path &other) const {
9220 if (path().empty() || other.path().empty()) {
9221 return false;
9222 }
9223
9224 std::string ancestor = abs_path();
9225 std::string descendant = other.abs_path();
9226
9227 /* We do not know if the descendant is a dir or a file.
9228 But the ancestor in this routine is always a directory.
9229 If it does not yet exist, it may not have a trailing separator.
9230 If there is no trailing separator, add it. */
9231 append_separator(ancestor);
9232
9233 if (descendant.length() <= ancestor.length()) {
9234 return false;
9235 }
9236
9237 return std::equal(ancestor.begin(), ancestor.end(), descendant.begin());
9238 }
9239
9240 bool Fil_path::is_ancestor(const std::string &other) const {
9241 if (path().empty() || other.empty()) {
9242 return false;
9243 }
9244
9245 Fil_path descendant(other);
9246
9247 return is_ancestor(descendant);
9248 }
9249
9250 bool Fil_path::is_hidden(std::string path) {
9251 std::string basename(path);
9252 while (!basename.empty()) {
9253 char c = basename.back();
9254 if (!(Fil_path::is_separator(c) || c == '*')) {
9255 break;
9256 }
9257 basename.resize(basename.size() - 1);
9258 }
9259 auto sep = basename.find_last_of(SEPARATOR);
9260
9261 return (sep != std::string::npos && basename[sep + 1] == '.');
9262 }
9263
9264 #ifdef _WIN32
9265 bool Fil_path::is_hidden(WIN32_FIND_DATA &dirent) {
9266 if (dirent.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN ||
9267 dirent.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
9268 return true;
9269 }
9270
9271 return false;
9272 }
9273 #endif /* WIN32 */
9274
9275 /** @return true if the path exists and is a file . */
9276 os_file_type_t Fil_path::get_file_type(const std::string &path) {
9277 os_file_type_t type;
9278
9279 os_file_status(path.c_str(), nullptr, &type);
9280
9281 return type;
9282 }
9283
9284 /** Return a string to display the file type of a path.
9285 @param[in] path path name
9286 @return true if the path exists and is a file . */
9287 const char *Fil_path::get_file_type_string(const std::string &path) {
9288 return get_file_type_string(Fil_path::get_file_type(path));
9289 }
9290
9291 /** Return a string to display the file type of a path.
9292 @param[in] type OS file type
9293 @return true if the path exists and is a file . */
9294 const char *Fil_path::get_file_type_string(os_file_type_t type) {
9295 switch (type) {
9296 case OS_FILE_TYPE_FILE:
9297 return "file";
9298 case OS_FILE_TYPE_LINK:
9299 return "symbolic link";
9300 case OS_FILE_TYPE_DIR:
9301 return "directory";
9302 case OS_FILE_TYPE_BLOCK:
9303 return "block device";
9304 case OS_FILE_TYPE_NAME_TOO_LONG:
9305 return "name too long";
9306 case OS_FILE_PERMISSION_ERROR:
9307 return "permission error";
9308 case OS_FILE_TYPE_MISSING:
9309 return "missing";
9310 case OS_FILE_TYPE_UNKNOWN:
9311 case OS_FILE_TYPE_FAILED:
9312 break;
9313 }
9314 return "unknown";
9315 }
9316
9317 /** @return true if the path exists and is a file . */
9318 bool Fil_path::is_file_and_exists() const {
9319 return (get_file_type(abs_path()) == OS_FILE_TYPE_FILE);
9320 }
9321
9322 /** @return true if the path exists and is a directory. */
9323 bool Fil_path::is_directory_and_exists() const {
9324 return (get_file_type(abs_path()) == OS_FILE_TYPE_DIR);
9325 }
9326
9327 /** This validation is only for ':'.
9328 @return true if the path is valid. */
9329 bool Fil_path::is_valid() const {
9330 auto count = std::count(m_path.begin(), m_path.end(), ':');
9331
9332 if (count == 0) {
9333 return true;
9334 }
9335
9336 #ifdef _WIN32
9337 /* Do not allow names like "C:name.ibd" because it
9338 specifies the "C:" drive but allows a relative location.
9339 It should be like "c:\". If a single colon is used it
9340 must be the second byte and the third byte must be a
9341 separator. */
9342
9343 /* 8 == strlen("c:\a,ibd") */
9344 if (count == 1 && m_path.length() >= 8 && isalpha(m_path.at(0)) &&
9345 m_path.at(1) == ':' && (m_path.at(2) == '\\' || m_path.at(2) == '/')) {
9346 return true;
9347 }
9348 #endif /* _WIN32 */
9349
9350 return false;
9351 }
9352
9353 bool Fil_path::is_circular() const {
9354 size_t first;
9355
9356 /* Find the first named directory. It is OK for a path to
9357 start with "../../../dir". */
9358 for (first = 0; m_path[first] == OS_SEPARATOR || m_path[first] == '.';
9359 ++first)
9360 ;
9361
9362 size_t back_up = m_path.find(SLASH_DOT_DOT_SLASH, first);
9363 if (back_up == std::string::npos) {
9364 return false;
9365 }
9366
9367 #ifndef _WIN32
9368 /* If the path contains a symlink before the /../ and the platform
9369 is not Windows, then '/../' does not go bback through the symlink,
9370 so it is not circular. It refers to the parent of the symlinked
9371 location and we must allow it. On Windows, it backs up to the directory
9372 where the symlink starts, which is a circular reference. */
9373 std::string up_path = m_path.substr(0, back_up);
9374 if (my_is_symlink(up_path.c_str(), nullptr)) {
9375 return false;
9376 }
9377 #endif /* _WIN32 */
9378
9379 return true;
9380 }
9381
9382 /** Sets the flags of the tablespace. The tablespace must be locked
9383 in MDL_EXCLUSIVE MODE.
9384 @param[in] space tablespace in-memory struct
9385 @param[in] flags tablespace flags */
9386 void fil_space_set_flags(fil_space_t *space, uint32_t flags) {
9387 ut_ad(fsp_flags_is_valid(flags));
9388
9389 rw_lock_x_lock(&space->latch, UT_LOCATION_HERE);
9390
9391 ut_a(flags < std::numeric_limits<uint32_t>::max());
9392 space->flags = (uint32_t)flags;
9393
9394 rw_lock_x_unlock(&space->latch);
9395 }
9396
9397 /* Unit Tests */
9398 #ifdef UNIV_ENABLE_UNIT_TEST_MAKE_FILEPATH
9399 #define MF Fil_path::make
9400 #define DISPLAY ib::info(ER_IB_MSG_342) << path
9401 void test_make_filepath() {
9402 char *path;
9403 const char *long_path =
9404 "this/is/a/very/long/path/including/a/very/"
9405 "looooooooooooooooooooooooooooooooooooooooooooooooo"
9406 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9407 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9408 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9409 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9410 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9411 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9412 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9413 "oooooooooooooooooooooooooooooooooooooooooooooooooo"
9414 "oooooooooooooooooooooooooooooooooooooooooooooooong"
9415 "/folder/name";
9416 path = MF("/this/is/a/path/with/a/filename", nullptr, IBD, false);
9417 DISPLAY;
9418 path = MF("/this/is/a/path/with/a/filename", nullptr, ISL, false);
9419 DISPLAY;
9420 path = MF("/this/is/a/path/with/a/filename", nullptr, CFG, false);
9421 DISPLAY;
9422 path = MF("/this/is/a/path/with/a/filename", nullptr, CFP, false);
9423 DISPLAY;
9424 path = MF("/this/is/a/path/with/a/filename.ibd", nullptr, IBD, false);
9425 DISPLAY;
9426 path = MF("/this/is/a/path/with/a/filename.ibd", nullptr, IBD, false);
9427 DISPLAY;
9428 path = MF("/this/is/a/path/with/a/filename.dat", nullptr, IBD, false);
9429 DISPLAY;
9430 path = MF(nullptr, "tablespacename", NO_EXT, false);
9431 DISPLAY;
9432 path = MF(nullptr, "tablespacename", IBD, false);
9433 DISPLAY;
9434 path = MF(nullptr, "dbname/tablespacename", NO_EXT, false);
9435 DISPLAY;
9436 path = MF(nullptr, "dbname/tablespacename", IBD, false);
9437 DISPLAY;
9438 path = MF(nullptr, "dbname/tablespacename", ISL, false);
9439 DISPLAY;
9440 path = MF(nullptr, "dbname/tablespacename", CFG, false);
9441 DISPLAY;
9442 path = MF(nullptr, "dbname/tablespacename", CFP, false);
9443 DISPLAY;
9444 path = MF(nullptr, "dbname\\tablespacename", NO_EXT, false);
9445 DISPLAY;
9446 path = MF(nullptr, "dbname\\tablespacename", IBD, false);
9447 DISPLAY;
9448 path = MF("/this/is/a/path", "dbname/tablespacename", IBD, false);
9449 DISPLAY;
9450 path = MF("/this/is/a/path", "dbname/tablespacename", IBD, true);
9451 DISPLAY;
9452 path = MF("./this/is/a/path", "dbname/tablespacename.ibd", IBD, true);
9453 DISPLAY;
9454 path = MF("this\\is\\a\\path", "dbname/tablespacename", IBD, true);
9455 DISPLAY;
9456 path = MF("/this/is/a/path", "dbname\\tablespacename", IBD, true);
9457 DISPLAY;
9458 path = MF(long_path, nullptr, IBD, false);
9459 DISPLAY;
9460 path = MF(long_path, "tablespacename", IBD, false);
9461 DISPLAY;
9462 path = MF(long_path, "tablespacename", IBD, true);
9463 DISPLAY;
9464 }
9465 #endif /* UNIV_ENABLE_UNIT_TEST_MAKE_FILEPATH */
9466
9467 /** Release the reserved free extents.
9468 @param[in] n_reserved number of reserved extents */
9469 void fil_space_t::release_free_extents(ulint n_reserved) {
9470 #ifndef UNIV_HOTBACKUP
9471 ut_ad(rw_lock_own(&latch, RW_LOCK_X));
9472 #endif /* !UNIV_HOTBACKUP */
9473
9474 ut_a(n_reserved < std::numeric_limits<uint32_t>::max());
9475 ut_a(n_reserved_extents >= n_reserved);
9476
9477 n_reserved_extents -= (uint32_t)n_reserved;
9478 }
9479
9480 #ifndef UNIV_HOTBACKUP
9481
9482 #ifdef UNIV_DEBUG
9483
9484 /** Print the extent descriptor pages of this tablespace into
9485 the given file.
9486 @param[in] filename the output file name. */
9487 void fil_space_t::print_xdes_pages(const char *filename) const {
9488 std::ofstream out(filename);
9489 print_xdes_pages(out);
9490 }
9491
9492 /** Print the extent descriptor pages of this tablespace into
9493 the given output stream.
9494 @param[in] out the output stream.
9495 @return the output stream. */
9496 std::ostream &fil_space_t::print_xdes_pages(std::ostream &out) const {
9497 mtr_t mtr;
9498 const page_size_t page_size(flags);
9499
9500 mtr_start(&mtr);
9501
9502 for (page_no_t i = 0; i < 100; ++i) {
9503 page_no_t xdes_page_no = i * UNIV_PAGE_SIZE;
9504
9505 if (xdes_page_no >= size) {
9506 break;
9507 }
9508
9509 buf_block_t *xdes_block =
9510 buf_page_get(page_id_t(id, xdes_page_no), page_size, RW_S_LATCH,
9511 UT_LOCATION_HERE, &mtr);
9512
9513 page_t *page = buf_block_get_frame(xdes_block);
9514
9515 ulint page_type = fil_page_get_type(page);
9516
9517 switch (page_type) {
9518 case FIL_PAGE_TYPE_ALLOCATED:
9519
9520 ut_ad(xdes_page_no >= free_limit);
9521
9522 mtr_commit(&mtr);
9523 return out;
9524
9525 case FIL_PAGE_TYPE_FSP_HDR:
9526 case FIL_PAGE_TYPE_XDES:
9527 break;
9528 default:
9529 ut_error;
9530 }
9531
9532 xdes_page_print(out, page, xdes_page_no, &mtr);
9533 }
9534
9535 mtr_commit(&mtr);
9536 return out;
9537 }
9538 #endif /* UNIV_DEBUG */
9539
9540 /** Initialize the table space encryption
9541 @param[in,out] space Tablespace instance */
9542 static void fil_tablespace_encryption_init(const fil_space_t *space) {
9543 for (auto &key : *recv_sys->keys) {
9544 if (key.space_id != space->id) {
9545 continue;
9546 }
9547
9548 dberr_t err = DB_SUCCESS;
9549
9550 ut_ad(!fsp_is_system_tablespace(space->id));
9551
9552 if (fsp_is_file_per_table(space->id, space->flags)) {
9553 /* For file-per-table tablespace, which is not INPLACE algorithm, copy
9554 what is found on REDO Log. */
9555 err = fil_set_encryption(space->id, Encryption::AES, key.ptr, key.iv);
9556 } else {
9557 /* Here we try to populate space tablespace_key which is read during
9558 REDO scan.
9559
9560 Consider following scenario:
9561 1. Alter tablespce .. encrypt=y (KEY1)
9562 2. Alter tablespce .. encrypt=n
9563 3. Alter tablespce .. encrypt=y (KEY2)
9564
9565 Lets say there is a crash after (3) is finished successfully. Let's say
9566 we scanned till REDO of (1) but couldn't reach to REDO of (3).
9567
9568 During recovery:
9569 ----------------
9570 Case 1:
9571 - Before crash, pages of tablespace were encrypted with KEY2 and flushed.
9572 - In recovery, on REDO we've got tablespace key as KEY1.
9573 - Note, during tablespce load, KEY2 would have been found on page 0 and
9574 thus loaded already in file_space_t.
9575 - If we overwrite this space key (KEY2) with the one we got from REDO log
9576 scan (KEY1), then when we try to read a page from Disk, we will try to
9577 decrypt it using KEY1 whereas page was encrypted with KEY2. ERROR.
9578 - So don't overwrite keys on tablespace in this scenario.
9579
9580 Case 2:
9581 - Before crash, if tablespace pages were not flushed.
9582 - On disk, there may be
9583 - No Key (after decrypt page 0 was flushed)
9584 - KEY1 (after decrypt, page 0 wasn't flushed)
9585 - KEY2. (After 3 starts, page 0 was flushed)
9586 Thus tablespace would have been loaded accordingly.
9587
9588 This function is called only during recovery when a tablespce is loaded.
9589 So we can see the LSN for REDO Entry (recv_sys->keys) and compare it with
9590 the LSN of page 0 and take decision of updating encryption accordingly. */
9591
9592 if (space->m_encryption_metadata.m_key_len == 0 ||
9593 key.lsn > space->m_header_page_flush_lsn) {
9594 /* Key on tablesapce isn't present or old. Update it. */
9595 err = fil_set_encryption(space->id, Encryption::AES, key.ptr, key.iv);
9596 } else {
9597 /* Key on tablespace is new. Skip updating. */
9598 }
9599 }
9600
9601 if (err != DB_SUCCESS) {
9602 ib::error(ER_IB_MSG_343) << "Can't set encryption information"
9603 << " for tablespace" << space->name << "!";
9604 }
9605
9606 ut::free(key.iv);
9607 ut::free(key.ptr);
9608
9609 key.iv = nullptr;
9610 key.ptr = nullptr;
9611
9612 key.space_id = std::numeric_limits<space_id_t>::max();
9613 }
9614 }
9615
9616 /** Modify table name in Innodb persistent stat tables, if needed. Required
9617 when partitioned table file names from old versions are modified to change
9618 the letter case.
9619 @param[in] old_path path to old file
9620 @param[in] new_path path to new file */
9621 static void fil_adjust_partition_stat(const std::string &old_path,
9622 const std::string &new_path) {
9623 char errstr[FN_REFLEN];
9624 std::string path;
9625
9626 /* Skip if not IBD file extension. */
9627 if (!Fil_path::has_suffix(IBD, old_path) ||
9628 !Fil_path::has_suffix(IBD, new_path)) {
9629 return;
9630 }
9631
9632 /* Check if partitioned table. */
9633 if (!dict_name::is_partition(old_path) ||
9634 !dict_name::is_partition(new_path)) {
9635 return;
9636 }
9637
9638 std::string old_name;
9639 path.assign(old_path);
9640 if (!Fil_path::parse_file_path(path, IBD, old_name)) {
9641 return;
9642 }
9643 ut_ad(!old_name.empty());
9644
9645 std::string new_name;
9646 path.assign(new_path);
9647 if (!Fil_path::parse_file_path(path, IBD, new_name)) {
9648 return;
9649 }
9650 ut_ad(!new_name.empty());
9651
9652 /* Required for case insensitive file system where file path letter case
9653 doesn't matter. We need to keep the name in stat table consistent. */
9654 dict_name::rebuild(new_name);
9655
9656 if (old_name.compare(new_name) != 0) {
9657 dict_stats_rename_table(old_name.c_str(), new_name.c_str(), errstr,
9658 sizeof(errstr));
9659 }
9660 }
9661
9662 /** Update the DD if any files were moved to a new location.
9663 Free the Tablespace_files instance.
9664 @param[in] read_only_mode true if InnoDB is started in read only mode.
9665 @return DB_SUCCESS if all OK */
9666 dberr_t Fil_system::prepare_open_for_business(bool read_only_mode) {
9667 if (read_only_mode) {
9668 for (auto &tablespace : m_moved) {
9669 auto old_path = tablespace.old_path;
9670 auto new_path = tablespace.new_path;
9671
9672 /* m_moved might have 2 kinds of files
9673 1. Files which are actually moved to other directory.
9674 2. Files which are moved before upgrade and don't have
9675 DD_TABLE_DATA_DIRECTORY flag updated in DD.
9676
9677 In case of [2], old_path and new_path will be equal.
9678 In read only mode, we shall error out only in case of 1. */
9679 if (old_path != new_path) {
9680 ib::error(ER_IB_MSG_344)
9681 << m_moved.size() << " files have been relocated"
9682 << " and the server has been started in read"
9683 << " only mode. Cannot update the data dictionary.";
9684
9685 return DB_READ_ONLY;
9686 }
9687 }
9688 return DB_SUCCESS;
9689 }
9690
9691 trx_t *trx = check_trx_exists(current_thd);
9692
9693 TrxInInnoDB trx_in_innodb(trx);
9694
9695 /* The transaction should not be active yet, start it */
9696
9697 trx->isolation_level = trx_t::READ_UNCOMMITTED;
9698
9699 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
9700
9701 size_t count = 0;
9702 size_t failed = 0;
9703 size_t batch_size = 0;
9704 bool print_msg = false;
9705 auto start_time = std::chrono::steady_clock::now();
9706
9707 /* If some file paths have changed then update the DD */
9708 for (auto &tablespace : m_moved) {
9709 dberr_t err;
9710
9711 auto old_path = tablespace.old_path;
9712
9713 auto space_name = tablespace.space_name;
9714
9715 auto new_path = tablespace.new_path;
9716
9717 auto object_id = tablespace.object_id;
9718
9719 auto dd_flag_missing = tablespace.dd_flag_missing;
9720
9721 /* We already have the space name in system cs. */
9722 err = dd_tablespace_rename(object_id, true, space_name.c_str(),
9723 new_path.c_str());
9724
9725 if (err != DB_SUCCESS) {
9726 ib::error(ER_IB_MSG_345) << "Unable to update tablespace ID"
9727 << " " << object_id << " "
9728 << " '" << old_path << "' to"
9729 << " '" << new_path << "'";
9730
9731 ++failed;
9732 }
9733
9734 const Fil_path fpath_old{old_path};
9735 const Fil_path fpath_new{new_path};
9736 /* Check whether the path is changed from old_path to new_path
9737 If not, update the data directory flag */
9738 if (Fil_path::has_suffix(IBD, new_path)) {
9739 /* We want to update the dd_table data dir flag for those ibd files which
9740 are moved in this restart and thier current location is different from
9741 where it is originally created. This flag also needs to updated if
9742 dd_flag_missing is true since this flag represents those ibd files moved
9743 in previous versions where fpath_old and fpath_new point to newly moved
9744 location which is different from default data directory path. */
9745 if (dd_flag_missing || !fpath_old.is_dir_same_as(fpath_new)) {
9746 err = dd_update_table_and_partitions_after_dir_change(
9747 object_id, fpath_new.abs_path());
9748
9749 if (err != DB_SUCCESS) {
9750 ib::error(ER_DD_UPDATE_DATADIR_FLAG_FAIL, object_id,
9751 space_name.c_str(), new_path.c_str());
9752
9753 ++failed;
9754 }
9755 }
9756 }
9757
9758 /* Update persistent stat table if table name is modified. */
9759 fil_adjust_partition_stat(old_path, new_path);
9760
9761 ++count;
9762
9763 if (std::chrono::steady_clock::now() - start_time >= PRINT_INTERVAL) {
9764 ib::info(ER_IB_MSG_346) << "Processed " << count << "/" << m_moved.size()
9765 << " tablespace paths. Failures " << failed;
9766
9767 start_time = std::chrono::steady_clock::now();
9768 print_msg = true;
9769 }
9770
9771 ++batch_size;
9772
9773 if (batch_size > 10000) {
9774 innobase_commit_low(trx);
9775
9776 ib::info(ER_IB_MSG_347) << "Committed : " << batch_size;
9777
9778 batch_size = 0;
9779
9780 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
9781 }
9782 }
9783
9784 if (batch_size > 0) {
9785 ib::info(ER_IB_MSG_348) << "Committed : " << batch_size;
9786 }
9787
9788 innobase_commit_low(trx);
9789
9790 if (print_msg) {
9791 ib::info(ER_IB_MSG_349) << "Updated " << count << " tablespace paths"
9792 << ", failures " << failed;
9793 }
9794
9795 return failed == 0 ? DB_SUCCESS : DB_ERROR;
9796 }
9797
9798 /** Free the Tablespace_files instance.
9799 @param[in] read_only_mode true if InnoDB is started in read only mode.
9800 @return DB_SUCCESS if all OK */
9801 dberr_t fil_open_for_business(bool read_only_mode) {
9802 return fil_system->prepare_open_for_business(read_only_mode);
9803 }
9804
9805 /** Replay a file rename operation for ddl replay.
9806 @param[in] page_id Space ID and first page number in the file
9807 @param[in] old_name old file name
9808 @param[in] new_name new file name
9809 @return whether the operation was successfully applied (the name did not
9810 exist, or new_name did not exist and name was successfully renamed to
9811 new_name) */
9812 bool fil_op_replay_rename_for_ddl(const page_id_t &page_id,
9813 const char *old_name, const char *new_name) {
9814 space_id_t space_id = page_id.space();
9815 fil_space_t *space = fil_space_get(space_id);
9816
9817 if (space == nullptr && !fil_system->open_for_recovery(space_id)) {
9818 ib::info(ER_IB_MSG_350)
9819 << "Can not find space with space ID " << space_id
9820 << " when replaying the DDL log "
9821 << "rename from '" << old_name << "' to '" << new_name << "'";
9822
9823 return true;
9824 }
9825
9826 return fil_op_replay_rename(page_id, old_name, new_name);
9827 }
9828
9829 /** Lookup the tablespace ID for recovery and DDL log apply.
9830 @param[in] space_id Tablespace ID to lookup
9831 @return true if the space ID is known. */
9832 bool Fil_system::lookup_for_recovery(space_id_t space_id) {
9833 /* Single threaded code, no need to acquire mutex. */
9834 const bool is_known =
9835 get_scanned_filename_by_space_id(space_id).second != nullptr;
9836
9837 if (recv_recovery_is_on()) {
9838 /* Simple consistency checks */
9839 if (is_known) {
9840 /* It could only be in missing_ids if it was added here earlier,
9841 because get_scanned_filename_by_space_id has not found it. But it
9842 could not be a known space_id now, it would mean something went
9843 quite wrong. */
9844 ut_a(recv_sys->missing_ids.count(space_id) == 0);
9845
9846 /* Every time a space_id is marked deleted, the path
9847 is also removed from m_dirs. */
9848 ut_a(recv_sys->deleted.count(space_id) == 0);
9849 } else {
9850 /* Should belong to exactly one of `deleted` or `missing_ids`, as whenever
9851 adding to deleted we remove from missing_ids, and
9852 we add to missing_ids only if it's not in deleted. */
9853 if (recv_sys->deleted.count(space_id) != 0) {
9854 ut_a(recv_sys->missing_ids.count(space_id) == 0);
9855 } else {
9856 recv_sys->missing_ids.insert(space_id);
9857 }
9858 }
9859 } else {
9860 ut_a(Log_DDL::is_in_recovery());
9861 }
9862
9863 return is_known;
9864 }
9865
9866 /**
9867 Check if a discovered file-per-table .ibd refers to the same file as the
9868 implicit default-path .ibd under @@datadir for this tablespace name.
9869 This makes default-location detection robust against symlinks inside the
9870 datadir tree.
9871 @param[in] space_name Tablespace name
9872 @param[in] discovered_path Full path of the new directory
9873 @return true if both the files are same. */
9874 static bool fil_ibd_same_as_default_path(const char *space_name,
9875 const std::string &discovered_path) {
9876 if (space_name == nullptr || *space_name == '\0') {
9877 return false;
9878 }
9879
9880 if (!Fil_path::has_suffix(IBD, discovered_path)) {
9881 return false;
9882 }
9883
9884 /* Build the implicit default path for this table name under @@datadir. */
9885 char *default_path = Fil_path::make("", space_name, IBD);
9886
9887 if (default_path == nullptr || default_path[0] == '\0') {
9888 return false;
9889 }
9890
9891 Datafile df_default;
9892 Datafile df_found;
9893
9894 df_default.set_filepath(default_path);
9895 df_found.set_filepath(discovered_path.c_str());
9896
9897 if (df_default.open_read_only(false) != DB_SUCCESS) {
9898 return false;
9899 }
9900
9901 if (df_found.open_read_only(false) != DB_SUCCESS) {
9902 df_default.close();
9903 return false;
9904 }
9905
9906 const bool same = df_default.same_as(df_found);
9907
9908 df_found.close();
9909 df_default.close();
9910 ut::free(default_path);
9911
9912 return same;
9913 }
9914
9915 /** Lookup the tablespace ID.
9916 @param[in] space_id Tablespace ID to lookup
9917 @return true if the space ID is known. */
9918 bool fil_tablespace_lookup_for_recovery(space_id_t space_id) {
9919 return fil_system->lookup_for_recovery(space_id);
9920 }
9921
9922 dberr_t Fil_system::open_for_recovery(space_id_t space_id) {
9923 ut_ad(recv_recovery_is_on() || Log_DDL::is_in_recovery());
9924
9925 if (!lookup_for_recovery(space_id)) {
9926 return DB_FAIL;
9927 }
9928
9929 const auto result = get_scanned_filename_by_space_id(space_id);
9930
9931 /* Duplicates should have been sorted out before start of recovery. */
9932 ut_a(result.second->size() == 1);
9933
9934 const auto &filename = result.second->front();
9935 const std::string path = result.first + filename;
9936
9937 fil_space_t *space;
9938
9939 auto status = ibd_open_for_recovery(space_id, path, space);
9940
9941 if (status == FIL_LOAD_DBWLR_CORRUPTION) {
9942 return DB_CORRUPTION;
9943 }
9944
9945 if (status == FIL_LOAD_OK) {
9946 /* In the case of undo tablespace, even if the encryption flag is not
9947 enabled in space->flags, the encryption keys needs to be restored from
9948 recv_sys->keys to the corresponding fil_space_t object. */
9949 const bool is_undo = fsp_is_undo_tablespace(space_id);
9950
9951 if ((FSP_FLAGS_GET_ENCRYPTION(space->flags) || is_undo ||
9952 space->encryption_op_in_progress ==
9953 Encryption::Progress::ENCRYPTION) &&
9954 recv_sys->keys != nullptr) {
9955 fil_tablespace_encryption_init(space);
9956 }
9957
9958 if (!recv_sys->dblwr->empty()) {
9959 recv_sys->dblwr->recover(space);
9960 } else {
9961 ib::info(ER_IB_MSG_DBLWR_1317) << "DBLWR recovery skipped for "
9962 << space->name << " ID: " << space->id;
9963 }
9964
9965 return DB_SUCCESS;
9966 }
9967
9968 return DB_FAIL;
9969 }
9970
9971 dberr_t fil_tablespace_open_for_recovery(space_id_t space_id) {
9972 return fil_system->open_for_recovery(space_id);
9973 }
9974
9975 Fil_state fil_tablespace_path_equals(space_id_t space_id,
9976 const char *space_name, ulint fsp_flags,
9977 std::string old_path,
9978 std::string *new_path) {
9979 ut_a(!recv_recovery_is_on());
9980 ut_ad((fsp_is_ibd_tablespace(space_id) &&
9981 Fil_path::has_suffix(IBD, old_path)) ||
9982 fsp_is_undo_tablespace(space_id));
9983
9984 /* Watch out for implicit undo tablespaces that are created during startup.
9985 They will not be in the list of scanned files. But the DD might need to be
9986 updated if the undo directory is different now from when the database was
9987 initialized. The DD will be updated if we put it in fil_system->moved. */
9988 if (fsp_is_undo_tablespace(space_id)) {
9989 undo::spaces->s_lock();
9990 space_id_t space_num = undo::id2num(space_id);
9991 undo::Tablespace *undo_space = undo::spaces->find(space_num);
9992
9993 if (undo_space != nullptr && undo_space->is_new()) {
9994 *new_path = undo_space->file_name();
9995 Fil_state state = ((old_path.compare(*new_path) == 0) ? Fil_state::MATCHES
9996 : Fil_state::MOVED);
9997 undo::spaces->s_unlock();
9998 return state;
9999 }
10000 undo::spaces->s_unlock();
10001 }
10002
10003 const auto result = fil_system->get_scanned_filename_by_space_id(space_id);
10004
10005 if (result.second == nullptr) {
10006 /* The file was not scanned but the DD has the tablespace. Either;
10007 1. This file is missing
10008 2. The file could not be opened because of encryption or something else,
10009 3. The path is not included in --innodb-directories.
10010 We need to check if the DD path is valid before we tag the file
10011 as missing. */
10012
10013 if (Fil_path::get_file_type(old_path) == OS_FILE_TYPE_FILE) {
10014 /* This file from the DD exists where the DD thinks it is. It will be
10015 opened later. Make some noise if the location is unknown. */
10016 if (!fil_path_is_known(old_path)) {
10017 ib::warn(ER_IB_MSG_UNPROTECTED_LOCATION_ALLOWED, old_path.c_str(),
10018 space_name);
10019 }
10020 return Fil_state::MATCHES;
10021 }
10022
10023 return Fil_state::MISSING;
10024 }
10025
10026 /* While we redo the MLOG_FILE_DELETE in the redo log recovery, we are adding
10027 the space to the deleted list and we remove it from the tablespace_scanning
10028 mapping. A space once deleted, can't be created with the same ID. So we should
10029 never reach here with deleted space. We are running in context of threads of
10030 DD validation. No one is modifying this data in parallel
10031 so it is safe to read it without mutex protection. */
10032 ut_a(recv_sys->deleted.count(space_id) == 0);
10033
10034 /* A file with this space_id was found during scanning.
10035 Validate its location and check if it was moved from where
10036 the DD thinks it is.
10037
10038 Don't compare the full filename, there can be a mismatch if
10039 there was a DDL in progress and we will end up renaming the path
10040 in the DD dictionary. Such renames should be handled by the
10041 atomic DDL "ddl_log". */
10042
10043 std::string old_dir{old_path};
10044
10045 /* Ignore the filename component of the old path. */
10046 auto pos = old_dir.find_last_of(Fil_path::SEPARATOR);
10047 if (pos == std::string::npos) {
10048 old_dir = MySQL_datadir_path;
10049 } else {
10050 old_dir.resize(pos + 1);
10051 ut_ad(Fil_path::is_separator(old_dir.back()));
10052 }
10053 old_dir = Fil_path::get_real_path(old_dir);
10054
10055 /* Build the new path from the scan path and the found path. */
10056 std::string new_dir{result.first};
10057
10058 ut_ad(Fil_path::is_separator(new_dir.back()));
10059
10060 new_dir.append(result.second->front());
10061
10062 new_dir = Fil_path::get_real_path(new_dir);
10063
10064 /* Keep the full file path before we trim it to a directory. */
10065 const std::string new_full_path{new_dir};
10066
10067 /* Do not use a datafile that is in the wrong place. */
10068 if (!Fil_path::is_valid_location(space_name, space_id, fsp_flags, new_dir)) {
10069 return Fil_state::MISSING;
10070 }
10071
10072 /* Ignore the filename component of the new path. */
10073 pos = new_dir.find_last_of(Fil_path::SEPARATOR);
10074
10075 ut_ad(pos != std::string::npos);
10076
10077 new_dir.resize(pos + 1);
10078 bool same_file_as_default_path = false;
10079 /* Only attempt inode matching for file-per-table .ibd (not shared TS). */
10080 if (!fsp_is_shared_tablespace(fsp_flags) &&
10081 Fil_path::has_suffix(IBD, old_path)) {
10082 same_file_as_default_path =
10083 fil_ibd_same_as_default_path(space_name, new_full_path);
10084 }
10085
10086 const bool new_same_as_default = same_file_as_default_path ||
10087 MySQL_datadir_path.is_same_as(new_dir) ||
10088 MySQL_datadir_path.is_ancestor(new_dir);
10089
10090 if (old_dir != new_dir) {
10091 *new_path = result.first + result.second->front();
10092 return Fil_state::MOVED;
10093 } else if (!new_same_as_default && Fil_path::has_suffix(IBD, old_path) &&
10094 !fsp_is_shared_tablespace(fsp_flags)) {
10095 /* We want to recognize those tables which are moved in previous versions
10096 and mark the DD_TABLE_DATA_DIRECTORY flag as true as we need to make sure
10097 dd_table is in sync with current status of the table. This condition is hit
10098 by tables which are moved in previous versions of server
10099 before 8.0.38/8.4.1/9.0. old dir and new dir will be same but different from
10100 default dir. So marking these tables as MOVED_PREV which is referred later
10101 to set the flag. The shared tablespace are ignored becasue they can't have
10102 data directory flag.*/
10103
10104 const auto components = dict_name::parse_tablespace_path(old_path);
10105 if (components.has_value()) {
10106 auto thd = current_thd;
10107 const auto table_info = components.value();
10108 const dd::Table *dd_table = nullptr;
10109 auto &dc = *thd->dd_client();
10110 dd::cache::Dictionary_client::Auto_releaser releaser(&dc);
10111 MDL_ticket *mdl_tkt = nullptr;
10112
10113 /* DD system thread is also one of the worker threads validating the
10114 tablespaces but it doesn't need to take the shared MDL lock on the
10115 table. The tablespaces alloted to each of the worker threads are
10116 distinct.*/
10117 if (!thd->is_dd_system_thread()) {
10118 if (dd::acquire_shared_table_mdl(thd, table_info.schema_name.c_str(),
10119 table_info.table_name.c_str(), true,
10120 &mdl_tkt)) {
10121 return Fil_state::COMPARE_ERROR;
10122 }
10123 }
10124 auto guard = create_scope_guard([&]() {
10125 if (!thd->is_dd_system_thread()) {
10126 dd_release_mdl(mdl_tkt);
10127 }
10128 });
10129
10130 if (dc.acquire<dd::Table>(table_info.schema_name.c_str(),
10131 table_info.table_name.c_str(), &dd_table)) {
10132 return Fil_state::COMPARE_ERROR;
10133 }
10134
10135 /* dd_table may not exist for some system tables */
10136 if (dd_table) {
10137 if (dd_table_is_partitioned(*dd_table)) {
10138 const dd::Partition *part_obj = dd_table->get_leaf_partition(
10139 (!table_info.subpartition.empty()) ? table_info.subpartition
10140 : table_info.partition);
10141 if (!part_obj) {
10142 return Fil_state::COMPARE_ERROR;
10143 }
10144
10145 if (!part_obj->se_private_data().exists(
10146 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY])) {
10147 *new_path = old_path;
10148 return Fil_state::MOVED_PREV;
10149 }
10150 } else {
10151 if (!dd_table->se_private_data().exists(
10152 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY])) {
10153 *new_path = old_path;
10154 return Fil_state::MOVED_PREV;
10155 }
10156 }
10157 }
10158 }
10159 }
10160 *new_path = old_path;
10161 return Fil_state::MATCHES;
10162 }
10163
10164 void fil_add_moved_space(dd::Object_id dd_object_id, space_id_t space_id,
10165 const char *space_name, const std::string &old_path,
10166 const std::string &new_path, bool dd_flag_missing) {
10167 /* Keep space_name in system cs. We handle it while modifying DD. */
10168 fil_system->moved(dd_object_id, space_id, space_name, old_path, new_path,
10169 dd_flag_missing);
10170 }
10171
10172 bool fil_update_partition_name(space_id_t space_id, uint32_t fsp_flags,
10173 bool update_space, std::string &space_name,
10174 std::string &dd_path) {
10175 #ifdef _WIN32
10176 /* Safe check. Never needed on Windows for path. */
10177 if (!update_space) {
10178 return false;
10179 }
10180 #endif /* WIN32 */
10181
10182 /* Never needed in case insensitive file system for path. */
10183 if (!update_space && lower_case_file_system) {
10184 return false;
10185 }
10186
10187 /* Only needed for file per table. */
10188 if (update_space && !fsp_is_file_per_table(space_id, fsp_flags)) {
10189 return false;
10190 }
10191
10192 /* Extract dictionary name schema_name/table_name from dd path. */
10193 std::string table_name;
10194
10195 if (!Fil_path::parse_file_path(dd_path, IBD, table_name)) {
10196 /* Not a valid file-per-table IBD path */
10197 return false;
10198 }
10199 ut_ad(!table_name.empty());
10200
10201 /* Only needed for partition file. */
10202 if (!dict_name::is_partition(table_name)) {
10203 return false;
10204 }
10205
10206 /* Rebuild dictionary name to convert partition names to lower case. */
10207 dict_name::rebuild(table_name);
10208
10209 if (update_space) {
10210 /* Rebuild space name if required. */
10211 dict_name::rebuild_space(table_name, space_name);
10212 }
10213
10214 /* No need to update file name for lower case file system. */
10215 if (lower_case_file_system) {
10216 return false;
10217 }
10218
10219 /* Rebuild path and compare. */
10220 std::string table_path = Fil_path::make_new_path(dd_path, table_name, IBD);
10221 ut_ad(!table_path.empty());
10222
10223 if (dd_path.compare(table_path) != 0) {
10224 /* Validate that the file exists. */
10225 if (os_file_exists(table_path.c_str())) {
10226 dd_path.assign(table_path);
10227 return true;
10228
10229 } else {
10230 ib::warn(ER_IB_WARN_OPEN_PARTITION_FILE, table_path.c_str());
10231 }
10232 }
10233
10234 return false;
10235 }
10236
10237 #endif /* !UNIV_HOTBACKUP */
10238
10239 /** This function should be called after recovery has completed.
10240 Check for tablespace files for which we did not see any MLOG_FILE_DELETE
10241 or MLOG_FILE_RENAME record. These could not be recovered.
10242 @return true if there were some filenames missing for which we had to
10243 ignore redo log records during the apply phase */
10244 bool Fil_system::check_missing_tablespaces() {
10245 bool missing = false;
10246
10247 /* Called in single threaded mode, no need to acquire the mutex. */
10248
10249 recv_sys->dblwr->check_missing_tablespaces();
10250
10251 for (auto space_id : recv_sys->missing_ids) {
10252 /* space_id can't belong to recv_sys->deleted, because whenever we insert
10253 an id into it, we remove it from recv_sys->missing_ids, and we insert into
10254 recv_sys->missing_ids only if it's not in recv_sys->deleted.
10255 No space id should be present in both containers. */
10256 ut_a(recv_sys->deleted.count(space_id) == 0);
10257
10258 const auto result = get_scanned_filename_by_space_id(space_id).second;
10259
10260 if (result == nullptr) {
10261 if (fsp_is_undo_tablespace(space_id)) {
10262 /* This could happen if an undo truncate is in progress because
10263 undo tablespace construction is not redo logged. The DD is updated
10264 at the end and may be out of sync. */
10265 continue;
10266 }
10267
10268 ib::error(ER_IB_MSG_354) << "Could not find any file associated with"
10269 << " the tablespace ID: " << space_id;
10270 missing = true;
10271
10272 } else {
10273 ut_a(!result->empty());
10274 }
10275 }
10276
10277 return missing;
10278 }
10279
10280 /** This function should be called after recovery has completed.
10281 Check for tablespace files for which we did not see any MLOG_FILE_DELETE
10282 or MLOG_FILE_RENAME record. These could not be recovered
10283 @return true if there were some filenames missing for which we had to
10284 ignore redo log records during the apply phase */
10285 bool fil_check_missing_tablespaces() {
10286 return fil_system->check_missing_tablespaces();
10287 }
10288
10289 /** Redo a tablespace create.
10290 @param[in] ptr redo log record
10291 @param[in] end end of the redo log buffer
10292 @param[in] page_id Tablespace Id and first page in file
10293 @param[in] parsed_bytes Number of bytes parsed so far
10294 @param[in] parse_only Don't apply, parse only
10295 @return pointer to next redo log record
10296 @retval nullptr if this log record was truncated */
10297 byte *fil_tablespace_redo_create(byte *ptr, const byte *end,
10298 const page_id_t &page_id, ulint parsed_bytes,
10299 bool parse_only) {
10300 ut_a(page_id.page_no() == 0);
10301
10302 /* We never recreate the system tablespace. */
10303 ut_a(page_id.space() != TRX_SYS_SPACE);
10304
10305 ut_a(parsed_bytes != ULINT_UNDEFINED);
10306
10307 /* Where 6 = flags (uint32_t) + name len (uint16_t). */
10308 if (end <= ptr + 6) {
10309 return nullptr;
10310 }
10311
10312 #ifdef UNIV_HOTBACKUP
10313 uint32_t flags = mach_read_from_4(ptr);
10314 #else
10315 /* Skip the flags, not used here. */
10316 #endif /* UNIV_HOTBACKUP */
10317
10318 ptr += 4;
10319
10320 ulint len = mach_read_from_2(ptr);
10321
10322 ptr += 2;
10323
10324 /* Do we have the full/valid file name. */
10325 if (end < ptr + len || len < 5) {
10326 if (len < 5) {
10327 char name[6];
10328
10329 snprintf(name, sizeof(name), "%.*s", (int)len, ptr);
10330
10331 ib::error(ER_IB_MSG_355) << "MLOG_FILE_CREATE : Invalid file name."
10332 << " Length (" << len << ") must be >= 5"
10333 << " and end in '.ibd'. File name in the"
10334 << " redo log is '" << name << "'";
10335
10336 recv_sys->found_corrupt_log = true;
10337 }
10338
10339 return nullptr;
10340 }
10341
10342 char *name = reinterpret_cast<char *>(ptr);
10343
10344 Fil_path::normalize(name);
10345
10346 ptr += len;
10347
10348 if (!(Fil_path::has_suffix(IBD, name) ||
10349 fsp_is_undo_tablespace(page_id.space()))) {
10350 recv_sys->found_corrupt_log = true;
10351
10352 return nullptr;
10353 }
10354
10355 if (parse_only) {
10356 return ptr;
10357 }
10358 #ifdef UNIV_HOTBACKUP
10359
10360 meb_tablespace_redo_create(page_id, flags, name);
10361
10362 #else /* !UNIV_HOTBACKUP */
10363
10364 const auto result =
10365 fil_system->get_scanned_filename_by_space_id(page_id.space());
10366
10367 if (result.second == nullptr) {
10368 /* No file maps to this tablespace ID. It's possible that
10369 the file was deleted later or is missing. */
10370
10371 return ptr;
10372 }
10373
10374 /* Update filename with correct partition case, if needed. */
10375 std::string name_str(name);
10376 std::string space_name;
10377 fil_update_partition_name(page_id.space(), 0, false, space_name, name_str);
10378
10379 auto abs_name = Fil_path::get_real_path(name_str);
10380
10381 /* Duplicates should have been sorted out before we get here. */
10382 ut_a(result.second->size() == 1);
10383
10384 /* It's possible that the tablespace file was renamed later. */
10385 if (result.second->front().compare(abs_name) == 0) {
10386 dberr_t success = fil_tablespace_open_for_recovery(page_id.space());
10387
10388 if (success != DB_SUCCESS) {
10389 ib::info(ER_IB_MSG_356) << "Create '" << abs_name << "' failed!";
10390 }
10391 }
10392 #endif /* UNIV_HOTBACKUP */
10393
10394 return ptr;
10395 }
10396
10397 byte *fil_tablespace_redo_rename(byte *ptr, const byte *end,
10398 const page_id_t &page_id, ulint parsed_bytes,
10399 bool parse_only [[maybe_unused]]) {
10400 ut_a(page_id.page_no() == 0);
10401
10402 /* We never recreate the system tablespace. */
10403 ut_a(page_id.space() != TRX_SYS_SPACE);
10404
10405 ut_a(parsed_bytes != ULINT_UNDEFINED);
10406
10407 /* Where 2 = from name len (uint16_t). */
10408 if (end <= ptr + 2) {
10409 return nullptr;
10410 }
10411
10412 /* Read and check the RENAME FROM_NAME. */
10413 ulint from_len = mach_read_from_2(ptr);
10414 ptr += 2;
10415 char *from_name = reinterpret_cast<char *>(ptr);
10416
10417 /* Check if the 'from' file name is valid. */
10418 if (end < ptr + from_len) {
10419 return nullptr;
10420 }
10421
10422 std::string whats_wrong;
10423 constexpr char more_than_five[] = "The length must be >= 5.";
10424 constexpr char end_with_ibd[] = "The file suffix must be '.ibd'.";
10425 if (from_len < 5) {
10426 recv_sys->found_corrupt_log = true;
10427 whats_wrong.assign(more_than_five);
10428 } else {
10429 std::string name{from_name};
10430
10431 if (!Fil_path::has_suffix(IBD, name)) {
10432 recv_sys->found_corrupt_log = true;
10433 whats_wrong.assign(end_with_ibd);
10434 }
10435 }
10436
10437 if (recv_sys->found_corrupt_log) {
10438 ib::info(ER_IB_MSG_357) << "MLOG_FILE_RENAME: Invalid {from} file name: '"
10439 << from_name << "'. " << whats_wrong;
10440
10441 return nullptr;
10442 }
10443
10444 ptr += from_len;
10445 Fil_path::normalize(from_name);
10446
10447 /* Read and check the RENAME TO_NAME. */
10448 ulint to_len = mach_read_from_2(ptr);
10449 ptr += 2;
10450 char *to_name = reinterpret_cast<char *>(ptr);
10451
10452 /* Check if the 'to' file name is valid. */
10453 if (end < ptr + to_len) {
10454 return nullptr;
10455 }
10456
10457 if (to_len < 5) {
10458 recv_sys->found_corrupt_log = true;
10459 whats_wrong.assign(more_than_five);
10460 } else {
10461 std::string name{to_name};
10462
10463 if (!Fil_path::has_suffix(IBD, name)) {
10464 recv_sys->found_corrupt_log = true;
10465 whats_wrong.assign(end_with_ibd);
10466 }
10467 }
10468
10469 if (recv_sys->found_corrupt_log) {
10470 ib::info(ER_IB_MSG_357) << "MLOG_FILE_RENAME: Invalid {to} file name: '"
10471 << to_name << "'. " << whats_wrong;
10472
10473 return nullptr;
10474 }
10475
10476 ptr += to_len;
10477 Fil_path::normalize(to_name);
10478
10479 #ifdef UNIV_HOTBACKUP
10480
10481 if (!parse_only) {
10482 meb_tablespace_redo_rename(page_id, from_name, to_name);
10483 }
10484
10485 #else /* !UNIV_HOTBACKUP */
10486
10487 /* Update filename with correct partition case, if needed. */
10488 std::string to_name_str(to_name);
10489 std::string space_name;
10490 fil_update_partition_name(page_id.space(), 0, false, space_name, to_name_str);
10491
10492 if (from_len == to_len && strncmp(to_name, from_name, to_len) == 0) {
10493 ib::error(ER_IB_MSG_360)
10494 << "MLOG_FILE_RENAME: The from and to name are the"
10495 << " same: '" << from_name << "', '" << to_name << "'";
10496
10497 recv_sys->found_corrupt_log = true;
10498
10499 return nullptr;
10500 }
10501
10502 #endif /* UNIV_HOTBACKUP */
10503
10504 return ptr;
10505 }
10506
10507 byte *fil_tablespace_redo_extend(byte *ptr, const byte *end,
10508 const page_id_t &page_id, ulint parsed_bytes,
10509 bool parse_only) {
10510 ut_a(page_id.page_no() == 0);
10511 ut_a(parsed_bytes != ULINT_UNDEFINED);
10512
10513 /* Check for valid offset and size values */
10514 if (end < ptr + 16) {
10515 return nullptr;
10516 }
10517
10518 /* Offset within the file to start writing zeros */
10519 os_offset_t offset = mach_read_from_8(ptr);
10520 ptr += 8;
10521
10522 /* Size of the space which needs to be initialized by
10523 writing zeros */
10524 os_offset_t size = mach_read_from_8(ptr);
10525 ptr += 8;
10526
10527 if (size == 0) {
10528 ib::error(ER_IB_MSG_INCORRECT_SIZE)
10529 << "MLOG_FILE_EXTEND: Incorrect value for size encountered."
10530 << "Redo log corruption found.";
10531 recv_sys->found_corrupt_log = true;
10532 return nullptr;
10533 }
10534
10535 if (parse_only) {
10536 return ptr;
10537 }
10538
10539 #ifndef UNIV_HOTBACKUP
10540 dberr_t err = DB_SUCCESS;
10541 if (page_id.space() == TRX_SYS_SPACE) {
10542 /* System tablespace must have been loaded in the fil system at the time
10543 of server start up. Tablespace scanning of the fil system doesn't expect to
10544 be probed for the system tablespace. */
10545 ut_a(fil_space_t::s_sys_space);
10546 } else {
10547 const auto result =
10548 fil_system->get_scanned_filename_by_space_id(page_id.space());
10549
10550 if (result.second == nullptr) {
10551 /* No files found for this tablespace ID. It's possible that the
10552 files were deleted later. */
10553 return ptr;
10554 }
10555
10556 err = fil_tablespace_open_for_recovery(page_id.space());
10557
10558 if (err != DB_SUCCESS) {
10559 /* fil_tablespace_open_for_recovery may fail if the tablespace being
10560 opened is an undo tablespace which is also marked for truncation.
10561 In such a case, skip processing this redo log further and goto the
10562 next record without doing anything more here. */
10563 if (fsp_is_undo_tablespace(page_id.space()) &&
10564 undo::is_active_truncate_log_present(undo::id2num(page_id.space()))) {
10565 return ptr;
10566 }
10567 return nullptr;
10568 }
10569
10570 /* Open the space */
10571 bool success = fil_space_open(page_id.space());
10572
10573 if (!success) {
10574 return nullptr;
10575 }
10576 }
10577
10578 fil_space_t *space = fil_space_get(page_id.space());
10579
10580 ut_a(space != nullptr);
10581 ut_a(!space->files.empty());
10582
10583 /* Space extension operations on temporary tablespaces
10584 are not redo logged as they are always recreated on
10585 server startup. */
10586 ut_a(space->purpose != FIL_TYPE_TEMPORARY);
10587
10588 fil_node_t *file = &space->files.back();
10589
10590 ut_a(file != nullptr);
10591
10592 page_size_t page_size(space->flags);
10593
10594 size_t phy_page_size = page_size.physical();
10595
10596 /* No one else should be extending this file. */
10597 ut_a(!file->is_being_extended);
10598
10599 ut_a(offset > 0);
10600 os_offset_t initial_fsize = os_file_get_size(file->handle);
10601 ut_a(offset <= initial_fsize);
10602 /* file->size unit is FSP_EXTENT_SIZE.
10603 Disk-full might cause partial FSP_EXTENT_SIZE extension. */
10604 ut_a(initial_fsize / (phy_page_size * FSP_EXTENT_SIZE) ==
10605 file->size / FSP_EXTENT_SIZE);
10606
10607 /* Because punch_hole flush might recover disk-full situation.
10608 We might be able to extend from the partial extension at the
10609 previous disk-full. So, offset might not be at boundary.
10610 But target is aligned to the page boundary */
10611 ut_a(((offset + size) % phy_page_size) == 0);
10612
10613 /* If the physical size of the file is greater than or equal to the
10614 expected size (offset + size), it means that posix_fallocate was
10615 successfully executed.
10616 However, if the redo log record requests an expected size (offset + size)
10617 which is more than the physical size of the file, it means that
10618 posix_fallocate() either allocated partially (in case of emulated
10619 posix_fallocate) or did not allocate at all. In case posix_fallocate()
10620 fails, the server calls fil_write_zeros to extend the space, which
10621 can also fail after allocating space partially because of reasons like
10622 lack of disk space. The real indicator of how much file was actually
10623 allocated is the physical file size itself.
10624 Write out the 0's in the extended space only if the physical size of
10625 the file is less than the expected size (offset + size). */
10626
10627 /* If the file is already equal or larger than the expected size,
10628 nothing more to do here. */
10629 if ((offset + size) <= initial_fsize) {
10630 return ptr;
10631 }
10632
10633 #if defined(UNIV_DEBUG)
10634 /* Validate that there are no pages in the buffer pool. */
10635 buf_assert_all_are_replaceable();
10636 #endif /* UNIV_DEBUG */
10637
10638 /* Adjust the actual allocation size to take care of the allocation
10639 problems described above.
10640 Find out the size by which the file should be extended to have
10641 a file of expected size while ensuring that the already allocated
10642 pages are not overwritten with zeros. */
10643 os_offset_t new_ext_size = size - (initial_fsize - offset);
10644
10645 /* Initialize the region starting from current end of file with zeros. */
10646 err = fil_write_zeros(file, phy_page_size, initial_fsize, new_ext_size);
10647
10648 if (err != DB_SUCCESS) {
10649 /* Error writing zeros to the file. */
10650 ib::warn(ER_IB_MSG_320) << "Error while writing " << size << " zeroes to "
10651 << file->name << " starting at offset " << offset;
10652 /* Should return normally. If "return nullptr", it means "broken log"
10653 and will skip to apply the all of following logs. */
10654 }
10655
10656 /* Get the final size of the file and adjust file->size accordingly. */
10657 os_offset_t end_fsize = os_file_get_size(file->handle);
10658
10659 auto shard = fil_system->shard_by_id(page_id.space());
10660 shard->mutex_acquire();
10661
10662 file->size = end_fsize / phy_page_size;
10663 space->size = file->size;
10664
10665 shard->space_flush(page_id.space());
10666 shard->mutex_release();
10667
10668 fil_space_close(space->id);
10669 #endif /* !UNIV_HOTBACKUP */
10670
10671 return ptr;
10672 }
10673
10674 /** Redo a tablespace delete.
10675 @param[in] ptr redo log record
10676 @param[in] end end of the redo log buffer
10677 @param[in] page_id Tablespace Id and first page in file
10678 @param[in] parsed_bytes Number of bytes parsed so far
10679 @param[in] parse_only Don't apply, parse only
10680 @return pointer to next redo log record
10681 @retval nullptr if this log record was truncated */
10682 byte *fil_tablespace_redo_delete(byte *ptr, const byte *end,
10683 const page_id_t &page_id, ulint parsed_bytes,
10684 bool parse_only) {
10685 ut_a(page_id.page_no() == 0);
10686
10687 /* We never recreate the system tablespace. */
10688 ut_a(page_id.space() != TRX_SYS_SPACE);
10689
10690 ut_a(parsed_bytes != ULINT_UNDEFINED);
10691
10692 /* Where 2 = len (uint16_t). */
10693 if (end <= ptr + 2) {
10694 return nullptr;
10695 }
10696
10697 ulint len = mach_read_from_2(ptr);
10698
10699 ptr += 2;
10700
10701 /* Do we have the full/valid file name. */
10702 if (end < ptr + len || len < 5) {
10703 if (len < 5) {
10704 char name[6];
10705
10706 snprintf(name, sizeof(name), "%.*s", (int)len, ptr);
10707
10708 ib::error(ER_IB_MSG_362) << "MLOG_FILE_DELETE : Invalid file name."
10709 << " Length (" << len << ") must be >= 5"
10710 << " and end in '.ibd'. File name in the"
10711 << " redo log is '" << name << "'";
10712 }
10713
10714 return nullptr;
10715 }
10716
10717 char *name = reinterpret_cast<char *>(ptr);
10718
10719 Fil_path::normalize(name);
10720
10721 ptr += len;
10722
10723 if (!(Fil_path::has_suffix(IBD, name) ||
10724 fsp_is_undo_tablespace(page_id.space()))) {
10725 recv_sys->found_corrupt_log = true;
10726
10727 return nullptr;
10728 }
10729
10730 if (parse_only) {
10731 return ptr;
10732 }
10733 #ifdef UNIV_HOTBACKUP
10734
10735 meb_tablespace_redo_delete(page_id, name);
10736
10737 #else /* !UNIV_HOTBACKUP */
10738
10739 const auto result =
10740 fil_system->get_scanned_filename_by_space_id(page_id.space());
10741
10742 recv_sys->deleted.insert(page_id.space());
10743 recv_sys->missing_ids.erase(page_id.space());
10744
10745 if (result.second == nullptr) {
10746 /* No files map to this tablespace ID. The drop must
10747 have succeeded. */
10748
10749 return ptr;
10750 }
10751
10752 /* Space_id_set should have been sorted out before we get here. */
10753
10754 ut_a(result.second->size() == 1);
10755
10756 /* Update filename with correct partition case, if needed. */
10757 std::string name_str(name);
10758 std::string space_name;
10759 fil_update_partition_name(page_id.space(), 0, false, space_name, name_str);
10760
10761 fil_space_free(page_id.space(), false);
10762
10763 bool success = fil_system->erase_path(page_id.space());
10764 ut_a(success);
10765 #endif /* UNIV_HOTBACKUP */
10766
10767 return ptr;
10768 }
10769
10770 byte *fil_tablespace_redo_encryption(byte *ptr, const byte *end,
10771 space_id_t space_id, lsn_t lsn) {
10772 fil_space_t *space = fil_space_get(space_id);
10773
10774 /* An undo space might be open but not have the ENCRYPTION bit set
10775 in its header if the current value of innodb_undo_log_encrypt=OFF
10776 and a crash occurred between flushing this redo record and the header
10777 page of the undo space. So if the flag is missing, ignore the header
10778 page. */
10779 if (fsp_is_undo_tablespace(space_id) && space != nullptr &&
10780 !FSP_FLAGS_GET_ENCRYPTION(space->flags)) {
10781 space = nullptr;
10782 }
10783
10784 ulint offset = mach_read_from_2(ptr);
10785 ptr += 2;
10786
10787 const ulint len = mach_read_from_2(ptr);
10788 ptr += 2;
10789
10790 if (end < ptr + len) {
10791 return (nullptr);
10792 }
10793
10794 if (offset >= UNIV_PAGE_SIZE || len + offset > UNIV_PAGE_SIZE ||
10795 len != Encryption::INFO_SIZE) {
10796 recv_sys->found_corrupt_log = true;
10797 return (nullptr);
10798 }
10799
10800 byte *encryption_ptr = ptr;
10801 ptr += len;
10802
10803 /* If space is already loaded and have header_page_flushed_lsn greater than
10804 this REDO entry LSN, then skip it coz header has latest information. */
10805 if (space != nullptr && space->m_header_page_flush_lsn > lsn) {
10806 return (ptr);
10807 }
10808
10809 /* If encryption info is 0 filled, then this is erasing encryption info
10810 during unencryption operation. Skip decrypting it. */
10811 {
10812 byte buf[Encryption::INFO_SIZE] = {0};
10813
10814 if (memcmp(encryption_ptr + 4, buf, Encryption::INFO_SIZE - 4) == 0) {
10815 /* NOTE: We don't need to reset encryption info of space here because it
10816 might be needed. It will be reset when this REDO record is applied. */
10817 return (ptr);
10818 }
10819 }
10820
10821 byte iv[Encryption::KEY_LEN] = {0};
10822 byte key[Encryption::KEY_LEN] = {0};
10823
10824 Encryption_key e_key{key, iv};
10825 if (!Encryption::decode_encryption_info(space_id, e_key, encryption_ptr,
10826 true)) {
10827 recv_sys->found_corrupt_log = true;
10828
10829 ib::warn(ER_IB_MSG_364)
10830 << "Encryption information"
10831 << " in the redo log of space " << space_id << " is invalid";
10832
10833 return (nullptr);
10834 }
10835
10836 ut_ad(len == Encryption::INFO_SIZE);
10837
10838 if (space != nullptr) {
10839 Encryption::set_or_generate(Encryption::AES, key, iv,
10840 space->m_encryption_metadata);
10841 fsp_flags_set_encryption(space->flags);
10842 return ptr;
10843 }
10844
10845 /* Space is not loaded yet. Remember this key in recv_sys and use it later
10846 to pupulate space encryption info once it is loaded. */
10847 DBUG_EXECUTE_IF("dont_update_key_found_during_REDO_scan", return ptr;);
10848
10849 if (recv_sys->keys == nullptr) {
10850 recv_sys->keys =
10851 ut::new_withkey<recv_sys_t::Encryption_Keys>(UT_NEW_THIS_FILE_PSI_KEY);
10852 }
10853
10854 /* Search if key entry already exists for this tablespace, update it. */
10855 for (auto &recv_key : *recv_sys->keys) {
10856 if (recv_key.space_id == space_id) {
10857 memcpy(recv_key.iv, iv, Encryption::KEY_LEN);
10858 memcpy(recv_key.ptr, key, Encryption::KEY_LEN);
10859 recv_key.lsn = lsn;
10860 return ptr;
10861 }
10862 }
10863
10864 /* No existing entry found, create new one and insert it. */
10865 recv_sys_t::Encryption_Key new_key;
10866 new_key.iv = static_cast<byte *>(
10867 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, Encryption::KEY_LEN));
10868 memcpy(new_key.iv, iv, Encryption::KEY_LEN);
10869 new_key.ptr = static_cast<byte *>(
10870 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, Encryption::KEY_LEN));
10871 memcpy(new_key.ptr, key, Encryption::KEY_LEN);
10872 new_key.space_id = space_id;
10873 new_key.lsn = lsn;
10874 recv_sys->keys->push_back(new_key);
10875
10876 return ptr;
10877 }
10878
10879 void Tablespace_dirs::warn_ignore(std::string ignore_path, const char *reason) {
10880 ib::warn(ER_IB_MSG_IGNORE_SCAN_PATH, ignore_path.c_str(), reason);
10881 }
10882
10883 void Tablespace_dirs::add_path(const std::string &path_in, bool is_undo_dir) {
10884 /* Ignore an invalid path. */
10885 if (path_in == "") {
10886 return;
10887 }
10888 if (path_in == "/") {
10889 warn_ignore(path_in,
10890 "the root directory '/' is not allowed to be scanned.");
10891 return;
10892 }
10893 if (std::string::npos != path_in.find('*')) {
10894 warn_ignore(path_in, "it contains '*'.");
10895 return;
10896 }
10897
10898 /* Assume this path is a directory and put a trailing slash on it. */
10899 std::string dir_in(path_in);
10900 Fil_path::append_separator(dir_in);
10901
10902 Fil_path found_path(dir_in, true);
10903
10904 /* Exclude this path if it is a duplicate of a path already stored or
10905 if a previously stored path is an ancestor. Remove any previously stored
10906 path that is a descendant of this path. */
10907 for (auto it = m_dirs.cbegin(); it != m_dirs.cend(); /* No op */) {
10908 if (it->root().is_same_as(found_path)) {
10909 /* The exact same path is obviously ignored, so there is no need to
10910 log a warning. */
10911 return;
10912 }
10913
10914 /* Check if dir_abs_path is an ancestor of this path */
10915 if (it->root().is_ancestor(found_path)) {
10916 /* Descendant directories will be scanned recursively, so don't
10917 add it to the scan list. Log a warning unless this descendant
10918 is the undo directory since it must be supplied even if it is
10919 a descendant of another data location. */
10920 if (!is_undo_dir) {
10921 std::string reason = "it is a sub-directory of '";
10922 reason += it->root().abs_path();
10923 warn_ignore(path_in, reason.c_str());
10924 }
10925 return;
10926 }
10927
10928 if (found_path.is_ancestor(it->root())) {
10929 /* This path is an ancestor of an existing dir in fil_system::m_dirs.
10930 The settings have overlapping locations. Put a note about it to
10931 the error log. The undo_dir is added last, so if it is an ancestor,
10932 the descendant was listed as a datafile directory. So always issue
10933 this message*/
10934 std::string reason = "it is a sub-directory of '";
10935 reason += found_path;
10936 warn_ignore(it->root().path(), reason.c_str());
10937
10938 /* It might also be an ancestor to another dir as well, so keep looking.
10939 We must delete this descendant because we know that this ancestor path
10940 will be inserted and all its descendants will be scanned. */
10941 it = m_dirs.erase(it);
10942 } else {
10943 it++;
10944 }
10945 }
10946
10947 m_dirs.push_back(Tablespace_files{found_path.path()});
10948 return;
10949 }
10950
10951 void Tablespace_dirs::add_paths(const std::string &str,
10952 const std::string &delimiters) {
10953 std::string::size_type start = 0;
10954 std::string::size_type end = 0;
10955
10956 /* Scan until 'start' reaches the end of the string (npos) */
10957 for (;;) {
10958 start = str.find_first_not_of(delimiters, end);
10959 if (std::string::npos == start) {
10960 break;
10961 }
10962
10963 end = str.find_first_of(delimiters, start);
10964
10965 const auto path = str.substr(start, end - start);
10966
10967 add_path(path);
10968 }
10969 }
10970
10971 /** Check whether we can rename the file
10972 @param[in] space Tablespace for which to rename
10973 @param[in] name Source file name
10974 @param[in] df Target file that exists on disk
10975 @return DB_SUCCESS if all OK */
10976 static dberr_t fil_rename_validate(fil_space_t *space, const std::string &name,
10977 Datafile &&df) {
10978 dberr_t err = df.validate_for_recovery(space->id);
10979 /* The validate_for_recovery will set space_id, but will close the file. It is
10980 safe to access filepath and space_id. */
10981
10982 if (err == DB_TABLESPACE_NOT_FOUND) {
10983 /* Tablespace header doesn't contain the expected
10984 tablespace ID. This is can happen during truncate. */
10985
10986 return err;
10987
10988 } else if (err != DB_SUCCESS) {
10989 ib::warn(ER_IB_MSG_367) << "Failed to read the first page of the"
10990 << " file '" << df.filepath() << "'."
10991 << " You will need to verify and move the"
10992 << " file out of the way retry recovery.";
10993
10994 return err;
10995 }
10996
10997 auto file = &space->files.front();
10998
10999 if (strcmp(df.filepath(), file->name) == 0) {
11000 /* Check if already points to the correct file.
11001 Must have the same space ID */
11002
11003 ib::info(ER_IB_MSG_368) << "Tablespace ID already maps to: '"
11004 << df.filepath() << "', rename ignored.";
11005
11006 ut_a(df.space_id() == space->id);
11007
11008 return DB_SUCCESS;
11009
11010 } else if (df.space_id() != space->id) {
11011 /* Target file exists on disk but has a different
11012 tablespace ID. The user should manually delete it. */
11013
11014 ib::error(ER_IB_MSG_369)
11015 << "Cannot rename '" << name << "' to '" << df.filepath() << "'. File '"
11016 << df.filepath() << "' tablespace ID " << df.space_id()
11017 << " doesn't match the expected tablespace"
11018 << " ID " << space->id << ". You will need to verify and move '"
11019 << df.filepath() << "' manually and retry recovery!";
11020
11021 return DB_ERROR;
11022 }
11023
11024 /* Target file exists on disk and has the same ID. */
11025
11026 ib::error(ER_IB_MSG_370)
11027 << "Cannot rename '" << name << "' to '" << df.filepath()
11028 << "'. The File '" << df.filepath() << " already exists on"
11029 << " disk. You will need to verify and move either file"
11030 << " manually and retry recovery!";
11031
11032 return DB_ERROR;
11033 }
11034
11035 /** Replay a file rename operation if possible.
11036 @param[in] page_id Space ID and first page number in the file
11037 @param[in] old_name old file name
11038 @param[in] new_name new file name
11039 @return whether the operation was successfully applied (the name did not exist,
11040 or new_name did not exist and name was successfully renamed to new_name) */
11041 static bool fil_op_replay_rename(const page_id_t &page_id,
11042 const std::string &old_name,
11043 const std::string &new_name) {
11044 ut_ad(page_id.page_no() == 0);
11045 ut_ad(old_name.compare(new_name) != 0);
11046 ut_ad(Fil_path::has_suffix(IBD, new_name));
11047 ut_ad(page_id.space() != TRX_SYS_SPACE);
11048
11049 /* In order to replay the rename, the following must hold:
11050 1. The new name is not already used.
11051 2. A tablespace exists with the old name.
11052 3. The space ID for that tablespace matches this log entry.
11053 This will prevent unintended renames during recovery. */
11054
11055 space_id_t space_id = page_id.space();
11056 fil_space_t *space = fil_space_get(space_id);
11057
11058 if (space == nullptr) {
11059 return true;
11060 }
11061
11062 std::string name{new_name};
11063 {
11064 Datafile df;
11065
11066 df.set_filepath(name.c_str());
11067
11068 if (df.open_read_only(false) == DB_SUCCESS) {
11069 dberr_t err = fil_rename_validate(space, old_name, std::move(df));
11070
11071 if (err == DB_TABLESPACE_NOT_FOUND) {
11072 /* This can happen during truncate. */
11073 ib::info(ER_IB_MSG_371) << "Tablespace ID mismatch in '" << name << "'";
11074 }
11075 return (err == DB_SUCCESS);
11076 }
11077 }
11078
11079 auto path_sep_pos = name.find_last_of(Fil_path::SEPARATOR);
11080
11081 ut_a(path_sep_pos != std::string::npos);
11082
11083 /* Create the database directory for the new name, if
11084 it does not exist yet */
11085
11086 name.resize(path_sep_pos);
11087
11088 bool success = os_file_create_directory(name.c_str(), false);
11089 ut_a(success);
11090
11091 auto datadir_pos = name.find_last_of(Fil_path::SEPARATOR);
11092
11093 ut_ad(datadir_pos != std::string::npos);
11094
11095 name.erase(0, datadir_pos + 1);
11096
11097 ut_ad(!Fil_path::is_separator(name.back()));
11098
11099 /* schema/table separator is always a '/'. */
11100 name.push_back('/');
11101
11102 /* Strip the '.ibd' suffix. */
11103 name.append(new_name.begin() + path_sep_pos + 1, new_name.end() - 4);
11104
11105 ut_ad(!Fil_path::has_suffix(IBD, name));
11106
11107 const auto ptr = name.c_str();
11108
11109 dberr_t err =
11110 fil_rename_tablespace(space_id, old_name.c_str(), ptr, new_name.c_str());
11111
11112 /* Stop recovery if this does not succeed. */
11113 ut_a(err == DB_SUCCESS);
11114
11115 return true;
11116 }
11117
11118 space_id_t Fil_system::get_tablespace_id(const std::string &filename) {
11119 pfs_os_file_t file;
11120 bool success;
11121
11122 /* Lambda function for heavy-duty method of finding the space id from
11123 Datafile::find_space_id() which we fallback into, if the first page
11124 cannot be read properly. */
11125 const auto find_space_id_reliably = [&filename]() -> space_id_t {
11126 Datafile data_file;
11127
11128 data_file.set_filepath(filename.c_str());
11129 const dberr_t err = data_file.open_read_only(false);
11130
11131 ut_a(data_file.is_open());
11132 ut_a(err == DB_SUCCESS);
11133
11134 /* Use the heavier Datafile::find_space_id() method to find the space id. */
11135 return (data_file.find_space_id() == DB_SUCCESS)
11136 ? data_file.space_id()
11137 : dict_sys_t::s_invalid_space_id;
11138 };
11139
11140 /* Open the file with O_DIRECT flag for faster access */
11141 file = os_file_create(innodb_data_file_key, filename.c_str(), OS_FILE_OPEN,
11142 OS_DATA_FILE_FOR_SPACE_ID_READ, true, &success);
11143 if (!success) {
11144 os_file_get_last_error(true);
11145 ib::warn(ER_IB_MSG_372) << "Unable to open '" << filename << "'";
11146 return dict_sys_t::s_invalid_space_id;
11147 }
11148
11149 space_id_t space_id = dict_sys_t::s_invalid_space_id;
11150
11151 auto buf = ut::make_unique_aligned<byte[]>(srv_page_size, srv_page_size);
11152
11153 IORequest request(IORequest::READ);
11154 ulint bytes_read = 0;
11155 /* Disable the warning if we try to read compressed tablespace which has
11156 data less than the read size i.e., srv_page_size */
11157 request.disable_partial_io_warnings();
11158
11159 dberr_t err =
11160 os_file_read_no_error_handling(request, filename.c_str(), file, buf.get(),
11161 0, srv_page_size, &bytes_read);
11162
11163 os_file_close(file);
11164
11165 DBUG_EXECUTE_IF("invalid_header", bytes_read = 0;);
11166
11167 if (err != DB_SUCCESS || (bytes_read != srv_page_size)) {
11168 /* Reading from the first page failed, falling back to heavy duty method */
11169 return find_space_id_reliably();
11170 }
11171
11172 /* Read the space_id from buf at offset FIL_PAGE_SPACE_ID */
11173 space_id = fsp_header_get_space_id(buf.get());
11174
11175 if (space_id == 0 || space_id == SPACE_UNKNOWN) {
11176 return find_space_id_reliably();
11177 }
11178
11179 return space_id;
11180 }
11181
11182 void Fil_system::rename_partition_files(bool revert) {
11183 #ifndef UNIV_HOTBACKUP
11184 /* If revert, then we are downgrading after upgrade failure from 5.7 */
11185 ut_ad(!revert || srv_downgrade_partition_files);
11186
11187 if (m_old_paths.empty()) {
11188 return;
11189 }
11190
11191 ut_ad(!lower_case_file_system);
11192
11193 for (auto &old_path : m_old_paths) {
11194 ut_ad(Fil_path::has_suffix(IBD, old_path));
11195 ut_ad(dict_name::is_partition(old_path));
11196
11197 fil_rename_partition_file(old_path, IBD, revert, false);
11198 }
11199 #endif /* !UNIV_HOTBACKUP */
11200 }
11201
11202 void Tablespace_dirs::duplicate_check(const Const_iter &start,
11203 const Const_iter &end, size_t thread_id,
11204 std::mutex *mutex, Space_id_set *unique,
11205 Space_id_set *duplicates) {
11206 size_t count = 0;
11207 bool printed_msg = false;
11208 auto start_time = std::chrono::steady_clock::now();
11209
11210 for (auto it = start; it != end; ++it, ++m_checked) {
11211 const std::string filename = it->second;
11212 auto &files = m_dirs[it->first];
11213 const std::string phy_filename = files.path() + filename;
11214
11215 space_id_t space_id;
11216
11217 space_id = Fil_system::get_tablespace_id(phy_filename);
11218
11219 if (space_id != 0 && space_id != dict_sys_t::s_invalid_space_id) {
11220 std::lock_guard<std::mutex> guard(*mutex);
11221
11222 auto ret = unique->insert(space_id);
11223
11224 size_t n_files;
11225
11226 n_files = files.add(space_id, filename);
11227
11228 if (n_files > 1 || !ret.second) {
11229 duplicates->insert(space_id);
11230 }
11231
11232 } else if (space_id != 0 &&
11233 Fil_path::is_undo_tablespace_name(phy_filename)) {
11234 ib::info(ER_IB_MSG_373) << "Can't determine the undo file tablespace"
11235 << " ID for '" << phy_filename << "', could be"
11236 << " an undo truncate in progress";
11237
11238 } else {
11239 ib::info(ER_IB_MSG_374) << "Ignoring '" << phy_filename << "' invalid"
11240 << " tablespace ID in the header";
11241 }
11242
11243 ++count;
11244
11245 if (std::chrono::steady_clock::now() - start_time >= PRINT_INTERVAL) {
11246 ib::info(ER_IB_MSG_375) << "Thread# " << thread_id << " - Checked "
11247 << count << "/" << (end - start) << " files";
11248
11249 start_time = std::chrono::steady_clock::now();
11250
11251 printed_msg = true;
11252 }
11253 }
11254
11255 if (printed_msg) {
11256 ib::info(ER_IB_MSG_376) << "Checked " << count << " files";
11257 }
11258 }
11259
11260 /** Print the duplicate filenames for a tablespce ID to the log
11261 @param[in] duplicates Duplicate tablespace IDs*/
11262 void Tablespace_dirs::print_duplicates(const Space_id_set &duplicates) {
11263 /* Print the duplicate names to the error log. */
11264 for (auto space_id : duplicates) {
11265 Dirs files;
11266
11267 for (auto &dir : m_dirs) {
11268 const auto names = dir.find_by_id(space_id);
11269
11270 if (names == nullptr) {
11271 continue;
11272 }
11273
11274 files.insert(files.end(), names->begin(), names->end());
11275 }
11276
11277 /* Fixes the order in the mtr tests. */
11278 std::sort(files.begin(), files.end());
11279
11280 ut_a(files.size() > 1);
11281
11282 std::ostringstream oss;
11283
11284 oss << "Tablespace ID: " << space_id << " = [";
11285
11286 for (size_t i = 0; i < files.size(); ++i) {
11287 oss << "'" << files[i] << "'";
11288
11289 if (i < files.size() - 1) {
11290 oss << ", ";
11291 }
11292 }
11293
11294 oss << "]" << std::endl;
11295
11296 ib::error(ER_IB_MSG_377) << oss.str();
11297 }
11298 }
11299
11300 static bool fil_get_partition_file(const std::string &old_path [[maybe_unused]],
11301 ib_file_suffix extn [[maybe_unused]],
11302 std::string &new_path [[maybe_unused]]) {
11303 /* Safe check. Never needed on Windows. */
11304 #ifdef _WIN32
11305 return false;
11306 #else /* WIN32 */
11307
11308 #ifndef UNIV_HOTBACKUP
11309 /* Needed only for case sensitive file system. */
11310 if (lower_case_file_system) {
11311 return false;
11312 }
11313
11314 /* Skip if not right file extension. */
11315 if (!Fil_path::has_suffix(extn, old_path)) {
11316 return false;
11317 }
11318
11319 /* Check if partitioned table. */
11320 if (!dict_name::is_partition(old_path)) {
11321 return false;
11322 }
11323
11324 std::string table_name;
11325 /* Get Innodb dictionary name from file path. */
11326 if (!Fil_path::parse_file_path(old_path, extn, table_name)) {
11327 ut_d(ut_error);
11328 ut_o(return false);
11329 }
11330 ut_ad(!table_name.empty());
11331
11332 /* Rebuild partition table name with lower case. */
11333 std::string save_name(table_name);
11334 dict_name::rebuild(table_name);
11335
11336 if (save_name.compare(table_name) == 0) {
11337 return false;
11338 }
11339
11340 /* Build new partition file name. */
11341 new_path = Fil_path::make_new_path(old_path, table_name, extn);
11342 ut_ad(!new_path.empty());
11343 #endif /* !UNIV_HOTBACKUP */
11344
11345 return true;
11346 #endif /* WIN32 */
11347 }
11348
11349 #ifndef UNIV_HOTBACKUP
11350 static void fil_rename_partition_file(const std::string &old_path,
11351 ib_file_suffix extn, bool revert,
11352 bool import) {
11353 std::string new_path;
11354
11355 if (!fil_get_partition_file(old_path, extn, new_path)) {
11356 ut_d(ut_error);
11357 ut_o(return);
11358 }
11359
11360 ut_ad(!new_path.empty());
11361
11362 bool old_exists = os_file_exists(old_path.c_str());
11363 bool new_exists = os_file_exists(new_path.c_str());
11364
11365 static bool print_upgrade = true;
11366 static bool print_downgrade = true;
11367 bool ret = false;
11368
11369 if (revert) {
11370 /* Check if rename is required. */
11371 if (!new_exists || old_exists) {
11372 return;
11373 }
11374 ret = os_file_rename(innodb_data_file_key, new_path.c_str(),
11375 old_path.c_str());
11376 ut_ad(ret);
11377
11378 if (ret && print_downgrade) {
11379 ib::info(ER_IB_MSG_DOWNGRADE_PARTITION_FILE, new_path.c_str(),
11380 old_path.c_str());
11381 print_downgrade = false;
11382 }
11383 return;
11384 }
11385
11386 /* Check if rename is required. */
11387 if (new_exists || !old_exists) {
11388 return;
11389 }
11390
11391 ret =
11392 os_file_rename(innodb_data_file_key, old_path.c_str(), new_path.c_str());
11393
11394 if (!ret) {
11395 /* File rename failed. */
11396 ut_d(ut_error);
11397 ut_o(return);
11398 }
11399
11400 if (import) {
11401 ib::info(ER_IB_MSG_UPGRADE_PARTITION_FILE_IMPORT, old_path.c_str(),
11402 new_path.c_str());
11403 return;
11404 }
11405
11406 if (print_upgrade) {
11407 ib::info(ER_IB_MSG_UPGRADE_PARTITION_FILE, old_path.c_str(),
11408 new_path.c_str());
11409 print_upgrade = false;
11410 }
11411 }
11412 #endif /* !UNIV_HOTBACKUP */
11413
11414 void Tablespace_dirs::set_scan_dir(const std::string &in_directory,
11415 bool is_undo_dir) {
11416 std::string directory(in_directory);
11417
11418 Fil_path::normalize(directory);
11419
11420 add_path(directory, is_undo_dir);
11421 }
11422
11423 void Tablespace_dirs::set_scan_dirs(const std::string &in_directories) {
11424 std::string directories(in_directories);
11425
11426 Fil_path::normalize(directories);
11427
11428 std::string separators;
11429
11430 separators.push_back(FIL_PATH_SEPARATOR);
11431
11432 add_paths(directories, separators);
11433 }
11434
11435 /** Discover tablespaces by reading the header from .ibd files.
11436 @return DB_SUCCESS if all goes well */
11437 dberr_t Tablespace_dirs::scan() {
11438 Scanned_files ibd_files;
11439 Scanned_files undo_files;
11440 uint16_t count = 0;
11441 bool print_msg = false;
11442 auto start_time = std::chrono::steady_clock::now();
11443
11444 /* Should be trivial to parallelize the scan and ID check. */
11445 for (const auto &dir : m_dirs) {
11446 const auto real_path_dir = dir.root().abs_path();
11447
11448 ut_a(Fil_path::is_separator(dir.path().back()));
11449
11450 ib::info(ER_IB_MSG_379) << "Scanning '" << dir.path() << "'";
11451
11452 /* Walk the sub-tree of dir. */
11453
11454 Dir_Walker::walk(real_path_dir, true, [&](const std::string &path) {
11455 /* If it is a file and the suffix matches ".ibd"
11456 or the undo file name format then store it for
11457 determining the space ID. */
11458
11459 ut_a(path.length() > real_path_dir.length());
11460 ut_a(Fil_path::get_file_type(path) != OS_FILE_TYPE_DIR);
11461
11462 /* Check if need to alter partition file names to lower case. */
11463 std::string new_path;
11464
11465 if (fil_get_partition_file(path, IBD, new_path)) {
11466 /* Note all old file names to be renamed. */
11467 ut_ad(!new_path.empty());
11468 fil_system->add_old_file(path);
11469
11470 } else {
11471 new_path.assign(path);
11472 }
11473
11474 /* Make the filename relative to the directory that was scanned. */
11475 std::string file = new_path.substr(real_path_dir.length());
11476
11477 if (file.size() <= 4) {
11478 return;
11479 }
11480
11481 using Value = Scanned_files::value_type;
11482
11483 if (Fil_path::has_suffix(IBD, file.c_str())) {
11484 ibd_files.push_back(Value{count, file});
11485
11486 } else if (Fil_path::is_undo_tablespace_name(file)) {
11487 undo_files.push_back(Value{count, file});
11488 }
11489
11490 if (std::chrono::steady_clock::now() - start_time >= PRINT_INTERVAL) {
11491 ib::info(ER_IB_MSG_380)
11492 << "Files found so far: " << ibd_files.size() << " data files"
11493 << " and " << undo_files.size() << " undo files";
11494
11495 start_time = std::chrono::steady_clock::now();
11496 print_msg = true;
11497 }
11498 });
11499
11500 ++count;
11501 }
11502
11503 /* Rename all old partition files. */
11504 fil_system->rename_partition_files(false);
11505
11506 if (print_msg) {
11507 ib::info(ER_IB_MSG_381) << "Found " << ibd_files.size() << " '.ibd' and "
11508 << undo_files.size() << " undo files";
11509 }
11510
11511 Space_id_set unique;
11512 Space_id_set duplicates;
11513
11514 /* Get the number of additional threads needed to scan the files. */
11515 size_t n_threads = fil_get_scan_threads(ibd_files.size());
11516
11517 if (n_threads > 0) {
11518 ib::info(ER_IB_MSG_382)
11519 << "Using " << (n_threads + 1) << " threads to"
11520 << " scan " << ibd_files.size() << " tablespace files";
11521 }
11522
11523 std::mutex m;
11524
11525 using std::placeholders::_1;
11526 using std::placeholders::_2;
11527 using std::placeholders::_3;
11528 using std::placeholders::_4;
11529 using std::placeholders::_5;
11530 using std::placeholders::_6;
11531
11532 std::function<void(const Const_iter &, const Const_iter &, size_t,
11533 std::mutex *, Space_id_set *, Space_id_set *)>
11534 check = std::bind(&Tablespace_dirs::duplicate_check, this, _1, _2, _3, _4,
11535 _5, _6);
11536
11537 par_for(PFS_NOT_INSTRUMENTED, ibd_files, n_threads, check, &m, &unique,
11538 &duplicates);
11539
11540 duplicate_check(undo_files.begin(), undo_files.end(), n_threads, &m, &unique,
11541 &duplicates);
11542
11543 ut_a(m_checked == ibd_files.size() + undo_files.size());
11544
11545 ib::info(ER_IB_MSG_383) << "Completed space ID check of " << m_checked.load()
11546 << " files.";
11547
11548 dberr_t err;
11549
11550 if (!duplicates.empty()) {
11551 ib::error(ER_IB_MSG_384)
11552 << "Multiple files found for the same tablespace ID:";
11553
11554 print_duplicates(duplicates);
11555
11556 err = DB_FAIL;
11557 } else {
11558 err = DB_SUCCESS;
11559 }
11560
11561 return err;
11562 }
11563
11564 void fil_set_scan_dir(const std::string &directory, bool is_undo_dir) {
11565 fil_system->set_scan_dir(directory, is_undo_dir);
11566 }
11567
11568 void fil_set_scan_dirs(const std::string &directories) {
11569 fil_system->set_scan_dirs(directories);
11570 }
11571
11572 /** Discover tablespaces by reading the header from .ibd files.
11573 @return DB_SUCCESS if all goes well */
11574 dberr_t fil_scan_for_tablespaces() { return fil_system->scan(); }
11575
11576 /** Check if a path is known to InnoDB meaning that it is in or under
11577 one of the four path settings scanned at startup for file discovery.
11578 @param[in] path Path to check
11579 @return true if path is known to InnoDB */
11580 bool fil_path_is_known(const std::string &path) {
11581 return fil_system->check_path(path);
11582 }
11583
11584 /** Get the list of directories that datafiles can reside in.
11585 @return the list of directories 'dir1;dir2;....;dirN' */
11586 std::string fil_get_dirs() { return fil_system->get_dirs(); }
11587
11588 /** Free the data structures required for recovery. */
11589 void fil_free_scanned_files() { fil_system->free_scanned_files(); }
11590
11591 /** Update the tablespace name. In case, the new name
11592 and old name are same, no update done.
11593 @param[in,out] space tablespace object on which name
11594 will be updated
11595 @param[in] name new name for tablespace */
11596 void fil_space_update_name(fil_space_t *space, const char *name) {
11597 if (space == nullptr || name == nullptr || space->name == nullptr ||
11598 strcmp(space->name, name) == 0) {
11599 return;
11600 }
11601
11602 dberr_t err = fil_rename_tablespace_by_id(space->id, space->name, name);
11603
11604 if (err != DB_SUCCESS) {
11605 ib::warn(ER_IB_MSG_387) << "Tablespace rename '" << space->name << "' to"
11606 << " '" << name << "' failed!";
11607 }
11608 }
11609
11610 #ifndef UNIV_HOTBACKUP
11611 bool Fil_path::is_valid_location(const char *space_name, space_id_t space_id,
11612 uint32_t fsp_flags, const std::string &path) {
11613 ut_ad(!path.empty());
11614 ut_ad(space_name != nullptr);
11615
11616 /* All files sent to this routine have been found by scanning known
11617 locations. */
11618 ib_file_suffix type = (fsp_is_undo_tablespace(space_id) ? IBU : IBD);
11619
11620 if (type == IBD) {
11621 size_t dirname_len = dirname_length(path.c_str());
11622 Fil_path dirpath(path.c_str(), dirname_len, true);
11623
11624 bool is_shared = fsp_is_shared_tablespace(fsp_flags);
11625 bool under_datadir = MySQL_datadir_path.is_ancestor(dirpath);
11626
11627 if (is_shared) {
11628 if (under_datadir) {
11629 ib::error(ER_IB_MSG_GENERAL_TABLESPACE_UNDER_DATADIR, path.c_str());
11630 return false;
11631 }
11632 } else {
11633 /* file-per-table */
11634 bool in_datadir =
11635 (under_datadir ? false : MySQL_datadir_path.is_same_as(dirpath));
11636
11637 if (in_datadir) {
11638 ib::error(ER_IB_MSG_IMPLICIT_TABLESPACE_IN_DATADIR, path.c_str());
11639 return false;
11640 }
11641
11642 /* Make sure that the last directory of an implicit tablespace is a
11643 filesystem charset version of the schema name. */
11644 if (!is_valid_location_within_db(space_name, path)) {
11645 ib::error(ER_IB_MSG_INVALID_LOCATION_WRONG_DB, path.c_str(),
11646 space_name);
11647 return false;
11648 }
11649 }
11650 }
11651
11652 return true;
11653 }
11654
11655 bool Fil_path::is_valid_location_within_db(const char *space_name,
11656 const std::string &path) {
11657 /* Strip off the basename to reduce the path to a directory. */
11658 std::string dirpath{path};
11659 auto pos = dirpath.find_last_of(SEPARATOR);
11660 dirpath.resize(pos);
11661
11662 /* Only implicit tablespaces are sent to this routine.
11663 They are always prefixed by `schema/`. */
11664 ut_ad(pos != std::string::npos);
11665
11666 /* Get the subdir that the file is in. */
11667 pos = dirpath.find_last_of(SEPARATOR);
11668 std::string db_dir = (pos == std::string::npos)
11669 ? dirpath
11670 : dirpath.substr(pos + 1, dirpath.length());
11671
11672 /* Convert to lowercase if necessary. */
11673 if (innobase_get_lower_case_table_names() == 2) {
11674 Fil_path::convert_to_lower_case(db_dir);
11675 }
11676
11677 /* Make sure the db_dir matches the schema name.
11678 db_dir is in filesystem charset and space_name is usually in the
11679 system charset.
11680
11681 The problem here is that the system charset version of a schema or
11682 table name may contain a '/' and the tablespace name we were sent
11683 is a combination of the two with '/' as a delimiter.
11684 For example `my/schema` + `my/table` == `my/schema/my/table`
11685
11686 Search the space_name string backwards until we find the db name that
11687 matches the schema name from the path. */
11688
11689 std::string name(space_name);
11690 pos = name.find_last_of(SEPARATOR);
11691 while (pos < std::string::npos) {
11692 name.resize(pos);
11693 std::string temp = name;
11694 if (temp == db_dir) {
11695 return true;
11696 }
11697
11698 /* Convert to filename charset and compare again. */
11699 Fil_path::convert_to_filename_charset(temp);
11700 if (temp == db_dir) {
11701 return true;
11702 }
11703
11704 /* Still no match, iterate through the next SEPARATOR. */
11705 pos = name.find_last_of(SEPARATOR);
11706
11707 /* If end of string is hit, there is no match. */
11708 if (pos == std::string::npos) {
11709 return false;
11710 }
11711 }
11712
11713 return true;
11714 }
11715
11716 /** Convert filename to the file system charset format.
11717 @param[in,out] name Filename to convert */
11718 void Fil_path::convert_to_filename_charset(std::string &name) {
11719 uint errors = 0;
11720 char old_name[MAX_TABLE_NAME_LEN + 20];
11721 char filename[MAX_TABLE_NAME_LEN + 20];
11722
11723 strncpy(filename, name.c_str(), sizeof(filename) - 1);
11724 strncpy(old_name, filename, sizeof(old_name));
11725
11726 innobase_convert_to_filename_charset(filename, old_name, MAX_TABLE_NAME_LEN);
11727
11728 if (errors == 0) {
11729 name.assign(filename);
11730 }
11731 }
11732
11733 /** Convert to lower case using the file system charset.
11734 @param[in,out] path Filepath to convert */
11735 void Fil_path::convert_to_lower_case(std::string &path) {
11736 char lc_path[MAX_TABLE_NAME_LEN + 20];
11737
11738 ut_ad(path.length() < sizeof(lc_path) - 1);
11739
11740 strncpy(lc_path, path.c_str(), sizeof(lc_path) - 1);
11741
11742 innobase_casedn_path(lc_path);
11743
11744 path.assign(lc_path);
11745 }
11746
11747 void fil_purge() { fil_system->purge(); }
11748
11749 size_t fil_count_undo_deleted(space_id_t undo_num) {
11750 return fil_system->count_undo_deleted(undo_num);
11751 }
11752
11753 #endif /* !UNIV_HOTBACKUP */
11754
11755 #define PAGE_TYPE(x) \
11756 case x: \
11757 return #x;
11758
11759 const char *fil_get_page_type_str(page_type_t type) noexcept {
11760 switch (type) {
11761 PAGE_TYPE(FIL_PAGE_INDEX);
11762 PAGE_TYPE(FIL_PAGE_RTREE);
11763 PAGE_TYPE(FIL_PAGE_SDI);
11764 PAGE_TYPE(FIL_PAGE_UNDO_LOG);
11765 PAGE_TYPE(FIL_PAGE_INODE);
11766 PAGE_TYPE(FIL_PAGE_IBUF_FREE_LIST);
11767 PAGE_TYPE(FIL_PAGE_TYPE_ALLOCATED);
11768 PAGE_TYPE(FIL_PAGE_IBUF_BITMAP);
11769 PAGE_TYPE(FIL_PAGE_TYPE_SYS);
11770 PAGE_TYPE(FIL_PAGE_TYPE_TRX_SYS);
11771 PAGE_TYPE(FIL_PAGE_TYPE_FSP_HDR);
11772 PAGE_TYPE(FIL_PAGE_TYPE_XDES);
11773 PAGE_TYPE(FIL_PAGE_TYPE_BLOB);
11774 PAGE_TYPE(FIL_PAGE_TYPE_ZBLOB);
11775 PAGE_TYPE(FIL_PAGE_TYPE_ZBLOB2);
11776 PAGE_TYPE(FIL_PAGE_TYPE_UNKNOWN);
11777 PAGE_TYPE(FIL_PAGE_COMPRESSED);
11778 PAGE_TYPE(FIL_PAGE_ENCRYPTED);
11779 PAGE_TYPE(FIL_PAGE_COMPRESSED_AND_ENCRYPTED);
11780 PAGE_TYPE(FIL_PAGE_ENCRYPTED_RTREE);
11781 PAGE_TYPE(FIL_PAGE_SDI_BLOB);
11782 PAGE_TYPE(FIL_PAGE_SDI_ZBLOB);
11783 PAGE_TYPE(FIL_PAGE_TYPE_LOB_INDEX);
11784 PAGE_TYPE(FIL_PAGE_TYPE_LOB_DATA);
11785 PAGE_TYPE(FIL_PAGE_TYPE_LOB_FIRST);
11786 PAGE_TYPE(FIL_PAGE_TYPE_ZLOB_FIRST);
11787 PAGE_TYPE(FIL_PAGE_TYPE_ZLOB_DATA);
11788 PAGE_TYPE(FIL_PAGE_TYPE_ZLOB_INDEX);
11789 PAGE_TYPE(FIL_PAGE_TYPE_ZLOB_FRAG);
11790 PAGE_TYPE(FIL_PAGE_TYPE_ZLOB_FRAG_ENTRY);
11791 PAGE_TYPE(FIL_PAGE_TYPE_RSEG_ARRAY);
11792 PAGE_TYPE(FIL_PAGE_TYPE_LEGACY_DBLWR);
11793 }
11794 ut_d(ut_error);
11795 ut_o(return "UNKNOWN");
11796 }
11797
11798 bool fil_is_page_type_valid(page_type_t type) noexcept {
11799 if (fil_page_type_is_index(type)) {
11800 return true;
11801 }
11802
11803 if (type <= FIL_PAGE_TYPE_LAST && type != FIL_PAGE_TYPE_UNUSED) {
11804 return true;
11805 }
11806
11807 ut_d(ut_error);
11808 ut_o(return false);
11809 }
11810
11811 std::ostream &Fil_page_header::print(std::ostream &out) const noexcept {
11812 /* Print the header information in the order it is stored. */
11813 out << "[Fil_page_header: FIL_PAGE_OFFSET=" << get_page_no()
11814 << ", FIL_PAGE_TYPE=" << get_page_type()
11815 << ", FIL_PAGE_SPACE_ID=" << get_space_id() << "]";
11816 return out;
11817 }
11818
11819 space_id_t Fil_page_header::get_space_id() const noexcept {
11820 return mach_read_from_4(m_frame + FIL_PAGE_SPACE_ID);
11821 }
11822
11823 page_no_t Fil_page_header::get_page_no() const noexcept {
11824 return mach_read_from_4(m_frame + FIL_PAGE_OFFSET);
11825 }
11826
11827 uint16_t Fil_page_header::get_page_type() const noexcept {
11828 return mach_read_from_2(m_frame + FIL_PAGE_TYPE);
11829 }
11830
11831 fil_node_t *fil_space_t::get_file_node(page_no_t *page_no) noexcept {
11832 if (files.size() > 1) {
11833 ut_a(id == TRX_SYS_SPACE || purpose == FIL_TYPE_TEMPORARY);
11834
11835 for (auto &f : files) {
11836 if (f.size > *page_no) {
11837 return &f;
11838 }
11839 *page_no -= f.size;
11840 }
11841
11842 } else if (!files.empty()) {
11843 fil_node_t &f = files.front();
11844
11845 if ((fsp_is_ibd_tablespace(id) && f.size == 0) || f.size > *page_no) {
11846 /* We do not know the size of a single-table tablespace
11847 before we open the file */
11848 return &f;
11849 }
11850 /* The page is outside the current bounds of the file. We should not assert
11851 here as we could be loading pages in buffer pool from dump file having pages
11852 from dropped tablespaces. Specifically, for undo tablespace it is possible
11853 to re-use the dropped space ID and the page could be out of bound. We need
11854 to ignore such cases. */
11855 }
11856
11857 return nullptr;
11858 }
11859
11860 bool fil_space_t::is_deleted() const {
11861 ut_ad(fil_system->shard_by_id(id)->mutex_owned());
11862 return m_deleted;
11863 }
11864
11865 bool fil_space_t::was_not_deleted() const {
11866 /* This is not a critical assertion - if you have this mutex, then possibly
11867 you want to call !is_deleted(). */
11868 ut_ad(!fil_system->shard_by_id(id)->mutex_owned());
11869 return !m_deleted;
11870 }
11871
11872 #ifndef UNIV_HOTBACKUP
11873 uint32_t fil_space_t::get_current_version() const {
11874 ut_ad(fil_system->shard_by_id(id)->mutex_owned());
11875 return m_version;
11876 }
11877 uint32_t fil_space_t::get_recent_version() const {
11878 /* This is not a critical assertion - if you have this mutex, then possibly
11879 you want to call get_current_version(). */
11880 ut_ad(!fil_system->shard_by_id(id)->mutex_owned());
11881 return m_version;
11882 }
11883 bool fil_space_t::has_no_references() const {
11884 /* To assure the ref count can't be increased, we must either operate on
11885 detached space that is ready to be removed, or have the fil shard latched. */
11886 #ifdef UNIV_DEBUG
11887 if (!fil_system->shard_by_id(id)->mutex_owned()) {
11888 ut_a(fil_space_get(id) != this);
11889 }
11890 #endif
11891 return m_n_ref_count.load() == 0;
11892 }
11893 size_t fil_space_t::get_reference_count() const {
11894 /* This should be only called on server shutdown. */
11895 ut_ad(fil_system->shard_by_id(id)->mutex_owned());
11896 return m_n_ref_count.load();
11897 }
11898
11899 #endif /* !UNIV_HOTBACKUP */
11900
11901 void fil_space_t::set_deleted() {
11902 ut_ad(fil_system->shard_by_id(id)->mutex_owned());
11903 ut_a(files.size() == 1);
11904 ut_a(n_pending_ops == 0);
11905
11906 #ifndef UNIV_HOTBACKUP
11907 bump_version();
11908
11909 m_deleted = true;
11910 #endif /* !UNIV_HOTBACKUP */
11911 }
11912
11913 #ifndef UNIV_HOTBACKUP
11914
11915 void fil_space_t::bump_version() {
11916 ut_ad(fil_system->shard_by_id(id)->mutex_owned());
11917 ut_a(files.size() == 1);
11918 ut_a(n_pending_ops == 0);
11919
11920 /* Bump the version. This will make all pages in buffer pool that reference
11921 the current space version to be stale and freed on first encounter. */
11922 ut_a(stop_new_ops);
11923 ut_a(!m_deleted);
11924
11925 ++m_version;
11926 }
11927 #endif /* !UNIV_HOTBACKUP */