-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathmf_keycache.cc
3682 lines (3293 loc) · 139 KB
/
mf_keycache.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) 2000, 2024, Oracle and/or its affiliates.
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.
Without limiting anything contained in the foregoing, this file,
which is part of C Driver for MySQL (Connector/C), is also subject to the
Universal FOSS Exception, version 1.0, a copy of which can be found at
http://oss.oracle.com/licenses/universal-foss-exception.
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 mysys/mf_keycache.cc
These functions handle keyblock caching for ISAM and MyISAM tables.
One cache can handle many files.
It must contain buffers of the same blocksize.
init_key_cache() should be used to init cache handler.
The free list (free_block_list) is a stack like structure.
When a block is freed by free_block(), it is pushed onto the stack.
When a new block is required it is first tried to pop one from the stack.
If the stack is empty, it is tried to get a never-used block from the pool.
If this is empty too, then a block is taken from the LRU ring, flushing it
to disk, if necessary. This is handled in find_key_block().
With the new free list, the blocks can have three temperatures:
hot, warm and cold (which is free). This is remembered in the block header
by the enum BLOCK_TEMPERATURE temperature variable. Remembering the
temperature is necessary to correctly count the number of warm blocks,
which is required to decide when blocks are allowed to become hot. Whenever
a block is inserted to another (sub-)chain, we take the old and new
temperature into account to decide if we got one more or less warm block.
blocks_unused is the sum of never used blocks in the pool and of currently
free blocks. blocks_used is the number of blocks fetched from the pool and
as such gives the maximum number of in-use blocks at any time.
*/
/*
Key Cache Locking
=================
All key cache locking is done with a single mutex per key cache:
keycache->cache_lock. This mutex is locked almost all the time
when executing code in this file (mf_keycache.c).
However it is released for I/O and some copy operations.
The cache_lock is also released when waiting for some event. Waiting
and signalling is done via condition variables. In most cases the
thread waits on its thread->suspend condition variable. Every thread
has a my_thread_var structure, which contains this variable and a
'*next' and '**prev' pointer. These pointers are used to insert the
thread into a wait queue.
A thread can wait for one block and thus be in one wait queue at a
time only.
Before starting to wait on its condition variable with
mysql_cond_wait(), the thread enters itself to a specific wait queue
with link_into_queue() (double linked with '*next' + '**prev') or
wait_on_queue() (single linked with '*next').
Another thread, when releasing a resource, looks up the waiting thread
in the related wait queue. It sends a signal with
mysql_cond_signal() to the waiting thread.
NOTE: Depending on the particular wait situation, either the sending
thread removes the waiting thread from the wait queue with
unlink_from_queue() or release_whole_queue() respectively, or the waiting
thread removes itself.
There is one exception from this locking scheme when one thread wants
to reuse a block for some other address. This works by first marking
the block reserved (status= BLOCK_IN_SWITCH) and then waiting for all
threads that are reading the block to finish. Each block has a
reference to a condition variable (condvar). It holds a reference to
the thread->suspend condition variable for the waiting thread (if such
a thread exists). When that thread is signaled, the reference is
cleared. The number of readers of a block is registered in
block->hash_link->requests. See wait_for_readers() / remove_reader()
for details. This is similar to the above, but it clearly means that
only one thread can wait for a particular block. There is no queue in
this case. Strangely enough block->convar is used for waiting for the
assigned hash_link only. More precisely it is used to wait for all
requests to be unregistered from the assigned hash_link.
The resize_queue serves two purposes:
1. Threads that want to do a resize wait there if in_resize is set.
This is not used in the server. The server refuses a second resize
request if one is already active. keycache->in_init is used for the
synchronization. See set_var.cc.
2. Threads that want to access blocks during resize wait here during
the re-initialization phase.
When the resize is done, all threads on the queue are signalled.
Hypothetical resizers can compete for resizing, and read/write
requests will restart to request blocks from the freshly resized
cache. If the cache has been resized too small, it is disabled and
'can_be_used' is false. In this case read/write requests bypass the
cache. Since they increment and decrement 'cnt_for_resize_op', the
next resizer can wait on the queue 'waiting_for_resize_cnt' until all
I/O finished.
*/
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include "keycache.h"
#include "my_bit.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_io.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_pointer_arithmetic.h"
#include "my_sys.h"
#include "my_thread_local.h"
#include "mysql/psi/mysql_cond.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/service_mysql_alloc.h"
#include "mysys/mysys_priv.h"
#include "mysys_err.h"
#include "template_utils.h"
#include "thr_mutex.h"
#define STRUCT_PTR(TYPE, MEMBER, a) (TYPE *)((char *)(a)-offsetof(TYPE, MEMBER))
/* types of condition variables */
#define COND_FOR_REQUESTED 0
#define COND_FOR_SAVED 1
typedef mysql_cond_t KEYCACHE_CONDVAR;
/* descriptor of the page in the key cache block buffer */
struct KEYCACHE_PAGE {
int file; /* file to which the page belongs to */
my_off_t filepos; /* position of the page in the file */
};
/* element in the chain of a hash table bucket */
struct HASH_LINK {
HASH_LINK *next, **prev; /* to connect links in the same bucket */
BLOCK_LINK *block; /* reference to the block for the page: */
File file; /* from such a file */
my_off_t diskpos; /* with such an offset */
uint requests; /* number of requests for the page */
};
// clang-format off
/* simple states of a block */
#define BLOCK_ERROR 1 /* an error occurred when performing file i/o */
#define BLOCK_READ 2 /* file block is in the block buffer */
#define BLOCK_IN_SWITCH 4 /* block is preparing to read new page */
#define BLOCK_REASSIGNED 8 /* blk does not accept requests for old page */
#define BLOCK_IN_FLUSH 16 /* block is selected for flush */
#define BLOCK_CHANGED 32 /* block buffer contains a dirty page */
#define BLOCK_IN_USE 64 /* block is not free */
#define BLOCK_IN_EVICTION 128 /* block is selected for eviction */
#define BLOCK_IN_FLUSHWRITE 256 /* block is in write to file */
#define BLOCK_FOR_UPDATE 512 /* block is selected for buffer modification */
// clang-format on
/* page status, returned by find_key_block */
#define PAGE_READ 0
#define PAGE_TO_BE_READ 1
#define PAGE_WAIT_TO_BE_READ 2
/* block temperature determines in which (sub-)chain the block currently is */
enum BLOCK_TEMPERATURE { BLOCK_COLD /*free*/, BLOCK_WARM, BLOCK_HOT };
/* key cache block */
struct BLOCK_LINK {
BLOCK_LINK
*next_used, **prev_used; /* to connect links in the LRU chain (ring) */
BLOCK_LINK
*next_changed, **prev_changed; /* for lists of file dirty/clean blocks */
HASH_LINK *hash_link; /* backward ptr to referring hash_link */
KEYCACHE_WQUEUE wqueue[2]; /* queues on waiting requests for new/old pages */
uint requests; /* number of requests for the block */
uchar *buffer; /* buffer for the block page */
uint offset; /* beginning of modified data in the buffer */
uint length; /* end of data in the buffer */
uint status; /* state of the block */
enum BLOCK_TEMPERATURE temperature; /* block temperature: cold, warm, hot */
uint hits_left; /* number of hits left until promotion */
ulonglong last_hit_time; /* timestamp of the last hit */
KEYCACHE_CONDVAR *condvar; /* condition variable for 'no readers' event */
};
KEY_CACHE dflt_key_cache_var;
KEY_CACHE *dflt_key_cache = &dflt_key_cache_var;
#define FLUSH_CACHE 2000 /* sort this many blocks at once */
static void change_key_cache_param(KEY_CACHE *keycache,
ulonglong division_limit,
ulonglong age_threshold);
static int flush_all_key_blocks(KEY_CACHE *keycache,
st_keycache_thread_var *thread_var);
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue, mysql_mutex_t *mutex,
st_keycache_thread_var *thread);
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue);
static void free_block(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
BLOCK_LINK *block);
#define KEYCACHE_HASH(f, pos) \
(((ulong)((pos) / keycache->key_cache_block_size) + (ulong)(f)) & \
(keycache->hash_entries - 1))
#define FILE_HASH(f) ((uint)(f) & (CHANGED_BLOCKS_HASH - 1))
#define BLOCK_NUMBER(b) \
((uint)(((char *)(b) - (char *)keycache->block_root) / sizeof(BLOCK_LINK)))
#ifdef KEYCACHE_TIMEOUT
#define HASH_LINK_NUMBER(h) \
((uint)(((char *)(h) - (char *)keycache->hash_link_root) / sizeof(HASH_LINK)))
#endif
#if !defined(NDEBUG)
static int fail_block(BLOCK_LINK *block);
static int fail_hlink(HASH_LINK *hlink);
static int cache_empty(KEY_CACHE *keycache);
#endif
static inline uint next_power(uint value) {
return (uint)my_round_up_to_next_power((uint32)value) << 1;
}
/*
Initialize a key cache
SYNOPSIS
init_key_cache()
keycache pointer to a key cache data structure
key_cache_block_size size of blocks to keep cached data
use_mem total memory to use for the key cache
division_limit division limit (may be zero)
age_threshold age threshold (may be zero)
RETURN VALUE
number of blocks in the key cache, if successful,
0 - otherwise.
NOTES.
if keycache->key_cache_inited != 0 we assume that the key cache
is already initialized. This is for now used by myisamchk, but shouldn't
be something that a program should rely on!
It's assumed that no two threads call this function simultaneously
referring to the same key cache handle.
*/
int init_key_cache(KEY_CACHE *keycache, ulonglong key_cache_block_size,
size_t use_mem, ulonglong division_limit,
ulonglong age_threshold) {
ulong blocks, hash_links;
size_t length;
int error;
DBUG_TRACE;
assert(key_cache_block_size >= 512);
if (keycache->key_cache_inited && keycache->disk_blocks > 0) {
DBUG_PRINT("warning", ("key cache already in use"));
return 0;
}
keycache->global_cache_w_requests = keycache->global_cache_r_requests = 0;
keycache->global_cache_read = keycache->global_cache_write = 0;
keycache->disk_blocks = -1;
if (!keycache->key_cache_inited) {
keycache->key_cache_inited = true;
/*
Initialize these variables once only.
Their value must survive re-initialization during resizing.
*/
keycache->in_resize = false;
keycache->resize_in_flush = false;
keycache->cnt_for_resize_op = 0;
keycache->waiting_for_resize_cnt.last_thread = nullptr;
keycache->in_init = false;
mysql_mutex_init(key_KEY_CACHE_cache_lock, &keycache->cache_lock,
MY_MUTEX_INIT_FAST);
keycache->resize_queue.last_thread = nullptr;
}
keycache->key_cache_mem_size = use_mem;
keycache->key_cache_block_size = (uint)key_cache_block_size;
DBUG_PRINT("info", ("key_cache_block_size: %llu", key_cache_block_size));
blocks =
(ulong)(use_mem / (sizeof(BLOCK_LINK) + 2 * sizeof(HASH_LINK) +
sizeof(HASH_LINK *) * 5 / 4 + key_cache_block_size));
/* It doesn't make sense to have too few blocks (less than 8) */
if (blocks >= 8) {
for (;;) {
/* Set my_hash_entries to the next bigger 2 power */
if ((keycache->hash_entries = next_power(blocks)) < blocks * 5 / 4)
keycache->hash_entries <<= 1;
hash_links = 2 * blocks;
while ((length =
(ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)) +
ALIGN_SIZE(hash_links * sizeof(HASH_LINK)) +
ALIGN_SIZE(sizeof(HASH_LINK *) * keycache->hash_entries))) +
((size_t)blocks * keycache->key_cache_block_size) >
use_mem)
blocks--;
/* Allocate memory for cache page buffers */
if ((keycache->block_mem = static_cast<uchar *>(my_malloc(
key_memory_KEY_CACHE,
(size_t)blocks * keycache->key_cache_block_size, MYF(0))))) {
/*
Allocate memory for blocks, hash_links and hash entries;
For each block 2 hash links are allocated
*/
if ((keycache->block_root =
(BLOCK_LINK *)my_malloc(key_memory_KEY_CACHE, length, MYF(0))))
break;
my_free(keycache->block_mem);
keycache->block_mem = nullptr;
}
if (blocks < 8) {
set_my_errno(ENOMEM);
my_error(EE_OUTOFMEMORY, MYF(ME_FATALERROR),
blocks * keycache->key_cache_block_size);
goto err;
}
blocks = blocks / 4 * 3;
}
keycache->blocks_unused = blocks;
keycache->disk_blocks = (int)blocks;
keycache->hash_links = hash_links;
keycache->hash_root =
(HASH_LINK **)((char *)keycache->block_root +
ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)));
keycache->hash_link_root =
(HASH_LINK *)((char *)keycache->hash_root +
ALIGN_SIZE(
(sizeof(HASH_LINK *) * keycache->hash_entries)));
memset(keycache->block_root, 0, keycache->disk_blocks * sizeof(BLOCK_LINK));
memset(keycache->hash_root, 0,
keycache->hash_entries * sizeof(HASH_LINK *));
memset(keycache->hash_link_root, 0,
keycache->hash_links * sizeof(HASH_LINK));
keycache->hash_links_used = 0;
keycache->free_hash_list = nullptr;
keycache->blocks_used = keycache->blocks_changed = 0;
keycache->global_blocks_changed = 0;
keycache->blocks_available = 0; /* For debugging */
/* The LRU chain is empty after initialization */
keycache->used_last = nullptr;
keycache->used_ins = nullptr;
keycache->free_block_list = nullptr;
keycache->keycache_time = 0;
keycache->warm_blocks = 0;
keycache->min_warm_blocks =
(division_limit ? blocks * division_limit / 100 + 1 : blocks);
keycache->age_threshold =
(age_threshold ? blocks * age_threshold / 100 : blocks);
keycache->can_be_used = true;
keycache->waiting_for_hash_link.last_thread = nullptr;
keycache->waiting_for_block.last_thread = nullptr;
DBUG_PRINT("exit", ("disk_blocks: %d block_root: %p hash_entries: %d\
hash_root: %p hash_links: %d hash_link_root: %p",
keycache->disk_blocks, keycache->block_root,
keycache->hash_entries, keycache->hash_root,
keycache->hash_links, keycache->hash_link_root));
memset(keycache->changed_blocks, 0,
sizeof(keycache->changed_blocks[0]) * CHANGED_BLOCKS_HASH);
memset(keycache->file_blocks, 0,
sizeof(keycache->file_blocks[0]) * CHANGED_BLOCKS_HASH);
} else {
/* key_buffer_size is specified too small. Disable the cache. */
keycache->can_be_used = false;
}
keycache->blocks = keycache->disk_blocks > 0 ? keycache->disk_blocks : 0;
return (int)keycache->disk_blocks;
err:
error = my_errno();
keycache->disk_blocks = 0;
keycache->blocks = 0;
if (keycache->block_mem) {
my_free((uchar *)keycache->block_mem);
keycache->block_mem = nullptr;
}
if (keycache->block_root) {
my_free(keycache->block_root);
keycache->block_root = nullptr;
}
set_my_errno(error);
keycache->can_be_used = false;
return 0;
}
/*
Resize a key cache
SYNOPSIS
resize_key_cache()
keycache pointer to a key cache data structure
thread_var pointer to thread specific variables
key_cache_block_size size of blocks to keep cached data
use_mem total memory to use for the new key cache
division_limit new division limit (if not zero)
age_threshold new age threshold (if not zero)
RETURN VALUE
number of blocks in the key cache, if successful,
0 - otherwise.
NOTES.
The function first compares the memory size and the block size parameters
with the key cache values.
If they differ the function free the the memory allocated for the
old key cache blocks by calling the end_key_cache function and
then rebuilds the key cache with new blocks by calling
init_key_cache.
The function starts the operation only when all other threads
performing operations with the key cache let her to proceed
(when cnt_for_resize=0).
*/
int resize_key_cache(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
ulonglong key_cache_block_size, size_t use_mem,
ulonglong division_limit, ulonglong age_threshold) {
int blocks;
DBUG_TRACE;
if (!keycache->key_cache_inited) return keycache->disk_blocks;
if (key_cache_block_size == keycache->key_cache_block_size &&
use_mem == keycache->key_cache_mem_size) {
change_key_cache_param(keycache, division_limit, age_threshold);
return keycache->disk_blocks;
}
mysql_mutex_lock(&keycache->cache_lock);
/*
We may need to wait for another thread which is doing a resize
already. This cannot happen in the MySQL server though. It allows
one resizer only. In set_var.cc keycache->in_init is used to block
multiple attempts.
*/
while (keycache->in_resize) {
/* purecov: begin inspected */
wait_on_queue(&keycache->resize_queue, &keycache->cache_lock, thread_var);
/* purecov: end */
}
/*
Mark the operation in progress. This blocks other threads from doing
a resize in parallel. It prohibits new blocks to enter the cache.
Read/write requests can bypass the cache during the flush phase.
*/
keycache->in_resize = true;
/* Need to flush only if keycache is enabled. */
if (keycache->can_be_used) {
/* Start the flush phase. */
keycache->resize_in_flush = true;
if (flush_all_key_blocks(keycache, thread_var)) {
/* TODO: if this happens, we should write a warning in the log file ! */
keycache->resize_in_flush = false;
blocks = 0;
keycache->can_be_used = false;
goto finish;
}
assert(cache_empty(keycache));
/* End the flush phase. */
keycache->resize_in_flush = false;
}
/*
Some direct read/write operations (bypassing the cache) may still be
unfinished. Wait until they are done. If the key cache can be used,
direct I/O is done in increments of key_cache_block_size. That is,
every block is checked if it is in the cache. We need to wait for
pending I/O before re-initializing the cache, because we may change
the block size. Otherwise they could check for blocks at file
positions where the new block division has none. We do also want to
wait for I/O done when (if) the cache was disabled. It must not
run in parallel with normal cache operation.
*/
while (keycache->cnt_for_resize_op)
wait_on_queue(&keycache->waiting_for_resize_cnt, &keycache->cache_lock,
thread_var);
/*
Free old cache structures, allocate new structures, and initialize
them. Note that the cache_lock mutex and the resize_queue are left
untouched. We do not lose the cache_lock and will release it only at
the end of this function.
*/
end_key_cache(keycache, false); /* Don't free mutex */
/* The following will work even if use_mem is 0 */
blocks = init_key_cache(keycache, key_cache_block_size, use_mem,
division_limit, age_threshold);
finish:
/*
Mark the resize finished. This allows other threads to start a
resize or to request new cache blocks.
*/
keycache->in_resize = false;
/* Signal waiting threads. */
release_whole_queue(&keycache->resize_queue);
mysql_mutex_unlock(&keycache->cache_lock);
return blocks;
}
/*
Increment counter blocking resize key cache operation
*/
static inline void inc_counter_for_resize_op(KEY_CACHE *keycache) {
keycache->cnt_for_resize_op++;
}
/*
Decrement counter blocking resize key cache operation;
Signal the operation to proceed when counter becomes equal zero
*/
static inline void dec_counter_for_resize_op(KEY_CACHE *keycache) {
if (!--keycache->cnt_for_resize_op)
release_whole_queue(&keycache->waiting_for_resize_cnt);
}
/*
Change the key cache parameters
SYNOPSIS
change_key_cache_param()
keycache pointer to a key cache data structure
division_limit new division limit (if not zero)
age_threshold new age threshold (if not zero)
RETURN VALUE
none
NOTES.
Presently the function resets the key cache parameters
concerning midpoint insertion strategy - division_limit and
age_threshold.
*/
static void change_key_cache_param(KEY_CACHE *keycache,
ulonglong division_limit,
ulonglong age_threshold) {
DBUG_TRACE;
mysql_mutex_lock(&keycache->cache_lock);
if (division_limit)
keycache->min_warm_blocks =
(keycache->disk_blocks * division_limit / 100 + 1);
if (age_threshold)
keycache->age_threshold = (keycache->disk_blocks * age_threshold / 100);
mysql_mutex_unlock(&keycache->cache_lock);
}
/*
Remove key_cache from memory
SYNOPSIS
end_key_cache()
keycache key cache handle
cleanup Complete free (Free also mutex for key cache)
RETURN VALUE
none
*/
void end_key_cache(KEY_CACHE *keycache, bool cleanup) {
DBUG_TRACE;
DBUG_PRINT("enter", ("key_cache: %p", keycache));
if (!keycache->key_cache_inited) return;
if (keycache->disk_blocks > 0) {
if (keycache->block_mem) {
my_free((uchar *)keycache->block_mem);
keycache->block_mem = nullptr;
my_free(keycache->block_root);
keycache->block_root = nullptr;
}
keycache->disk_blocks = -1;
/* Reset blocks_changed to be safe if flush_all_key_blocks is called */
keycache->blocks_changed = 0;
}
DBUG_PRINT("status", ("used: %lu changed: %lu w_requests: %lu "
"writes: %lu r_requests: %lu reads: %lu",
keycache->blocks_used, keycache->global_blocks_changed,
(ulong)keycache->global_cache_w_requests,
(ulong)keycache->global_cache_write,
(ulong)keycache->global_cache_r_requests,
(ulong)keycache->global_cache_read));
/*
Reset these values to be able to detect a disabled key cache.
See Bug#44068 (RESTORE can disable the MyISAM Key Cache).
*/
keycache->blocks_used = 0;
keycache->blocks_unused = 0;
if (cleanup) {
mysql_mutex_destroy(&keycache->cache_lock);
keycache->key_cache_inited = keycache->can_be_used = false;
}
} /* end_key_cache */
/**
Link a thread into double-linked queue of waiting threads.
@param wqueue pointer to the queue structure
@param thread pointer to the keycache variables for the
thread to be added to the queue
Queue is represented by a circular list of the keycache variable structures.
Since each thread has its own keycache variables, this is equal to a list
of threads. The list is double-linked of the type (**prev,*next), accessed by
a pointer to the last element.
*/
static void link_into_queue(KEYCACHE_WQUEUE *wqueue,
st_keycache_thread_var *thread) {
st_keycache_thread_var *last;
assert(!thread->next && !thread->prev);
if (!(last = wqueue->last_thread)) {
/* Queue is empty */
thread->next = thread;
thread->prev = &thread->next;
} else {
thread->prev = last->next->prev;
last->next->prev = &thread->next;
thread->next = last->next;
last->next = thread;
}
wqueue->last_thread = thread;
}
/**
Unlink a thread from double-linked queue of waiting threads
@param wqueue pointer to the queue structure
@param thread pointer to the keycache variables for the
thread to be removed to the queue
@note See link_into_queue
*/
static void unlink_from_queue(KEYCACHE_WQUEUE *wqueue,
st_keycache_thread_var *thread) {
assert(thread->next && thread->prev);
if (thread->next == thread) /* The queue contains only one member */
wqueue->last_thread = nullptr;
else {
thread->next->prev = thread->prev;
*thread->prev = thread->next;
if (wqueue->last_thread == thread)
wqueue->last_thread =
STRUCT_PTR(st_keycache_thread_var, next, thread->prev);
}
thread->next = nullptr;
#if !defined(NDEBUG)
/*
This makes it easier to see it's not in a chain during debugging.
And some assert() rely on it.
*/
thread->prev = nullptr;
#endif
}
/*
Add a thread to single-linked queue of waiting threads
SYNOPSIS
wait_on_queue()
wqueue Pointer to the queue structure.
mutex Cache_lock to acquire after awake.
thread Thread to be added
RETURN VALUE
none
NOTES.
Queue is represented by a circular list of the thread structures
The list is single-linked of the type (*next), accessed by a pointer
to the last element.
The function protects against stray signals by verifying that the
current thread is unlinked from the queue when awaking. However,
since several threads can wait for the same event, it might be
necessary for the caller of the function to check again if the
condition for awake is indeed matched.
*/
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue, mysql_mutex_t *mutex,
st_keycache_thread_var *thread) {
st_keycache_thread_var *last;
/* Add to queue. */
assert(!thread->next);
assert(!thread->prev); /* Not required, but must be true anyway. */
if (!(last = wqueue->last_thread))
thread->next = thread;
else {
thread->next = last->next;
last->next = thread;
}
wqueue->last_thread = thread;
/*
Wait until thread is removed from queue by the signalling thread.
The loop protects against stray signals.
*/
do {
mysql_cond_wait(&thread->suspend, mutex);
} while (thread->next);
}
/*
Remove all threads from queue signaling them to proceed
SYNOPSIS
release_whole_queue()
wqueue pointer to the queue structure
RETURN VALUE
none
NOTES.
See notes for wait_on_queue().
When removed from the queue each thread is signaled via condition
variable thread->suspend.
*/
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue) {
st_keycache_thread_var *last;
st_keycache_thread_var *next;
st_keycache_thread_var *thread;
/* Queue may be empty. */
if (!(last = wqueue->last_thread)) return;
next = last->next;
do {
thread = next;
/* Signal the thread. */
mysql_cond_signal(&thread->suspend);
/* Take thread from queue. */
next = thread->next;
thread->next = nullptr;
} while (thread != last);
/* Now queue is definitely empty. */
wqueue->last_thread = nullptr;
}
/*
Unlink a block from the chain of dirty/clean blocks
*/
static inline void unlink_changed(BLOCK_LINK *block) {
assert(block->prev_changed && *block->prev_changed == block);
if (block->next_changed)
block->next_changed->prev_changed = block->prev_changed;
*block->prev_changed = block->next_changed;
#if !defined(NDEBUG)
/*
This makes it easier to see it's not in a chain during debugging.
And some assert() rely on it.
*/
block->next_changed = nullptr;
block->prev_changed = nullptr;
#endif
}
/*
Link a block into the chain of dirty/clean blocks
*/
static inline void link_changed(BLOCK_LINK *block, BLOCK_LINK **phead) {
assert(!block->next_changed);
assert(!block->prev_changed);
block->prev_changed = phead;
if ((block->next_changed = *phead))
(*phead)->prev_changed = &block->next_changed;
*phead = block;
}
/*
Link a block in a chain of clean blocks of a file.
SYNOPSIS
link_to_file_list()
keycache Key cache handle
block Block to relink
file File to be linked to
unlink If to unlink first
DESCRIPTION
Unlink a block from whichever chain it is linked in, if it's
asked for, and link it to the chain of clean blocks of the
specified file.
NOTE
Please do never set/clear BLOCK_CHANGED outside of
link_to_file_list() or link_to_changed_list().
You would risk to damage correct counting of changed blocks
and to find blocks in the wrong hash.
RETURN
void
*/
static void link_to_file_list(KEY_CACHE *keycache, BLOCK_LINK *block, int file,
bool unlink_block) {
assert(block->status & BLOCK_IN_USE);
assert(block->hash_link && block->hash_link->block == block);
assert(block->hash_link->file == file);
if (unlink_block) unlink_changed(block);
link_changed(block, &keycache->file_blocks[FILE_HASH(file)]);
if (block->status & BLOCK_CHANGED) {
block->status &= ~BLOCK_CHANGED;
keycache->blocks_changed--;
keycache->global_blocks_changed--;
}
}
/*
Re-link a block from the clean chain to the dirty chain of a file.
SYNOPSIS
link_to_changed_list()
keycache key cache handle
block block to relink
DESCRIPTION
Unlink a block from the chain of clean blocks of a file
and link it to the chain of dirty blocks of the same file.
NOTE
Please do never set/clear BLOCK_CHANGED outside of
link_to_file_list() or link_to_changed_list().
You would risk to damage correct counting of changed blocks
and to find blocks in the wrong hash.
RETURN
void
*/
static void link_to_changed_list(KEY_CACHE *keycache, BLOCK_LINK *block) {
assert(block->status & BLOCK_IN_USE);
assert(!(block->status & BLOCK_CHANGED));
assert(block->hash_link && block->hash_link->block == block);
unlink_changed(block);
link_changed(block,
&keycache->changed_blocks[FILE_HASH(block->hash_link->file)]);
block->status |= BLOCK_CHANGED;
keycache->blocks_changed++;
keycache->global_blocks_changed++;
}
/*
Link a block to the LRU chain at the beginning or at the end of
one of two parts.
SYNOPSIS
link_block()
keycache pointer to a key cache data structure
block pointer to the block to link to the LRU chain
hot <-> to link the block into the hot subchain
at_end <-> to link the block at the end of the subchain
RETURN VALUE
none
NOTES.
The LRU ring is represented by a circular list of block structures.
The list is double-linked of the type (**prev,*next) type.
The LRU ring is divided into two parts - hot and warm.
There are two pointers to access the last blocks of these two
parts. The beginning of the warm part follows right after the
end of the hot part.
Only blocks of the warm part can be used for eviction.
The first block from the beginning of this subchain is always
taken for eviction (keycache->last_used->next)
LRU chain: +------+ H O T +------+
+----| end |----...<----| beg |----+
| +------+last +------+ |
v<-link in latest hot (new end) |
| link in latest warm (new end)->^
| +------+ W A R M +------+ |
+----| beg |---->...----| end |----+
+------+ +------+ins
first for eviction
It is also possible that the block is selected for eviction and thus
not linked in the LRU ring.
*/
static void link_block(KEY_CACHE *keycache, BLOCK_LINK *block, bool hot,
bool at_end) {
BLOCK_LINK *ins;
BLOCK_LINK **pins;
assert((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
assert(block->hash_link); /*backptr to block NULL from free_block()*/
assert(!block->requests);
assert(block->prev_changed && *block->prev_changed == block);
assert(!block->next_used);
assert(!block->prev_used);
if (!hot && keycache->waiting_for_block.last_thread) {
/* Signal that in the LRU warm sub-chain an available block has appeared */
st_keycache_thread_var *last_thread =
keycache->waiting_for_block.last_thread;
st_keycache_thread_var *first_thread = last_thread->next;
st_keycache_thread_var *next_thread = first_thread;
HASH_LINK *hash_link = (HASH_LINK *)first_thread->opt_info;
st_keycache_thread_var *thread;
do {
thread = next_thread;
next_thread = thread->next;
/*
We notify about the event all threads that ask
for the same page as the first thread in the queue
*/
if ((HASH_LINK *)thread->opt_info == hash_link) {
mysql_cond_signal(&thread->suspend);
unlink_from_queue(&keycache->waiting_for_block, thread);
block->requests++;
}
} while (thread != last_thread);
hash_link->block = block;
/*
NOTE: We assigned the block to the hash_link and signalled the
requesting thread(s). But it is possible that other threads runs
first. These threads see the hash_link assigned to a block which
is assigned to another hash_link and not marked BLOCK_IN_SWITCH.
This can be a problem for functions that do not select the block
via its hash_link: flush and free. They do only see a block which
is in a "normal" state and don't know that it will be evicted soon.
We cannot set BLOCK_IN_SWITCH here because only one of the
requesting threads must handle the eviction. All others must wait
for it to complete. If we set the flag here, the threads would not
know who is in charge of the eviction. Without the flag, the first
thread takes the stick and sets the flag.
But we need to note in the block that is has been selected for
eviction. It must not be freed. The evicting thread will not
expect the block in the free list. Before freeing we could also
check if block->requests > 1. But I think including another flag
in the check of block->status is slightly more efficient and
probably easier to read.
*/
block->status |= BLOCK_IN_EVICTION;
return;
}
pins = hot ? &keycache->used_ins : &keycache->used_last;
ins = *pins;
if (ins) {