1
/* Copyright (C) 2000 MySQL AB
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
17
These functions handle keyblock cacheing for ISAM and MyISAM tables.
19
One cache can handle many files.
20
It must contain buffers of the same blocksize.
21
init_key_cache() should be used to init cache handler.
23
The free list (free_block_list) is a stack like structure.
24
When a block is freed by free_block(), it is pushed onto the stack.
25
When a new block is required it is first tried to pop one from the stack.
26
If the stack is empty, it is tried to get a never-used block from the pool.
27
If this is empty too, then a block is taken from the LRU ring, flushing it
28
to disk, if neccessary. This is handled in find_key_block().
29
With the new free list, the blocks can have three temperatures:
30
hot, warm and cold (which is free). This is remembered in the block header
31
by the enum BLOCK_TEMPERATURE temperature variable. Remembering the
32
temperature is neccessary to correctly count the number of warm blocks,
33
which is required to decide when blocks are allowed to become hot. Whenever
34
a block is inserted to another (sub-)chain, we take the old and new
35
temperature into account to decide if we got one more or less warm block.
36
blocks_unused is the sum of never used blocks in the pool and of currently
37
free blocks. blocks_used is the number of blocks fetched from the pool and
38
as such gives the maximum number of in-use blocks at any time.
43
All key cache locking is done with a single mutex per key cache:
44
keycache->cache_lock. This mutex is locked almost all the time
45
when executing code in this file (mf_keycache.c).
46
However it is released for I/O and some copy operations.
48
The cache_lock is also released when waiting for some event. Waiting
49
and signalling is done via condition variables. In most cases the
50
thread waits on its thread->suspend condition variable. Every thread
51
has a my_thread_var structure, which contains this variable and a
52
'*next' and '**prev' pointer. These pointers are used to insert the
53
thread into a wait queue.
55
A thread can wait for one block and thus be in one wait queue at a
58
Before starting to wait on its condition variable with
59
pthread_cond_wait(), the thread enters itself to a specific wait queue
60
with link_into_queue() (double linked with '*next' + '**prev') or
61
wait_on_queue() (single linked with '*next').
63
Another thread, when releasing a resource, looks up the waiting thread
64
in the related wait queue. It sends a signal with
65
pthread_cond_signal() to the waiting thread.
67
NOTE: Depending on the particular wait situation, either the sending
68
thread removes the waiting thread from the wait queue with
69
unlink_from_queue() or release_whole_queue() respectively, or the waiting
70
thread removes itself.
72
There is one exception from this locking scheme when one thread wants
73
to reuse a block for some other address. This works by first marking
74
the block reserved (status= BLOCK_IN_SWITCH) and then waiting for all
75
threads that are reading the block to finish. Each block has a
76
reference to a condition variable (condvar). It holds a reference to
77
the thread->suspend condition variable for the waiting thread (if such
78
a thread exists). When that thread is signaled, the reference is
79
cleared. The number of readers of a block is registered in
80
block->hash_link->requests. See wait_for_readers() / remove_reader()
81
for details. This is similar to the above, but it clearly means that
82
only one thread can wait for a particular block. There is no queue in
83
this case. Strangely enough block->convar is used for waiting for the
84
assigned hash_link only. More precisely it is used to wait for all
85
requests to be unregistered from the assigned hash_link.
87
The resize_queue serves two purposes:
88
1. Threads that want to do a resize wait there if in_resize is set.
89
This is not used in the server. The server refuses a second resize
90
request if one is already active. keycache->in_init is used for the
91
synchronization. See set_var.cc.
92
2. Threads that want to access blocks during resize wait here during
93
the re-initialization phase.
94
When the resize is done, all threads on the queue are signalled.
95
Hypothetical resizers can compete for resizing, and read/write
96
requests will restart to request blocks from the freshly resized
97
cache. If the cache has been resized too small, it is disabled and
98
'can_be_used' is false. In this case read/write requests bypass the
99
cache. Since they increment and decrement 'cnt_for_resize_op', the
100
next resizer can wait on the queue 'waiting_for_resize_cnt' until all
104
#include "mysys_priv.h"
105
#include "mysys_err.h"
106
#include <keycache.h>
107
#include "my_static.h"
108
#include <m_string.h>
114
Some compilation flags have been added specifically for this module
115
to control the following:
116
- not to let a thread to yield the control when reading directly
117
from key cache, which might improve performance in many cases;
119
#define SERIALIZED_READ_FROM_CACHE
120
- to set an upper bound for number of threads simultaneously
121
using the key cache; this setting helps to determine an optimal
122
size for hash table and improve performance when the number of
123
blocks in the key cache much less than the number of threads
125
to set this number equal to <N> add
126
#define MAX_THREADS <N>
127
- to substitute calls of pthread_cond_wait for calls of
128
pthread_cond_timedwait (wait with timeout set up);
129
this setting should be used only when you want to trap a deadlock
130
situation, which theoretically should not happen;
131
to set timeout equal to <T> seconds add
132
#define KEYCACHE_TIMEOUT <T>
133
- to enable the module traps and to send debug information from
134
key cache module to a special debug log add:
135
#define KEYCACHE_DEBUG
136
the name of this debug log file <LOG NAME> can be set through:
137
#define KEYCACHE_DEBUG_LOG <LOG NAME>
138
if the name is not defined, it's set by default;
139
if the KEYCACHE_DEBUG flag is not set up and we are in a debug
140
mode, i.e. when ! defined(DBUG_OFF), the debug information from the
141
module is sent to the regular debug log.
143
Example of the settings:
144
#define SERIALIZED_READ_FROM_CACHE
145
#define MAX_THREADS 100
146
#define KEYCACHE_TIMEOUT 1
147
#define KEYCACHE_DEBUG
148
#define KEYCACHE_DEBUG_LOG "my_key_cache_debug.log"
151
#define STRUCT_PTR(TYPE, MEMBER, a) \
152
(TYPE *) ((char *) (a) - offsetof(TYPE, MEMBER))
154
/* types of condition variables */
155
#define COND_FOR_REQUESTED 0
156
#define COND_FOR_SAVED 1
157
#define COND_FOR_READERS 2
159
typedef pthread_cond_t KEYCACHE_CONDVAR;
161
/* descriptor of the page in the key cache block buffer */
162
struct st_keycache_page
164
int file; /* file to which the page belongs to */
165
my_off_t filepos; /* position of the page in the file */
168
/* element in the chain of a hash table bucket */
171
struct st_hash_link *next, **prev; /* to connect links in the same bucket */
172
struct st_block_link *block; /* reference to the block for the page: */
173
File file; /* from such a file */
174
my_off_t diskpos; /* with such an offset */
175
uint requests; /* number of requests for the page */
178
/* simple states of a block */
179
#define BLOCK_ERROR 1 /* an error occured when performing file i/o */
180
#define BLOCK_READ 2 /* file block is in the block buffer */
181
#define BLOCK_IN_SWITCH 4 /* block is preparing to read new page */
182
#define BLOCK_REASSIGNED 8 /* blk does not accept requests for old page */
183
#define BLOCK_IN_FLUSH 16 /* block is selected for flush */
184
#define BLOCK_CHANGED 32 /* block buffer contains a dirty page */
185
#define BLOCK_IN_USE 64 /* block is not free */
186
#define BLOCK_IN_EVICTION 128 /* block is selected for eviction */
187
#define BLOCK_IN_FLUSHWRITE 256 /* block is in write to file */
188
#define BLOCK_FOR_UPDATE 512 /* block is selected for buffer modification */
190
/* page status, returned by find_key_block */
192
#define PAGE_TO_BE_READ 1
193
#define PAGE_WAIT_TO_BE_READ 2
195
/* block temperature determines in which (sub-)chain the block currently is */
196
enum BLOCK_TEMPERATURE { BLOCK_COLD /*free*/ , BLOCK_WARM , BLOCK_HOT };
198
/* key cache block */
202
*next_used, **prev_used; /* to connect links in the LRU chain (ring) */
204
*next_changed, **prev_changed; /* for lists of file dirty/clean blocks */
205
struct st_hash_link *hash_link; /* backward ptr to referring hash_link */
206
KEYCACHE_WQUEUE wqueue[2]; /* queues on waiting requests for new/old pages */
207
uint requests; /* number of requests for the block */
208
uchar *buffer; /* buffer for the block page */
209
uint offset; /* beginning of modified data in the buffer */
210
uint length; /* end of data in the buffer */
211
uint status; /* state of the block */
212
enum BLOCK_TEMPERATURE temperature; /* block temperature: cold, warm, hot */
213
uint hits_left; /* number of hits left until promotion */
214
ulonglong last_hit_time; /* timestamp of the last hit */
215
KEYCACHE_CONDVAR *condvar; /* condition variable for 'no readers' event */
218
KEY_CACHE dflt_key_cache_var;
219
KEY_CACHE *dflt_key_cache= &dflt_key_cache_var;
221
#define FLUSH_CACHE 2000 /* sort this many blocks at once */
223
static int flush_all_key_blocks(KEY_CACHE *keycache);
225
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
226
pthread_mutex_t *mutex);
227
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue);
229
#define wait_on_queue(wqueue, mutex) do {} while (0)
230
#define release_whole_queue(wqueue) do {} while (0)
232
static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block);
233
#if !defined(DBUG_OFF)
234
static void test_key_cache(KEY_CACHE *keycache,
235
const char *where, my_bool lock);
238
#define KEYCACHE_HASH(f, pos) \
239
(((ulong) ((pos) / keycache->key_cache_block_size) + \
240
(ulong) (f)) & (keycache->hash_entries-1))
241
#define FILE_HASH(f) ((uint) (f) & (CHANGED_BLOCKS_HASH-1))
243
#define DEFAULT_KEYCACHE_DEBUG_LOG "keycache_debug.log"
245
#if defined(KEYCACHE_DEBUG) && ! defined(KEYCACHE_DEBUG_LOG)
246
#define KEYCACHE_DEBUG_LOG DEFAULT_KEYCACHE_DEBUG_LOG
249
#if defined(KEYCACHE_DEBUG_LOG)
250
static FILE *keycache_debug_log=NULL;
251
static void keycache_debug_print _VARARGS((const char *fmt,...));
252
#define KEYCACHE_DEBUG_OPEN \
253
if (!keycache_debug_log) \
255
keycache_debug_log= fopen(KEYCACHE_DEBUG_LOG, "w"); \
256
(void) setvbuf(keycache_debug_log, NULL, _IOLBF, BUFSIZ); \
259
#define KEYCACHE_DEBUG_CLOSE \
260
if (keycache_debug_log) \
262
fclose(keycache_debug_log); \
263
keycache_debug_log= 0; \
266
#define KEYCACHE_DEBUG_OPEN
267
#define KEYCACHE_DEBUG_CLOSE
268
#endif /* defined(KEYCACHE_DEBUG_LOG) */
270
#if defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG)
271
#define KEYCACHE_DBUG_PRINT(l, m) \
272
{ if (keycache_debug_log) fprintf(keycache_debug_log, "%s: ", l); \
273
keycache_debug_print m; }
275
#define KEYCACHE_DBUG_ASSERT(a) \
276
{ if (! (a) && keycache_debug_log) fclose(keycache_debug_log); \
279
#define KEYCACHE_DBUG_PRINT(l, m) DBUG_PRINT(l, m)
280
#define KEYCACHE_DBUG_ASSERT(a) DBUG_ASSERT(a)
281
#endif /* defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG) */
283
#if defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF)
285
static long keycache_thread_id;
286
#define KEYCACHE_THREAD_TRACE(l) \
287
KEYCACHE_DBUG_PRINT(l,("|thread %ld",keycache_thread_id))
289
#define KEYCACHE_THREAD_TRACE_BEGIN(l) \
290
{ struct st_my_thread_var *thread_var= my_thread_var; \
291
keycache_thread_id= thread_var->id; \
292
KEYCACHE_DBUG_PRINT(l,("[thread %ld",keycache_thread_id)) }
294
#define KEYCACHE_THREAD_TRACE_END(l) \
295
KEYCACHE_DBUG_PRINT(l,("]thread %ld",keycache_thread_id))
297
#define KEYCACHE_THREAD_TRACE(l) KEYCACHE_DBUG_PRINT(l,(""))
298
#define KEYCACHE_THREAD_TRACE_BEGIN(l) KEYCACHE_DBUG_PRINT(l,(""))
299
#define KEYCACHE_THREAD_TRACE_END(l) KEYCACHE_DBUG_PRINT(l,(""))
302
#define KEYCACHE_THREAD_TRACE_BEGIN(l)
303
#define KEYCACHE_THREAD_TRACE_END(l)
304
#define KEYCACHE_THREAD_TRACE(l)
305
#endif /* defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF) */
307
#define BLOCK_NUMBER(b) \
308
((uint) (((char*)(b)-(char *) keycache->block_root)/sizeof(BLOCK_LINK)))
309
#define HASH_LINK_NUMBER(h) \
310
((uint) (((char*)(h)-(char *) keycache->hash_link_root)/sizeof(HASH_LINK)))
312
#if (defined(KEYCACHE_TIMEOUT)) || defined(KEYCACHE_DEBUG)
313
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
314
pthread_mutex_t *mutex);
316
#define keycache_pthread_cond_wait pthread_cond_wait
319
#if defined(KEYCACHE_DEBUG)
320
static int keycache_pthread_mutex_lock(pthread_mutex_t *mutex);
321
static void keycache_pthread_mutex_unlock(pthread_mutex_t *mutex);
322
static int keycache_pthread_cond_signal(pthread_cond_t *cond);
324
#define keycache_pthread_mutex_lock pthread_mutex_lock
325
#define keycache_pthread_mutex_unlock pthread_mutex_unlock
326
#define keycache_pthread_cond_signal pthread_cond_signal
327
#endif /* defined(KEYCACHE_DEBUG) */
329
#if !defined(DBUG_OFF)
333
#define inline /* disabled inline for easier debugging */
334
static int fail_block(BLOCK_LINK *block);
335
static int fail_hlink(HASH_LINK *hlink);
336
static int cache_empty(KEY_CACHE *keycache);
339
static inline uint next_power(uint value)
341
return (uint) my_round_up_to_next_power((uint32) value) << 1;
346
Initialize a key cache
350
keycache pointer to a key cache data structure
351
key_cache_block_size size of blocks to keep cached data
352
use_mem total memory to use for the key cache
353
division_limit division limit (may be zero)
354
age_threshold age threshold (may be zero)
357
number of blocks in the key cache, if successful,
361
if keycache->key_cache_inited != 0 we assume that the key cache
362
is already initialized. This is for now used by myisamchk, but shouldn't
363
be something that a program should rely on!
365
It's assumed that no two threads call this function simultaneously
366
referring to the same key cache handle.
370
int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
371
size_t use_mem, uint division_limit,
374
ulong blocks, hash_links;
377
DBUG_ENTER("init_key_cache");
378
DBUG_ASSERT(key_cache_block_size >= 512);
381
if (keycache->key_cache_inited && keycache->disk_blocks > 0)
383
DBUG_PRINT("warning",("key cache already in use"));
387
keycache->global_cache_w_requests= keycache->global_cache_r_requests= 0;
388
keycache->global_cache_read= keycache->global_cache_write= 0;
389
keycache->disk_blocks= -1;
390
if (! keycache->key_cache_inited)
392
keycache->key_cache_inited= 1;
394
Initialize these variables once only.
395
Their value must survive re-initialization during resizing.
397
keycache->in_resize= 0;
398
keycache->resize_in_flush= 0;
399
keycache->cnt_for_resize_op= 0;
400
keycache->waiting_for_resize_cnt.last_thread= NULL;
401
keycache->in_init= 0;
402
pthread_mutex_init(&keycache->cache_lock, MY_MUTEX_INIT_FAST);
403
keycache->resize_queue.last_thread= NULL;
406
keycache->key_cache_mem_size= use_mem;
407
keycache->key_cache_block_size= key_cache_block_size;
408
DBUG_PRINT("info", ("key_cache_block_size: %u",
409
key_cache_block_size));
411
blocks= (ulong) (use_mem / (sizeof(BLOCK_LINK) + 2 * sizeof(HASH_LINK) +
412
sizeof(HASH_LINK*) * 5/4 + key_cache_block_size));
413
/* It doesn't make sense to have too few blocks (less than 8) */
418
/* Set my_hash_entries to the next bigger 2 power */
419
if ((keycache->hash_entries= next_power(blocks)) < blocks * 5/4)
420
keycache->hash_entries<<= 1;
421
hash_links= 2 * blocks;
422
#if defined(MAX_THREADS)
423
if (hash_links < MAX_THREADS + blocks - 1)
424
hash_links= MAX_THREADS + blocks - 1;
426
while ((length= (ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)) +
427
ALIGN_SIZE(hash_links * sizeof(HASH_LINK)) +
428
ALIGN_SIZE(sizeof(HASH_LINK*) *
429
keycache->hash_entries))) +
430
((size_t) blocks * keycache->key_cache_block_size) > use_mem)
432
/* Allocate memory for cache page buffers */
433
if ((keycache->block_mem=
434
my_large_malloc((size_t) blocks * keycache->key_cache_block_size,
438
Allocate memory for blocks, hash_links and hash entries;
439
For each block 2 hash links are allocated
441
if ((keycache->block_root= (BLOCK_LINK*) my_malloc(length,
444
my_large_free(keycache->block_mem, MYF(0));
445
keycache->block_mem= 0;
450
my_error(EE_OUTOFMEMORY, MYF(0), blocks * keycache->key_cache_block_size);
453
blocks= blocks / 4*3;
455
keycache->blocks_unused= blocks;
456
keycache->disk_blocks= (int) blocks;
457
keycache->hash_links= hash_links;
458
keycache->hash_root= (HASH_LINK**) ((char*) keycache->block_root +
459
ALIGN_SIZE(blocks*sizeof(BLOCK_LINK)));
460
keycache->hash_link_root= (HASH_LINK*) ((char*) keycache->hash_root +
461
ALIGN_SIZE((sizeof(HASH_LINK*) *
462
keycache->hash_entries)));
463
bzero((uchar*) keycache->block_root,
464
keycache->disk_blocks * sizeof(BLOCK_LINK));
465
bzero((uchar*) keycache->hash_root,
466
keycache->hash_entries * sizeof(HASH_LINK*));
467
bzero((uchar*) keycache->hash_link_root,
468
keycache->hash_links * sizeof(HASH_LINK));
469
keycache->hash_links_used= 0;
470
keycache->free_hash_list= NULL;
471
keycache->blocks_used= keycache->blocks_changed= 0;
473
keycache->global_blocks_changed= 0;
474
keycache->blocks_available=0; /* For debugging */
476
/* The LRU chain is empty after initialization */
477
keycache->used_last= NULL;
478
keycache->used_ins= NULL;
479
keycache->free_block_list= NULL;
480
keycache->keycache_time= 0;
481
keycache->warm_blocks= 0;
482
keycache->min_warm_blocks= (division_limit ?
483
blocks * division_limit / 100 + 1 :
485
keycache->age_threshold= (age_threshold ?
486
blocks * age_threshold / 100 :
489
keycache->can_be_used= 1;
491
keycache->waiting_for_hash_link.last_thread= NULL;
492
keycache->waiting_for_block.last_thread= NULL;
494
("disk_blocks: %d block_root: 0x%lx hash_entries: %d\
495
hash_root: 0x%lx hash_links: %d hash_link_root: 0x%lx",
496
keycache->disk_blocks, (long) keycache->block_root,
497
keycache->hash_entries, (long) keycache->hash_root,
498
keycache->hash_links, (long) keycache->hash_link_root));
499
bzero((uchar*) keycache->changed_blocks,
500
sizeof(keycache->changed_blocks[0]) * CHANGED_BLOCKS_HASH);
501
bzero((uchar*) keycache->file_blocks,
502
sizeof(keycache->file_blocks[0]) * CHANGED_BLOCKS_HASH);
506
/* key_buffer_size is specified too small. Disable the cache. */
507
keycache->can_be_used= 0;
510
keycache->blocks= keycache->disk_blocks > 0 ? keycache->disk_blocks : 0;
511
DBUG_RETURN((int) keycache->disk_blocks);
515
keycache->disk_blocks= 0;
517
if (keycache->block_mem)
519
my_large_free((uchar*) keycache->block_mem, MYF(0));
520
keycache->block_mem= NULL;
522
if (keycache->block_root)
524
my_free((uchar*) keycache->block_root, MYF(0));
525
keycache->block_root= NULL;
528
keycache->can_be_used= 0;
538
keycache pointer to a key cache data structure
539
key_cache_block_size size of blocks to keep cached data
540
use_mem total memory to use for the new key cache
541
division_limit new division limit (if not zero)
542
age_threshold new age threshold (if not zero)
545
number of blocks in the key cache, if successful,
549
The function first compares the memory size and the block size parameters
550
with the key cache values.
552
If they differ the function free the the memory allocated for the
553
old key cache blocks by calling the end_key_cache function and
554
then rebuilds the key cache with new blocks by calling
557
The function starts the operation only when all other threads
558
performing operations with the key cache let her to proceed
559
(when cnt_for_resize=0).
562
int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
563
size_t use_mem, uint division_limit,
567
DBUG_ENTER("resize_key_cache");
569
if (!keycache->key_cache_inited)
570
DBUG_RETURN(keycache->disk_blocks);
572
if(key_cache_block_size == keycache->key_cache_block_size &&
573
use_mem == keycache->key_cache_mem_size)
575
change_key_cache_param(keycache, division_limit, age_threshold);
576
DBUG_RETURN(keycache->disk_blocks);
579
keycache_pthread_mutex_lock(&keycache->cache_lock);
583
We may need to wait for another thread which is doing a resize
584
already. This cannot happen in the MySQL server though. It allows
585
one resizer only. In set_var.cc keycache->in_init is used to block
588
while (keycache->in_resize)
590
/* purecov: begin inspected */
591
wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
597
Mark the operation in progress. This blocks other threads from doing
598
a resize in parallel. It prohibits new blocks to enter the cache.
599
Read/write requests can bypass the cache during the flush phase.
601
keycache->in_resize= 1;
603
/* Need to flush only if keycache is enabled. */
604
if (keycache->can_be_used)
606
/* Start the flush phase. */
607
keycache->resize_in_flush= 1;
609
if (flush_all_key_blocks(keycache))
611
/* TODO: if this happens, we should write a warning in the log file ! */
612
keycache->resize_in_flush= 0;
614
keycache->can_be_used= 0;
617
DBUG_ASSERT(cache_empty(keycache));
619
/* End the flush phase. */
620
keycache->resize_in_flush= 0;
625
Some direct read/write operations (bypassing the cache) may still be
626
unfinished. Wait until they are done. If the key cache can be used,
627
direct I/O is done in increments of key_cache_block_size. That is,
628
every block is checked if it is in the cache. We need to wait for
629
pending I/O before re-initializing the cache, because we may change
630
the block size. Otherwise they could check for blocks at file
631
positions where the new block division has none. We do also want to
632
wait for I/O done when (if) the cache was disabled. It must not
633
run in parallel with normal cache operation.
635
while (keycache->cnt_for_resize_op)
636
wait_on_queue(&keycache->waiting_for_resize_cnt, &keycache->cache_lock);
638
KEYCACHE_DBUG_ASSERT(keycache->cnt_for_resize_op == 0);
642
Free old cache structures, allocate new structures, and initialize
643
them. Note that the cache_lock mutex and the resize_queue are left
644
untouched. We do not lose the cache_lock and will release it only at
645
the end of this function.
647
end_key_cache(keycache, 0); /* Don't free mutex */
648
/* The following will work even if use_mem is 0 */
649
blocks= init_key_cache(keycache, key_cache_block_size, use_mem,
650
division_limit, age_threshold);
654
Mark the resize finished. This allows other threads to start a
655
resize or to request new cache blocks.
657
keycache->in_resize= 0;
659
/* Signal waiting threads. */
660
release_whole_queue(&keycache->resize_queue);
662
keycache_pthread_mutex_unlock(&keycache->cache_lock);
668
Increment counter blocking resize key cache operation
670
static inline void inc_counter_for_resize_op(KEY_CACHE *keycache)
672
keycache->cnt_for_resize_op++;
677
Decrement counter blocking resize key cache operation;
678
Signal the operation to proceed when counter becomes equal zero
680
static inline void dec_counter_for_resize_op(KEY_CACHE *keycache)
682
if (!--keycache->cnt_for_resize_op)
683
release_whole_queue(&keycache->waiting_for_resize_cnt);
687
Change the key cache parameters
690
change_key_cache_param()
691
keycache pointer to a key cache data structure
692
division_limit new division limit (if not zero)
693
age_threshold new age threshold (if not zero)
699
Presently the function resets the key cache parameters
700
concerning midpoint insertion strategy - division_limit and
704
void change_key_cache_param(KEY_CACHE *keycache, uint division_limit,
707
DBUG_ENTER("change_key_cache_param");
709
keycache_pthread_mutex_lock(&keycache->cache_lock);
711
keycache->min_warm_blocks= (keycache->disk_blocks *
712
division_limit / 100 + 1);
714
keycache->age_threshold= (keycache->disk_blocks *
715
age_threshold / 100);
716
keycache_pthread_mutex_unlock(&keycache->cache_lock);
722
Remove key_cache from memory
726
keycache key cache handle
727
cleanup Complete free (Free also mutex for key cache)
733
void end_key_cache(KEY_CACHE *keycache, my_bool cleanup)
735
DBUG_ENTER("end_key_cache");
736
DBUG_PRINT("enter", ("key_cache: 0x%lx", (long) keycache));
738
if (!keycache->key_cache_inited)
741
if (keycache->disk_blocks > 0)
743
if (keycache->block_mem)
745
my_large_free((uchar*) keycache->block_mem, MYF(0));
746
keycache->block_mem= NULL;
747
my_free((uchar*) keycache->block_root, MYF(0));
748
keycache->block_root= NULL;
750
keycache->disk_blocks= -1;
751
/* Reset blocks_changed to be safe if flush_all_key_blocks is called */
752
keycache->blocks_changed= 0;
755
DBUG_PRINT("status", ("used: %lu changed: %lu w_requests: %lu "
756
"writes: %lu r_requests: %lu reads: %lu",
757
keycache->blocks_used, keycache->global_blocks_changed,
758
(ulong) keycache->global_cache_w_requests,
759
(ulong) keycache->global_cache_write,
760
(ulong) keycache->global_cache_r_requests,
761
(ulong) keycache->global_cache_read));
765
pthread_mutex_destroy(&keycache->cache_lock);
766
keycache->key_cache_inited= keycache->can_be_used= 0;
767
KEYCACHE_DEBUG_CLOSE;
770
} /* end_key_cache */
776
Link a thread into double-linked queue of waiting threads.
780
wqueue pointer to the queue structure
781
thread pointer to the thread to be added to the queue
787
Queue is represented by a circular list of the thread structures
788
The list is double-linked of the type (**prev,*next), accessed by
789
a pointer to the last element.
792
static void link_into_queue(KEYCACHE_WQUEUE *wqueue,
793
struct st_my_thread_var *thread)
795
struct st_my_thread_var *last;
797
DBUG_ASSERT(!thread->next && !thread->prev);
798
if (! (last= wqueue->last_thread))
801
thread->next= thread;
802
thread->prev= &thread->next;
806
thread->prev= last->next->prev;
807
last->next->prev= &thread->next;
808
thread->next= last->next;
811
wqueue->last_thread= thread;
815
Unlink a thread from double-linked queue of waiting threads
819
wqueue pointer to the queue structure
820
thread pointer to the thread to be removed from the queue
826
See NOTES for link_into_queue
829
static void unlink_from_queue(KEYCACHE_WQUEUE *wqueue,
830
struct st_my_thread_var *thread)
832
KEYCACHE_DBUG_PRINT("unlink_from_queue", ("thread %ld", thread->id));
833
DBUG_ASSERT(thread->next && thread->prev);
834
if (thread->next == thread)
835
/* The queue contains only one member */
836
wqueue->last_thread= NULL;
839
thread->next->prev= thread->prev;
840
*thread->prev=thread->next;
841
if (wqueue->last_thread == thread)
842
wqueue->last_thread= STRUCT_PTR(struct st_my_thread_var, next,
846
#if !defined(DBUG_OFF)
848
This makes it easier to see it's not in a chain during debugging.
849
And some DBUG_ASSERT() rely on it.
857
Add a thread to single-linked queue of waiting threads
861
wqueue Pointer to the queue structure.
862
mutex Cache_lock to acquire after awake.
868
Queue is represented by a circular list of the thread structures
869
The list is single-linked of the type (*next), accessed by a pointer
872
The function protects against stray signals by verifying that the
873
current thread is unlinked from the queue when awaking. However,
874
since several threads can wait for the same event, it might be
875
necessary for the caller of the function to check again if the
876
condition for awake is indeed matched.
879
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
880
pthread_mutex_t *mutex)
882
struct st_my_thread_var *last;
883
struct st_my_thread_var *thread= my_thread_var;
886
DBUG_ASSERT(!thread->next);
887
DBUG_ASSERT(!thread->prev); /* Not required, but must be true anyway. */
888
if (! (last= wqueue->last_thread))
889
thread->next= thread;
892
thread->next= last->next;
895
wqueue->last_thread= thread;
898
Wait until thread is removed from queue by the signalling thread.
899
The loop protects against stray signals.
903
KEYCACHE_DBUG_PRINT("wait", ("suspend thread %ld", thread->id));
904
keycache_pthread_cond_wait(&thread->suspend, mutex);
906
while (thread->next);
911
Remove all threads from queue signaling them to proceed
914
release_whole_queue()
915
wqueue pointer to the queue structure
921
See notes for wait_on_queue().
922
When removed from the queue each thread is signaled via condition
923
variable thread->suspend.
926
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue)
928
struct st_my_thread_var *last;
929
struct st_my_thread_var *next;
930
struct st_my_thread_var *thread;
932
/* Queue may be empty. */
933
if (!(last= wqueue->last_thread))
940
KEYCACHE_DBUG_PRINT("release_whole_queue: signal",
941
("thread %ld", thread->id));
942
/* Signal the thread. */
943
keycache_pthread_cond_signal(&thread->suspend);
944
/* Take thread from queue. */
948
while (thread != last);
950
/* Now queue is definitely empty. */
951
wqueue->last_thread= NULL;
958
Unlink a block from the chain of dirty/clean blocks
961
static inline void unlink_changed(BLOCK_LINK *block)
963
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
964
if (block->next_changed)
965
block->next_changed->prev_changed= block->prev_changed;
966
*block->prev_changed= block->next_changed;
968
#if !defined(DBUG_OFF)
970
This makes it easier to see it's not in a chain during debugging.
971
And some DBUG_ASSERT() rely on it.
973
block->next_changed= NULL;
974
block->prev_changed= NULL;
980
Link a block into the chain of dirty/clean blocks
983
static inline void link_changed(BLOCK_LINK *block, BLOCK_LINK **phead)
985
DBUG_ASSERT(!block->next_changed);
986
DBUG_ASSERT(!block->prev_changed);
987
block->prev_changed= phead;
988
if ((block->next_changed= *phead))
989
(*phead)->prev_changed= &block->next_changed;
995
Link a block in a chain of clean blocks of a file.
999
keycache Key cache handle
1000
block Block to relink
1001
file File to be linked to
1002
unlink If to unlink first
1005
Unlink a block from whichever chain it is linked in, if it's
1006
asked for, and link it to the chain of clean blocks of the
1010
Please do never set/clear BLOCK_CHANGED outside of
1011
link_to_file_list() or link_to_changed_list().
1012
You would risk to damage correct counting of changed blocks
1013
and to find blocks in the wrong hash.
1019
static void link_to_file_list(KEY_CACHE *keycache,
1020
BLOCK_LINK *block, int file,
1021
my_bool unlink_block)
1023
DBUG_ASSERT(block->status & BLOCK_IN_USE);
1024
DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
1025
DBUG_ASSERT(block->hash_link->file == file);
1027
unlink_changed(block);
1028
link_changed(block, &keycache->file_blocks[FILE_HASH(file)]);
1029
if (block->status & BLOCK_CHANGED)
1031
block->status&= ~BLOCK_CHANGED;
1032
keycache->blocks_changed--;
1033
keycache->global_blocks_changed--;
1039
Re-link a block from the clean chain to the dirty chain of a file.
1042
link_to_changed_list()
1043
keycache key cache handle
1044
block block to relink
1047
Unlink a block from the chain of clean blocks of a file
1048
and link it to the chain of dirty blocks of the same file.
1051
Please do never set/clear BLOCK_CHANGED outside of
1052
link_to_file_list() or link_to_changed_list().
1053
You would risk to damage correct counting of changed blocks
1054
and to find blocks in the wrong hash.
1060
static void link_to_changed_list(KEY_CACHE *keycache,
1063
DBUG_ASSERT(block->status & BLOCK_IN_USE);
1064
DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
1065
DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
1067
unlink_changed(block);
1069
&keycache->changed_blocks[FILE_HASH(block->hash_link->file)]);
1070
block->status|=BLOCK_CHANGED;
1071
keycache->blocks_changed++;
1072
keycache->global_blocks_changed++;
1077
Link a block to the LRU chain at the beginning or at the end of
1082
keycache pointer to a key cache data structure
1083
block pointer to the block to link to the LRU chain
1084
hot <-> to link the block into the hot subchain
1085
at_end <-> to link the block at the end of the subchain
1091
The LRU ring is represented by a circular list of block structures.
1092
The list is double-linked of the type (**prev,*next) type.
1093
The LRU ring is divided into two parts - hot and warm.
1094
There are two pointers to access the last blocks of these two
1095
parts. The beginning of the warm part follows right after the
1096
end of the hot part.
1097
Only blocks of the warm part can be used for eviction.
1098
The first block from the beginning of this subchain is always
1099
taken for eviction (keycache->last_used->next)
1101
LRU chain: +------+ H O T +------+
1102
+----| end |----...<----| beg |----+
1103
| +------+last +------+ |
1104
v<-link in latest hot (new end) |
1105
| link in latest warm (new end)->^
1106
| +------+ W A R M +------+ |
1107
+----| beg |---->...----| end |----+
1108
+------+ +------+ins
1111
It is also possible that the block is selected for eviction and thus
1112
not linked in the LRU ring.
1115
static void link_block(KEY_CACHE *keycache, BLOCK_LINK *block, my_bool hot,
1121
DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
1122
DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
1123
DBUG_ASSERT(!block->requests);
1124
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
1125
DBUG_ASSERT(!block->next_used);
1126
DBUG_ASSERT(!block->prev_used);
1128
if (!hot && keycache->waiting_for_block.last_thread)
1130
/* Signal that in the LRU warm sub-chain an available block has appeared */
1131
struct st_my_thread_var *last_thread=
1132
keycache->waiting_for_block.last_thread;
1133
struct st_my_thread_var *first_thread= last_thread->next;
1134
struct st_my_thread_var *next_thread= first_thread;
1135
HASH_LINK *hash_link= (HASH_LINK *) first_thread->opt_info;
1136
struct st_my_thread_var *thread;
1139
thread= next_thread;
1140
next_thread= thread->next;
1142
We notify about the event all threads that ask
1143
for the same page as the first thread in the queue
1145
if ((HASH_LINK *) thread->opt_info == hash_link)
1147
KEYCACHE_DBUG_PRINT("link_block: signal", ("thread %ld", thread->id));
1148
keycache_pthread_cond_signal(&thread->suspend);
1149
unlink_from_queue(&keycache->waiting_for_block, thread);
1153
while (thread != last_thread);
1154
hash_link->block= block;
1156
NOTE: We assigned the block to the hash_link and signalled the
1157
requesting thread(s). But it is possible that other threads runs
1158
first. These threads see the hash_link assigned to a block which
1159
is assigned to another hash_link and not marked BLOCK_IN_SWITCH.
1160
This can be a problem for functions that do not select the block
1161
via its hash_link: flush and free. They do only see a block which
1162
is in a "normal" state and don't know that it will be evicted soon.
1164
We cannot set BLOCK_IN_SWITCH here because only one of the
1165
requesting threads must handle the eviction. All others must wait
1166
for it to complete. If we set the flag here, the threads would not
1167
know who is in charge of the eviction. Without the flag, the first
1168
thread takes the stick and sets the flag.
1170
But we need to note in the block that is has been selected for
1171
eviction. It must not be freed. The evicting thread will not
1172
expect the block in the free list. Before freeing we could also
1173
check if block->requests > 1. But I think including another flag
1174
in the check of block->status is slightly more efficient and
1175
probably easier to read.
1177
block->status|= BLOCK_IN_EVICTION;
1178
KEYCACHE_THREAD_TRACE("link_block: after signaling");
1179
#if defined(KEYCACHE_DEBUG)
1180
KEYCACHE_DBUG_PRINT("link_block",
1181
("linked,unlinked block %u status=%x #requests=%u #available=%u",
1182
BLOCK_NUMBER(block), block->status,
1183
block->requests, keycache->blocks_available));
1188
KEYCACHE_DBUG_ASSERT(! (!hot && keycache->waiting_for_block.last_thread));
1189
/* Condition not transformed using DeMorgan, to keep the text identical */
1191
pins= hot ? &keycache->used_ins : &keycache->used_last;
1195
ins->next_used->prev_used= &block->next_used;
1196
block->next_used= ins->next_used;
1197
block->prev_used= &ins->next_used;
1198
ins->next_used= block;
1204
/* The LRU ring is empty. Let the block point to itself. */
1205
keycache->used_last= keycache->used_ins= block->next_used= block;
1206
block->prev_used= &block->next_used;
1208
KEYCACHE_THREAD_TRACE("link_block");
1209
#if defined(KEYCACHE_DEBUG)
1210
keycache->blocks_available++;
1211
KEYCACHE_DBUG_PRINT("link_block",
1212
("linked block %u:%1u status=%x #requests=%u #available=%u",
1213
BLOCK_NUMBER(block), at_end, block->status,
1214
block->requests, keycache->blocks_available));
1215
KEYCACHE_DBUG_ASSERT((ulong) keycache->blocks_available <=
1216
keycache->blocks_used);
1222
Unlink a block from the LRU chain
1226
keycache pointer to a key cache data structure
1227
block pointer to the block to unlink from the LRU chain
1233
See NOTES for link_block
1236
static void unlink_block(KEY_CACHE *keycache, BLOCK_LINK *block)
1238
DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
1239
DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
1240
DBUG_ASSERT(!block->requests);
1241
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
1242
DBUG_ASSERT(block->next_used && block->prev_used &&
1243
(block->next_used->prev_used == &block->next_used) &&
1244
(*block->prev_used == block));
1245
if (block->next_used == block)
1246
/* The list contains only one member */
1247
keycache->used_last= keycache->used_ins= NULL;
1250
block->next_used->prev_used= block->prev_used;
1251
*block->prev_used= block->next_used;
1252
if (keycache->used_last == block)
1253
keycache->used_last= STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
1254
if (keycache->used_ins == block)
1255
keycache->used_ins=STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
1257
block->next_used= NULL;
1258
#if !defined(DBUG_OFF)
1260
This makes it easier to see it's not in a chain during debugging.
1261
And some DBUG_ASSERT() rely on it.
1263
block->prev_used= NULL;
1266
KEYCACHE_THREAD_TRACE("unlink_block");
1267
#if defined(KEYCACHE_DEBUG)
1268
KEYCACHE_DBUG_ASSERT(keycache->blocks_available != 0);
1269
keycache->blocks_available--;
1270
KEYCACHE_DBUG_PRINT("unlink_block",
1271
("unlinked block %u status=%x #requests=%u #available=%u",
1272
BLOCK_NUMBER(block), block->status,
1273
block->requests, keycache->blocks_available));
1279
Register requests for a block.
1283
keycache Pointer to a key cache data structure.
1284
block Pointer to the block to register a request on.
1285
count Number of requests. Always 1.
1288
The first request unlinks the block from the LRU ring. This means
1289
that it is protected against eveiction.
1294
static void reg_requests(KEY_CACHE *keycache, BLOCK_LINK *block, int count)
1296
DBUG_ASSERT(block->status & BLOCK_IN_USE);
1297
DBUG_ASSERT(block->hash_link);
1299
if (!block->requests)
1300
unlink_block(keycache, block);
1301
block->requests+=count;
1306
Unregister request for a block
1307
linking it to the LRU chain if it's the last request
1311
keycache pointer to a key cache data structure
1312
block pointer to the block to link to the LRU chain
1313
at_end <-> to link the block at the end of the LRU chain
1319
Every linking to the LRU ring decrements by one a special block
1320
counter (if it's positive). If the at_end parameter is TRUE the block is
1321
added either at the end of warm sub-chain or at the end of hot sub-chain.
1322
It is added to the hot subchain if its counter is zero and number of
1323
blocks in warm sub-chain is not less than some low limit (determined by
1324
the division_limit parameter). Otherwise the block is added to the warm
1325
sub-chain. If the at_end parameter is FALSE the block is always added
1326
at beginning of the warm sub-chain.
1327
Thus a warm block can be promoted to the hot sub-chain when its counter
1328
becomes zero for the first time.
1329
At the same time the block at the very beginning of the hot subchain
1330
might be moved to the beginning of the warm subchain if it stays untouched
1331
for a too long time (this time is determined by parameter age_threshold).
1333
It is also possible that the block is selected for eviction and thus
1334
not linked in the LRU ring.
1337
static void unreg_request(KEY_CACHE *keycache,
1338
BLOCK_LINK *block, int at_end)
1340
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1341
DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
1342
DBUG_ASSERT(block->requests);
1343
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
1344
DBUG_ASSERT(!block->next_used);
1345
DBUG_ASSERT(!block->prev_used);
1346
if (! --block->requests)
1349
if (block->hits_left)
1351
hot= !block->hits_left && at_end &&
1352
keycache->warm_blocks > keycache->min_warm_blocks;
1355
if (block->temperature == BLOCK_WARM)
1356
keycache->warm_blocks--;
1357
block->temperature= BLOCK_HOT;
1358
KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
1359
keycache->warm_blocks));
1361
link_block(keycache, block, hot, (my_bool)at_end);
1362
block->last_hit_time= keycache->keycache_time;
1363
keycache->keycache_time++;
1365
At this place, the block might be in the LRU ring or not. If an
1366
evicter was waiting for a block, it was selected for eviction and
1367
not linked in the LRU ring.
1371
Check if we should link a hot block to the warm block sub-chain.
1372
It is possible that we select the same block as above. But it can
1373
also be another block. In any case a block from the LRU ring is
1374
selected. In other words it works even if the above block was
1375
selected for eviction and not linked in the LRU ring. Since this
1376
happens only if the LRU ring is empty, the block selected below
1377
would be NULL and the rest of the function skipped.
1379
block= keycache->used_ins;
1380
if (block && keycache->keycache_time - block->last_hit_time >
1381
keycache->age_threshold)
1383
unlink_block(keycache, block);
1384
link_block(keycache, block, 0, 0);
1385
if (block->temperature != BLOCK_WARM)
1387
keycache->warm_blocks++;
1388
block->temperature= BLOCK_WARM;
1390
KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
1391
keycache->warm_blocks));
1397
Remove a reader of the page in block
1400
static void remove_reader(BLOCK_LINK *block)
1402
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1403
DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
1404
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
1405
DBUG_ASSERT(!block->next_used);
1406
DBUG_ASSERT(!block->prev_used);
1407
DBUG_ASSERT(block->hash_link->requests);
1409
if (! --block->hash_link->requests && block->condvar)
1410
keycache_pthread_cond_signal(block->condvar);
1412
--block->hash_link->requests;
1418
Wait until the last reader of the page in block
1419
signals on its termination
1422
static void wait_for_readers(KEY_CACHE *keycache,
1426
struct st_my_thread_var *thread= my_thread_var;
1427
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1428
DBUG_ASSERT(!(block->status & (BLOCK_ERROR | BLOCK_IN_FLUSH |
1430
DBUG_ASSERT(block->hash_link);
1431
DBUG_ASSERT(block->hash_link->block == block);
1432
/* Linked in file_blocks or changed_blocks hash. */
1433
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
1434
/* Not linked in LRU ring. */
1435
DBUG_ASSERT(!block->next_used);
1436
DBUG_ASSERT(!block->prev_used);
1437
while (block->hash_link->requests)
1439
KEYCACHE_DBUG_PRINT("wait_for_readers: wait",
1440
("suspend thread %ld block %u",
1441
thread->id, BLOCK_NUMBER(block)));
1442
/* There must be no other waiter. We have no queue here. */
1443
DBUG_ASSERT(!block->condvar);
1444
block->condvar= &thread->suspend;
1445
keycache_pthread_cond_wait(&thread->suspend, &keycache->cache_lock);
1446
block->condvar= NULL;
1449
KEYCACHE_DBUG_ASSERT(block->hash_link->requests == 0);
1455
Add a hash link to a bucket in the hash_table
1458
static inline void link_hash(HASH_LINK **start, HASH_LINK *hash_link)
1461
(*start)->prev= &hash_link->next;
1462
hash_link->next= *start;
1463
hash_link->prev= start;
1469
Remove a hash link from the hash table
1472
static void unlink_hash(KEY_CACHE *keycache, HASH_LINK *hash_link)
1474
KEYCACHE_DBUG_PRINT("unlink_hash", ("fd: %u pos_ %lu #requests=%u",
1475
(uint) hash_link->file,(ulong) hash_link->diskpos, hash_link->requests));
1476
KEYCACHE_DBUG_ASSERT(hash_link->requests == 0);
1477
if ((*hash_link->prev= hash_link->next))
1478
hash_link->next->prev= hash_link->prev;
1479
hash_link->block= NULL;
1481
if (keycache->waiting_for_hash_link.last_thread)
1483
/* Signal that a free hash link has appeared */
1484
struct st_my_thread_var *last_thread=
1485
keycache->waiting_for_hash_link.last_thread;
1486
struct st_my_thread_var *first_thread= last_thread->next;
1487
struct st_my_thread_var *next_thread= first_thread;
1488
KEYCACHE_PAGE *first_page= (KEYCACHE_PAGE *) (first_thread->opt_info);
1489
struct st_my_thread_var *thread;
1491
hash_link->file= first_page->file;
1492
hash_link->diskpos= first_page->filepos;
1495
KEYCACHE_PAGE *page;
1496
thread= next_thread;
1497
page= (KEYCACHE_PAGE *) thread->opt_info;
1498
next_thread= thread->next;
1500
We notify about the event all threads that ask
1501
for the same page as the first thread in the queue
1503
if (page->file == hash_link->file && page->filepos == hash_link->diskpos)
1505
KEYCACHE_DBUG_PRINT("unlink_hash: signal", ("thread %ld", thread->id));
1506
keycache_pthread_cond_signal(&thread->suspend);
1507
unlink_from_queue(&keycache->waiting_for_hash_link, thread);
1510
while (thread != last_thread);
1511
link_hash(&keycache->hash_root[KEYCACHE_HASH(hash_link->file,
1512
hash_link->diskpos)],
1517
KEYCACHE_DBUG_ASSERT(! (keycache->waiting_for_hash_link.last_thread));
1519
hash_link->next= keycache->free_hash_list;
1520
keycache->free_hash_list= hash_link;
1525
Get the hash link for a page
1528
static HASH_LINK *get_hash_link(KEY_CACHE *keycache,
1529
int file, my_off_t filepos)
1531
register HASH_LINK *hash_link, **start;
1532
#if defined(KEYCACHE_DEBUG)
1536
KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u pos: %lu",
1537
(uint) file,(ulong) filepos));
1541
Find the bucket in the hash table for the pair (file, filepos);
1542
start contains the head of the bucket list,
1543
hash_link points to the first member of the list
1545
hash_link= *(start= &keycache->hash_root[KEYCACHE_HASH(file, filepos)]);
1546
#if defined(KEYCACHE_DEBUG)
1549
/* Look for an element for the pair (file, filepos) in the bucket chain */
1551
(hash_link->diskpos != filepos || hash_link->file != file))
1553
hash_link= hash_link->next;
1554
#if defined(KEYCACHE_DEBUG)
1556
if (! (cnt <= keycache->hash_links_used))
1559
for (i=0, hash_link= *start ;
1560
i < cnt ; i++, hash_link= hash_link->next)
1562
KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u pos: %lu",
1563
(uint) hash_link->file,(ulong) hash_link->diskpos));
1566
KEYCACHE_DBUG_ASSERT(cnt <= keycache->hash_links_used);
1571
/* There is no hash link in the hash table for the pair (file, filepos) */
1572
if (keycache->free_hash_list)
1574
hash_link= keycache->free_hash_list;
1575
keycache->free_hash_list= hash_link->next;
1577
else if (keycache->hash_links_used < keycache->hash_links)
1579
hash_link= &keycache->hash_link_root[keycache->hash_links_used++];
1584
/* Wait for a free hash link */
1585
struct st_my_thread_var *thread= my_thread_var;
1587
KEYCACHE_DBUG_PRINT("get_hash_link", ("waiting"));
1589
page.filepos= filepos;
1590
thread->opt_info= (void *) &page;
1591
link_into_queue(&keycache->waiting_for_hash_link, thread);
1592
KEYCACHE_DBUG_PRINT("get_hash_link: wait",
1593
("suspend thread %ld", thread->id));
1594
keycache_pthread_cond_wait(&thread->suspend,
1595
&keycache->cache_lock);
1596
thread->opt_info= NULL;
1598
KEYCACHE_DBUG_ASSERT(0);
1602
hash_link->file= file;
1603
hash_link->diskpos= filepos;
1604
link_hash(start, hash_link);
1606
/* Register the request for the page */
1607
hash_link->requests++;
1614
Get a block for the file page requested by a keycache read/write operation;
1615
If the page is not in the cache return a free block, if there is none
1616
return the lru block after saving its buffer if the page is dirty.
1621
keycache pointer to a key cache data structure
1622
file handler for the file to read page from
1623
filepos position of the page in the file
1624
init_hits_left how initialize the block counter for the page
1625
wrmode <-> get for writing
1626
page_st out {PAGE_READ,PAGE_TO_BE_READ,PAGE_WAIT_TO_BE_READ}
1629
Pointer to the found block if successful, 0 - otherwise
1632
For the page from file positioned at filepos the function checks whether
1633
the page is in the key cache specified by the first parameter.
1634
If this is the case it immediately returns the block.
1635
If not, the function first chooses a block for this page. If there is
1636
no not used blocks in the key cache yet, the function takes the block
1637
at the very beginning of the warm sub-chain. It saves the page in that
1638
block if it's dirty before returning the pointer to it.
1639
The function returns in the page_st parameter the following values:
1640
PAGE_READ - if page already in the block,
1641
PAGE_TO_BE_READ - if it is to be read yet by the current thread
1642
WAIT_TO_BE_READ - if it is to be read by another thread
1643
If an error occurs THE BLOCK_ERROR bit is set in the block status.
1644
It might happen that there are no blocks in LRU chain (in warm part) -
1645
all blocks are unlinked for some read/write operations. Then the function
1646
waits until first of this operations links any block back.
1649
static BLOCK_LINK *find_key_block(KEY_CACHE *keycache,
1650
File file, my_off_t filepos,
1652
int wrmode, int *page_st)
1654
HASH_LINK *hash_link;
1659
DBUG_ENTER("find_key_block");
1660
KEYCACHE_THREAD_TRACE("find_key_block:begin");
1661
DBUG_PRINT("enter", ("fd: %d pos: %lu wrmode: %d",
1662
file, (ulong) filepos, wrmode));
1663
KEYCACHE_DBUG_PRINT("find_key_block", ("fd: %d pos: %lu wrmode: %d",
1664
file, (ulong) filepos,
1666
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
1667
DBUG_EXECUTE("check_keycache2",
1668
test_key_cache(keycache, "start of find_key_block", 0););
1673
If the flush phase of a resize operation fails, the cache is left
1674
unusable. This will be detected only after "goto restart".
1676
if (!keycache->can_be_used)
1680
Find the hash_link for the requested file block (file, filepos). We
1681
do always get a hash_link here. It has registered our request so
1682
that no other thread can use it for another file block until we
1683
release the request (which is done by remove_reader() usually). The
1684
hash_link can have a block assigned to it or not. If there is a
1685
block, it may be assigned to this hash_link or not. In cases where a
1686
block is evicted from the cache, it is taken from the LRU ring and
1687
referenced by the new hash_link. But the block can still be assigned
1688
to its old hash_link for some time if it needs to be flushed first,
1689
or if there are other threads still reading it.
1692
hash_link is always returned.
1693
hash_link->block can be:
1695
- not assigned to this hash_link or
1696
- assigned to this hash_link. If assigned, the block can have
1697
- invalid data (when freshly assigned) or
1698
- valid data. Valid data can be
1699
- changed over the file contents (dirty) or
1700
- not changed (clean).
1702
hash_link= get_hash_link(keycache, file, filepos);
1703
DBUG_ASSERT((hash_link->file == file) && (hash_link->diskpos == filepos));
1706
if ((block= hash_link->block) &&
1707
block->hash_link == hash_link && (block->status & BLOCK_READ))
1709
/* Assigned block with valid (changed or unchanged) contents. */
1710
page_status= PAGE_READ;
1713
else (page_status == -1)
1715
- block not assigned to this hash_link or
1716
- block assigned but not yet read from file (invalid data).
1719
if (keycache->in_resize)
1721
/* This is a request during a resize operation */
1725
struct st_my_thread_var *thread;
1728
The file block is not in the cache. We don't need it in the
1729
cache: we are going to read or write directly to file. Cancel
1730
the request. We can simply decrement hash_link->requests because
1731
we did not release cache_lock since increasing it. So no other
1732
thread can wait for our request to become released.
1734
if (hash_link->requests == 1)
1737
We are the only one to request this hash_link (this file/pos).
1740
hash_link->requests--;
1741
unlink_hash(keycache, hash_link);
1746
More requests on the hash_link. Someone tries to evict a block
1747
for this hash_link (could have started before resizing started).
1748
This means that the LRU ring is empty. Otherwise a block could
1749
be assigned immediately. Behave like a thread that wants to
1750
evict a block for this file/pos. Add to the queue of threads
1751
waiting for a block. Wait until there is one assigned.
1753
Refresh the request on the hash-link so that it cannot be reused
1754
for another file/pos.
1756
thread= my_thread_var;
1757
thread->opt_info= (void *) hash_link;
1758
link_into_queue(&keycache->waiting_for_block, thread);
1761
KEYCACHE_DBUG_PRINT("find_key_block: wait",
1762
("suspend thread %ld", thread->id));
1763
keycache_pthread_cond_wait(&thread->suspend,
1764
&keycache->cache_lock);
1765
} while (thread->next);
1766
thread->opt_info= NULL;
1768
A block should now be assigned to the hash_link. But it may
1769
still need to be evicted. Anyway, we should re-check the
1770
situation. page_status must be set correctly.
1772
hash_link->requests--;
1774
} /* end of if (!block) */
1777
There is a block for this file/pos in the cache. Register a
1778
request on it. This unlinks it from the LRU ring (if it is there)
1779
and hence protects it against eviction (if not already in
1780
eviction). We need this for returning the block to the caller, for
1781
calling remove_reader() (for debugging purposes), and for calling
1782
free_block(). The only case where we don't need the request is if
1783
the block is in eviction. In that case we have to unregister the
1786
reg_requests(keycache, block, 1);
1788
if (page_status != PAGE_READ)
1791
- block not assigned to this hash_link or
1792
- block assigned but not yet read from file (invalid data).
1794
This must be a block in eviction. It will be read soon. We need
1795
to wait here until this happened. Otherwise the caller could
1796
access a wrong block or a block which is in read. While waiting
1797
we cannot lose hash_link nor block. We have registered a request
1798
on the hash_link. Everything can happen to the block but changes
1799
in the hash_link -> block relationship. In other words:
1800
everything can happen to the block but free or another completed
1803
Note that we bahave like a secondary requestor here. We just
1804
cannot return with PAGE_WAIT_TO_BE_READ. This would work for
1805
read requests and writes on dirty blocks that are not in flush
1806
only. Waiting here on COND_FOR_REQUESTED works in all
1809
DBUG_ASSERT(((block->hash_link != hash_link) &&
1810
(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
1811
((block->hash_link == hash_link) &&
1812
!(block->status & BLOCK_READ)));
1813
wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
1815
Here we can trust that the block has been assigned to this
1816
hash_link (block->hash_link == hash_link) and read into the
1817
buffer (BLOCK_READ). The worst things possible here are that the
1818
block is in free (BLOCK_REASSIGNED). But the block is still
1819
assigned to the hash_link. The freeing thread waits until we
1820
release our request on the hash_link. The block must not be
1821
again in eviction because we registered an request on it before
1824
DBUG_ASSERT(block->hash_link == hash_link);
1825
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1826
DBUG_ASSERT(!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)));
1829
The block is in the cache. Assigned to the hash_link. Valid data.
1830
Note that in case of page_st == PAGE_READ, the block can be marked
1831
for eviction. In any case it can be marked for freeing.
1836
/* A reader can just read the block. */
1837
*page_st= PAGE_READ;
1838
DBUG_ASSERT((hash_link->file == file) &&
1839
(hash_link->diskpos == filepos) &&
1840
(block->hash_link == hash_link));
1845
This is a writer. No two writers for the same block can exist.
1846
This must be assured by locks outside of the key cache.
1848
DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
1850
while (block->status & BLOCK_IN_FLUSH)
1853
Wait until the block is flushed to file. Do not release the
1854
request on the hash_link yet to prevent that the block is freed
1855
or reassigned while we wait. While we wait, several things can
1856
happen to the block, including another flush. But the block
1857
cannot be reassigned to another hash_link until we release our
1858
request on it. But it can be marked BLOCK_REASSIGNED from free
1859
or eviction, while they wait for us to release the hash_link.
1861
wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
1863
If the flush phase failed, the resize could have finished while
1866
if (!keycache->in_resize)
1868
remove_reader(block);
1869
unreg_request(keycache, block, 1);
1872
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1873
DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
1874
DBUG_ASSERT(block->hash_link == hash_link);
1877
if (block->status & BLOCK_CHANGED)
1880
We want to write a block with changed contents. If the cache
1881
block size is bigger than the callers block size (e.g. MyISAM),
1882
the caller may replace part of the block only. Changes of the
1883
other part of the block must be preserved. Since the block has
1884
not yet been selected for flush, we can still add our changes.
1886
*page_st= PAGE_READ;
1887
DBUG_ASSERT((hash_link->file == file) &&
1888
(hash_link->diskpos == filepos) &&
1889
(block->hash_link == hash_link));
1894
This is a write request for a clean block. We do not want to have
1895
new dirty blocks in the cache while resizing. We will free the
1896
block and write directly to file. If the block is in eviction or
1897
in free, we just let it go.
1899
Unregister from the hash_link. This must be done before freeing
1900
the block. And it must be done if not freeing the block. Because
1901
we could have waited above, we need to call remove_reader(). Other
1902
threads could wait for us to release our request on the hash_link.
1904
remove_reader(block);
1906
/* If the block is not in eviction and not in free, we can free it. */
1907
if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
1911
Free block as we are going to write directly to file.
1912
Although we have an exlusive lock for the updated key part,
1913
the control can be yielded by the current thread as we might
1914
have unfinished readers of other key parts in the block
1915
buffer. Still we are guaranteed not to have any readers
1916
of the key part we are writing into until the block is
1917
removed from the cache as we set the BLOCK_REASSIGNED
1918
flag (see the code below that handles reading requests).
1920
free_block(keycache, block);
1925
The block will be evicted/freed soon. Don't touch it in any way.
1926
Unregister the request that we registered above.
1928
unreg_request(keycache, block, 1);
1931
The block is still assigned to the hash_link (the file/pos that
1932
we are going to write to). Wait until the eviction/free is
1933
complete. Otherwise the direct write could complete before all
1934
readers are done with the block. So they could read outdated
1937
Since we released our request on the hash_link, it can be reused
1938
for another file/pos. Hence we cannot just check for
1939
block->hash_link == hash_link. As long as the resize is
1940
proceeding the block cannot be reassigned to the same file/pos
1941
again. So we can terminate the loop when the block is no longer
1942
assigned to this file/pos.
1946
wait_on_queue(&block->wqueue[COND_FOR_SAVED],
1947
&keycache->cache_lock);
1949
If the flush phase failed, the resize could have finished
1950
while we waited here.
1952
if (!keycache->in_resize)
1954
} while (block->hash_link &&
1955
(block->hash_link->file == file) &&
1956
(block->hash_link->diskpos == filepos));
1961
if (page_status == PAGE_READ &&
1962
(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
1966
This is a request for a block to be removed from cache. The block
1967
is assigned to this hash_link and contains valid data, but is
1968
marked for eviction or to be freed. Possible reasons why it has
1969
not yet been evicted/freed can be a flush before reassignment
1970
(BLOCK_IN_SWITCH), readers of the block have not finished yet
1971
(BLOCK_REASSIGNED), or the evicting thread did not yet awake after
1972
the block has been selected for it (BLOCK_IN_EVICTION).
1975
KEYCACHE_DBUG_PRINT("find_key_block",
1976
("request for old page in block %u "
1977
"wrmode: %d block->status: %d",
1978
BLOCK_NUMBER(block), wrmode, block->status));
1980
Only reading requests can proceed until the old dirty page is flushed,
1981
all others are to be suspended, then resubmitted
1983
if (!wrmode && !(block->status & BLOCK_REASSIGNED))
1986
This is a read request and the block not yet reassigned. We can
1987
register our request and proceed. This unlinks the block from
1988
the LRU ring and protects it against eviction.
1990
reg_requests(keycache, block, 1);
1995
Either this is a write request for a block that is in eviction
1996
or in free. We must not use it any more. Instead we must evict
1997
another block. But we cannot do this before the eviction/free is
1998
done. Otherwise we would find the same hash_link + block again
2001
Or this is a read request for a block in eviction/free that does
2002
not require a flush, but waits for readers to finish with the
2003
block. We do not read this block to let the eviction/free happen
2004
as soon as possible. Again we must wait so that we don't find
2005
the same hash_link + block again and again.
2007
DBUG_ASSERT(hash_link->requests);
2008
hash_link->requests--;
2009
KEYCACHE_DBUG_PRINT("find_key_block",
2010
("request waiting for old page to be saved"));
2011
wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
2012
KEYCACHE_DBUG_PRINT("find_key_block",
2013
("request for old page resubmitted"));
2015
The block is no longer assigned to this hash_link.
2024
This is a request for a new block or for a block not to be removed.
2027
- block not assigned to this hash_link or
2028
- block assigned but not yet read from file,
2030
- block assigned with valid (changed or unchanged) data and
2031
- it will not be reassigned/freed.
2035
/* No block is assigned to the hash_link yet. */
2036
if (keycache->blocks_unused)
2038
if (keycache->free_block_list)
2040
/* There is a block in the free list. */
2041
block= keycache->free_block_list;
2042
keycache->free_block_list= block->next_used;
2043
block->next_used= NULL;
2047
/* There are some never used blocks, take first of them */
2048
DBUG_ASSERT(keycache->blocks_used <
2049
(ulong) keycache->disk_blocks);
2050
block= &keycache->block_root[keycache->blocks_used];
2051
block->buffer= ADD_TO_PTR(keycache->block_mem,
2052
((ulong) keycache->blocks_used*
2053
keycache->key_cache_block_size),
2055
keycache->blocks_used++;
2056
DBUG_ASSERT(!block->next_used);
2058
DBUG_ASSERT(!block->prev_used);
2059
DBUG_ASSERT(!block->next_changed);
2060
DBUG_ASSERT(!block->prev_changed);
2061
DBUG_ASSERT(!block->hash_link);
2062
DBUG_ASSERT(!block->status);
2063
DBUG_ASSERT(!block->requests);
2064
keycache->blocks_unused--;
2065
block->status= BLOCK_IN_USE;
2067
block->offset= keycache->key_cache_block_size;
2069
block->temperature= BLOCK_COLD;
2070
block->hits_left= init_hits_left;
2071
block->last_hit_time= 0;
2072
block->hash_link= hash_link;
2073
hash_link->block= block;
2074
link_to_file_list(keycache, block, file, 0);
2075
page_status= PAGE_TO_BE_READ;
2076
KEYCACHE_DBUG_PRINT("find_key_block",
2077
("got free or never used block %u",
2078
BLOCK_NUMBER(block)));
2083
There are no free blocks and no never used blocks, use a block
2088
if (! keycache->used_last)
2091
The LRU ring is empty. Wait until a new block is added to
2092
it. Several threads might wait here for the same hash_link,
2093
all of them must get the same block. While waiting for a
2094
block, after a block is selected for this hash_link, other
2095
threads can run first before this one awakes. During this
2096
time interval other threads find this hash_link pointing to
2097
the block, which is still assigned to another hash_link. In
2098
this case the block is not marked BLOCK_IN_SWITCH yet, but
2099
it is marked BLOCK_IN_EVICTION.
2102
struct st_my_thread_var *thread= my_thread_var;
2103
thread->opt_info= (void *) hash_link;
2104
link_into_queue(&keycache->waiting_for_block, thread);
2107
KEYCACHE_DBUG_PRINT("find_key_block: wait",
2108
("suspend thread %ld", thread->id));
2109
keycache_pthread_cond_wait(&thread->suspend,
2110
&keycache->cache_lock);
2112
while (thread->next);
2113
thread->opt_info= NULL;
2114
/* Assert that block has a request registered. */
2115
DBUG_ASSERT(hash_link->block->requests);
2116
/* Assert that block is not in LRU ring. */
2117
DBUG_ASSERT(!hash_link->block->next_used);
2118
DBUG_ASSERT(!hash_link->block->prev_used);
2121
KEYCACHE_DBUG_ASSERT(keycache->used_last);
2124
If we waited above, hash_link->block has been assigned by
2125
link_block(). Otherwise it is still NULL. In the latter case
2126
we need to grab a block from the LRU ring ourselves.
2128
block= hash_link->block;
2131
/* Select the last block from the LRU ring. */
2132
block= keycache->used_last->next_used;
2133
block->hits_left= init_hits_left;
2134
block->last_hit_time= 0;
2135
hash_link->block= block;
2137
Register a request on the block. This unlinks it from the
2138
LRU ring and protects it against eviction.
2140
DBUG_ASSERT(!block->requests);
2141
reg_requests(keycache, block,1);
2143
We do not need to set block->status|= BLOCK_IN_EVICTION here
2144
because we will set block->status|= BLOCK_IN_SWITCH
2145
immediately without releasing the lock in between. This does
2146
also support debugging. When looking at the block, one can
2147
see if the block has been selected by link_block() after the
2148
LRU ring was empty, or if it was grabbed directly from the
2149
LRU ring in this branch.
2154
If we had to wait above, there is a small chance that another
2155
thread grabbed this block for the same file block already. But
2156
in most cases the first condition is true.
2158
if (block->hash_link != hash_link &&
2159
! (block->status & BLOCK_IN_SWITCH) )
2161
/* this is a primary request for a new page */
2162
block->status|= BLOCK_IN_SWITCH;
2164
KEYCACHE_DBUG_PRINT("find_key_block",
2165
("got block %u for new page", BLOCK_NUMBER(block)));
2167
if (block->status & BLOCK_CHANGED)
2169
/* The block contains a dirty page - push it out of the cache */
2171
KEYCACHE_DBUG_PRINT("find_key_block", ("block is dirty"));
2172
if (block->status & BLOCK_IN_FLUSH)
2175
The block is marked for flush. If we do not wait here,
2176
it could happen that we write the block, reassign it to
2177
another file block, then, before the new owner can read
2178
the new file block, the flusher writes the cache block
2179
(which still has the old contents) to the new file block!
2181
wait_on_queue(&block->wqueue[COND_FOR_SAVED],
2182
&keycache->cache_lock);
2184
The block is marked BLOCK_IN_SWITCH. It should be left
2185
alone except for reading. No free, no write.
2187
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2188
DBUG_ASSERT(!(block->status & (BLOCK_REASSIGNED |
2190
BLOCK_FOR_UPDATE)));
2194
block->status|= BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE;
2196
BLOCK_IN_EVICTION may be true or not. Other flags must
2199
DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
2200
(BLOCK_READ | BLOCK_IN_SWITCH |
2201
BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
2202
BLOCK_CHANGED | BLOCK_IN_USE));
2203
DBUG_ASSERT(block->hash_link);
2205
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2207
The call is thread safe because only the current
2208
thread might change the block->hash_link value
2210
error= my_pwrite(block->hash_link->file,
2211
block->buffer+block->offset,
2212
block->length - block->offset,
2213
block->hash_link->diskpos+ block->offset,
2214
MYF(MY_NABP | MY_WAIT_IF_FULL));
2215
keycache_pthread_mutex_lock(&keycache->cache_lock);
2217
/* Block status must not have changed. */
2218
DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
2219
(BLOCK_READ | BLOCK_IN_SWITCH |
2220
BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
2221
BLOCK_CHANGED | BLOCK_IN_USE) || fail_block(block));
2222
keycache->global_cache_write++;
2226
block->status|= BLOCK_REASSIGNED;
2228
The block comes from the LRU ring. It must have a hash_link
2231
DBUG_ASSERT(block->hash_link);
2232
if (block->hash_link)
2235
All pending requests for this page must be resubmitted.
2236
This must be done before waiting for readers. They could
2237
wait for the flush to complete. And we must also do it
2238
after the wait. Flushers might try to free the block while
2239
we wait. They would wait until the reassignment is
2240
complete. Also the block status must reflect the correct
2241
situation: The block is not changed nor in flush any more.
2242
Note that we must not change the BLOCK_CHANGED flag
2243
outside of link_to_file_list() so that it is always in the
2244
correct queue and the *blocks_changed counters are
2247
block->status&= ~(BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE);
2248
link_to_file_list(keycache, block, block->hash_link->file, 1);
2249
release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
2251
The block is still assigned to its old hash_link.
2252
Wait until all pending read requests
2253
for this page are executed
2254
(we could have avoided this waiting, if we had read
2255
a page in the cache in a sweep, without yielding control)
2257
wait_for_readers(keycache, block);
2258
DBUG_ASSERT(block->hash_link && block->hash_link->block == block &&
2259
block->prev_changed);
2260
/* The reader must not have been a writer. */
2261
DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
2263
/* Wake flushers that might have found the block in between. */
2264
release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
2266
/* Remove the hash link for the old file block from the hash. */
2267
unlink_hash(keycache, block->hash_link);
2270
For sanity checks link_to_file_list() asserts that block
2271
and hash_link refer to each other. Hence we need to assign
2272
the hash_link first, but then we would not know if it was
2273
linked before. Hence we would not know if to unlink it. So
2274
unlink it here and call link_to_file_list(..., FALSE).
2276
unlink_changed(block);
2278
block->status= error ? BLOCK_ERROR : BLOCK_IN_USE ;
2280
block->offset= keycache->key_cache_block_size;
2281
block->hash_link= hash_link;
2282
link_to_file_list(keycache, block, file, 0);
2283
page_status= PAGE_TO_BE_READ;
2285
KEYCACHE_DBUG_ASSERT(block->hash_link->block == block);
2286
KEYCACHE_DBUG_ASSERT(hash_link->block->hash_link == hash_link);
2291
Either (block->hash_link == hash_link),
2292
or (block->status & BLOCK_IN_SWITCH).
2294
This is for secondary requests for a new file block only.
2295
Either it is already assigned to the new hash_link meanwhile
2296
(if we had to wait due to empty LRU), or it is already in
2297
eviction by another thread. Since this block has been
2298
grabbed from the LRU ring and attached to this hash_link,
2299
another thread cannot grab the same block from the LRU ring
2300
anymore. If the block is in eviction already, it must become
2301
attached to the same hash_link and as such destined for the
2304
KEYCACHE_DBUG_PRINT("find_key_block",
2305
("block->hash_link: %p hash_link: %p "
2306
"block->status: %u", block->hash_link,
2307
hash_link, block->status ));
2308
page_status= (((block->hash_link == hash_link) &&
2309
(block->status & BLOCK_READ)) ?
2310
PAGE_READ : PAGE_WAIT_TO_BE_READ);
2317
Block is not NULL. This hash_link points to a block.
2319
- block not assigned to this hash_link (yet) or
2320
- block assigned but not yet read from file,
2322
- block assigned with valid (changed or unchanged) data and
2323
- it will not be reassigned/freed.
2325
The first condition means hash_link points to a block in
2326
eviction. This is not necessarily marked by BLOCK_IN_SWITCH yet.
2327
But then it is marked BLOCK_IN_EVICTION. See the NOTE in
2328
link_block(). In both cases it is destined for this hash_link
2329
and its file block address. When this hash_link got its block
2330
address, the block was removed from the LRU ring and cannot be
2331
selected for eviction (for another hash_link) again.
2333
Register a request on the block. This is another protection
2336
DBUG_ASSERT(((block->hash_link != hash_link) &&
2337
(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
2338
((block->hash_link == hash_link) &&
2339
!(block->status & BLOCK_READ)) ||
2340
((block->status & BLOCK_READ) &&
2341
!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))));
2342
reg_requests(keycache, block, 1);
2343
KEYCACHE_DBUG_PRINT("find_key_block",
2344
("block->hash_link: %p hash_link: %p "
2345
"block->status: %u", block->hash_link,
2346
hash_link, block->status ));
2347
page_status= (((block->hash_link == hash_link) &&
2348
(block->status & BLOCK_READ)) ?
2349
PAGE_READ : PAGE_WAIT_TO_BE_READ);
2353
KEYCACHE_DBUG_ASSERT(page_status != -1);
2354
/* Same assert basically, but be very sure. */
2355
KEYCACHE_DBUG_ASSERT(block);
2356
/* Assert that block has a request and is not in LRU ring. */
2357
DBUG_ASSERT(block->requests);
2358
DBUG_ASSERT(!block->next_used);
2359
DBUG_ASSERT(!block->prev_used);
2360
/* Assert that we return the correct block. */
2361
DBUG_ASSERT((page_status == PAGE_WAIT_TO_BE_READ) ||
2362
((block->hash_link->file == file) &&
2363
(block->hash_link->diskpos == filepos)));
2364
*page_st=page_status;
2365
KEYCACHE_DBUG_PRINT("find_key_block",
2366
("fd: %d pos: %lu block->status: %u page_status: %d",
2367
file, (ulong) filepos, block->status,
2370
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
2371
DBUG_EXECUTE("check_keycache2",
2372
test_key_cache(keycache, "end of find_key_block",0););
2374
KEYCACHE_THREAD_TRACE("find_key_block:end");
2380
Read into a key cache block buffer from disk.
2385
keycache pointer to a key cache data structure
2386
block block to which buffer the data is to be read
2387
read_length size of data to be read
2388
min_length at least so much data must be read
2389
primary <-> the current thread will read the data
2395
The function either reads a page data from file to the block buffer,
2396
or waits until another thread reads it. What page to read is determined
2397
by a block parameter - reference to a hash link for this page.
2398
If an error occurs THE BLOCK_ERROR bit is set in the block status.
2399
We do not report error when the size of successfully read
2400
portion is less than read_length, but not less than min_length.
2403
static void read_block(KEY_CACHE *keycache,
2404
BLOCK_LINK *block, uint read_length,
2405
uint min_length, my_bool primary)
2409
/* On entry cache_lock is locked */
2411
KEYCACHE_THREAD_TRACE("read_block");
2415
This code is executed only by threads that submitted primary
2416
requests. Until block->status contains BLOCK_READ, all other
2417
request for the block become secondary requests. For a primary
2418
request the block must be properly initialized.
2420
DBUG_ASSERT(((block->status & ~BLOCK_FOR_UPDATE) == BLOCK_IN_USE) ||
2422
DBUG_ASSERT((block->length == 0) || fail_block(block));
2423
DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
2425
DBUG_ASSERT((block->requests > 0) || fail_block(block));
2427
KEYCACHE_DBUG_PRINT("read_block",
2428
("page to be read by primary request"));
2430
keycache->global_cache_read++;
2431
/* Page is not in buffer yet, is to be read from disk */
2432
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2434
Here other threads may step in and register as secondary readers.
2435
They will register in block->wqueue[COND_FOR_REQUESTED].
2437
got_length= my_pread(block->hash_link->file, block->buffer,
2438
read_length, block->hash_link->diskpos, MYF(0));
2439
keycache_pthread_mutex_lock(&keycache->cache_lock);
2441
The block can now have been marked for free (in case of
2442
FLUSH_RELEASE). Otherwise the state must be unchanged.
2444
DBUG_ASSERT(((block->status & ~(BLOCK_REASSIGNED |
2445
BLOCK_FOR_UPDATE)) == BLOCK_IN_USE) ||
2447
DBUG_ASSERT((block->length == 0) || fail_block(block));
2448
DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
2450
DBUG_ASSERT((block->requests > 0) || fail_block(block));
2452
if (got_length < min_length)
2453
block->status|= BLOCK_ERROR;
2456
block->status|= BLOCK_READ;
2457
block->length= got_length;
2459
Do not set block->offset here. If this block is marked
2460
BLOCK_CHANGED later, we want to flush only the modified part. So
2461
only a writer may set block->offset down from
2462
keycache->key_cache_block_size.
2465
KEYCACHE_DBUG_PRINT("read_block",
2466
("primary request: new page in cache"));
2467
/* Signal that all pending requests for this page now can be processed */
2468
release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
2473
This code is executed only by threads that submitted secondary
2474
requests. At this point it could happen that the cache block is
2475
not yet assigned to the hash_link for the requested file block.
2476
But at awake from the wait this should be the case. Unfortunately
2477
we cannot assert this here because we do not know the hash_link
2478
for the requested file block nor the file and position. So we have
2479
to assert this in the caller.
2481
KEYCACHE_DBUG_PRINT("read_block",
2482
("secondary request waiting for new page to be read"));
2483
wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
2484
KEYCACHE_DBUG_PRINT("read_block",
2485
("secondary request: new page in cache"));
2491
Read a block of data from a cached file into a buffer;
2496
keycache pointer to a key cache data structure
2497
file handler for the file for the block of data to be read
2498
filepos position of the block of data in the file
2499
level determines the weight of the data
2500
buff buffer to where the data must be placed
2501
length length of the buffer
2502
block_length length of the block in the key cache buffer
2503
return_buffer return pointer to the key cache buffer with the data
2506
Returns address from where the data is placed if sucessful, 0 - otherwise.
2509
The function ensures that a block of data of size length from file
2510
positioned at filepos is in the buffers for some key cache blocks.
2511
Then the function either copies the data into the buffer buff, or,
2512
if return_buffer is TRUE, it just returns the pointer to the key cache
2513
buffer with the data.
2514
Filepos must be a multiple of 'block_length', but it doesn't
2515
have to be a multiple of key_cache_block_size;
2518
uchar *key_cache_read(KEY_CACHE *keycache,
2519
File file, my_off_t filepos, int level,
2520
uchar *buff, uint length,
2521
uint block_length __attribute__((unused)),
2522
int return_buffer __attribute__((unused)))
2524
my_bool locked_and_incremented= FALSE;
2527
DBUG_ENTER("key_cache_read");
2528
DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u",
2529
(uint) file, (ulong) filepos, length));
2531
if (keycache->key_cache_inited)
2533
/* Key cache is used */
2534
register BLOCK_LINK *block;
2541
When the key cache is once initialized, we use the cache_lock to
2542
reliably distinguish the cases of normal operation, resizing, and
2543
disabled cache. We always increment and decrement
2544
'cnt_for_resize_op' so that a resizer can wait for pending I/O.
2546
keycache_pthread_mutex_lock(&keycache->cache_lock);
2548
Cache resizing has two phases: Flushing and re-initializing. In
2549
the flush phase read requests are allowed to bypass the cache for
2550
blocks not in the cache. find_key_block() returns NULL in this
2553
After the flush phase new I/O requests must wait until the
2554
re-initialization is done. The re-initialization can be done only
2555
if no I/O request is in progress. The reason is that
2556
key_cache_block_size can change. With enabled cache, I/O is done
2557
in chunks of key_cache_block_size. Every chunk tries to use a
2558
cache block first. If the block size changes in the middle, a
2559
block could be missed and old data could be read.
2561
while (keycache->in_resize && !keycache->resize_in_flush)
2562
wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
2563
/* Register the I/O for the next resize. */
2564
inc_counter_for_resize_op(keycache);
2565
locked_and_incremented= TRUE;
2566
/* Requested data may not always be aligned to cache blocks. */
2567
offset= (uint) (filepos % keycache->key_cache_block_size);
2568
/* Read data in key_cache_block_size increments */
2571
/* Cache could be disabled in a later iteration. */
2573
if (!keycache->can_be_used)
2575
/* Start reading at the beginning of the cache block. */
2577
/* Do not read beyond the end of the cache block. */
2578
read_length= length;
2579
set_if_smaller(read_length, keycache->key_cache_block_size-offset);
2580
KEYCACHE_DBUG_ASSERT(read_length > 0);
2583
if (block_length > keycache->key_cache_block_size || offset)
2587
/* Request the cache block that matches file/pos. */
2588
keycache->global_cache_r_requests++;
2589
block=find_key_block(keycache, file, filepos, level, 0, &page_st);
2593
This happens only for requests submitted during key cache
2594
resize. The block is not in the cache and shall not go in.
2595
Read directly from file.
2597
keycache->global_cache_read++;
2598
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2599
error= (my_pread(file, (uchar*) buff, read_length,
2600
filepos + offset, MYF(MY_NABP)) != 0);
2601
keycache_pthread_mutex_lock(&keycache->cache_lock);
2604
if (!(block->status & BLOCK_ERROR))
2606
if (page_st != PAGE_READ)
2608
/* The requested page is to be read into the block buffer */
2609
read_block(keycache, block,
2610
keycache->key_cache_block_size, read_length+offset,
2611
(my_bool)(page_st == PAGE_TO_BE_READ));
2613
A secondary request must now have the block assigned to the
2614
requested file block. It does not hurt to check it for
2615
primary requests too.
2617
DBUG_ASSERT(keycache->can_be_used);
2618
DBUG_ASSERT(block->hash_link->file == file);
2619
DBUG_ASSERT(block->hash_link->diskpos == filepos);
2620
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2622
else if (block->length < read_length + offset)
2625
Impossible if nothing goes wrong:
2626
this could only happen if we are using a file with
2627
small key blocks and are trying to read outside the file
2630
block->status|= BLOCK_ERROR;
2634
/* block status may have added BLOCK_ERROR in the above 'if'. */
2635
if (!((status= block->status) & BLOCK_ERROR))
2638
if (! return_buffer)
2641
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2642
#if !defined(SERIALIZED_READ_FROM_CACHE)
2643
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2646
/* Copy data from the cache buffer */
2647
if (!(read_length & 511))
2648
bmove512(buff, block->buffer+offset, read_length);
2650
memcpy(buff, block->buffer+offset, (size_t) read_length);
2652
#if !defined(SERIALIZED_READ_FROM_CACHE)
2653
keycache_pthread_mutex_lock(&keycache->cache_lock);
2654
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2659
remove_reader(block);
2662
Link the block into the LRU ring if it's the last submitted
2663
request for the block. This enables eviction for the block.
2665
unreg_request(keycache, block, 1);
2667
if (status & BLOCK_ERROR)
2674
/* This is only true if we where able to read everything in one block */
2676
DBUG_RETURN(block->buffer);
2680
filepos+= read_length+offset;
2683
} while ((length-= read_length));
2688
/* Key cache is not used */
2690
keycache->global_cache_r_requests++;
2691
keycache->global_cache_read++;
2693
if (locked_and_incremented)
2694
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2695
if (my_pread(file, (uchar*) buff, length, filepos, MYF(MY_NABP)))
2697
if (locked_and_incremented)
2698
keycache_pthread_mutex_lock(&keycache->cache_lock);
2701
if (locked_and_incremented)
2703
dec_counter_for_resize_op(keycache);
2704
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2706
DBUG_RETURN(error ? (uchar*) 0 : start);
2711
Insert a block of file data from a buffer into key cache
2715
keycache pointer to a key cache data structure
2716
file handler for the file to insert data from
2717
filepos position of the block of data in the file to insert
2718
level determines the weight of the data
2719
buff buffer to read data from
2720
length length of the data in the buffer
2723
This is used by MyISAM to move all blocks from a index file to the key
2727
0 if a success, 1 - otherwise.
2730
int key_cache_insert(KEY_CACHE *keycache,
2731
File file, my_off_t filepos, int level,
2732
uchar *buff, uint length)
2735
DBUG_ENTER("key_cache_insert");
2736
DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u",
2737
(uint) file,(ulong) filepos, length));
2739
if (keycache->key_cache_inited)
2741
/* Key cache is used */
2742
register BLOCK_LINK *block;
2746
my_bool locked_and_incremented= FALSE;
2749
When the keycache is once initialized, we use the cache_lock to
2750
reliably distinguish the cases of normal operation, resizing, and
2751
disabled cache. We always increment and decrement
2752
'cnt_for_resize_op' so that a resizer can wait for pending I/O.
2754
keycache_pthread_mutex_lock(&keycache->cache_lock);
2756
We do not load index data into a disabled cache nor into an
2759
if (!keycache->can_be_used || keycache->in_resize)
2761
/* Register the pseudo I/O for the next resize. */
2762
inc_counter_for_resize_op(keycache);
2763
locked_and_incremented= TRUE;
2764
/* Loaded data may not always be aligned to cache blocks. */
2765
offset= (uint) (filepos % keycache->key_cache_block_size);
2766
/* Load data in key_cache_block_size increments. */
2769
/* Cache could be disabled or resizing in a later iteration. */
2770
if (!keycache->can_be_used || keycache->in_resize)
2772
/* Start loading at the beginning of the cache block. */
2774
/* Do not load beyond the end of the cache block. */
2775
read_length= length;
2776
set_if_smaller(read_length, keycache->key_cache_block_size-offset);
2777
KEYCACHE_DBUG_ASSERT(read_length > 0);
2779
/* The block has been read by the caller already. */
2780
keycache->global_cache_read++;
2781
/* Request the cache block that matches file/pos. */
2782
keycache->global_cache_r_requests++;
2783
block= find_key_block(keycache, file, filepos, level, 0, &page_st);
2787
This happens only for requests submitted during key cache
2788
resize. The block is not in the cache and shall not go in.
2789
Stop loading index data.
2793
if (!(block->status & BLOCK_ERROR))
2795
if ((page_st == PAGE_WAIT_TO_BE_READ) ||
2796
((page_st == PAGE_TO_BE_READ) &&
2797
(offset || (read_length < keycache->key_cache_block_size))))
2802
this is a secondary request for a block to be read into the
2803
cache. The block is in eviction. It is not yet assigned to
2804
the requested file block (It does not point to the right
2805
hash_link). So we cannot call remove_reader() on the block.
2806
And we cannot access the hash_link directly here. We need to
2807
wait until the assignment is complete. read_block() executes
2808
the correct wait when called with primary == FALSE.
2812
this is a primary request for a block to be read into the
2813
cache and the supplied data does not fill the whole block.
2815
This function is called on behalf of a LOAD INDEX INTO CACHE
2816
statement, which is a read-only task and allows other
2817
readers. It is possible that a parallel running reader tries
2818
to access this block. If it needs more data than has been
2819
supplied here, it would report an error. To be sure that we
2820
have all data in the block that is available in the file, we
2821
read the block ourselves.
2823
Though reading again what the caller did read already is an
2824
expensive operation, we need to do this for correctness.
2826
read_block(keycache, block, keycache->key_cache_block_size,
2827
read_length + offset, (page_st == PAGE_TO_BE_READ));
2829
A secondary request must now have the block assigned to the
2830
requested file block. It does not hurt to check it for
2831
primary requests too.
2833
DBUG_ASSERT(keycache->can_be_used);
2834
DBUG_ASSERT(block->hash_link->file == file);
2835
DBUG_ASSERT(block->hash_link->diskpos == filepos);
2836
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2838
else if (page_st == PAGE_TO_BE_READ)
2841
This is a new block in the cache. If we come here, we have
2842
data for the whole block.
2844
DBUG_ASSERT(block->hash_link->requests);
2845
DBUG_ASSERT(block->status & BLOCK_IN_USE);
2846
DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
2847
(block->status & BLOCK_READ));
2849
#if !defined(SERIALIZED_READ_FROM_CACHE)
2850
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2852
Here other threads may step in and register as secondary readers.
2853
They will register in block->wqueue[COND_FOR_REQUESTED].
2857
/* Copy data from buff */
2858
if (!(read_length & 511))
2859
bmove512(block->buffer+offset, buff, read_length);
2861
memcpy(block->buffer+offset, buff, (size_t) read_length);
2863
#if !defined(SERIALIZED_READ_FROM_CACHE)
2864
keycache_pthread_mutex_lock(&keycache->cache_lock);
2865
DBUG_ASSERT(block->status & BLOCK_IN_USE);
2866
DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
2867
(block->status & BLOCK_READ));
2870
After the data is in the buffer, we can declare the block
2871
valid. Now other threads do not need to register as
2872
secondary readers any more. They can immediately access the
2875
block->status|= BLOCK_READ;
2876
block->length= read_length+offset;
2878
Do not set block->offset here. If this block is marked
2879
BLOCK_CHANGED later, we want to flush only the modified part. So
2880
only a writer may set block->offset down from
2881
keycache->key_cache_block_size.
2883
KEYCACHE_DBUG_PRINT("key_cache_insert",
2884
("primary request: new page in cache"));
2885
/* Signal all pending requests. */
2886
release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
2891
page_st == PAGE_READ. The block is in the buffer. All data
2892
must already be present. Blocks are always read with all
2893
data available on file. Assert that the block does not have
2894
less contents than the preloader supplies. If the caller has
2895
data beyond block->length, it means that a file write has
2896
been done while this block was in cache and not extended
2897
with the new data. If the condition is met, we can simply
2900
DBUG_ASSERT((page_st == PAGE_READ) &&
2901
(read_length + offset <= block->length));
2905
A secondary request must now have the block assigned to the
2906
requested file block. It does not hurt to check it for primary
2909
DBUG_ASSERT(block->hash_link->file == file);
2910
DBUG_ASSERT(block->hash_link->diskpos == filepos);
2911
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2912
} /* end of if (!(block->status & BLOCK_ERROR)) */
2915
remove_reader(block);
2918
Link the block into the LRU ring if it's the last submitted
2919
request for the block. This enables eviction for the block.
2921
unreg_request(keycache, block, 1);
2923
error= (block->status & BLOCK_ERROR);
2929
filepos+= read_length+offset;
2932
} while ((length-= read_length));
2935
if (locked_and_incremented)
2936
dec_counter_for_resize_op(keycache);
2937
keycache_pthread_mutex_unlock(&keycache->cache_lock);
2944
Write a buffer into a cached file.
2949
keycache pointer to a key cache data structure
2950
file handler for the file to write data to
2951
filepos position in the file to write data to
2952
level determines the weight of the data
2953
buff buffer with the data
2954
length length of the buffer
2955
dont_write if is 0 then all dirty pages involved in writing
2956
should have been flushed from key cache
2959
0 if a success, 1 - otherwise.
2962
The function copies the data of size length from buff into buffers
2963
for key cache blocks that are assigned to contain the portion of
2964
the file starting with position filepos.
2965
It ensures that this data is flushed to the file if dont_write is FALSE.
2966
Filepos must be a multiple of 'block_length', but it doesn't
2967
have to be a multiple of key_cache_block_size;
2969
dont_write is always TRUE in the server (info->lock_type is never F_UNLCK).
2972
int key_cache_write(KEY_CACHE *keycache,
2973
File file, my_off_t filepos, int level,
2974
uchar *buff, uint length,
2975
uint block_length __attribute__((unused)),
2978
my_bool locked_and_incremented= FALSE;
2980
DBUG_ENTER("key_cache_write");
2982
("fd: %u pos: %lu length: %u block_length: %u"
2983
" key_block_length: %u",
2984
(uint) file, (ulong) filepos, length, block_length,
2985
keycache ? keycache->key_cache_block_size : 0));
2989
/* purecov: begin inspected */
2990
/* Not used in the server. */
2991
/* Force writing from buff into disk. */
2992
keycache->global_cache_w_requests++;
2993
keycache->global_cache_write++;
2994
if (my_pwrite(file, buff, length, filepos, MYF(MY_NABP | MY_WAIT_IF_FULL)))
2999
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
3000
DBUG_EXECUTE("check_keycache",
3001
test_key_cache(keycache, "start of key_cache_write", 1););
3004
if (keycache->key_cache_inited)
3006
/* Key cache is used */
3007
register BLOCK_LINK *block;
3013
When the key cache is once initialized, we use the cache_lock to
3014
reliably distinguish the cases of normal operation, resizing, and
3015
disabled cache. We always increment and decrement
3016
'cnt_for_resize_op' so that a resizer can wait for pending I/O.
3018
keycache_pthread_mutex_lock(&keycache->cache_lock);
3020
Cache resizing has two phases: Flushing and re-initializing. In
3021
the flush phase write requests can modify dirty blocks that are
3022
not yet in flush. Otherwise they are allowed to bypass the cache.
3023
find_key_block() returns NULL in both cases (clean blocks and
3026
After the flush phase new I/O requests must wait until the
3027
re-initialization is done. The re-initialization can be done only
3028
if no I/O request is in progress. The reason is that
3029
key_cache_block_size can change. With enabled cache I/O is done in
3030
chunks of key_cache_block_size. Every chunk tries to use a cache
3031
block first. If the block size changes in the middle, a block
3032
could be missed and data could be written below a cached block.
3034
while (keycache->in_resize && !keycache->resize_in_flush)
3035
wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
3036
/* Register the I/O for the next resize. */
3037
inc_counter_for_resize_op(keycache);
3038
locked_and_incremented= TRUE;
3039
/* Requested data may not always be aligned to cache blocks. */
3040
offset= (uint) (filepos % keycache->key_cache_block_size);
3041
/* Write data in key_cache_block_size increments. */
3044
/* Cache could be disabled in a later iteration. */
3045
if (!keycache->can_be_used)
3047
/* Start writing at the beginning of the cache block. */
3049
/* Do not write beyond the end of the cache block. */
3050
read_length= length;
3051
set_if_smaller(read_length, keycache->key_cache_block_size-offset);
3052
KEYCACHE_DBUG_ASSERT(read_length > 0);
3054
/* Request the cache block that matches file/pos. */
3055
keycache->global_cache_w_requests++;
3056
block= find_key_block(keycache, file, filepos, level, 1, &page_st);
3060
This happens only for requests submitted during key cache
3061
resize. The block is not in the cache and shall not go in.
3062
Write directly to file.
3066
/* Used in the server. */
3067
keycache->global_cache_write++;
3068
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3069
if (my_pwrite(file, (uchar*) buff, read_length, filepos + offset,
3070
MYF(MY_NABP | MY_WAIT_IF_FULL)))
3072
keycache_pthread_mutex_lock(&keycache->cache_lock);
3077
Prevent block from flushing and from being selected for to be
3078
freed. This must be set when we release the cache_lock.
3079
However, we must not set the status of the block before it is
3080
assigned to this file/pos.
3082
if (page_st != PAGE_WAIT_TO_BE_READ)
3083
block->status|= BLOCK_FOR_UPDATE;
3085
We must read the file block first if it is not yet in the cache
3086
and we do not replace all of its contents.
3088
In cases where the cache block is big enough to contain (parts
3089
of) index blocks of different indexes, our request can be
3090
secondary (PAGE_WAIT_TO_BE_READ). In this case another thread is
3091
reading the file block. If the read completes after us, it
3092
overwrites our new contents with the old contents. So we have to
3093
wait for the other thread to complete the read of this block.
3094
read_block() takes care for the wait.
3096
if (!(block->status & BLOCK_ERROR) &&
3097
((page_st == PAGE_TO_BE_READ &&
3098
(offset || read_length < keycache->key_cache_block_size)) ||
3099
(page_st == PAGE_WAIT_TO_BE_READ)))
3101
read_block(keycache, block,
3102
offset + read_length >= keycache->key_cache_block_size?
3103
offset : keycache->key_cache_block_size,
3104
offset, (page_st == PAGE_TO_BE_READ));
3105
DBUG_ASSERT(keycache->can_be_used);
3106
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
3108
Prevent block from flushing and from being selected for to be
3109
freed. This must be set when we release the cache_lock.
3110
Here we set it in case we could not set it above.
3112
block->status|= BLOCK_FOR_UPDATE;
3115
The block should always be assigned to the requested file block
3116
here. It need not be BLOCK_READ when overwriting the whole block.
3118
DBUG_ASSERT(block->hash_link->file == file);
3119
DBUG_ASSERT(block->hash_link->diskpos == filepos);
3120
DBUG_ASSERT(block->status & BLOCK_IN_USE);
3121
DBUG_ASSERT((page_st == PAGE_TO_BE_READ) || (block->status & BLOCK_READ));
3123
The block to be written must not be marked BLOCK_REASSIGNED.
3124
Otherwise it could be freed in dirty state or reused without
3125
another flush during eviction. It must also not be in flush.
3126
Otherwise the old contens may have been flushed already and
3127
the flusher could clear BLOCK_CHANGED without flushing the
3130
DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
3132
while (block->status & BLOCK_IN_FLUSHWRITE)
3135
Another thread is flushing the block. It was dirty already.
3136
Wait until the block is flushed to file. Otherwise we could
3137
modify the buffer contents just while it is written to file.
3138
An unpredictable file block contents would be the result.
3139
While we wait, several things can happen to the block,
3140
including another flush. But the block cannot be reassigned to
3141
another hash_link until we release our request on it.
3143
wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
3144
DBUG_ASSERT(keycache->can_be_used);
3145
DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
3146
/* Still must not be marked for free. */
3147
DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
3148
DBUG_ASSERT(block->hash_link && (block->hash_link->block == block));
3152
We could perhaps release the cache_lock during access of the
3153
data like in the other functions. Locks outside of the key cache
3154
assure that readers and a writer do not access the same range of
3155
data. Parallel accesses should happen only if the cache block
3156
contains multiple index block(fragment)s. So different parts of
3157
the buffer would be read/written. An attempt to flush during
3158
memcpy() is prevented with BLOCK_FOR_UPDATE.
3160
if (!(block->status & BLOCK_ERROR))
3162
#if !defined(SERIALIZED_READ_FROM_CACHE)
3163
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3165
if (!(read_length & 511))
3166
bmove512(block->buffer+offset, buff, read_length);
3168
memcpy(block->buffer+offset, buff, (size_t) read_length);
3170
#if !defined(SERIALIZED_READ_FROM_CACHE)
3171
keycache_pthread_mutex_lock(&keycache->cache_lock);
3177
/* Not used in the server. buff has been written to disk at start. */
3178
if ((block->status & BLOCK_CHANGED) &&
3179
(!offset && read_length >= keycache->key_cache_block_size))
3180
link_to_file_list(keycache, block, block->hash_link->file, 1);
3182
else if (! (block->status & BLOCK_CHANGED))
3183
link_to_changed_list(keycache, block);
3184
block->status|=BLOCK_READ;
3186
Allow block to be selected for to be freed. Since it is marked
3187
BLOCK_CHANGED too, it won't be selected for to be freed without
3190
block->status&= ~BLOCK_FOR_UPDATE;
3191
set_if_smaller(block->offset, offset);
3192
set_if_bigger(block->length, read_length+offset);
3194
/* Threads may be waiting for the changes to be complete. */
3195
release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
3198
If only a part of the cache block is to be replaced, and the
3199
rest has been read from file, then the cache lock has been
3200
released for I/O and it could be possible that another thread
3201
wants to evict or free the block and waits for it to be
3202
released. So we must not just decrement hash_link->requests, but
3203
also wake a waiting thread.
3205
remove_reader(block);
3208
Link the block into the LRU ring if it's the last submitted
3209
request for the block. This enables eviction for the block.
3211
unreg_request(keycache, block, 1);
3213
if (block->status & BLOCK_ERROR)
3221
filepos+= read_length+offset;
3224
} while ((length-= read_length));
3229
/* Key cache is not used */
3232
/* Used in the server. */
3233
keycache->global_cache_w_requests++;
3234
keycache->global_cache_write++;
3235
if (locked_and_incremented)
3236
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3237
if (my_pwrite(file, (uchar*) buff, length, filepos,
3238
MYF(MY_NABP | MY_WAIT_IF_FULL)))
3240
if (locked_and_incremented)
3241
keycache_pthread_mutex_lock(&keycache->cache_lock);
3245
if (locked_and_incremented)
3247
dec_counter_for_resize_op(keycache);
3248
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3250
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
3251
DBUG_EXECUTE("exec",
3252
test_key_cache(keycache, "end of key_cache_write", 1););
3263
keycache Pointer to a key cache data structure
3264
block Pointer to the block to free
3267
Remove reference to block from hash table.
3268
Remove block from the chain of clean blocks.
3269
Add block to the free list.
3272
Block must not be free (status == 0).
3273
Block must not be in free_block_list.
3274
Block must not be in the LRU ring.
3275
Block must not be in eviction (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH).
3276
Block must not be in free (BLOCK_REASSIGNED).
3277
Block must not be in flush (BLOCK_IN_FLUSH).
3278
Block must not be dirty (BLOCK_CHANGED).
3279
Block must not be in changed_blocks (dirty) hash.
3280
Block must be in file_blocks (clean) hash.
3281
Block must refer to a hash_link.
3282
Block must have a request registered on it.
3285
static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block)
3287
KEYCACHE_THREAD_TRACE("free block");
3288
KEYCACHE_DBUG_PRINT("free_block",
3289
("block %u to be freed, hash_link %p",
3290
BLOCK_NUMBER(block), block->hash_link));
3292
Assert that the block is not free already. And that it is in a clean
3293
state. Note that the block might just be assigned to a hash_link and
3294
not yet read (BLOCK_READ may not be set here). In this case a reader
3295
is registered in the hash_link and free_block() will wait for it
3298
DBUG_ASSERT((block->status & BLOCK_IN_USE) &&
3299
!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
3300
BLOCK_REASSIGNED | BLOCK_IN_FLUSH |
3301
BLOCK_CHANGED | BLOCK_FOR_UPDATE)));
3302
/* Assert that the block is in a file_blocks chain. */
3303
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
3304
/* Assert that the block is not in the LRU ring. */
3305
DBUG_ASSERT(!block->next_used && !block->prev_used);
3307
IMHO the below condition (if()) makes no sense. I can't see how it
3308
could be possible that free_block() is entered with a NULL hash_link
3309
pointer. The only place where it can become NULL is in free_block()
3310
(or before its first use ever, but for those blocks free_block() is
3311
not called). I don't remove the conditional as it cannot harm, but
3312
place an DBUG_ASSERT to confirm my hypothesis. Eventually the
3313
condition (if()) can be removed.
3315
DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
3316
if (block->hash_link)
3319
While waiting for readers to finish, new readers might request the
3320
block. But since we set block->status|= BLOCK_REASSIGNED, they
3321
will wait on block->wqueue[COND_FOR_SAVED]. They must be signalled
3324
block->status|= BLOCK_REASSIGNED;
3325
wait_for_readers(keycache, block);
3327
The block must not have been freed by another thread. Repeat some
3328
checks. An additional requirement is that it must be read now
3331
DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
3332
DBUG_ASSERT((block->status & (BLOCK_READ | BLOCK_IN_USE |
3333
BLOCK_REASSIGNED)) &&
3334
!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
3335
BLOCK_IN_FLUSH | BLOCK_CHANGED |
3336
BLOCK_FOR_UPDATE)));
3337
DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
3338
DBUG_ASSERT(!block->prev_used);
3340
Unset BLOCK_REASSIGNED again. If we hand the block to an evicting
3341
thread (through unreg_request() below), other threads must not see
3342
this flag. They could become confused.
3344
block->status&= ~BLOCK_REASSIGNED;
3346
Do not release the hash_link until the block is off all lists.
3347
At least not if we hand it over for eviction in unreg_request().
3352
Unregister the block request and link the block into the LRU ring.
3353
This enables eviction for the block. If the LRU ring was empty and
3354
threads are waiting for a block, then the block wil be handed over
3355
for eviction immediately. Otherwise we will unlink it from the LRU
3356
ring again, without releasing the lock in between. So decrementing
3357
the request counter and updating statistics are the only relevant
3358
operation in this case. Assert that there are no other requests
3361
DBUG_ASSERT(block->requests == 1);
3362
unreg_request(keycache, block, 0);
3364
Note that even without releasing the cache lock it is possible that
3365
the block is immediately selected for eviction by link_block() and
3366
thus not added to the LRU ring. In this case we must not touch the
3369
if (block->status & BLOCK_IN_EVICTION)
3372
/* Here the block must be in the LRU ring. Unlink it again. */
3373
DBUG_ASSERT(block->next_used && block->prev_used &&
3374
*block->prev_used == block);
3375
unlink_block(keycache, block);
3376
if (block->temperature == BLOCK_WARM)
3377
keycache->warm_blocks--;
3378
block->temperature= BLOCK_COLD;
3380
/* Remove from file_blocks hash. */
3381
unlink_changed(block);
3383
/* Remove reference to block from hash table. */
3384
unlink_hash(keycache, block->hash_link);
3385
block->hash_link= NULL;
3389
block->offset= keycache->key_cache_block_size;
3390
KEYCACHE_THREAD_TRACE("free block");
3391
KEYCACHE_DBUG_PRINT("free_block", ("block is freed"));
3393
/* Enforced by unlink_changed(), but just to be sure. */
3394
DBUG_ASSERT(!block->next_changed && !block->prev_changed);
3395
/* Enforced by unlink_block(): not in LRU ring nor in free_block_list. */
3396
DBUG_ASSERT(!block->next_used && !block->prev_used);
3397
/* Insert the free block in the free list. */
3398
block->next_used= keycache->free_block_list;
3399
keycache->free_block_list= block;
3400
/* Keep track of the number of currently unused blocks. */
3401
keycache->blocks_unused++;
3403
/* All pending requests for this page must be resubmitted. */
3404
release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
3408
static int cmp_sec_link(BLOCK_LINK **a, BLOCK_LINK **b)
3410
return (((*a)->hash_link->diskpos < (*b)->hash_link->diskpos) ? -1 :
3411
((*a)->hash_link->diskpos > (*b)->hash_link->diskpos) ? 1 : 0);
3416
Flush a portion of changed blocks to disk,
3417
free used blocks if requested
3420
static int flush_cached_blocks(KEY_CACHE *keycache,
3421
File file, BLOCK_LINK **cache,
3423
enum flush_type type)
3427
uint count= (uint) (end-cache);
3429
/* Don't lock the cache during the flush */
3430
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3432
As all blocks referred in 'cache' are marked by BLOCK_IN_FLUSH
3433
we are guarunteed no thread will change them
3435
my_qsort((uchar*) cache, count, sizeof(*cache), (qsort_cmp) cmp_sec_link);
3437
keycache_pthread_mutex_lock(&keycache->cache_lock);
3439
Note: Do not break the loop. We have registered a request on every
3440
block in 'cache'. These must be unregistered by free_block() or
3443
for ( ; cache != end ; cache++)
3445
BLOCK_LINK *block= *cache;
3447
KEYCACHE_DBUG_PRINT("flush_cached_blocks",
3448
("block %u to be flushed", BLOCK_NUMBER(block)));
3450
If the block contents is going to be changed, we abandon the flush
3451
for this block. flush_key_blocks_int() will restart its search and
3452
handle the block properly.
3454
if (!(block->status & BLOCK_FOR_UPDATE))
3456
/* Blocks coming here must have a certain status. */
3457
DBUG_ASSERT(block->hash_link);
3458
DBUG_ASSERT(block->hash_link->block == block);
3459
DBUG_ASSERT(block->hash_link->file == file);
3460
DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
3461
(BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
3462
block->status|= BLOCK_IN_FLUSHWRITE;
3463
keycache_pthread_mutex_unlock(&keycache->cache_lock);
3464
error= my_pwrite(file,
3465
block->buffer+block->offset,
3466
block->length - block->offset,
3467
block->hash_link->diskpos+ block->offset,
3468
MYF(MY_NABP | MY_WAIT_IF_FULL));
3469
keycache_pthread_mutex_lock(&keycache->cache_lock);
3470
keycache->global_cache_write++;
3473
block->status|= BLOCK_ERROR;
3475
last_errno= errno ? errno : -1;
3477
block->status&= ~BLOCK_IN_FLUSHWRITE;
3478
/* Block must not have changed status except BLOCK_FOR_UPDATE. */
3479
DBUG_ASSERT(block->hash_link);
3480
DBUG_ASSERT(block->hash_link->block == block);
3481
DBUG_ASSERT(block->hash_link->file == file);
3482
DBUG_ASSERT((block->status & ~(BLOCK_FOR_UPDATE | BLOCK_IN_EVICTION)) ==
3483
(BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
3485
Set correct status and link in right queue for free or later use.
3486
free_block() must not see BLOCK_CHANGED and it may need to wait
3487
for readers of the block. These should not see the block in the
3488
wrong hash. If not freeing the block, we need to have it in the
3491
link_to_file_list(keycache, block, file, 1);
3494
block->status&= ~BLOCK_IN_FLUSH;
3496
Let to proceed for possible waiting requests to write to the block page.
3497
It might happen only during an operation to resize the key cache.
3499
release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
3500
/* type will never be FLUSH_IGNORE_CHANGED here */
3501
if (!(type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE) &&
3502
!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
3506
Note that a request has been registered against the block in
3507
flush_key_blocks_int().
3509
free_block(keycache, block);
3514
Link the block into the LRU ring if it's the last submitted
3515
request for the block. This enables eviction for the block.
3516
Note that a request has been registered against the block in
3517
flush_key_blocks_int().
3519
unreg_request(keycache, block, 1);
3522
} /* end of for ( ; cache != end ; cache++) */
3528
flush all key blocks for a file to disk, but don't do any mutex locks.
3531
flush_key_blocks_int()
3532
keycache pointer to a key cache data structure
3533
file handler for the file to flush to
3534
flush_type type of the flush
3537
This function doesn't do any mutex locks because it needs to be called both
3538
from flush_key_blocks and flush_all_key_blocks (the later one does the
3539
mutex lock in the resize_key_cache() function).
3541
We do only care about changed blocks that exist when the function is
3542
entered. We do not guarantee that all changed blocks of the file are
3543
flushed if more blocks change while this function is running.
3550
static int flush_key_blocks_int(KEY_CACHE *keycache,
3551
File file, enum flush_type type)
3553
BLOCK_LINK *cache_buff[FLUSH_CACHE],**cache;
3556
DBUG_ENTER("flush_key_blocks_int");
3557
DBUG_PRINT("enter",("file: %d blocks_used: %lu blocks_changed: %lu",
3558
file, keycache->blocks_used, keycache->blocks_changed));
3560
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
3561
DBUG_EXECUTE("check_keycache",
3562
test_key_cache(keycache, "start of flush_key_blocks", 0););
3566
if (keycache->disk_blocks > 0 &&
3567
(!my_disable_flush_key_blocks || type != FLUSH_KEEP))
3569
/* Key cache exists and flush is not disabled */
3571
uint count= FLUSH_CACHE;
3572
BLOCK_LINK **pos,**end;
3573
BLOCK_LINK *first_in_switch= NULL;
3574
BLOCK_LINK *last_in_flush;
3575
BLOCK_LINK *last_for_update;
3576
BLOCK_LINK *block, *next;
3577
#if defined(KEYCACHE_DEBUG)
3581
if (type != FLUSH_IGNORE_CHANGED)
3584
Count how many key blocks we have to cache to be able
3585
to flush all dirty pages with minimum seek moves
3588
for (block= keycache->changed_blocks[FILE_HASH(file)] ;
3590
block= block->next_changed)
3592
if ((block->hash_link->file == file) &&
3593
!(block->status & BLOCK_IN_FLUSH))
3596
KEYCACHE_DBUG_ASSERT(count<= keycache->blocks_used);
3600
Allocate a new buffer only if its bigger than the one we have.
3601
Assure that we always have some entries for the case that new
3602
changed blocks appear while we need to wait for something.
3604
if ((count > FLUSH_CACHE) &&
3605
!(cache= (BLOCK_LINK**) my_malloc(sizeof(BLOCK_LINK*)*count,
3609
After a restart there could be more changed blocks than now.
3610
So we should not let count become smaller than the fixed buffer.
3612
if (cache == cache_buff)
3616
/* Retrieve the blocks and write them to a buffer to be flushed */
3618
last_in_flush= NULL;
3619
last_for_update= NULL;
3620
end= (pos= cache)+count;
3621
for (block= keycache->changed_blocks[FILE_HASH(file)] ;
3625
#if defined(KEYCACHE_DEBUG)
3627
KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
3629
next= block->next_changed;
3630
if (block->hash_link->file == file)
3632
if (!(block->status & (BLOCK_IN_FLUSH | BLOCK_FOR_UPDATE)))
3635
Note: The special handling of BLOCK_IN_SWITCH is obsolete
3636
since we set BLOCK_IN_FLUSH if the eviction includes a
3637
flush. It can be removed in a later version.
3639
if (!(block->status & BLOCK_IN_SWITCH))
3642
We care only for the blocks for which flushing was not
3643
initiated by another thread and which are not in eviction.
3644
Registering a request on the block unlinks it from the LRU
3645
ring and protects against eviction.
3647
reg_requests(keycache, block, 1);
3648
if (type != FLUSH_IGNORE_CHANGED)
3650
/* It's not a temporary file */
3654
This should happen relatively seldom. Remove the
3655
request because we won't do anything with the block
3656
but restart and pick it again in the next iteration.
3658
unreg_request(keycache, block, 0);
3660
This happens only if there is not enough
3661
memory for the big block
3663
if ((error= flush_cached_blocks(keycache, file, cache,
3666
/* Do not loop infinitely trying to flush in vain. */
3667
if ((last_errno == error) && (++last_errcnt > 5))
3672
Restart the scan as some other thread might have changed
3673
the changed blocks chain: the blocks that were in switch
3674
state before the flush started have to be excluded
3679
Mark the block with BLOCK_IN_FLUSH in order not to let
3680
other threads to use it for new pages and interfere with
3681
our sequence of flushing dirty file pages. We must not
3682
set this flag before actually putting the block on the
3683
write burst array called 'cache'.
3685
block->status|= BLOCK_IN_FLUSH;
3686
/* Add block to the array for a write burst. */
3691
/* It's a temporary file */
3692
DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
3695
free_block() must not be called with BLOCK_CHANGED. Note
3696
that we must not change the BLOCK_CHANGED flag outside of
3697
link_to_file_list() so that it is always in the correct
3698
queue and the *blocks_changed counters are correct.
3700
link_to_file_list(keycache, block, file, 1);
3701
if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)))
3703
/* A request has been registered against the block above. */
3704
free_block(keycache, block);
3709
Link the block into the LRU ring if it's the last
3710
submitted request for the block. This enables eviction
3711
for the block. A request has been registered against
3714
unreg_request(keycache, block, 1);
3721
Link the block into a list of blocks 'in switch'.
3723
WARNING: Here we introduce a place where a changed block
3724
is not in the changed_blocks hash! This is acceptable for
3725
a BLOCK_IN_SWITCH. Never try this for another situation.
3726
Other parts of the key cache code rely on changed blocks
3727
being in the changed_blocks hash.
3729
unlink_changed(block);
3730
link_changed(block, &first_in_switch);
3733
else if (type != FLUSH_KEEP)
3736
During the normal flush at end of statement (FLUSH_KEEP) we
3737
do not need to ensure that blocks in flush or update by
3738
other threads are flushed. They will be flushed by them
3739
later. In all other cases we must assure that we do not have
3740
any changed block of this file in the cache when this
3743
if (block->status & BLOCK_IN_FLUSH)
3745
/* Remember the last block found to be in flush. */
3746
last_in_flush= block;
3750
/* Remember the last block found to be selected for update. */
3751
last_for_update= block;
3758
if ((error= flush_cached_blocks(keycache, file, cache, pos, type)))
3760
/* Do not loop inifnitely trying to flush in vain. */
3761
if ((last_errno == error) && (++last_errcnt > 5))
3766
Do not restart here during the normal flush at end of statement
3767
(FLUSH_KEEP). We have now flushed at least all blocks that were
3768
changed when entering this function. In all other cases we must
3769
assure that we do not have any changed block of this file in the
3770
cache when this function returns.
3772
if (type != FLUSH_KEEP)
3778
There are no blocks to be flushed by this thread, but blocks in
3779
flush by other threads. Wait until one of the blocks is flushed.
3780
Re-check the condition for last_in_flush. We may have unlocked
3781
the cache_lock in flush_cached_blocks(). The state of the block
3784
if (last_in_flush->status & BLOCK_IN_FLUSH)
3785
wait_on_queue(&last_in_flush->wqueue[COND_FOR_SAVED],
3786
&keycache->cache_lock);
3787
/* Be sure not to lose a block. They may be flushed in random order. */
3790
if (last_for_update)
3793
There are no blocks to be flushed by this thread, but blocks for
3794
update by other threads. Wait until one of the blocks is updated.
3795
Re-check the condition for last_for_update. We may have unlocked
3796
the cache_lock in flush_cached_blocks(). The state of the block
3799
if (last_for_update->status & BLOCK_FOR_UPDATE)
3800
wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
3801
&keycache->cache_lock);
3802
/* The block is now changed. Flush it. */
3807
Wait until the list of blocks in switch is empty. The threads that
3808
are switching these blocks will relink them to clean file chains
3809
while we wait and thus empty the 'first_in_switch' chain.
3811
while (first_in_switch)
3813
#if defined(KEYCACHE_DEBUG)
3816
wait_on_queue(&first_in_switch->wqueue[COND_FOR_SAVED],
3817
&keycache->cache_lock);
3818
#if defined(KEYCACHE_DEBUG)
3820
KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
3823
Do not restart here. We have flushed all blocks that were
3824
changed when entering this function and were not marked for
3825
eviction. Other threads have now flushed all remaining blocks in
3826
the course of their eviction.
3830
if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE))
3832
BLOCK_LINK *last_for_update= NULL;
3833
BLOCK_LINK *last_in_switch= NULL;
3834
uint total_found= 0;
3838
Finally free all clean blocks for this file.
3839
During resize this may be run by two threads in parallel.
3844
for (block= keycache->file_blocks[FILE_HASH(file)] ;
3848
/* Remember the next block. After freeing we cannot get at it. */
3849
next= block->next_changed;
3851
/* Changed blocks cannot appear in the file_blocks hash. */
3852
DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
3853
if (block->hash_link->file == file)
3855
/* We must skip blocks that will be changed. */
3856
if (block->status & BLOCK_FOR_UPDATE)
3858
last_for_update= block;
3863
We must not free blocks in eviction (BLOCK_IN_EVICTION |
3864
BLOCK_IN_SWITCH) or blocks intended to be freed
3867
if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
3870
struct st_hash_link *next_hash_link;
3871
my_off_t next_diskpos;
3878
KEYCACHE_DBUG_ASSERT(found <= keycache->blocks_used);
3881
Register a request. This unlinks the block from the LRU
3882
ring and protects it against eviction. This is required
3885
reg_requests(keycache, block, 1);
3888
free_block() may need to wait for readers of the block.
3889
This is the moment where the other thread can move the
3890
'next' block from the chain. free_block() needs to wait
3891
if there are requests for the block pending.
3893
if (next && (hash_requests= block->hash_link->requests))
3895
/* Copy values from the 'next' block and its hash_link. */
3896
next_status= next->status;
3897
next_hash_link= next->hash_link;
3898
next_diskpos= next_hash_link->diskpos;
3899
next_file= next_hash_link->file;
3900
DBUG_ASSERT(next == next_hash_link->block);
3903
free_block(keycache, block);
3905
If we had to wait and the state of the 'next' block
3906
changed, break the inner loop. 'next' may no longer be
3907
part of the current chain.
3909
We do not want to break the loop after every free_block(),
3910
not even only after waits. The chain might be quite long
3911
and contain blocks for many files. Traversing it again and
3912
again to find more blocks for this file could become quite
3915
if (next && hash_requests &&
3916
((next_status != next->status) ||
3917
(next_hash_link != next->hash_link) ||
3918
(next_file != next_hash_link->file) ||
3919
(next_diskpos != next_hash_link->diskpos) ||
3920
(next != next_hash_link->block)))
3925
last_in_switch= block;
3928
} /* end for block in file_blocks */
3932
If any clean block has been found, we may have waited for it to
3933
become free. In this case it could be possible that another clean
3934
block became dirty. This is possible if the write request existed
3935
before the flush started (BLOCK_FOR_UPDATE). Re-check the hashes.
3941
To avoid an infinite loop, wait until one of the blocks marked
3942
for update is updated.
3944
if (last_for_update)
3946
/* We did not wait. Block must not have changed status. */
3947
DBUG_ASSERT(last_for_update->status & BLOCK_FOR_UPDATE);
3948
wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
3949
&keycache->cache_lock);
3954
To avoid an infinite loop wait until one of the blocks marked
3955
for eviction is switched.
3959
/* We did not wait. Block must not have changed status. */
3960
DBUG_ASSERT(last_in_switch->status & (BLOCK_IN_EVICTION |
3963
wait_on_queue(&last_in_switch->wqueue[COND_FOR_SAVED],
3964
&keycache->cache_lock);
3968
} /* if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE)) */
3970
} /* if (keycache->disk_blocks > 0 */
3973
DBUG_EXECUTE("check_keycache",
3974
test_key_cache(keycache, "end of flush_key_blocks", 0););
3977
if (cache != cache_buff)
3978
my_free((uchar*) cache, MYF(0));
3980
errno=last_errno; /* Return first error */
3981
DBUG_RETURN(last_errno != 0);
3986
Flush all blocks for a file to disk
3991
keycache pointer to a key cache data structure
3992
file handler for the file to flush to
3993
flush_type type of the flush
4000
int flush_key_blocks(KEY_CACHE *keycache,
4001
File file, enum flush_type type)
4004
DBUG_ENTER("flush_key_blocks");
4005
DBUG_PRINT("enter", ("keycache: 0x%lx", (long) keycache));
4007
if (!keycache->key_cache_inited)
4010
keycache_pthread_mutex_lock(&keycache->cache_lock);
4011
/* While waiting for lock, keycache could have been ended. */
4012
if (keycache->disk_blocks > 0)
4014
inc_counter_for_resize_op(keycache);
4015
res= flush_key_blocks_int(keycache, file, type);
4016
dec_counter_for_resize_op(keycache);
4018
keycache_pthread_mutex_unlock(&keycache->cache_lock);
4024
Flush all blocks in the key cache to disk.
4027
flush_all_key_blocks()
4028
keycache pointer to key cache root structure
4032
Flushing of the whole key cache is done in two phases.
4034
1. Flush all changed blocks, waiting for them if necessary. Loop
4035
until there is no changed block left in the cache.
4037
2. Free all clean blocks. Normally this means free all blocks. The
4038
changed blocks were flushed in phase 1 and became clean. However we
4039
may need to wait for blocks that are read by other threads. While we
4040
wait, a clean block could become changed if that operation started
4041
before the resize operation started. To be safe we must restart at
4044
When we can run through the changed_blocks and file_blocks hashes
4045
without finding a block any more, then we are done.
4047
Note that we hold keycache->cache_lock all the time unless we need
4048
to wait for something.
4055
static int flush_all_key_blocks(KEY_CACHE *keycache)
4061
DBUG_ENTER("flush_all_key_blocks");
4065
safe_mutex_assert_owner(&keycache->cache_lock);
4069
Phase1: Flush all changed blocks, waiting for them if necessary.
4070
Loop until there is no changed block left in the cache.
4075
/* Step over the whole changed_blocks hash array. */
4076
for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
4079
If an array element is non-empty, use the first block from its
4080
chain to find a file for flush. All changed blocks for this
4081
file are flushed. So the same block will not appear at this
4082
place again with the next iteration. New writes for blocks are
4083
not accepted during the flush. If multiple files share the
4084
same hash bucket, one of them will be flushed per iteration
4085
of the outer loop of phase 1.
4087
if ((block= keycache->changed_blocks[idx]))
4091
Flush dirty blocks but do not free them yet. They can be used
4092
for reading until all other blocks are flushed too.
4094
if (flush_key_blocks_int(keycache, block->hash_link->file,
4103
Phase 2: Free all clean blocks. Normally this means free all
4104
blocks. The changed blocks were flushed in phase 1 and became
4105
clean. However we may need to wait for blocks that are read by
4106
other threads. While we wait, a clean block could become changed
4107
if that operation started before the resize operation started. To
4108
be safe we must restart at phase 1.
4113
/* Step over the whole file_blocks hash array. */
4114
for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
4117
If an array element is non-empty, use the first block from its
4118
chain to find a file for flush. All blocks for this file are
4119
freed. So the same block will not appear at this place again
4120
with the next iteration. If multiple files share the
4121
same hash bucket, one of them will be flushed per iteration
4122
of the outer loop of phase 2.
4124
if ((block= keycache->file_blocks[idx]))
4128
if (flush_key_blocks_int(keycache, block->hash_link->file,
4137
If any clean block has been found, we may have waited for it to
4138
become free. In this case it could be possible that another clean
4139
block became dirty. This is possible if the write request existed
4140
before the resize started (BLOCK_FOR_UPDATE). Re-check the hashes.
4142
} while (total_found);
4145
/* Now there should not exist any block any more. */
4146
for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
4148
DBUG_ASSERT(!keycache->changed_blocks[idx]);
4149
DBUG_ASSERT(!keycache->file_blocks[idx]);
4158
Reset the counters of a key cache.
4161
reset_key_cache_counters()
4162
name the name of a key cache
4163
key_cache pointer to the key kache to be reset
4166
This procedure is used by process_key_caches() to reset the counters of all
4167
currently used key caches, both the default one and the named ones.
4170
0 on success (always because it can't fail)
4173
int reset_key_cache_counters(const char *name __attribute__((unused)),
4174
KEY_CACHE *key_cache)
4176
DBUG_ENTER("reset_key_cache_counters");
4177
if (!key_cache->key_cache_inited)
4179
DBUG_PRINT("info", ("Key cache %s not initialized.", name));
4182
DBUG_PRINT("info", ("Resetting counters for key cache %s.", name));
4184
key_cache->global_blocks_changed= 0; /* Key_blocks_not_flushed */
4185
key_cache->global_cache_r_requests= 0; /* Key_read_requests */
4186
key_cache->global_cache_read= 0; /* Key_reads */
4187
key_cache->global_cache_w_requests= 0; /* Key_write_requests */
4188
key_cache->global_cache_write= 0; /* Key_writes */
4195
Test if disk-cache is ok
4197
static void test_key_cache(KEY_CACHE *keycache __attribute__((unused)),
4198
const char *where __attribute__((unused)),
4199
my_bool lock __attribute__((unused)))
4205
#if defined(KEYCACHE_TIMEOUT)
4207
#define KEYCACHE_DUMP_FILE "keycache_dump.txt"
4208
#define MAX_QUEUE_LEN 100
4211
static void keycache_dump(KEY_CACHE *keycache)
4213
FILE *keycache_dump_file=fopen(KEYCACHE_DUMP_FILE, "w");
4214
struct st_my_thread_var *last;
4215
struct st_my_thread_var *thread;
4217
HASH_LINK *hash_link;
4218
KEYCACHE_PAGE *page;
4221
fprintf(keycache_dump_file, "thread:%u\n", thread->id);
4224
thread=last=waiting_for_hash_link.last_thread;
4225
fprintf(keycache_dump_file, "queue of threads waiting for hash link\n");
4229
thread=thread->next;
4230
page= (KEYCACHE_PAGE *) thread->opt_info;
4231
fprintf(keycache_dump_file,
4232
"thread:%u, (file,filepos)=(%u,%lu)\n",
4233
thread->id,(uint) page->file,(ulong) page->filepos);
4234
if (++i == MAX_QUEUE_LEN)
4237
while (thread != last);
4240
thread=last=waiting_for_block.last_thread;
4241
fprintf(keycache_dump_file, "queue of threads waiting for block\n");
4245
thread=thread->next;
4246
hash_link= (HASH_LINK *) thread->opt_info;
4247
fprintf(keycache_dump_file,
4248
"thread:%u hash_link:%u (file,filepos)=(%u,%lu)\n",
4249
thread->id, (uint) HASH_LINK_NUMBER(hash_link),
4250
(uint) hash_link->file,(ulong) hash_link->diskpos);
4251
if (++i == MAX_QUEUE_LEN)
4254
while (thread != last);
4256
for (i=0 ; i< keycache->blocks_used ; i++)
4259
block= &keycache->block_root[i];
4260
hash_link= block->hash_link;
4261
fprintf(keycache_dump_file,
4262
"block:%u hash_link:%d status:%x #requests=%u waiting_for_readers:%d\n",
4263
i, (int) (hash_link ? HASH_LINK_NUMBER(hash_link) : -1),
4264
block->status, block->requests, block->condvar ? 1 : 0);
4265
for (j=0 ; j < 2; j++)
4267
KEYCACHE_WQUEUE *wqueue=&block->wqueue[j];
4268
thread= last= wqueue->last_thread;
4269
fprintf(keycache_dump_file, "queue #%d\n", j);
4274
thread=thread->next;
4275
fprintf(keycache_dump_file,
4276
"thread:%u\n", thread->id);
4277
if (++i == MAX_QUEUE_LEN)
4280
while (thread != last);
4284
fprintf(keycache_dump_file, "LRU chain:");
4285
block= keycache= used_last;
4290
block= block->next_used;
4291
fprintf(keycache_dump_file,
4292
"block:%u, ", BLOCK_NUMBER(block));
4294
while (block != keycache->used_last);
4296
fprintf(keycache_dump_file, "\n");
4298
fclose(keycache_dump_file);
4301
#endif /* defined(KEYCACHE_TIMEOUT) */
4303
#if defined(KEYCACHE_TIMEOUT)
4306
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
4307
pthread_mutex_t *mutex)
4310
struct timeval now; /* time when we started waiting */
4311
struct timespec timeout; /* timeout value for the wait function */
4313
#if defined(KEYCACHE_DEBUG)
4317
/* Get current time */
4318
gettimeofday(&now, &tz);
4319
/* Prepare timeout value */
4320
timeout.tv_sec= now.tv_sec + KEYCACHE_TIMEOUT;
4322
timeval uses microseconds.
4323
timespec uses nanoseconds.
4324
1 nanosecond = 1000 micro seconds
4326
timeout.tv_nsec= now.tv_usec * 1000;
4327
KEYCACHE_THREAD_TRACE_END("started waiting");
4328
#if defined(KEYCACHE_DEBUG)
4331
fprintf(keycache_debug_log, "waiting...\n");
4332
fflush(keycache_debug_log);
4334
rc= pthread_cond_timedwait(cond, mutex, &timeout);
4335
KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
4336
if (rc == ETIMEDOUT || rc == ETIME)
4338
#if defined(KEYCACHE_DEBUG)
4339
fprintf(keycache_debug_log,"aborted by keycache timeout\n");
4340
fclose(keycache_debug_log);
4346
#if defined(KEYCACHE_DEBUG)
4347
KEYCACHE_DBUG_ASSERT(rc != ETIMEDOUT);
4349
assert(rc != ETIMEDOUT);
4354
#if defined(KEYCACHE_DEBUG)
4355
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
4356
pthread_mutex_t *mutex)
4359
KEYCACHE_THREAD_TRACE_END("started waiting");
4360
rc= pthread_cond_wait(cond, mutex);
4361
KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
4365
#endif /* defined(KEYCACHE_TIMEOUT) */
4367
#if defined(KEYCACHE_DEBUG)
4370
static int keycache_pthread_mutex_lock(pthread_mutex_t *mutex)
4373
rc= pthread_mutex_lock(mutex);
4374
KEYCACHE_THREAD_TRACE_BEGIN("");
4379
static void keycache_pthread_mutex_unlock(pthread_mutex_t *mutex)
4381
KEYCACHE_THREAD_TRACE_END("");
4382
pthread_mutex_unlock(mutex);
4386
static int keycache_pthread_cond_signal(pthread_cond_t *cond)
4389
KEYCACHE_THREAD_TRACE("signal");
4390
rc= pthread_cond_signal(cond);
4395
#if defined(KEYCACHE_DEBUG_LOG)
4398
static void keycache_debug_print(const char * fmt,...)
4402
if (keycache_debug_log)
4404
VOID(vfprintf(keycache_debug_log, fmt, args));
4405
VOID(fputc('\n',keycache_debug_log));
4409
#endif /* defined(KEYCACHE_DEBUG_LOG) */
4411
#if defined(KEYCACHE_DEBUG_LOG)
4414
void keycache_debug_log_close(void)
4416
if (keycache_debug_log)
4417
fclose(keycache_debug_log);
4419
#endif /* defined(KEYCACHE_DEBUG_LOG) */
4421
#endif /* defined(KEYCACHE_DEBUG) */
4423
#if !defined(DBUG_OFF)
4424
#define F_B_PRT(_f_, _v_) DBUG_PRINT("assert_fail", (_f_, _v_))
4426
static int fail_block(BLOCK_LINK *block)
4428
F_B_PRT("block->next_used: %lx\n", (ulong) block->next_used);
4429
F_B_PRT("block->prev_used: %lx\n", (ulong) block->prev_used);
4430
F_B_PRT("block->next_changed: %lx\n", (ulong) block->next_changed);
4431
F_B_PRT("block->prev_changed: %lx\n", (ulong) block->prev_changed);
4432
F_B_PRT("block->hash_link: %lx\n", (ulong) block->hash_link);
4433
F_B_PRT("block->status: %u\n", block->status);
4434
F_B_PRT("block->length: %u\n", block->length);
4435
F_B_PRT("block->offset: %u\n", block->offset);
4436
F_B_PRT("block->requests: %u\n", block->requests);
4437
F_B_PRT("block->temperature: %u\n", block->temperature);
4438
return 0; /* Let the assert fail. */
4441
static int fail_hlink(HASH_LINK *hlink)
4443
F_B_PRT("hlink->next: %lx\n", (ulong) hlink->next);
4444
F_B_PRT("hlink->prev: %lx\n", (ulong) hlink->prev);
4445
F_B_PRT("hlink->block: %lx\n", (ulong) hlink->block);
4446
F_B_PRT("hlink->diskpos: %lu\n", (ulong) hlink->diskpos);
4447
F_B_PRT("hlink->file: %d\n", hlink->file);
4448
return 0; /* Let the assert fail. */
4451
static int cache_empty(KEY_CACHE *keycache)
4455
if (keycache->disk_blocks <= 0)
4457
for (idx= 0; idx < keycache->disk_blocks; idx++)
4459
BLOCK_LINK *block= keycache->block_root + idx;
4460
if (block->status || block->requests || block->hash_link)
4462
fprintf(stderr, "block index: %u\n", idx);
4467
for (idx= 0; idx < keycache->hash_links; idx++)
4469
HASH_LINK *hash_link= keycache->hash_link_root + idx;
4470
if (hash_link->requests || hash_link->block)
4472
fprintf(stderr, "hash_link index: %u\n", idx);
4473
fail_hlink(hash_link);
4479
fprintf(stderr, "blocks: %d used: %lu\n",
4480
keycache->disk_blocks, keycache->blocks_used);
4481
fprintf(stderr, "hash_links: %d used: %d\n",
4482
keycache->hash_links, keycache->hash_links_used);
4483
fprintf(stderr, "\n");