Debian Codegraph @

storage/innobase/row/row0pread.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2018, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file row/row0pread.cc
29 Parallel read implementation
30
31 Created 2018-01-27 by Sunny Bains */
32
33 #include <array>
34
35 #include "btr0pcur.h"
36 #include "dict0dict.h"
37 #include "os0thread-create.h"
38 #include "row0mysql.h"
39 #include "row0pread.h"
40 #include "row0row.h"
41 #include "row0vers.h"
42 #include "ut0new.h"
43
44 #ifdef UNIV_PFS_THREAD
45 mysql_pfs_key_t parallel_read_thread_key;
46 #endif /* UNIV_PFS_THREAD */
47
48 std::atomic_size_t Parallel_reader::s_active_threads{};
49
50 /** Tree depth at which we decide to split blocks further. */
51 static constexpr size_t SPLIT_THRESHOLD{3};
52
53 /** No. of pages to scan, in the case of large tables, before the check for
54 trx interrupted is made as the call is expensive. */
55 static constexpr size_t TRX_IS_INTERRUPTED_PROBE{50000};
56
57 std::string Parallel_reader::Scan_range::to_string() const {
58 std::ostringstream os;
59
60 os << "m_start: ";
61 if (m_start != nullptr) {
62 m_start->print(os);
63 } else {
64 os << "null";
65 }
66 os << ", m_end: ";
67 if (m_end != nullptr) {
68 m_end->print(os);
69 } else {
70 os << "null";
71 }
72 return (os.str());
73 }
74
75 Parallel_reader::Scan_ctx::Iter::~Iter() {
76 if (m_heap == nullptr) {
77 return;
78 }
79
80 if (m_pcur != nullptr) {
81 m_pcur->free_rec_buf();
82 /* Created with placement new on the heap. */
83 call_destructor(m_pcur);
84 }
85
86 mem_heap_free(m_heap);
87 m_heap = nullptr;
88 }
89
90 Parallel_reader::~Parallel_reader() {
91 mutex_destroy(&m_mutex);
92 os_event_destroy(m_event);
93 if (!m_sync) {
94 release_unused_threads(m_n_threads);
95 }
96 for (auto thread_ctx : m_thread_ctxs) {
97 if (thread_ctx != nullptr) {
98 ut::delete_(thread_ctx);
99 }
100 }
101 }
102
103 size_t Parallel_reader::available_threads(size_t n_required,
104 bool use_reserved) {
105 auto max_threads = MAX_THREADS;
106 constexpr auto SEQ_CST = std::memory_order_seq_cst;
107 auto active = s_active_threads.fetch_add(n_required, SEQ_CST);
108
109 if (use_reserved) {
110 max_threads += MAX_RESERVED_THREADS;
111 }
112
113 if (active < max_threads) {
114 const auto available = max_threads - active;
115
116 if (n_required <= available) {
117 return n_required;
118 } else {
119 const auto release = n_required - available;
120 const auto o = s_active_threads.fetch_sub(release, SEQ_CST);
121 ut_a(o >= release);
122 return available;
123 }
124 }
125
126 const auto o = s_active_threads.fetch_sub(n_required, SEQ_CST);
127 ut_a(o >= n_required);
128
129 return 0;
130 }
131
132 void Parallel_reader::Scan_ctx::index_s_lock() {
133 if (m_s_locks.fetch_add(1, std::memory_order_acquire) == 0) {
134 auto index = m_config.m_index;
135 /* The latch can be unlocked by a thread that didn't originally lock it. */
136 rw_lock_s_lock_gen(dict_index_get_lock(index), true, UT_LOCATION_HERE);
137 }
138 }
139
140 void Parallel_reader::Scan_ctx::index_s_unlock() {
141 if (m_s_locks.fetch_sub(1, std::memory_order_acquire) == 1) {
142 auto index = m_config.m_index;
143 /* The latch can be unlocked by a thread that didn't originally lock it. */
144 rw_lock_s_unlock_gen(dict_index_get_lock(index), true);
145 }
146 }
147
148 dberr_t Parallel_reader::Ctx::split() {
149 ut_ad(m_range.first->m_tuple == nullptr ||
150 dtuple_validate(m_range.first->m_tuple));
151 ut_ad(m_range.second->m_tuple == nullptr ||
152 dtuple_validate(m_range.second->m_tuple));
153
154 /* Setup the sub-range. */
155 Scan_range scan_range(m_range.first->m_tuple, m_range.second->m_tuple);
156
157 /* S lock so that the tree structure doesn't change while we are
158 figuring out the sub-trees to scan. */
159 m_scan_ctx->index_s_lock();
160
161 Parallel_reader::Scan_ctx::Ranges ranges{};
162 m_scan_ctx->partition(scan_range, ranges, 1);
163
164 if (!ranges.empty()) {
165 ranges.back().second = m_range.second;
166 }
167
168 dberr_t err{DB_SUCCESS};
169
170 /* Create the partitioned scan execution contexts. */
171 for (auto &range : ranges) {
172 err = m_scan_ctx->create_context(range, false);
173
174 if (err != DB_SUCCESS) {
175 break;
176 }
177 }
178
179 if (err != DB_SUCCESS) {
180 m_scan_ctx->set_error_state(err);
181 }
182
183 m_scan_ctx->index_s_unlock();
184
185 return err;
186 }
187
188 Parallel_reader::Parallel_reader(size_t max_threads)
189 : m_max_threads(max_threads),
190 m_n_threads(max_threads),
191 m_ctxs(),
192 m_sync(max_threads == 0) {
193 m_n_completed = 0;
194
195 mutex_create(LATCH_ID_PARALLEL_READ, &m_mutex);
196
197 m_event = os_event_create();
198 m_sig_count = os_event_reset(m_event);
199 }
200
201 Parallel_reader::Scan_ctx::Scan_ctx(Parallel_reader *reader, size_t id,
202 trx_t *trx,
203 const Parallel_reader::Config &config,
204 F &&f)
205 : m_id(id), m_config(config), m_trx(trx), m_f(f), m_reader(reader) {}
206
207 /** Persistent cursor wrapper around btr_pcur_t */
208 class PCursor {
209 public:
210 /** Constructor.
211 @param[in,out] pcur Persistent cursor in use.
212 @param[in] mtr Mini-transaction used by the persistent cursor.
213 @param[in] read_level Read level where the block should be present. */
214 PCursor(btr_pcur_t *pcur, mtr_t *mtr, size_t read_level)
215 : m_mtr(mtr), m_pcur(pcur), m_read_level(read_level) {}
216
217 /** Store the position of the user record that is added to the key buffer and,
218 commit the mini-transaction. The cursor must not be positioned at infimum
219 or supremum.
220 @note This method must be paired with
221 restore_to_last_processed_user_record() to restore the record position */
222 void save_current_user_record_as_last_processed() noexcept;
223
224 /** Restore the cursor to the saved record. If the saved record was physically
225 removed then restore to the largest record which is smaller than the saved
226 record. If all records were removed then restore the cursor to the infimum;
227 this must be fine if the next step of the caller is to advance the cursor.
228 @note This method must be paired with
229 save_current_user_record_as_last_processed() to save the record position */
230 void restore_to_last_processed_user_record() noexcept;
231
232 /** This method must be called after all records on a page are processed and
233 cursor is positioned at supremum. Under this assumption, it stores the
234 position BTR_PCUR_AFTER the last user record on the page.
235 This method must be paired with restore_to_first_unprocessed() to restore to
236 a record which comes right after the value of the stored last processed
237 record @see restore_to_first_unprocessed for details. */
238 void save_previous_user_record_as_last_processed() noexcept;
239
240 /** Restore the cursor to the record which comes next after the saved
241 position by the paired method save_previous_user_record_as_last_processed().
242 If there is no such record, it will restore to supremum on the last leaf
243 page.
244 @note This method must be paired with
245 save_previous_user_record_as_last_processed() to save the record position */
246 void restore_to_first_unprocessed() noexcept;
247
248 /** Move to the next block.
249 @param[in] index Index being traversed.
250 @return DB_SUCCESS or error code. */
251 [[nodiscard]] dberr_t move_to_next_block(dict_index_t *index);
252
253 /** Restore the cursor to the saved record. If the saved record
254 was physically removed, then restore to the largest record which
255 is smaller than the saved record.
256 @return true if restored to the same record, false otherwise */
257 bool restore_to_largest_le_position_saved() noexcept;
258
259 /** @return the current page cursor. */
260 [[nodiscard]] page_cur_t *get_page_cursor() noexcept {
261 return m_pcur->get_page_cur();
262 }
263
264 /** @return true if cursor is after last on page. */
265 [[nodiscard]] bool is_after_last_on_page() const noexcept {
266 return m_pcur->is_after_last_on_page();
267 }
268
269 /** @return Level where the cursor is intended. */
270 size_t read_level() const noexcept { return m_read_level; }
271
272 private:
273 /** This method must be called when cursor is positioned at supremum of
274 the page at the level one of the index. It saves the min-key value of
275 the last leaf page referenced on the page.
276 This method must be paired with restore_level_one_progress() to restore
277 cursor to a record on the non-leaf page which points to the next leaf
278 page to process.
279 @see restore_level_one_progress for details. */
280 void save_level_one_progress() noexcept;
281
282 /** This method must be called to restore to the record on the non-leaf page
283 (level one) of the index. It must be paired with save_level_one_progress().
284 If the cursor was saved to the record <min-key value, child_page_no> position,
285 then the restored cursor is positioned to the
286 <min-key value+, child_page_no^>. The min-key value+ is the value that comes
287 next after the saved value min-key value.
288 As PAGE_CUR_G mode is not supported for level 1, this function searches for
289 such a record in two steps:
290 1. using PAGE_CUR_LE it finds a record which is lower-or-equal min_key value
291 2. adjusts the position by moving one record forward
292 The later step might require moving to the next page, and this function
293 tries to latch the next page without any other thread waiting to latch it.
294 If the latch could not be obtained on the page, then the method returns the
295 DB_LOCK_NOWAIT error code. The caller must implement retry logic to handle
296 this error code.
297 @return DB_SUCCESS or error code. */
298 [[nodiscard]] dberr_t restore_level_one_progress() noexcept;
299
300 /** Move to the next block at the leaf level of the index. If other
301 thread(s) are waiting to acquire the latches on the index then first
302 save the last processed user record, pause, give chance to the other
303 threads to execute, then restore the cursor to next unprocessed record,
304 which typically is the first record on next page, if the tree was not
305 modified meanwhile.
306 @param[in] index Index being traversed.
307 @return DB_SUCCESS or error code. */
308 [[nodiscard]] dberr_t move_to_next_block_at_leaf_level(dict_index_t *index);
309
310 /** Move to the next block at the level one of the index. If other
311 thread(s) are waiting to acquire the latches on the index then first
312 pause, give chance the other threads to execute, then restore the
313 cursor before positioning it to user record on next page. The latch
314 on next page is acquired without waiting in a retry loop, otherwise
315 waiting might cause deadlock with other tree modifying operations.
316 @param[in] index Index being traversed.
317 @return DB_SUCCESS or error code. */
318 [[nodiscard]] dberr_t move_to_next_block_at_level_one(dict_index_t *index);
319
320 /** Move to the first user record on the next page. Release the latches
321 on the current page and obtain the S-latch on next page. If it is non-leaf
322 level then S-latch is obtained in the optimistic/non-blocking way, which
323 can fail with DB_LOCK_WAIT. Caller must add the retry logic to handle
324 this error code.
325 @return DB_SUCCESS or error code. */
326 [[nodiscard]] dberr_t move_to_user_rec_on_next_page() noexcept;
327
328 /** Mini-transaction. */
329 mtr_t *m_mtr{};
330
331 /** Persistent cursor. */
332 btr_pcur_t *m_pcur{};
333
334 /** Level where the cursor is positioned or need to be positioned in case of
335 restore. */
336 size_t m_read_level{};
337 };
338
339 buf_block_t *Parallel_reader::Scan_ctx::block_get_s_latched(
340 const page_id_t &page_id, mtr_t *mtr, size_t line) const {
341 /* We never scan undo tablespaces. */
342 ut_a(!fsp_is_undo_tablespace(page_id.space()));
343
344 auto block =
345 buf_page_get_gen(page_id, m_config.m_page_size, RW_S_LATCH, nullptr,
346 Page_fetch::SCAN, {__FILE__, line}, mtr);
347
348 buf_block_dbg_add_level(block, SYNC_TREE_NODE);
349
350 return (block);
351 }
352
353 void PCursor::save_level_one_progress() noexcept {
354 ut_ad(m_read_level == 1);
355 ut_ad(m_pcur->is_after_last_on_page());
356
357 /* Store the cursor position on the previous user record on the page.
358
359 @note: If btr_pcur_t::store_position() detects that cursor is positioned to
360 after the last record then it moves the position to previous user record too.
361 The reason we have to move to previous user record explicitly is that,
362 btr_pcur_t::store_position() changes the relative position to BTR_PCUR_AFTER
363 in that case btr_pcur_t::restore_position() restores the next user record
364 which is not allowed at non-leaf level. We use modified search modes on the
365 non-leaf levels, @see btr_cur_search_to_nth_level for details. Therefore, we
366 explicitly move to cursor position to previous record */
367 m_pcur->move_to_prev_on_page();
368
369 m_pcur->store_position(m_mtr);
370
371 ut_ad(m_pcur->m_rel_pos == BTR_PCUR_ON);
372
373 m_mtr->commit();
374 }
375
376 dberr_t PCursor::restore_level_one_progress() noexcept {
377 ut_ad(m_read_level == 1);
378 ut_ad(m_pcur->m_rel_pos == BTR_PCUR_ON);
379 m_mtr->start();
380 m_mtr->set_log_mode(MTR_LOG_NO_REDO);
381
382 restore_to_largest_le_position_saved();
383
384 /* Move to the next record on the page */
385 page_cur_move_to_next(get_page_cursor());
386
387 if (m_pcur->is_on_user_rec()) {
388 /* Cursor is still on a user record so we can claim success */
389 return DB_SUCCESS;
390 }
391
392 return move_to_user_rec_on_next_page();
393 }
394
395 void PCursor::save_current_user_record_as_last_processed() noexcept {
396 ut_a(m_pcur->is_on_user_rec());
397 ut_ad(m_read_level == 0);
398 m_pcur->store_position(m_mtr);
399 m_mtr->commit();
400 }
401
402 void PCursor::restore_to_last_processed_user_record() noexcept {
403 ut_a(m_pcur->m_rel_pos == BTR_PCUR_ON);
404 ut_ad(m_read_level == 0);
405 m_mtr->start();
406 m_mtr->set_log_mode(MTR_LOG_NO_REDO);
407
408 [[maybe_unused]] const auto same_row =
409 m_pcur->restore_position(BTR_SEARCH_LEAF, m_mtr, UT_LOCATION_HERE);
410
411 /* Restored cursor is positioned on the page at the level intended before */
412 ut_ad(m_read_level == btr_page_get_level(m_pcur->get_page()));
413
414 /* Since m_rel_pos was BTR_PCUR_ON, the state can't be
415 BTR_PCUR_IS_POSITIONED_OPTIMISTIC */
416 ut_a(BTR_PCUR_IS_POSITIONED_OPTIMISTIC != m_pcur->m_pos_state);
417
418 /* If the cursor was pointing to the user record then 'PAGE_CUR_LE' mode
419 used by the btr_pcur_t::restore_position() restores the cursor to a record
420 lower than the original one if it was removed, and in particular, if all
421 smaller ones were removed, cur could be on infimum now. This would be fine,
422 as our next step will be to advance the cursor, anyway.
423 However, right now the only usage of this method is in the bulk inserter
424 for a B-Tree. which only calls it when the current row was visible to the
425 scan, and thus can't be purged. So, we know it can't happen, unless someone
426 reuses this function in a new context, in which case they should probably
427 repeat the proof of correctness. The purpose of following debug assert is
428 to show the limited the scope of this method, and thus how risky it
429 is to use it in new context: */
430 ut_ad(same_row);
431 }
432
433 void PCursor::save_previous_user_record_as_last_processed() noexcept {
434 ut_a(m_pcur->is_after_last_on_page());
435 ut_ad(m_read_level == 0);
436 m_pcur->store_position(m_mtr);
437 ut_a(m_pcur->m_rel_pos == BTR_PCUR_AFTER);
438 m_mtr->commit();
439 }
440
441 void PCursor::restore_to_first_unprocessed() noexcept {
442 ut_a(m_pcur->m_rel_pos == BTR_PCUR_AFTER);
443 ut_ad(m_read_level == 0);
444 m_mtr->start();
445 m_mtr->set_log_mode(MTR_LOG_NO_REDO);
446 m_pcur->restore_position(BTR_SEARCH_LEAF, m_mtr, UT_LOCATION_HERE);
447
448 /* Restored cursor is positioned on the page at the level intended before */
449 ut_ad(m_read_level == btr_page_get_level(m_pcur->get_page()));
450
451 /* The BTR_PCUR_IS_POSITIONED_OPTIMISTIC only happens in case of a successful
452 optimistic restoration in which the cursor points to a user record after
453 restoration. But, in save_previous_user_record_as_last_processed() the cursor
454 pointed to SUPREMUM before calling m_ptr->store_position(mtr), so it would
455 also point there if optimistic restoration succeeded, which is not a user
456 record. */
457 ut_ad(m_pcur->m_pos_state != BTR_PCUR_IS_POSITIONED_OPTIMISTIC);
458 }
459
460 bool PCursor::restore_to_largest_le_position_saved() noexcept {
461 ut_ad(m_pcur->m_rel_pos == BTR_PCUR_ON);
462 ut_ad(m_mtr->is_active());
463
464 const auto same_row =
465 m_pcur->restore_position(BTR_SEARCH_LEAF, m_mtr, UT_LOCATION_HERE);
466
467 ut_ad(!m_pcur->is_after_last_on_page());
468
469 return same_row;
470 }
471
472 dberr_t PCursor::move_to_user_rec_on_next_page() noexcept {
473 auto cur = m_pcur->get_page_cur();
474 const auto next_page_no = btr_page_get_next(page_cur_get_page(cur), m_mtr);
475
476 if (next_page_no == FIL_NULL) {
477 m_mtr->commit();
478 return DB_END_OF_INDEX;
479 }
480
481 buf_block_t *current_block = page_cur_get_block(cur);
482 buf_block_t *next_block{nullptr};
483
484 const auto space_id = current_block->page.id.space();
485 const auto page_size = current_block->page.size;
486
487 DEBUG_SYNC_C("parallel_reader_next_block");
488
489 /* We never scan undo tablespaces. */
490 ut_a(!fsp_is_undo_tablespace(space_id));
491
492 if (m_read_level == 0) {
493 next_block = buf_page_get_gen(page_id_t(space_id, next_page_no), page_size,
494 RW_S_LATCH, nullptr, Page_fetch::SCAN,
495 UT_LOCATION_HERE, m_mtr);
496 } else {
497 /* Read IO should be waited for. But s-latch should be nowait,
498 to avoid deadlock opportunity completely. */
499 next_block = buf_page_get_gen(page_id_t(space_id, next_page_no), page_size,
500 RW_NO_LATCH, nullptr, Page_fetch::SCAN,
501 UT_LOCATION_HERE, m_mtr);
502 bool success =
503 buf_page_get_known_nowait(RW_S_LATCH, next_block, Cache_hint::KEEP_OLD,
504 __FILE__, __LINE__, m_mtr);
505 btr_leaf_page_release(next_block, RW_NO_LATCH, m_mtr);
506
507 if (!success) {
508 return DB_LOCK_NOWAIT;
509 }
510 }
511
512 buf_block_dbg_add_level(next_block, SYNC_TREE_NODE);
513
514 btr_leaf_page_release(current_block, RW_S_LATCH, m_mtr);
515
516 page_cur_set_before_first(next_block, cur);
517
518 /* Skip the infimum record. */
519 page_cur_move_to_next(cur);
520
521 /* Page can't be empty unless it is a root page. */
522 ut_ad(!page_cur_is_after_last(cur));
523
524 return DB_SUCCESS;
525 }
526
527 void Parallel_reader::Thread_ctx::
528 save_current_user_record_as_last_processed() noexcept {
529 m_pcursor->save_current_user_record_as_last_processed();
530 }
531
532 void Parallel_reader::Thread_ctx::
533 restore_to_last_processed_user_record() noexcept {
534 m_pcursor->restore_to_last_processed_user_record();
535 }
536
537 void Parallel_reader::Thread_ctx::
538 save_previous_user_record_as_last_processed() noexcept {
539 m_pcursor->save_previous_user_record_as_last_processed();
540 }
541
542 void Parallel_reader::Thread_ctx::restore_to_first_unprocessed() noexcept {
543 m_pcursor->restore_to_first_unprocessed();
544 }
545
546 dberr_t PCursor::move_to_next_block_at_leaf_level(dict_index_t *index) {
547 ut_ad(m_read_level == 0);
548 if (DBUG_EVALUATE_IF("pcursor_move_to_next_block_release_latches", true,
549 rw_lock_get_waiters(dict_index_get_lock(index)))) {
550 save_previous_user_record_as_last_processed();
551 DEBUG_SYNC_C("pcursor_move_to_next_block_latches_released");
552 std::this_thread::yield();
553 restore_to_first_unprocessed();
554 if (m_pcur->is_after_last_on_page()) {
555 /* There's nothing wrong here, as restore_to_first_unprocessed() is not
556 obliged to position the cursor on a *user* record - it can be a
557 supremum. This can happen if
558 a) the block in BP wasn't modified and thus we've restored the cursor
559 exactly where it was, i.e. on supremum
560 b) there is no more records in the table
561 These options aren't mutually exclusive. Both are well handled by: */
562 return move_to_user_rec_on_next_page();
563 }
564 /* This happens if we were descending the B-tree, in which case we try
565 to navigate in such a way to arrive at a user record. */
566 ut_a(m_pcur->is_on_user_rec());
567 return DB_SUCCESS;
568 }
569 return move_to_user_rec_on_next_page();
570 }
571
572 dberr_t PCursor::move_to_next_block_at_level_one(dict_index_t *index) {
573 ut_ad(m_read_level != 0);
574 dberr_t err = DB_SUCCESS;
575
576 if (rw_lock_get_waiters(dict_index_get_lock(index))) {
577 /* There are waiters on the index tree lock. Store and restore
578 the cursor position, and yield so that scanning a large table
579 will not starve other threads. */
580
581 /* We should always yield on a block boundary. */
582 ut_ad(m_pcur->is_after_last_on_page());
583
584 save_level_one_progress();
585
586 /* Yield so that another thread can proceed. */
587 std::this_thread::yield();
588
589 err = restore_level_one_progress();
590 } else {
591 err = move_to_user_rec_on_next_page();
592 }
593
594 int n_retries [[maybe_unused]] = 0;
595 while (err == DB_LOCK_NOWAIT) {
596 /* We should restore the cursor from index root page,
597 to avoid deadlock opportunity. */
598
599 save_level_one_progress();
600
601 /* Forces to restore from index root. */
602 m_pcur->m_block_when_stored.clear();
603
604 err = restore_level_one_progress();
605
606 n_retries++;
607 ut_ad(n_retries < 10);
608 }
609
610 return err;
611 }
612
613 dberr_t PCursor::move_to_next_block(dict_index_t *index) {
614 ut_ad(m_pcur->is_after_last_on_page());
615 if (m_read_level == 0) {
616 return move_to_next_block_at_leaf_level(index);
617 }
618 ut_ad(m_read_level == 1);
619 return move_to_next_block_at_level_one(index);
620 }
621
622 bool Parallel_reader::Scan_ctx::check_visibility(const rec_t *&rec,
623 ulint *&offsets,
624 mem_heap_t *&heap,
625 mtr_t *mtr) {
626 const auto table_name = m_config.m_index->table->name;
627
628 ut_ad(!m_trx || m_trx->read_view == nullptr ||
629 MVCC::is_view_active(m_trx->read_view));
630
631 if (!m_trx) {
632 /* Do nothing */
633 } else if (m_trx->read_view != nullptr) {
634 auto view = m_trx->read_view;
635
636 if (m_config.m_index->is_clustered()) {
637 trx_id_t rec_trx_id;
638
639 if (m_config.m_index->trx_id_offset > 0) {
640 rec_trx_id = trx_read_trx_id(rec + m_config.m_index->trx_id_offset);
641 } else {
642 rec_trx_id = row_get_rec_trx_id(rec, m_config.m_index, offsets);
643 }
644
645 if (m_trx->isolation_level > TRX_ISO_READ_UNCOMMITTED &&
646 !view->changes_visible(rec_trx_id, table_name)) {
647 rec_t *old_vers;
648
649 row_vers_build_for_consistent_read(rec, mtr, m_config.m_index, &offsets,
650 view, &heap, heap, &old_vers,
651 nullptr, nullptr);
652
653 rec = old_vers;
654
655 if (rec == nullptr) {
656 return (false);
657 }
658 }
659 } else {
660 /* Secondary index scan not supported yet. */
661 ut_error;
662 }
663 }
664
665 if (rec_get_deleted_flag(rec, m_config.m_is_compact)) {
666 /* This record was deleted in the latest committed version, or it was
667 deleted and then reinserted-by-update before purge kicked in. Skip it. */
668 return (false);
669 }
670
671 ut_ad(!m_trx || m_trx->isolation_level == TRX_ISO_READ_UNCOMMITTED ||
672 !rec_offs_any_null_extern(m_config.m_index, rec, offsets));
673
674 return (true);
675 }
676
677 void Parallel_reader::Scan_ctx::copy_row(const rec_t *rec, Iter *iter) const {
678 iter->m_offsets =
679 rec_get_offsets(rec, m_config.m_index, nullptr, ULINT_UNDEFINED,
680 UT_LOCATION_HERE, &iter->m_heap);
681
682 /* Copy the row from the page to the scan iterator. The copy should use
683 memory from the iterator heap because the scan iterator owns the copy. */
684 auto rec_len = rec_offs_size(iter->m_offsets);
685
686 auto copy_rec = static_cast<rec_t *>(mem_heap_alloc(iter->m_heap, rec_len));
687
688 /* In InnoDB rec_t points after the extra bytes. */
689 const auto extra = rec_offs_extra_size(iter->m_offsets);
690 ut_ad(extra <= rec_len);
691
692 memcpy(copy_rec, rec - extra, rec_len);
693 /* Even though we (by convention) point after extra bytes, all of them
694 will be freed, as instead of free(iter->m_rec) we use mem_heap_empty(). */
695 iter->m_rec = copy_rec + extra;
696
697 auto tuple = row_rec_to_index_entry_low(iter->m_rec, m_config.m_index,
698 iter->m_offsets, iter->m_heap);
699
700 ut_ad(dtuple_validate(tuple));
701
702 /* We have copied the entire record but we only need to compare the
703 key columns when we check for boundary conditions. */
704 const auto n_compare = dict_index_get_n_unique_in_tree(m_config.m_index);
705
706 dtuple_set_n_fields_cmp(tuple, n_compare);
707
708 iter->m_tuple = tuple;
709 }
710
711 std::shared_ptr<Parallel_reader::Scan_ctx::Iter>
712 Parallel_reader::Scan_ctx::create_persistent_cursor(
713 const page_cur_t &page_cursor, mtr_t *mtr) const {
714 ut_ad(index_s_own());
715
716 std::shared_ptr<Iter> iter = std::make_shared<Iter>();
717
718 iter->m_heap = mem_heap_create(sizeof(btr_pcur_t) + (srv_page_size / 16),
719 UT_LOCATION_HERE);
720
721 auto rec = page_cursor.rec;
722
723 const bool is_infimum = page_rec_is_infimum(rec);
724
725 if (is_infimum) {
726 rec = page_rec_get_next(rec);
727 }
728
729 if (page_rec_is_supremum(rec)) {
730 /* Empty page, only root page can be empty. */
731 ut_a(!is_infimum ||
732 page_cursor.block->page.id.page_no() == m_config.m_index->page);
733 return (iter);
734 }
735
736 void *ptr = mem_heap_alloc(iter->m_heap, sizeof(btr_pcur_t));
737
738 ::new (ptr) btr_pcur_t();
739
740 iter->m_pcur = reinterpret_cast<btr_pcur_t *>(ptr);
741
742 iter->m_pcur->init(m_config.m_read_level);
743
744 /* Make a copy of the rec. */
745 copy_row(rec, iter.get());
746
747 iter->m_pcur->open_on_user_rec(page_cursor, PAGE_CUR_GE,
748 BTR_ALREADY_S_LATCHED | BTR_SEARCH_LEAF);
749
750 ut_ad(btr_page_get_level(buf_block_get_frame(iter->m_pcur->get_block())) ==
751 m_config.m_read_level);
752
753 iter->m_pcur->store_position(mtr);
754 iter->m_pcur->set_fetch_type(Page_fetch::SCAN);
755
756 return (iter);
757 }
758
759 bool Parallel_reader::Ctx::move_to_next_node(PCursor *pcursor) {
760 IF_DEBUG(auto cur = m_range.first->m_pcur->get_page_cur();)
761
762 auto err = pcursor->move_to_next_block(const_cast<dict_index_t *>(index()));
763
764 if (err != DB_SUCCESS) {
765 ut_a(err == DB_END_OF_INDEX);
766 return false;
767 } else {
768 /* Page can't be empty unless it is a root page. */
769 ut_ad(!page_cur_is_after_last(cur));
770 ut_ad(!page_cur_is_before_first(cur));
771 return true;
772 }
773 }
774
775 dberr_t Parallel_reader::Ctx::traverse() {
776 /* Take index lock if the requested read level is on a non-leaf level as the
777 index lock is required to access non-leaf page. */
778 if (m_scan_ctx->m_config.m_read_level != 0) {
779 m_scan_ctx->index_s_lock();
780 }
781
782 mtr_t mtr;
783 mtr.start();
784 mtr.set_log_mode(MTR_LOG_NO_REDO);
785
786 auto &from = m_range.first;
787
788 PCursor pcursor(from->m_pcur, &mtr, m_scan_ctx->m_config.m_read_level);
789 if (!pcursor.restore_to_largest_le_position_saved()) {
790 /* Move to the next record on the page */
791 page_cur_move_to_next(pcursor.get_page_cursor());
792 }
793
794 dberr_t err{DB_SUCCESS};
795
796 m_thread_ctx->m_pcursor = &pcursor;
797
798 err = traverse_recs(&pcursor, &mtr);
799
800 if (mtr.is_active()) {
801 mtr.commit();
802 }
803
804 m_thread_ctx->m_pcursor = nullptr;
805
806 if (m_scan_ctx->m_config.m_read_level != 0) {
807 m_scan_ctx->index_s_unlock();
808 }
809
810 return (err);
811 }
812
813 dberr_t Parallel_reader::Ctx::traverse_recs(PCursor *pcursor, mtr_t *mtr) {
814 const auto &end_tuple = m_range.second->m_tuple;
815 auto heap = mem_heap_create(srv_page_size / 4, UT_LOCATION_HERE);
816 auto index = m_scan_ctx->m_config.m_index;
817
818 m_start = true;
819
820 dberr_t err{DB_SUCCESS};
821
822 if (m_scan_ctx->m_reader->m_start_callback) {
823 /* Page start. */
824 m_thread_ctx->m_state = State::PAGE;
825 err = m_scan_ctx->m_reader->m_start_callback(m_thread_ctx);
826 }
827
828 bool call_end_page{true};
829 auto cur = pcursor->get_page_cursor();
830
831 while (err == DB_SUCCESS) {
832 if (page_cur_is_after_last(cur)) {
833 call_end_page = false;
834
835 if (m_scan_ctx->m_reader->m_finish_callback) {
836 /* End of page. */
837 m_thread_ctx->m_state = State::PAGE;
838 err = m_scan_ctx->m_reader->m_finish_callback(m_thread_ctx);
839 if (err != DB_SUCCESS) {
840 break;
841 }
842 }
843
844 mem_heap_empty(heap);
845
846 if (!(m_n_pages % TRX_IS_INTERRUPTED_PROBE) &&
847 trx_is_interrupted(trx())) {
848 err = DB_INTERRUPTED;
849 break;
850 }
851
852 if (is_error_set()) {
853 break;
854 }
855
856 /* Note: The page end callback (above) can save and restore the cursor.
857 The restore can end up in the middle of a page. */
858 if (pcursor->is_after_last_on_page() && !move_to_next_node(pcursor)) {
859 break;
860 }
861
862 ++m_n_pages;
863 m_first_rec = true;
864
865 call_end_page = true;
866
867 if (m_scan_ctx->m_reader->m_start_callback) {
868 /* Page start. */
869 m_thread_ctx->m_state = State::PAGE;
870 err = m_scan_ctx->m_reader->m_start_callback(m_thread_ctx);
871 if (err != DB_SUCCESS) {
872 break;
873 }
874 }
875 }
876
877 ulint offsets_[REC_OFFS_NORMAL_SIZE];
878 ulint *offsets = offsets_;
879
880 rec_offs_init(offsets_);
881
882 const rec_t *rec = page_cur_get_rec(cur);
883 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
884 UT_LOCATION_HERE, &heap);
885
886 if (end_tuple != nullptr) {
887 ut_ad(rec != nullptr);
888
889 /* Key value of a record can change only if the record is deleted or if
890 it's updated. An update is essentially a delete + insert. So in both
891 the cases we just delete mark the record and the original key value is
892 preserved on the page.
893
894 Since the range creation is based on the key values and the key value do
895 not ever change the, latest (non-MVCC) version of the record should always
896 tell us correctly whether we're within the range or outside of it. */
897 auto ret = end_tuple->compare(rec, index, offsets);
898
899 /* Note: The range creation doesn't use MVCC. Therefore it's possible
900 that the range boundary entry could have been deleted. */
901 if (ret <= 0) {
902 break;
903 }
904 }
905
906 bool skip{};
907
908 if (page_is_leaf(cur->block->frame)) {
909 skip = !m_scan_ctx->check_visibility(rec, offsets, heap, mtr);
910 }
911
912 if (!skip) {
913 m_rec = rec;
914 m_offsets = offsets;
915 m_block = cur->block;
916
917 err = m_scan_ctx->m_f(this);
918
919 if (err != DB_SUCCESS) {
920 break;
921 }
922
923 m_start = false;
924 }
925
926 m_first_rec = false;
927
928 page_cur_move_to_next(cur);
929 }
930
931 if (err != DB_SUCCESS) {
932 m_scan_ctx->set_error_state(err);
933 }
934
935 mem_heap_free(heap);
936
937 if (call_end_page && m_scan_ctx->m_reader->m_finish_callback) {
938 /* Page finished. */
939 m_thread_ctx->m_state = State::PAGE;
940 auto cb_err = m_scan_ctx->m_reader->m_finish_callback(m_thread_ctx);
941
942 if (cb_err != DB_SUCCESS && !m_scan_ctx->is_error_set()) {
943 err = cb_err;
944 }
945 }
946
947 return (err);
948 }
949
950 void Parallel_reader::enqueue(std::shared_ptr<Ctx> ctx) {
951 mutex_enter(&m_mutex);
952 m_ctxs.push_back(ctx);
953 mutex_exit(&m_mutex);
954 }
955
956 std::shared_ptr<Parallel_reader::Ctx> Parallel_reader::dequeue() {
957 mutex_enter(&m_mutex);
958
959 if (m_ctxs.empty()) {
960 mutex_exit(&m_mutex);
961 return (nullptr);
962 }
963
964 auto ctx = m_ctxs.front();
965 m_ctxs.pop_front();
966
967 mutex_exit(&m_mutex);
968
969 return (ctx);
970 }
971
972 bool Parallel_reader::is_queue_empty() const {
973 mutex_enter(&m_mutex);
974 auto empty = m_ctxs.empty();
975 mutex_exit(&m_mutex);
976 return (empty);
977 }
978
979 void Parallel_reader::worker(Parallel_reader::Thread_ctx *thread_ctx) {
980 dberr_t err{DB_SUCCESS};
981 dberr_t cb_err{DB_SUCCESS};
982
983 if (m_start_callback) {
984 /* Thread start. */
985 thread_ctx->m_state = State::THREAD;
986 cb_err = m_start_callback(thread_ctx);
987
988 if (cb_err != DB_SUCCESS) {
989 err = cb_err;
990 set_error_state(cb_err);
991 }
992 }
993
994 /* Wait for all the threads to be spawned as it's possible that we could
995 abort the operation if there are not enough resources to spawn all the
996 threads. */
997 if (!m_sync) {
998 os_event_wait_time_low(m_event, std::chrono::microseconds::max(),
999 m_sig_count);
1000 }
1001
1002 for (;;) {
1003 size_t n_completed{};
1004 int64_t sig_count = os_event_reset(m_event);
1005
1006 while (err == DB_SUCCESS && cb_err == DB_SUCCESS && !is_error_set()) {
1007 auto ctx = dequeue();
1008
1009 if (ctx == nullptr) {
1010 break;
1011 }
1012
1013 auto scan_ctx = ctx->m_scan_ctx;
1014
1015 if (scan_ctx->is_error_set()) {
1016 break;
1017 }
1018
1019 ctx->m_thread_ctx = thread_ctx;
1020
1021 if (ctx->m_split) {
1022 err = ctx->split();
1023 /* Tell the other threads that there is work to do. */
1024 os_event_set(m_event);
1025 } else {
1026 if (m_start_callback) {
1027 /* Context start. */
1028 thread_ctx->m_state = State::CTX;
1029 cb_err = m_start_callback(thread_ctx);
1030 }
1031
1032 if (cb_err == DB_SUCCESS && err == DB_SUCCESS) {
1033 err = ctx->traverse();
1034 }
1035
1036 if (m_finish_callback) {
1037 /* Context finished. */
1038 thread_ctx->m_state = State::CTX;
1039 cb_err = m_finish_callback(thread_ctx);
1040 }
1041 }
1042
1043 /* Check for trx interrupted (useful in the case of small tables). */
1044 if (err == DB_SUCCESS && trx_is_interrupted(ctx->trx())) {
1045 err = DB_INTERRUPTED;
1046 scan_ctx->set_error_state(err);
1047 break;
1048 }
1049
1050 ut_ad(err == DB_SUCCESS || scan_ctx->is_error_set());
1051
1052 ++n_completed;
1053 }
1054
1055 if (cb_err != DB_SUCCESS || err != DB_SUCCESS || is_error_set()) {
1056 break;
1057 }
1058
1059 m_n_completed.fetch_add(n_completed, std::memory_order_relaxed);
1060
1061 if (m_n_completed == m_ctx_id) {
1062 /* Wakeup other worker threads before exiting */
1063 os_event_set(m_event);
1064 break;
1065 }
1066
1067 if (!m_sync) {
1068 os_event_wait_time_low(m_event, std::chrono::microseconds::max(),
1069 sig_count);
1070 }
1071 }
1072
1073 if (err != DB_SUCCESS && !is_error_set()) {
1074 /* Set the "global" error state. */
1075 set_error_state(err);
1076 }
1077
1078 if (is_error_set()) {
1079 /* Wake up any sleeping threads. */
1080 os_event_set(m_event);
1081 }
1082
1083 if (m_finish_callback) {
1084 /* Thread finished. */
1085 thread_ctx->m_state = State::THREAD;
1086 cb_err = m_finish_callback(thread_ctx);
1087
1088 /* Keep the err status from previous failed operations */
1089 if (cb_err != DB_SUCCESS) {
1090 err = cb_err;
1091 set_error_state(cb_err);
1092 }
1093 }
1094
1095 ut_a(is_error_set() || (m_n_completed == m_ctx_id && is_queue_empty()));
1096 }
1097
1098 page_no_t Parallel_reader::Scan_ctx::search(const buf_block_t *block,
1099 const dtuple_t *key) const {
1100 ut_ad(index_s_own());
1101
1102 page_cur_t page_cursor;
1103 const auto index = m_config.m_index;
1104
1105 if (key != nullptr) {
1106 page_cur_search(block, index, key, PAGE_CUR_LE, &page_cursor);
1107 } else {
1108 page_cur_set_before_first(block, &page_cursor);
1109 }
1110
1111 if (page_rec_is_infimum(page_cur_get_rec(&page_cursor))) {
1112 page_cur_move_to_next(&page_cursor);
1113 }
1114
1115 const auto rec = page_cur_get_rec(&page_cursor);
1116
1117 mem_heap_t *heap = nullptr;
1118
1119 ulint offsets_[REC_OFFS_NORMAL_SIZE];
1120 auto offsets = offsets_;
1121
1122 rec_offs_init(offsets_);
1123
1124 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
1125 UT_LOCATION_HERE, &heap);
1126
1127 auto page_no = btr_node_ptr_get_child_page_no(rec, offsets);
1128
1129 if (heap != nullptr) {
1130 mem_heap_free(heap);
1131 }
1132
1133 return (page_no);
1134 }
1135
1136 page_cur_t Parallel_reader::Scan_ctx::start_range(
1137 page_no_t page_no, mtr_t *mtr, const dtuple_t *key,
1138 Savepoints &savepoints) const {
1139 ut_ad(index_s_own());
1140
1141 auto index = m_config.m_index;
1142 page_id_t page_id(index->space, page_no);
1143 ulint height{};
1144
1145 /* Follow the left most pointer down on each page. */
1146 for (;;) {
1147 auto savepoint = mtr->get_savepoint();
1148
1149 auto block = block_get_s_latched(page_id, mtr, __LINE__);
1150
1151 height = btr_page_get_level(buf_block_get_frame(block));
1152
1153 savepoints.push_back({savepoint, block});
1154
1155 if (height != 0 && height != m_config.m_read_level) {
1156 page_id.set_page_no(search(block, key));
1157 continue;
1158 }
1159
1160 page_cur_t page_cursor;
1161
1162 if (key != nullptr) {
1163 page_cur_search(block, index, key, PAGE_CUR_GE, &page_cursor);
1164 } else {
1165 page_cur_set_before_first(block, &page_cursor);
1166 }
1167
1168 if (page_rec_is_infimum(page_cur_get_rec(&page_cursor))) {
1169 page_cur_move_to_next(&page_cursor);
1170 }
1171
1172 return (page_cursor);
1173 }
1174 }
1175
1176 void Parallel_reader::Scan_ctx::create_range(Ranges &ranges,
1177 page_cur_t &leaf_page_cursor,
1178 mtr_t *mtr) const {
1179 leaf_page_cursor.index = m_config.m_index;
1180
1181 auto iter = create_persistent_cursor(leaf_page_cursor, mtr);
1182
1183 /* Setup the previous range (next) to point to the current range. */
1184 if (!ranges.empty()) {
1185 ut_a(ranges.back().second->m_heap == nullptr);
1186 ranges.back().second = iter;
1187 }
1188
1189 ranges.push_back(Range(iter, std::make_shared<Iter>()));
1190 }
1191
1192 dberr_t Parallel_reader::Scan_ctx::create_ranges(const Scan_range &scan_range,
1193 page_no_t page_no,
1194 size_t depth,
1195 const size_t split_level,
1196 Ranges &ranges, mtr_t *mtr) {
1197 ut_ad(index_s_own());
1198 ut_a(page_no != FIL_NULL);
1199
1200 /* Do a breadth first traversal of the B+Tree using recursion. We want to
1201 set up the scan ranges in one pass. This guarantees that the tree structure
1202 cannot change while we are creating the scan sub-ranges.
1203
1204 Once we create the persistent cursor (Range) for a sub-tree we can release
1205 the latches on all blocks traversed for that sub-tree. */
1206
1207 const auto index = m_config.m_index;
1208
1209 page_id_t page_id(index->space, page_no);
1210
1211 Savepoint savepoint({mtr->get_savepoint(), nullptr});
1212
1213 auto block = block_get_s_latched(page_id, mtr, __LINE__);
1214
1215 /* read_level requested should be less than the tree height. */
1216 ut_ad(m_config.m_read_level <
1217 btr_page_get_level(buf_block_get_frame(block)) + 1);
1218
1219 savepoint.second = block;
1220
1221 ulint offsets_[REC_OFFS_NORMAL_SIZE];
1222 auto offsets = offsets_;
1223
1224 rec_offs_init(offsets_);
1225
1226 page_cur_t page_cursor;
1227
1228 page_cursor.index = index;
1229
1230 auto start = scan_range.m_start;
1231
1232 if (start != nullptr) {
1233 page_cur_search(block, index, start, PAGE_CUR_LE, &page_cursor);
1234
1235 if (page_cur_is_after_last(&page_cursor)) {
1236 return (DB_SUCCESS);
1237 } else if (page_cur_is_before_first((&page_cursor))) {
1238 page_cur_move_to_next(&page_cursor);
1239 }
1240 } else {
1241 page_cur_set_before_first(block, &page_cursor);
1242 /* Skip the infimum record. */
1243 page_cur_move_to_next(&page_cursor);
1244 }
1245
1246 mem_heap_t *heap{};
1247
1248 const auto at_leaf = page_is_leaf(buf_block_get_frame(block));
1249 const auto at_level = btr_page_get_level(buf_block_get_frame(block));
1250
1251 Savepoints savepoints{};
1252
1253 while (!page_cur_is_after_last(&page_cursor)) {
1254 const auto rec = page_cur_get_rec(&page_cursor);
1255
1256 ut_a(at_leaf || rec_get_node_ptr_flag(rec) ||
1257 !dict_table_is_comp(index->table));
1258
1259 if (heap == nullptr) {
1260 heap = mem_heap_create(srv_page_size / 4, UT_LOCATION_HERE);
1261 }
1262
1263 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
1264 UT_LOCATION_HERE, &heap);
1265
1266 const auto end = scan_range.m_end;
1267
1268 if (end != nullptr && end->compare(rec, index, offsets) <= 0) {
1269 break;
1270 }
1271
1272 page_cur_t level_page_cursor;
1273
1274 /* Split the tree one level below the root if read_level requested is below
1275 the root level. */
1276 if (at_level > m_config.m_read_level) {
1277 auto page_no = btr_node_ptr_get_child_page_no(rec, offsets);
1278
1279 if (depth < split_level) {
1280 /* Need to create a range starting at a lower level in the tree. */
1281 create_ranges(scan_range, page_no, depth + 1, split_level, ranges, mtr);
1282
1283 page_cur_move_to_next(&page_cursor);
1284 continue;
1285 }
1286
1287 /* Find the range start in the leaf node. */
1288 level_page_cursor = start_range(page_no, mtr, start, savepoints);
1289 } else {
1290 /* In case of root node being the leaf node or in case we've been asked to
1291 read the root node (via read_level) place the cursor on the root node and
1292 proceed. */
1293
1294 if (start != nullptr) {
1295 page_cur_search(block, index, start, PAGE_CUR_GE, &page_cursor);
1296 ut_a(!page_rec_is_infimum(page_cur_get_rec(&page_cursor)));
1297 } else {
1298 page_cur_set_before_first(block, &page_cursor);
1299
1300 /* Skip the infimum record. */
1301 page_cur_move_to_next(&page_cursor);
1302 ut_a(!page_cur_is_after_last(&page_cursor));
1303 }
1304
1305 /* Since we are already at the requested level use the current page
1306 cursor. */
1307 memcpy(&level_page_cursor, &page_cursor, sizeof(level_page_cursor));
1308 }
1309
1310 if (!page_rec_is_supremum(page_cur_get_rec(&level_page_cursor))) {
1311 create_range(ranges, level_page_cursor, mtr);
1312 }
1313
1314 /* We've created the persistent cursor, safe to release S latches on
1315 the blocks that are in this range (sub-tree). */
1316 for (auto &savepoint : savepoints) {
1317 mtr->release_block_at_savepoint(savepoint.first, savepoint.second);
1318 }
1319
1320 if (m_depth == 0 && depth == 0) {
1321 m_depth = savepoints.size();
1322 }
1323
1324 savepoints.clear();
1325
1326 if (at_level == m_config.m_read_level) {
1327 break;
1328 }
1329
1330 start = nullptr;
1331
1332 page_cur_move_to_next(&page_cursor);
1333 }
1334
1335 savepoints.push_back(savepoint);
1336
1337 for (auto &savepoint : savepoints) {
1338 mtr->release_block_at_savepoint(savepoint.first, savepoint.second);
1339 }
1340
1341 if (heap != nullptr) {
1342 mem_heap_free(heap);
1343 }
1344
1345 return (DB_SUCCESS);
1346 }
1347
1348 dberr_t Parallel_reader::Scan_ctx::partition(
1349 const Scan_range &scan_range, Parallel_reader::Scan_ctx::Ranges &ranges,
1350 size_t split_level) {
1351 ut_ad(index_s_own());
1352
1353 mtr_t mtr;
1354 mtr.start();
1355 mtr.set_log_mode(MTR_LOG_NO_REDO);
1356
1357 dberr_t err{DB_SUCCESS};
1358
1359 err = create_ranges(scan_range, m_config.m_index->page, 0, split_level,
1360 ranges, &mtr);
1361
1362 if (err == DB_SUCCESS && scan_range.m_end != nullptr && !ranges.empty()) {
1363 auto &iter = ranges.back().second;
1364
1365 ut_a(iter->m_heap == nullptr);
1366
1367 iter->m_heap = mem_heap_create(sizeof(btr_pcur_t) + (srv_page_size / 16),
1368 UT_LOCATION_HERE);
1369
1370 iter->m_tuple = dtuple_copy(scan_range.m_end, iter->m_heap);
1371
1372 /* Do a deep copy. */
1373 for (size_t i = 0; i < dtuple_get_n_fields(iter->m_tuple); ++i) {
1374 dfield_dup(&iter->m_tuple->fields[i], iter->m_heap);
1375 }
1376 }
1377
1378 mtr.commit();
1379
1380 return (err);
1381 }
1382
1383 dberr_t Parallel_reader::Scan_ctx::create_context(const Range &range,
1384 bool split) {
1385 auto ctx_id = m_reader->m_ctx_id.fetch_add(1, std::memory_order_relaxed);
1386
1387 // clang-format off
1388
1389 auto ctx = std::shared_ptr<Ctx>(
1390 ut::new_withkey<Ctx>(UT_NEW_THIS_FILE_PSI_KEY, ctx_id, this, range),
1391 [](Ctx *ctx) { ut::delete_(ctx); });
1392
1393 // clang-format on
1394
1395 dberr_t err{DB_SUCCESS};
1396
1397 if (ctx.get() == nullptr) {
1398 m_reader->m_ctx_id.fetch_sub(1, std::memory_order_relaxed);
1399 return (DB_OUT_OF_MEMORY);
1400 } else {
1401 ctx->m_split = split;
1402 m_reader->enqueue(ctx);
1403 }
1404
1405 return (err);
1406 }
1407
1408 dberr_t Parallel_reader::Scan_ctx::create_contexts(const Ranges &ranges) {
1409 size_t split_point{};
1410
1411 {
1412 const auto n = std::max(max_threads(), size_t{1});
1413
1414 ut_a(n <= Parallel_reader::MAX_TOTAL_THREADS);
1415
1416 if (ranges.size() > n) {
1417 split_point = (ranges.size() / n) * n;
1418 } else if (m_depth < SPLIT_THRESHOLD) {
1419 /* If the tree is not very deep then don't split. For smaller tables
1420 it is more expensive to split because we end up traversing more blocks*/
1421 split_point = n;
1422 }
1423 }
1424
1425 size_t i{};
1426
1427 for (auto range : ranges) {
1428 auto err = create_context(range, i >= split_point);
1429
1430 if (err != DB_SUCCESS) {
1431 return (err);
1432 }
1433
1434 ++i;
1435 }
1436
1437 return DB_SUCCESS;
1438 }
1439
1440 void Parallel_reader::parallel_read() {
1441 if (m_ctxs.empty()) {
1442 return;
1443 }
1444
1445 if (m_sync) {
1446 auto ptr = ut::new_withkey<Thread_ctx>(UT_NEW_THIS_FILE_PSI_KEY, 0);
1447
1448 if (ptr == nullptr) {
1449 set_error_state(DB_OUT_OF_MEMORY);
1450 return;
1451 }
1452
1453 m_thread_ctxs.push_back(ptr);
1454
1455 /* Set event to indicate to ::worker() that no threads will be spawned. */
1456 os_event_set(m_event);
1457
1458 worker(m_thread_ctxs[0]);
1459
1460 return;
1461 }
1462
1463 ut_a(m_n_threads > 0);
1464
1465 m_thread_ctxs.reserve(m_n_threads);
1466
1467 dberr_t err{DB_SUCCESS};
1468
1469 for (size_t i = 0; i < m_n_threads; ++i) {
1470 try {
1471 auto ptr = ut::new_withkey<Thread_ctx>(UT_NEW_THIS_FILE_PSI_KEY, i);
1472 if (ptr == nullptr) {
1473 set_error_state(DB_OUT_OF_MEMORY);
1474 return;
1475 }
1476 m_thread_ctxs.emplace_back(ptr);
1477 m_parallel_read_threads.emplace_back(
1478 os_thread_create(parallel_read_thread_key, i + 1,
1479 &Parallel_reader::worker, this, m_thread_ctxs[i]));
1480 m_parallel_read_threads.back().start();
1481 } catch (...) {
1482 err = DB_OUT_OF_RESOURCES;
1483 /* Set the global error state to tell the worker threads to exit. */
1484 set_error_state(err);
1485 break;
1486 }
1487 }
1488
1489 DEBUG_SYNC_C("parallel_read_wait_for_kill_query");
1490
1491 DBUG_EXECUTE_IF(
1492 "innodb_pread_thread_OOR", if (!m_sync) {
1493 err = DB_OUT_OF_RESOURCES;
1494 set_error_state(err);
1495 });
1496
1497 os_event_set(m_event);
1498
1499 DBUG_EXECUTE_IF("bug28079850", set_error_state(DB_INTERRUPTED););
1500 }
1501
1502 dberr_t Parallel_reader::spawn(size_t n_threads) noexcept {
1503 /* In case this is a retry after a DB_OUT_OF_RESOURCES error. */
1504 m_err = DB_SUCCESS;
1505
1506 m_n_threads = n_threads;
1507
1508 if (max_threads() > m_n_threads) {
1509 release_unused_threads(max_threads() - m_n_threads);
1510 }
1511
1512 parallel_read();
1513
1514 return DB_SUCCESS;
1515 }
1516
1517 dberr_t Parallel_reader::run(size_t n_threads) {
1518 /* In case this is a retry after a DB_OUT_OF_RESOURCES error. */
1519 m_err = DB_SUCCESS;
1520
1521 ut_a(max_threads() >= n_threads);
1522
1523 if (n_threads == 0) {
1524 m_sync = true;
1525 }
1526
1527 const auto err = spawn(n_threads);
1528
1529 /* Don't wait for the threads to finish if the read is not synchronous or
1530 if there's no parallel read. */
1531 if (m_sync) {
1532 if (err != DB_SUCCESS) {
1533 return err;
1534 }
1535 ut_a(m_n_threads == 0);
1536 return is_error_set() ? m_err.load() : DB_SUCCESS;
1537 } else {
1538 join();
1539
1540 if (err != DB_SUCCESS) {
1541 return err;
1542 } else if (is_error_set()) {
1543 return m_err;
1544 }
1545
1546 for (auto &scan_ctx : m_scan_ctxs) {
1547 if (scan_ctx->is_error_set()) {
1548 /* Return the state of the first Scan context that is in state ERROR. */
1549 return scan_ctx->m_err;
1550 }
1551 }
1552 }
1553
1554 return DB_SUCCESS;
1555 }
1556
1557 dberr_t Parallel_reader::add_scan(trx_t *trx,
1558 const Parallel_reader::Config &config,
1559 Parallel_reader::F &&f) {
1560 // clang-format off
1561
1562 auto scan_ctx = std::shared_ptr<Scan_ctx>(
1563 ut::new_withkey<Scan_ctx>(UT_NEW_THIS_FILE_PSI_KEY, this, m_scan_ctx_id, trx, config, std::move(f)),
1564 [](Scan_ctx *scan_ctx) { ut::delete_(scan_ctx); });
1565
1566 // clang-format on
1567
1568 if (scan_ctx.get() == nullptr) {
1569 ib::error(ER_IB_ERR_PARALLEL_READ_OOM) << "Out of memory";
1570 return (DB_OUT_OF_MEMORY);
1571 }
1572
1573 m_scan_ctxs.push_back(scan_ctx);
1574
1575 ++m_scan_ctx_id;
1576
1577 scan_ctx->index_s_lock();
1578
1579 Parallel_reader::Scan_ctx::Ranges ranges{};
1580 dberr_t err{DB_SUCCESS};
1581
1582 /* Split at the root node (level == 0). */
1583 err = scan_ctx->partition(config.m_scan_range, ranges, 0);
1584
1585 if (ranges.empty() || err != DB_SUCCESS) {
1586 /* Table is empty. */
1587 scan_ctx->index_s_unlock();
1588 return (err);
1589 }
1590
1591 err = scan_ctx->create_contexts(ranges);
1592
1593 scan_ctx->index_s_unlock();
1594
1595 return (err);
1596 }