-
Notifications
You must be signed in to change notification settings - Fork 482
/
Copy pathbtr0sea.cc
2063 lines (1668 loc) · 70 KB
/
btr0sea.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
Copyright (c) 1996, 2024, Oracle and/or its affiliates.
Copyright (c) 2008, Google Inc.
Portions of this file contain modifications contributed and copyrighted by
Google, Inc. Those modifications are gratefully acknowledged and are described
briefly in the InnoDB documentation. The contributions by Google are
incorporated with their permission, and subject to the conditions contained in
the file COPYING.Google.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2.0, as published by the
Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
/** @file btr/btr0sea.cc
The index tree adaptive search
Created 2/17/1996 Heikki Tuuri
*************************************************************************/
#include "btr0sea.h"
#include <sys/types.h>
#include "btr0btr.h"
#include "btr0cur.h"
#include "btr0pcur.h"
#include "buf0buf.h"
#include "ha0ha.h"
#include "page0cur.h"
#include "page0page.h"
#include "srv0mon.h"
#include "sync0sync.h"
#include <scope_guard.h>
/** Flag storing if the search system is in enabled state. While it is false,
the AHI data structures can't have new entries added, they can only be
removed. It is changed to false while having all AHI latches X-latched, so any
section that adds entries to AHI data structures must have at least one S-latch.
All changes to this flag are protected by the btr_search_enable_mutex. */
std::atomic_bool btr_search_enabled = true;
/** A value that basically stores the same as btr_search_enabled, but is not
atomic and thus can be used as SYSVAR. */
bool srv_btr_search_enabled = true;
/** Protects changes of btr_search_enabled flag. */
static ib_mutex_t btr_search_enabled_mutex;
/** Number of adaptive hash index partition. */
ulong btr_ahi_parts = 8;
ut::fast_modulo_t btr_ahi_parts_fast_modulo(8);
#ifdef UNIV_SEARCH_PERF_STAT
/** Number of successful adaptive hash index lookups */
ulint btr_search_n_succ = 0;
/** Number of failed adaptive hash index lookups */
ulint btr_search_n_hash_fail = 0;
#endif /* UNIV_SEARCH_PERF_STAT */
/* It is not unique_ptr, as destroying it at exit() will destroy its rw_lock
after the PFS is deinitialized. */
btr_search_sys_t *btr_search_sys;
/** If the number of records on the page divided by this parameter
would have been successfully accessed using a hash index, the index
is then built on the page, assuming the global limit has been reached */
constexpr uint32_t BTR_SEARCH_PAGE_BUILD_LIMIT = 16;
/** The global limit for consecutive potentially successful hash searches,
before hash index building is started */
constexpr uint32_t BTR_SEARCH_BUILD_LIMIT = 100;
/** Compute a value to seed the hash value of a record.
@param[in] index Index structure
@return hash value for seed */
static ulint btr_hash_seed_for_record(const dict_index_t *index) {
ut_ad(index != nullptr);
return btr_search_hash_index_id(index);
}
/** Get the hash-table based on index attributes.
A table is selected from an array of tables using pair of index-id, space-id.
@param[in] index index handler
@return hash table */
static inline hash_table_t *btr_get_search_table(const dict_index_t *index) {
/* One can't use the returned table if these latches are not taken. Any resize
of the AHI that is run in meantime will delete it. Note that btr_ahi_parts
can't change once AHI is initialized. */
ut_ad(rw_lock_own_flagged(btr_get_search_latch(index),
RW_LOCK_FLAG_S | RW_LOCK_FLAG_X));
return btr_get_search_part(index).hash_table;
}
/** Determine the number of accessed key fields.
@param[in] prefix_info prefix information to get number of fields from
@return number of complete or incomplete fields */
[[nodiscard]] inline uint16_t btr_search_get_n_fields(
btr_search_prefix_info_t prefix_info) {
return prefix_info.n_fields + (prefix_info.n_bytes > 0 ? 1 : 0);
}
/** Determine the number of accessed key fields.
@param[in] cursor b-tree cursor
@return number of complete or incomplete fields */
[[nodiscard]] inline uint16_t btr_search_get_n_fields(const btr_cur_t *cursor) {
return btr_search_get_n_fields(cursor->ahi.prefix_info);
}
/** Builds a hash index on a page with the block's recommended parameters. If
the page already has a hash index with different parameters, the old hash index
is removed. This function checks if n_fields and n_bytes are sensible, and does
not build a hash index if not.
@param[in,out] index index for which to build
@param[in,out] block index page, s-/x- latched.
@param[in] update specifies if the page should be only added to index
(false) or possibly updated if any hash entries are
already added for the records this page has (true) */
static void btr_search_build_page_hash_index(dict_index_t *index,
buf_block_t *block, bool update);
/** Checks that there is a free buffer frame allocated for hash table heap in
the btr search system. If not, allocates a free frame for the heap. This
function should be called before reserving any btr search mutex, if the intended
operation might add nodes to the search system hash table. The heap frame will
allow to do some insertions to the AHI hash table, but does not guarantee
anything, i.e. there may be a space in frame only for a part of the nodes to
insert or some other concurrent operation on AHI could consume the frame's
memory before we latch the AHI.
@param[in] index index handler
*/
static inline void btr_search_check_free_space_in_heap(dict_index_t *index) {
if (!btr_search_enabled) {
return;
}
ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_S));
ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X));
auto &free_block_for_heap = btr_get_search_part(index).free_block_for_heap;
const bool no_free_block = free_block_for_heap.load() == nullptr;
/* We can't do this check and alloc a block from Buffer pool only when needed
while inserting new nodes to AHI hash table, as in case the eviction is needed
to free up a block from LRU, the AHI latches may be required to complete the
page eviction. The execution can reach the following path: buf_block_alloc ->
buf_LRU_get_free_block -> buf_LRU_scan_and_free_block ->
buf_LRU_free_from_common_LRU_list -> buf_LRU_free_page ->
btr_search_drop_page_hash_index */
if (no_free_block) {
const auto block = buf_block_alloc(nullptr);
buf_block_t *expected = nullptr;
ut_ad(block != nullptr);
if (!free_block_for_heap.compare_exchange_strong(expected, block)) {
/* Someone must have set the free_block in meantime, return the allocated
block to pool. */
buf_block_free(block);
}
}
}
void btr_search_sys_create(ulint hash_size) {
/* Copy the initial SYSVAR value. While the Server is starting, the updater
for SYSVARs is not called to set their initial value. */
btr_search_enabled = srv_btr_search_enabled;
btr_search_sys = ut::new_withkey<btr_search_sys_t>(
ut::make_psi_memory_key(mem_key_ahi), hash_size);
mutex_create(LATCH_ID_AHI_ENABLED, &btr_search_enabled_mutex);
}
btr_search_sys_t::btr_search_sys_t(size_t hash_size) {
using part_type = btr_search_sys_t::search_part_t;
parts = ut::make_unique_aligned<part_type[]>(
ut::make_psi_memory_key(mem_key_ahi), alignof(part_type), btr_ahi_parts);
static_assert(alignof(part_type) >= ut::INNODB_CACHE_LINE_SIZE);
/* It is written only from one thread during server initialization, so it is
safe. */
btr_ahi_parts_fast_modulo = ut::fast_modulo_t{btr_ahi_parts};
for (ulint i = 0; i < btr_ahi_parts; ++i) {
parts[i].initialize(hash_size);
}
}
void btr_search_sys_t::search_part_t::initialize(size_t hash_size) {
/* Step-1: Init latches. */
rw_lock_create(btr_search_latch_key, &latch, LATCH_ID_BTR_SEARCH);
/* Step-2: Allocate hash tables. */
hash_table = ib_create((hash_size / btr_ahi_parts), LATCH_ID_HASH_TABLE_MUTEX,
0, MEM_HEAP_FOR_BTR_SEARCH);
hash_table->heap->free_block_ptr = &free_block_for_heap;
#if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG
hash_table->adaptive = true;
#endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */
}
void btr_search_sys_resize(ulint hash_size) {
/* Step-1: Lock all search latches in exclusive mode. */
btr_search_x_lock_all(UT_LOCATION_HERE);
if (btr_search_enabled) {
btr_search_x_unlock_all();
ib::error(ER_IB_MSG_45) << "btr_search_sys_resize failed because"
" hash index hash table is not empty.";
ut_d(ut_error);
ut_o(return);
}
/* Step-2: Recreate hash tables with new size. */
for (ulint i = 0; i < btr_ahi_parts; ++i) {
auto &part = btr_search_sys->parts[i];
mem_heap_free(part.hash_table->heap);
ut::delete_(part.hash_table);
part.hash_table =
ib_create((hash_size / btr_ahi_parts), LATCH_ID_HASH_TABLE_MUTEX, 0,
MEM_HEAP_FOR_BTR_SEARCH);
part.hash_table->heap->free_block_ptr = &part.free_block_for_heap;
#if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG
part.hash_table->adaptive = true;
#endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */
}
/* Step-3: Unlock all search latches from exclusive mode. */
btr_search_x_unlock_all();
}
void btr_search_sys_free() {
if (btr_search_sys == nullptr) {
return;
}
for (ulint i = 0; i < btr_ahi_parts; ++i) {
auto &part = btr_search_sys->parts[i];
mem_heap_free(part.hash_table->heap);
ut::delete_(part.hash_table);
}
ut::delete_(btr_search_sys);
btr_search_sys = nullptr;
mutex_destroy(&btr_search_enabled_mutex);
}
void btr_search_await_no_reference(dict_table_t *table, dict_index_t *index,
bool force) {
ut_ad(dict_sys_mutex_own());
uint sleep_counter = 0;
/* We always create search info whether adaptive hash index is enabled or not.
*/
ut_ad(index->search_info);
while (index->search_info->ref_count.load() != 0 &&
(force || srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP)) {
std::this_thread::sleep_for(std::chrono::milliseconds{10});
sleep_counter++;
if (sleep_counter % 500 == 0) {
ib::error(ER_IB_LONG_AHI_DISABLE_WAIT, sleep_counter / 100,
index->search_info->ref_count.load(), index->name(),
table->name.m_name);
}
/* To avoid a hang here we commit suicide if the ref_count doesn't drop to
zero in 600 seconds. */
ut_a(sleep_counter < 60000);
}
}
/** Wait for every index in the specified table to have all references from AHI
dropped. This can only be called while the AHI is being disabled. The last fact
causes that no new references to indexes can be added from AHI, so the reference
count will monotonically drop to zero.
@param[in,out] table table handler */
static void btr_search_await_no_reference(dict_table_t *table) {
ut_ad(dict_sys_mutex_own());
ut_ad(mutex_own(&btr_search_enabled_mutex));
for (auto index = table->first_index(); index != nullptr;
index = index->next()) {
btr_search_await_no_reference(table, index, false);
}
}
bool btr_search_disable() {
if (!dict_sys) return false;
mutex_enter(&btr_search_enabled_mutex);
if (!btr_search_enabled) {
mutex_exit(&btr_search_enabled_mutex);
return false;
}
btr_search_x_lock_all(UT_LOCATION_HERE);
ut_a(btr_search_enabled);
btr_search_enabled = false;
srv_btr_search_enabled = false;
btr_search_x_unlock_all();
/* Clear AHI info for all non-private blocks from Buffer Pool. */
buf_pool_clear_hash_index();
dict_sys_mutex_enter();
/* Wait for every index in the data dictionary cache to have no references to
AHI. After the buf_pool_clear_hash_index() is called, there might be some
blocks that are being evicted by buf_LRU_free_page() and they are in
BUF_BLOCK_REMOVE_HASH state. We will wait for them to be removed from AHI. */
for (auto table : dict_sys->table_LRU) {
btr_search_await_no_reference(table);
}
for (auto table : dict_sys->table_non_LRU) {
btr_search_await_no_reference(table);
}
dict_sys_mutex_exit();
/* Clear the adaptive hash index. */
for (ulint i = 0; i < btr_ahi_parts; ++i) {
const auto hash_table = btr_search_sys->parts[i].hash_table;
hash_table_clear(hash_table);
mem_heap_empty(hash_table->heap);
}
mutex_exit(&btr_search_enabled_mutex);
return true;
}
void btr_search_enable() {
os_rmb;
/* Don't allow enabling AHI if buffer pool resize is happening.
Ignore it silently. */
if (srv_buf_pool_old_size != srv_buf_pool_size) return;
/* We need to synchronize with any threads that are in the middle of
btr_search_disable() - they must first clear all structures before we can
re-enable AHI again. */
mutex_enter(&btr_search_enabled_mutex);
btr_search_enabled = true;
srv_btr_search_enabled = true;
mutex_exit(&btr_search_enabled_mutex);
}
btr_search_t *btr_search_info_create(mem_heap_t *heap) {
btr_search_t *info;
info = (btr_search_t *)mem_heap_alloc(heap, sizeof(btr_search_t));
ut_d(info->magic_n = BTR_SEARCH_MAGIC_N);
info->ref_count = 0;
info->root_guess = nullptr;
info->hash_analysis = 0;
info->n_hash_potential = 0;
info->last_hash_succ = false;
#ifdef UNIV_SEARCH_PERF_STAT
info->n_hash_succ = 0;
info->n_hash_fail = 0;
info->n_patt_succ = 0;
info->n_searches = 0;
#endif /* UNIV_SEARCH_PERF_STAT */
/* Set some sensible values */
info->prefix_info = {0, 1, true};
return info;
}
/** Updates the search info of an index about hash successes. NOTE that info
is NOT protected by any semaphore, to save CPU time! Do not assume its fields
are consistent.
@param[in] cursor cursor which was just positioned */
static void btr_search_info_update_hash(btr_cur_t *cursor) {
dict_index_t *index = cursor->index;
int cmp;
ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_S));
ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X));
if (dict_index_is_ibuf(index)) {
/* So many deletes are performed on an insert buffer tree
that we do not consider a hash index useful on it: */
return;
}
const uint16_t n_unique =
static_cast<uint16_t>(dict_index_get_n_unique_in_tree(index));
const auto info = index->search_info;
if (info->n_hash_potential != 0) {
const auto prefix_info = info->prefix_info.load();
/* Test if the search would have succeeded using the recommended
hash prefix */
/* If AHI uses all unique columns as a key, then each record is in its own
equal-prefix-group, so it doesn't matter if we use left_side or not. Such
a cache is only useful for searches with the whole unique part of the key
specified in the query. */
ut_a(prefix_info.n_fields <= n_unique);
ut_ad(cursor->up_match <= n_unique);
ut_ad(cursor->low_match <= n_unique);
if (prefix_info.n_fields == n_unique &&
std::max(cursor->up_match, cursor->low_match) == n_unique) {
info->n_hash_potential++;
return;
}
/* The search in B-tree has stopped at two consecutive tuples 'low' and
'up', and we'd like the search in AHI to also find one of them. First, it
means that one of them needs to have same first prefix_info.n_fields fields
and n_bytes of next field equal to the sought tuple. In other words
`low_matches_prefix||up_matches_prefix`. But, AHI keeps only one record from
each equal-prefix-group of records, either the left-most or right-most of
the group, depending on `prefix_info.left_side`. So if both
`low_matches_prefix` and `up_matches_prefix` are true, it means there's no
group boundary between them, and even if one of them is at the boundary it's
"by accident" and the procedure for recommending a prefix length would not
choose such a short prefix, as it tries to pick a prefix length which would
create the boundary between low and up. What we want is that if we cache
the left-most record from each group, then up matches, and low not, so that
up is at the boundary, and would get cached. And the opposite if we cache
right-most. */
const bool low_matches_prefix =
0 >= ut_pair_cmp(prefix_info.n_fields, prefix_info.n_bytes,
cursor->low_match, cursor->low_bytes);
const bool up_matches_prefix =
0 >= ut_pair_cmp(prefix_info.n_fields, prefix_info.n_bytes,
cursor->up_match, cursor->up_bytes);
if (prefix_info.left_side ? (!low_matches_prefix && up_matches_prefix)
: (low_matches_prefix && !up_matches_prefix)) {
info->n_hash_potential++;
return;
}
}
/* We have to set a new recommendation; skip the hash analysis
for a while to avoid unnecessary CPU time usage when there is no
chance for success */
info->hash_analysis = 0;
cmp = ut_pair_cmp(cursor->up_match, cursor->up_bytes, cursor->low_match,
cursor->low_bytes);
if (cmp == 0) {
info->n_hash_potential = 0;
/* For extra safety, we set some sensible values here */
info->prefix_info = {0, 1, true};
} else if (cmp > 0) {
info->n_hash_potential = 1;
ut_ad(cursor->up_match <= n_unique);
if (cursor->up_match == n_unique) {
info->prefix_info = {0, n_unique, true};
} else if (cursor->low_match < cursor->up_match) {
info->prefix_info = {0, static_cast<uint16_t>(cursor->low_match + 1),
true};
} else {
info->prefix_info = {static_cast<uint32_t>(cursor->low_bytes + 1),
static_cast<uint16_t>(cursor->low_match), true};
}
} else {
info->n_hash_potential = 1;
ut_ad(cursor->low_match <= n_unique);
if (cursor->low_match == n_unique) {
info->prefix_info = {0, n_unique, false};
} else if (cursor->low_match > cursor->up_match) {
info->prefix_info = {0, static_cast<uint16_t>(cursor->up_match + 1),
false};
} else {
info->prefix_info = {static_cast<uint32_t>(cursor->up_bytes + 1),
static_cast<uint16_t>(cursor->up_match), false};
}
}
}
/** Update the block search info on hash successes. NOTE that info and
block->n_hash_helps, ahi.prefix_info are NOT protected by any
semaphore, to save CPU time! Do not assume the fields are consistent.
@return true if building a (new) hash index on the block is recommended
@param[in,out] block buffer block
@param[in] cursor cursor */
static bool btr_search_update_block_hash_info(buf_block_t *block,
const btr_cur_t *cursor) {
ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_S));
ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X));
ut_ad(rw_lock_own_flagged(&block->lock, RW_LOCK_FLAG_S | RW_LOCK_FLAG_X));
const auto info = cursor->index->search_info;
info->last_hash_succ = false;
ut_a(buf_block_state_valid(block));
ut_ad(info->magic_n == BTR_SEARCH_MAGIC_N);
if (block->n_hash_helps > 0 && info->n_hash_potential > 0 &&
block->ahi.recommended_prefix_info.load() == info->prefix_info.load()) {
/* The current index's prefix info is already used as recommendation for
this block's prefix. */
if (block->ahi.index &&
block->ahi.prefix_info.load() == info->prefix_info.load()) {
/* The recommended prefix is what is actually being used in this block.
The search would presumably have succeeded using the hash index. */
info->last_hash_succ = true;
}
block->n_hash_helps++;
} else {
block->n_hash_helps = 1;
block->ahi.recommended_prefix_info = info->prefix_info.load();
}
#ifdef UNIV_DEBUG
if (cursor->index->table->does_not_fit_in_memory) {
block->n_hash_helps = 0;
}
#endif /* UNIV_DEBUG */
if (info->n_hash_potential >= BTR_SEARCH_BUILD_LIMIT &&
block->n_hash_helps >
page_get_n_recs(block->frame) / BTR_SEARCH_PAGE_BUILD_LIMIT) {
if (!block->ahi.index ||
block->n_hash_helps > 2 * page_get_n_recs(block->frame) ||
block->ahi.recommended_prefix_info.load() !=
block->ahi.prefix_info.load()) {
/* Build a new hash index on the page if:
- the block is not yet in AHI, or
- we queried 2 times the number of records on this page successfully (TODO
explain the reason why it is needed), or
- the recommendation differs from what prefix info is currently used in
block for hashing in AHI. */
return true;
}
}
return false;
}
/** Updates a hash node reference when it has been unsuccessfully used in a
search which could have succeeded with the used hash parameters. This can
happen because when building a hash index for a page, we do not check
what happens at page boundaries, and therefore there can be misleading
hash nodes. Also, collisions in the hash value can lead to misleading
references. This function lazily fixes these imperfections in the hash
index.
@param[in] block buffer block where cursor positioned
@param[in] cursor cursor */
static void btr_search_update_hash_ref(buf_block_t *block,
const btr_cur_t *cursor) {
ut_ad(cursor->flag == BTR_CUR_HASH_FAIL);
ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X));
ut_ad(rw_lock_own_flagged(&(block->lock), RW_LOCK_FLAG_S | RW_LOCK_FLAG_X));
ut_ad(page_align(btr_cur_get_rec(cursor)) == buf_block_get_frame(block));
block->ahi.validate();
const auto index = block->ahi.index.load();
const auto block_prefix_info = block->ahi.prefix_info.load();
if (!index) {
return;
}
ut_ad(block->page.id.space() == index->space);
ut_a(index == cursor->index);
ut_a(!dict_index_is_ibuf(index));
const auto info = index->search_info;
/* Dirty read without latch, will be repeated after we take the x-latch, which
we take after we have the hash value ready, to reduce time consumed under the
latch. If the current index's prefix info is different than current block's
prefix info used in AHI, then the block will have to be removed (and
reinserted) from AHI very soon. It does not make sense to update any records
using outdated prefix info. Note that only records folded using the block's
current prefix info can be in AHI. */
if (info->n_hash_potential > 0 &&
block_prefix_info == info->prefix_info.load()) {
const auto rec = btr_cur_get_rec(cursor);
if (!page_rec_is_user_rec(rec)) {
return;
}
const auto hash_value = rec_hash(
rec, Rec_offsets{}.compute(rec, index), block_prefix_info.n_fields,
block_prefix_info.n_bytes, btr_hash_seed_for_record(index), index);
btr_search_check_free_space_in_heap(cursor->index);
if (!btr_search_x_lock_nowait(cursor->index, UT_LOCATION_HERE)) {
return;
}
/* After we acquire AHI latch we re-check the AHI is enabled, and was not
disabled and re-enabled in meantime (the block's index would be reset to
nullptr then, and later maybe even re-inserted to AHI again in case we don't
have the block->lock X-latched). The block's prefix info will be current and
we check if it still matches the prefix info we used to fold the record. If
it does not match, we can't add the entry to hash table, as it would never
be deleted and would corrupt the AHI. */
if (btr_search_enabled && block->ahi.index != nullptr) {
ut_ad(block->ahi.index == index);
if (info->n_hash_potential > 0 &&
block_prefix_info == block->ahi.prefix_info.load()) {
const auto hash_table = btr_get_search_table(index);
ha_insert_for_hash(hash_table, hash_value, block, rec);
}
}
btr_search_x_unlock(cursor->index);
}
}
void btr_search_info_update_slow(btr_cur_t *cursor) {
ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_S));
ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X));
const auto block = btr_cur_get_block(cursor);
SRV_CORRUPT_TABLE_CHECK(block, return;);
/* NOTE that the following two function calls do NOT protect
info or block->ahi with any semaphore, to save CPU time!
We cannot assume the fields are consistent when we return from
those functions! */
btr_search_info_update_hash(cursor);
#ifdef UNIV_SEARCH_PERF_STAT
if (cursor->flag == BTR_CUR_HASH_FAIL) {
btr_search_n_hash_fail++;
}
#endif /* UNIV_SEARCH_PERF_STAT */
if (btr_search_update_block_hash_info(block, cursor)) {
/* Note that since we did not protect block->ahi with any semaphore, the
values can be inconsistent. We have to check inside the function call that
they make sense. */
btr_search_build_page_hash_index(cursor->index, block, false);
} else if (cursor->flag == BTR_CUR_HASH_FAIL) {
/* Update the hash node reference, if appropriate. If
btr_search_update_block_hash_info decided to build the index for this
block, the record should be hashed correctly with the rest of the block's
records. */
btr_search_update_hash_ref(block, cursor);
}
}
/** Checks if a guessed position for a tree cursor is right. Note that if
mode is PAGE_CUR_LE, which is used in inserts, and the function returns
true, then cursor->up_match and cursor->low_match both have sensible values.
@param[in,out] cursor Guess cursor position
@param[in] can_only_compare_to_cursor_rec
If we do not have a latch on the page of cursor, but a
latch corresponding search system, then ONLY the columns
of the record UNDER the cursor are protected, not the
next or previous record in the chain: we cannot look at
the next or previous record to check our guess!
@param[in] tuple Data tuple
@param[in] mode PAGE_CUR_L, PAGE_CUR_LE, PAGE_CUR_G, PAGE_CUR_GE
@param[in] mtr Mini-transaction
@return true if success */
static bool btr_search_check_guess(btr_cur_t *cursor,
bool can_only_compare_to_cursor_rec,
const dtuple_t *tuple, ulint mode,
mtr_t *mtr) {
rec_t *rec;
ulint match;
const auto n_unique = dict_index_get_n_unique_in_tree(cursor->index);
rec = btr_cur_get_rec(cursor);
ut_ad(page_rec_is_user_rec(rec));
match = 0;
Rec_offsets offsets;
{
const auto cmp =
tuple->compare(rec, cursor->index,
offsets.compute(rec, cursor->index, n_unique), &match);
if (mode == PAGE_CUR_GE) {
if (cmp > 0) {
return false;
}
cursor->up_match = match;
if (match >= n_unique) {
return true;
}
} else if (mode == PAGE_CUR_LE) {
if (cmp < 0) {
return false;
}
cursor->low_match = match;
} else if (mode == PAGE_CUR_G) {
if (cmp >= 0) {
return false;
}
} else if (mode == PAGE_CUR_L) {
if (cmp <= 0) {
return false;
}
}
if (can_only_compare_to_cursor_rec) {
/* Since we could not determine if our guess is right just by
looking at the record under the cursor, return false */
return false;
}
}
match = 0;
if ((mode == PAGE_CUR_G) || (mode == PAGE_CUR_GE)) {
rec_t *prev_rec;
ut_ad(!page_rec_is_infimum(rec));
prev_rec = page_rec_get_prev(rec);
if (page_rec_is_infimum(prev_rec)) {
return btr_page_get_prev(page_align(prev_rec), mtr) == FIL_NULL;
}
const auto cmp = tuple->compare(
prev_rec, cursor->index,
offsets.compute(prev_rec, cursor->index, n_unique), &match);
bool success;
if (mode == PAGE_CUR_GE) {
success = cmp > 0;
} else {
success = cmp >= 0;
}
return success;
} else {
rec_t *next_rec;
ut_ad(!page_rec_is_supremum(rec));
next_rec = page_rec_get_next(rec);
if (page_rec_is_supremum(next_rec)) {
if (btr_page_get_next(page_align(next_rec), mtr) == FIL_NULL) {
cursor->up_match = 0;
return true;
}
return false;
}
const auto cmp = tuple->compare(
next_rec, cursor->index,
offsets.compute(next_rec, cursor->index, n_unique), &match);
bool success;
if (mode == PAGE_CUR_LE) {
success = cmp < 0;
cursor->up_match = match;
} else {
success = cmp <= 0;
}
return success;
}
}
bool btr_search_guess_on_hash(const dtuple_t *tuple, ulint mode,
ulint latch_mode, btr_cur_t *cursor,
ulint has_search_latch, mtr_t *mtr) {
const rec_t *rec;
#ifdef notdefined
btr_cur_t cursor2;
btr_pcur_t pcur;
#endif
if (!btr_search_enabled) {
return false;
}
ut_ad(tuple && cursor && mtr);
const auto index = cursor->index;
ut_ad(index != nullptr);
const auto info = index->search_info;
ut_ad(info != nullptr);
ut_ad(!dict_index_is_ibuf(index));
ut_ad((latch_mode == BTR_SEARCH_LEAF) || (latch_mode == BTR_MODIFY_LEAF));
/* Not supported for spatial index */
ut_ad(!dict_index_is_spatial(index));
/* If we decide to return before doing actual hash search, we will return with
the following state of the cursor. */
cursor->flag = BTR_CUR_HASH_NOT_ATTEMPTED;
/* Note that, for efficiency, the struct info may not be protected by
any latch here! */
if (info->n_hash_potential == 0) {
return false;
}
const auto prefix_info = info->prefix_info.load();
cursor->ahi.prefix_info = prefix_info;
if (dtuple_get_n_fields(tuple) < btr_search_get_n_fields(cursor)) {
return false;
}
const auto hash_value =
dtuple_hash(tuple, prefix_info.n_fields, prefix_info.n_bytes,
btr_hash_seed_for_record(index));
cursor->ahi.ahi_hash_value = hash_value;
if (!has_search_latch) {
if (!btr_search_s_lock_nowait(index, UT_LOCATION_HERE)) {
return false;
}
}
auto latch_guard =
create_scope_guard([index]() { btr_search_s_unlock(index); });
if (!has_search_latch) {
if (!btr_search_enabled) {
return false;
}
} else {
/* If we had a latch, then the guard is not needed. */
latch_guard.release();
}
ut_ad(rw_lock_get_writer(btr_get_search_latch(index)) != RW_LOCK_X);
ut_ad(rw_lock_get_reader_count(btr_get_search_latch(index)) > 0);
rec =
(rec_t *)ha_search_and_get_data(btr_get_search_table(index), hash_value);
/* We did the hash search. If we decide to return before successfully
verifying the search is correct, we will return with the following state of
the cursor. */
cursor->flag = BTR_CUR_HASH_FAIL;
#ifdef UNIV_SEARCH_PERF_STAT
info->n_hash_fail++;
#endif /* UNIV_SEARCH_PERF_STAT */
info->last_hash_succ = false;
if (rec == nullptr) {
return false;
}
buf_block_t *block = buf_block_from_ahi(rec);
if (!has_search_latch) {
if (!buf_page_get_known_nowait(latch_mode, block, Cache_hint::MAKE_YOUNG,
__FILE__, __LINE__, mtr)) {
return false;
}
/* Release the AHI S-latch. It is released after the
buf_page_get_known_nowait which is latching the block, so no one else can
remove it. Up to this point we have the AHI is S-latched and since we found
an AHI entry that leads to this block, the entry can't be removed and thus
the block must be still in the buffer pool. */
latch_guard.reset();
buf_block_dbg_add_level(block, SYNC_TREE_NODE_FROM_HASH);
}
if (buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) {
ut_ad(buf_block_get_state(block) == BUF_BLOCK_REMOVE_HASH);
if (!has_search_latch) {
btr_leaf_page_release(block, latch_mode, mtr);
}
return false;
}
ut_ad(page_rec_is_user_rec(rec));
btr_cur_position(index, (rec_t *)rec, block, cursor);
/* Check the validity of the guess within the page */
/* If we only have the latch on search system, not on the
page, it only protects the columns of the record the cursor
is positioned on. We cannot look at the next of the previous
record to determine if our guess for the cursor position is
right. */
if (index->space != block->page.id.space() ||
index->id != btr_page_get_index_id(block->frame) ||
!btr_search_check_guess(cursor, has_search_latch, tuple, mode, mtr)) {
if (!has_search_latch) {
btr_leaf_page_release(block, latch_mode, mtr);
}
return false;
}
if (info->n_hash_potential < BTR_SEARCH_BUILD_LIMIT + 5) {
info->n_hash_potential++;
}
#ifdef notdefined
/* These lines of code can be used in a debug version to check
the correctness of the searched cursor position: */
info->last_hash_succ = false;
/* Currently, does not work if the following fails: */
ut_ad(!has_search_latch);
btr_leaf_page_release(block, latch_mode, mtr);
btr_cur_search_to_nth_level(index, 0, tuple, mode, latch_mode, &cursor2, 0,
mtr);
if (mode == PAGE_CUR_GE && page_rec_is_supremum(btr_cur_get_rec(&cursor2))) {
/* If mode is PAGE_CUR_GE, then the binary search
in the index tree may actually take us to the supremum
of the previous page */
info->last_hash_succ = false;
pcur.open_on_user_rec(index, tuple, mode, latch_mode, mtr,
UT_LOCATION_HERE);
ut_ad(pcur.get_rec() == btr_cur_get_rec(cursor));
} else {
ut_ad(btr_cur_get_rec(&cursor2) == btr_cur_get_rec(cursor));
}
/* NOTE that it is theoretically possible that the above assertions
fail if the page of the cursor gets removed from the buffer pool
meanwhile! Thus it might not be a bug. */
#endif
info->last_hash_succ = true;
cursor->flag = BTR_CUR_HASH;
#ifdef UNIV_SEARCH_PERF_STAT
/* Revert the accounting we did for the hash search failure that was prepared
above. */
info->n_hash_fail--;
info->n_hash_succ++;
btr_search_n_succ++;
#endif
/* Increment the page get statistics though we did not really
fix the page: for user info only */
{
buf_pool_t *buf_pool = buf_pool_from_bpage(&block->page);
Counter::inc(buf_pool->stat.m_n_page_gets, block->page.id.page_no());