mf_keycache.c 160 KB
Newer Older
unknown's avatar
unknown committed
1 2 3 4
/* Copyright (C) 2000 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6 7

   This program is distributed in the hope that it will be useful,
unknown's avatar
unknown committed
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
unknown's avatar
unknown committed
9 10 11 12 13 14
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
unknown's avatar
unknown committed
15

16 17
/**
  @file
unknown's avatar
unknown committed
18 19
  These functions handle keyblock cacheing for ISAM and MyISAM tables.

20 21
  One cache can handle many files.
  It must contain buffers of the same blocksize.
unknown's avatar
unknown committed
22
  init_key_cache() should be used to init cache handler.
23 24 25 26 27 28 29 30 31

  The free list (free_block_list) is a stack like structure.
  When a block is freed by free_block(), it is pushed onto the stack.
  When a new block is required it is first tried to pop one from the stack.
  If the stack is empty, it is tried to get a never-used block from the pool.
  If this is empty too, then a block is taken from the LRU ring, flushing it
  to disk, if neccessary. This is handled in find_key_block().
  With the new free list, the blocks can have three temperatures:
  hot, warm and cold (which is free). This is remembered in the block header
32 33 34 35
  by the enum BLOCK_TEMPERATURE temperature variable. Remembering the
  temperature is neccessary to correctly count the number of warm blocks,
  which is required to decide when blocks are allowed to become hot. Whenever
  a block is inserted to another (sub-)chain, we take the old and new
36 37 38 39
  temperature into account to decide if we got one more or less warm block.
  blocks_unused is the sum of never used blocks in the pool and of currently
  free blocks. blocks_used is the number of blocks fetched from the pool and
  as such gives the maximum number of in-use blocks at any time.
40
*/
41

42
/*
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  Key Cache Locking
  =================

  All key cache locking is done with a single mutex per key cache:
  keycache->cache_lock. This mutex is locked almost all the time
  when executing code in this file (mf_keycache.c).
  However it is released for I/O and some copy operations.

  The cache_lock is also released when waiting for some event. Waiting
  and signalling is done via condition variables. In most cases the
  thread waits on its thread->suspend condition variable. Every thread
  has a my_thread_var structure, which contains this variable and a
  '*next' and '**prev' pointer. These pointers are used to insert the
  thread into a wait queue.

58 59
  A thread can wait for one block and thus be in one wait queue at a
  time only.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

  Before starting to wait on its condition variable with
  pthread_cond_wait(), the thread enters itself to a specific wait queue
  with link_into_queue() (double linked with '*next' + '**prev') or
  wait_on_queue() (single linked with '*next').

  Another thread, when releasing a resource, looks up the waiting thread
  in the related wait queue. It sends a signal with
  pthread_cond_signal() to the waiting thread.

  NOTE: Depending on the particular wait situation, either the sending
  thread removes the waiting thread from the wait queue with
  unlink_from_queue() or release_whole_queue() respectively, or the waiting
  thread removes itself.

75 76 77 78
  There is one exception from this locking scheme when one thread wants
  to reuse a block for some other address. This works by first marking
  the block reserved (status= BLOCK_IN_SWITCH) and then waiting for all
  threads that are reading the block to finish. Each block has a
79
  reference to a condition variable (condvar). It holds a reference to
80 81 82 83 84 85 86
  the thread->suspend condition variable for the waiting thread (if such
  a thread exists). When that thread is signaled, the reference is
  cleared. The number of readers of a block is registered in
  block->hash_link->requests. See wait_for_readers() / remove_reader()
  for details. This is similar to the above, but it clearly means that
  only one thread can wait for a particular block. There is no queue in
  this case. Strangely enough block->convar is used for waiting for the
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  assigned hash_link only. More precisely it is used to wait for all
  requests to be unregistered from the assigned hash_link.

  The resize_queue serves two purposes:
  1. Threads that want to do a resize wait there if in_resize is set.
     This is not used in the server. The server refuses a second resize
     request if one is already active. keycache->in_init is used for the
     synchronization. See set_var.cc.
  2. Threads that want to access blocks during resize wait here during
     the re-initialization phase.
  When the resize is done, all threads on the queue are signalled.
  Hypothetical resizers can compete for resizing, and read/write
  requests will restart to request blocks from the freshly resized
  cache. If the cache has been resized too small, it is disabled and
  'can_be_used' is false. In this case read/write requests bypass the
  cache. Since they increment and decrement 'cnt_for_resize_op', the
  next resizer can wait on the queue 'waiting_for_resize_cnt' until all
  I/O finished.
105
*/
unknown's avatar
unknown committed
106 107

#include "mysys_priv.h"
108
#include "mysys_err.h"
unknown's avatar
unknown committed
109
#include <keycache.h>
unknown's avatar
unknown committed
110 111
#include "my_static.h"
#include <m_string.h>
112
#include <my_bit.h>
unknown's avatar
unknown committed
113
#include <errno.h>
114 115
#include <stdarg.h>

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
/*
  Some compilation flags have been added specifically for this module
  to control the following:
  - not to let a thread to yield the control when reading directly
    from key cache, which might improve performance in many cases;
    to enable this add:
    #define SERIALIZED_READ_FROM_CACHE
  - to set an upper bound for number of threads simultaneously
    using the key cache; this setting helps to determine an optimal
    size for hash table and improve performance when the number of
    blocks in the key cache much less than the number of threads
    accessing it;
    to set this number equal to <N> add
      #define MAX_THREADS <N>
  - to substitute calls of pthread_cond_wait for calls of
    pthread_cond_timedwait (wait with timeout set up);
    this setting should be used only when you want to trap a deadlock
    situation, which theoretically should not happen;
    to set timeout equal to <T> seconds add
      #define KEYCACHE_TIMEOUT <T>
  - to enable the module traps and to send debug information from
    key cache module to a special debug log add:
      #define KEYCACHE_DEBUG
    the name of this debug log file <LOG NAME> can be set through:
      #define KEYCACHE_DEBUG_LOG  <LOG NAME>
    if the name is not defined, it's set by default;
    if the KEYCACHE_DEBUG flag is not set up and we are in a debug
    mode, i.e. when ! defined(DBUG_OFF), the debug information from the
    module is sent to the regular debug log.

  Example of the settings:
    #define SERIALIZED_READ_FROM_CACHE
    #define MAX_THREADS   100
    #define KEYCACHE_TIMEOUT  1
    #define KEYCACHE_DEBUG
    #define KEYCACHE_DEBUG_LOG  "my_key_cache_debug.log"
152
*/
unknown's avatar
unknown committed
153

154 155 156 157 158 159 160 161
#define STRUCT_PTR(TYPE, MEMBER, a)                                           \
          (TYPE *) ((char *) (a) - offsetof(TYPE, MEMBER))

/* types of condition variables */
#define  COND_FOR_REQUESTED 0
#define  COND_FOR_SAVED     1
#define  COND_FOR_READERS   2

162 163 164
typedef pthread_cond_t KEYCACHE_CONDVAR;

/* descriptor of the page in the key cache block buffer */
unknown's avatar
unknown committed
165
struct st_keycache_page
166
{
167 168
  int file;               /* file to which the page belongs to  */
  my_off_t filepos;       /* position of the page in the file   */
unknown's avatar
unknown committed
169
};
170

171
/* element in the chain of a hash table bucket */
unknown's avatar
unknown committed
172
struct st_hash_link
173
{
174 175 176 177 178
  struct st_hash_link *next, **prev; /* to connect links in the same bucket  */
  struct st_block_link *block;       /* reference to the block for the page: */
  File file;                         /* from such a file                     */
  my_off_t diskpos;                  /* with such an offset                  */
  uint requests;                     /* number of requests for the page      */
unknown's avatar
unknown committed
179
};
180 181

/* simple states of a block */
182 183 184 185 186 187 188 189 190 191
#define BLOCK_ERROR           1 /* an error occured when performing file i/o */
#define BLOCK_READ            2 /* file block is in the block buffer         */
#define BLOCK_IN_SWITCH       4 /* block is preparing to read new page       */
#define BLOCK_REASSIGNED      8 /* blk does not accept requests for old page */
#define BLOCK_IN_FLUSH       16 /* block is selected for flush               */
#define BLOCK_CHANGED        32 /* block buffer contains a dirty page        */
#define BLOCK_IN_USE         64 /* block is not free                         */
#define BLOCK_IN_EVICTION   128 /* block is selected for eviction            */
#define BLOCK_IN_FLUSHWRITE 256 /* block is in write to file                 */
#define BLOCK_FOR_UPDATE    512 /* block is selected for buffer modification */
192 193 194 195 196 197

/* page status, returned by find_key_block */
#define PAGE_READ               0
#define PAGE_TO_BE_READ         1
#define PAGE_WAIT_TO_BE_READ    2

198 199 200
/* block temperature determines in which (sub-)chain the block currently is */
enum BLOCK_TEMPERATURE { BLOCK_COLD /*free*/ , BLOCK_WARM , BLOCK_HOT };

201
/* key cache block */
unknown's avatar
unknown committed
202
struct st_block_link
203
{
204 205 206 207 208 209 210
  struct st_block_link
    *next_used, **prev_used;   /* to connect links in the LRU chain (ring)   */
  struct st_block_link
    *next_changed, **prev_changed; /* for lists of file dirty/clean blocks   */
  struct st_hash_link *hash_link; /* backward ptr to referring hash_link     */
  KEYCACHE_WQUEUE wqueue[2]; /* queues on waiting requests for new/old pages */
  uint requests;          /* number of requests for the block                */
211
  uchar *buffer;           /* buffer for the block page                       */
212 213 214
  uint offset;            /* beginning of modified data in the buffer        */
  uint length;            /* end of data in the buffer                       */
  uint status;            /* state of the block                              */
215
  enum BLOCK_TEMPERATURE temperature; /* block temperature: cold, warm, hot */
216 217
  uint hits_left;         /* number of hits left until promotion             */
  ulonglong last_hit_time; /* timestamp of the last hit                      */
218
  KEYCACHE_CONDVAR *condvar; /* condition variable for 'no readers' event    */
unknown's avatar
unknown committed
219
};
220

unknown's avatar
unknown committed
221 222 223
KEY_CACHE dflt_key_cache_var;
KEY_CACHE *dflt_key_cache= &dflt_key_cache_var;

224 225
#define FLUSH_CACHE         2000            /* sort this many blocks at once */

unknown's avatar
unknown committed
226
static int flush_all_key_blocks(KEY_CACHE *keycache);
227
#ifdef THREAD
228 229 230 231
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
                          pthread_mutex_t *mutex);
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue);
#else
232 233
#define wait_on_queue(wqueue, mutex)    do {} while (0)
#define release_whole_queue(wqueue)     do {} while (0)
234
#endif
unknown's avatar
unknown committed
235
static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block);
236
#if !defined(DBUG_OFF)
237
static void test_key_cache(KEY_CACHE *keycache,
unknown's avatar
unknown committed
238
                           const char *where, my_bool lock);
unknown's avatar
unknown committed
239
#endif
unknown's avatar
unknown committed
240

241
#define KEYCACHE_HASH(f, pos)                                                 \
242
(((ulong) ((pos) / keycache->key_cache_block_size) +                          \
unknown's avatar
unknown committed
243
                                     (ulong) (f)) & (keycache->hash_entries-1))
244
#define FILE_HASH(f)                 ((uint) (f) & (CHANGED_BLOCKS_HASH-1))
unknown's avatar
unknown committed
245

246
#define DEFAULT_KEYCACHE_DEBUG_LOG  "keycache_debug.log"
unknown's avatar
unknown committed
247

248 249 250
#if defined(KEYCACHE_DEBUG) && ! defined(KEYCACHE_DEBUG_LOG)
#define KEYCACHE_DEBUG_LOG  DEFAULT_KEYCACHE_DEBUG_LOG
#endif
unknown's avatar
unknown committed
251

252 253 254 255
#if defined(KEYCACHE_DEBUG_LOG)
static FILE *keycache_debug_log=NULL;
static void keycache_debug_print _VARARGS((const char *fmt,...));
#define KEYCACHE_DEBUG_OPEN                                                   \
256 257 258 259 260
          if (!keycache_debug_log)                                            \
          {                                                                   \
            keycache_debug_log= fopen(KEYCACHE_DEBUG_LOG, "w");               \
            (void) setvbuf(keycache_debug_log, NULL, _IOLBF, BUFSIZ);         \
          }
261 262

#define KEYCACHE_DEBUG_CLOSE                                                  \
263 264 265 266 267
          if (keycache_debug_log)                                             \
          {                                                                   \
            fclose(keycache_debug_log);                                       \
            keycache_debug_log= 0;                                            \
          }
268
#else
269
#define KEYCACHE_DEBUG_OPEN
270 271 272
#define KEYCACHE_DEBUG_CLOSE
#endif /* defined(KEYCACHE_DEBUG_LOG) */

273
#if defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG)
274 275 276 277 278 279 280 281 282 283 284 285 286
#define KEYCACHE_DBUG_PRINT(l, m)                                             \
            { if (keycache_debug_log) fprintf(keycache_debug_log, "%s: ", l); \
              keycache_debug_print m; }

#define KEYCACHE_DBUG_ASSERT(a)                                               \
            { if (! (a) && keycache_debug_log) fclose(keycache_debug_log);    \
              assert(a); }
#else
#define KEYCACHE_DBUG_PRINT(l, m)  DBUG_PRINT(l, m)
#define KEYCACHE_DBUG_ASSERT(a)    DBUG_ASSERT(a)
#endif /* defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG) */

#if defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF)
287
#ifdef THREAD
288 289 290 291 292
static long keycache_thread_id;
#define KEYCACHE_THREAD_TRACE(l)                                              \
             KEYCACHE_DBUG_PRINT(l,("|thread %ld",keycache_thread_id))

#define KEYCACHE_THREAD_TRACE_BEGIN(l)                                        \
unknown's avatar
unknown committed
293
            { struct st_my_thread_var *thread_var= my_thread_var;             \
294
              keycache_thread_id= thread_var->id;                             \
295 296 297 298
              KEYCACHE_DBUG_PRINT(l,("[thread %ld",keycache_thread_id)) }

#define KEYCACHE_THREAD_TRACE_END(l)                                          \
            KEYCACHE_DBUG_PRINT(l,("]thread %ld",keycache_thread_id))
299 300 301 302 303
#else /* THREAD */
#define KEYCACHE_THREAD_TRACE(l)        KEYCACHE_DBUG_PRINT(l,(""))
#define KEYCACHE_THREAD_TRACE_BEGIN(l)  KEYCACHE_DBUG_PRINT(l,(""))
#define KEYCACHE_THREAD_TRACE_END(l)    KEYCACHE_DBUG_PRINT(l,(""))
#endif /* THREAD */
304
#else
305 306 307
#define KEYCACHE_THREAD_TRACE_BEGIN(l)
#define KEYCACHE_THREAD_TRACE_END(l)
#define KEYCACHE_THREAD_TRACE(l)
308 309 310
#endif /* defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF) */

#define BLOCK_NUMBER(b)                                                       \
unknown's avatar
unknown committed
311
  ((uint) (((char*)(b)-(char *) keycache->block_root)/sizeof(BLOCK_LINK)))
312
#define HASH_LINK_NUMBER(h)                                                   \
unknown's avatar
unknown committed
313
  ((uint) (((char*)(h)-(char *) keycache->hash_link_root)/sizeof(HASH_LINK)))
314 315 316 317 318 319

#if (defined(KEYCACHE_TIMEOUT) && !defined(__WIN__)) || defined(KEYCACHE_DEBUG)
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
                                      pthread_mutex_t *mutex);
#else
#define  keycache_pthread_cond_wait pthread_cond_wait
unknown's avatar
unknown committed
320 321
#endif

322 323 324 325 326 327 328 329 330 331
#if defined(KEYCACHE_DEBUG)
static int keycache_pthread_mutex_lock(pthread_mutex_t *mutex);
static void keycache_pthread_mutex_unlock(pthread_mutex_t *mutex);
static int keycache_pthread_cond_signal(pthread_cond_t *cond);
#else
#define keycache_pthread_mutex_lock pthread_mutex_lock
#define keycache_pthread_mutex_unlock pthread_mutex_unlock
#define keycache_pthread_cond_signal pthread_cond_signal
#endif /* defined(KEYCACHE_DEBUG) */

332
#if !defined(DBUG_OFF)
333 334 335
#if defined(inline)
#undef inline
#endif
336 337 338 339 340 341
#define inline  /* disabled inline for easier debugging */
static int fail_block(BLOCK_LINK *block);
static int fail_hlink(HASH_LINK *hlink);
static int cache_empty(KEY_CACHE *keycache);
#endif

342
static inline uint next_power(uint value)
343
{
344
  return (uint) my_round_up_to_next_power((uint32) value) << 1;
345
}
unknown's avatar
unknown committed
346 347


348
/*
349 350 351
  Initialize a key cache

  SYNOPSIS
unknown's avatar
unknown committed
352 353
    init_key_cache()
    keycache			pointer to a key cache data structure
unknown's avatar
unknown committed
354 355 356 357
    key_cache_block_size	size of blocks to keep cached data
    use_mem                 	total memory to use for the key cache
    division_limit		division limit (may be zero)
    age_threshold		age threshold (may be zero)
358 359 360 361 362 363

  RETURN VALUE
    number of blocks in the key cache, if successful,
    0 - otherwise.

  NOTES.
unknown's avatar
unknown committed
364 365 366 367
    if keycache->key_cache_inited != 0 we assume that the key cache
    is already initialized.  This is for now used by myisamchk, but shouldn't
    be something that a program should rely on!

368 369
    It's assumed that no two threads call this function simultaneously
    referring to the same key cache handle.
370

371
*/
372

unknown's avatar
unknown committed
373
int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
374 375
                   size_t use_mem, uint division_limit,
                   uint age_threshold)
unknown's avatar
unknown committed
376
{
377 378
  ulong blocks, hash_links;
  size_t length;
379
  int error;
unknown's avatar
unknown committed
380
  DBUG_ENTER("init_key_cache");
381
  DBUG_ASSERT(key_cache_block_size >= 512);
382

383
  KEYCACHE_DEBUG_OPEN;
unknown's avatar
unknown committed
384
  if (keycache->key_cache_inited && keycache->disk_blocks > 0)
unknown's avatar
unknown committed
385
  {
386 387
    DBUG_PRINT("warning",("key cache already in use"));
    DBUG_RETURN(0);
unknown's avatar
unknown committed
388
  }
unknown's avatar
unknown committed
389

unknown's avatar
unknown committed
390 391 392
  keycache->global_cache_w_requests= keycache->global_cache_r_requests= 0;
  keycache->global_cache_read= keycache->global_cache_write= 0;
  keycache->disk_blocks= -1;
unknown's avatar
unknown committed
393
  if (! keycache->key_cache_inited)
unknown's avatar
unknown committed
394
  {
395
    keycache->key_cache_inited= 1;
396 397 398 399 400 401 402 403
    /*
      Initialize these variables once only.
      Their value must survive re-initialization during resizing.
    */
    keycache->in_resize= 0;
    keycache->resize_in_flush= 0;
    keycache->cnt_for_resize_op= 0;
    keycache->waiting_for_resize_cnt.last_thread= NULL;
unknown's avatar
unknown committed
404
    keycache->in_init= 0;
unknown's avatar
unknown committed
405
    pthread_mutex_init(&keycache->cache_lock, MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
406
    keycache->resize_queue.last_thread= NULL;
unknown's avatar
unknown committed
407
  }
408

unknown's avatar
unknown committed
409 410 411 412
  keycache->key_cache_mem_size= use_mem;
  keycache->key_cache_block_size= key_cache_block_size;
  DBUG_PRINT("info", ("key_cache_block_size: %u",
		      key_cache_block_size));
413

414 415
  blocks= (ulong) (use_mem / (sizeof(BLOCK_LINK) + 2 * sizeof(HASH_LINK) +
                              sizeof(HASH_LINK*) * 5/4 + key_cache_block_size));
416
  /* It doesn't make sense to have too few blocks (less than 8) */
417
  if (blocks >= 8)
unknown's avatar
unknown committed
418
  {
419
    for ( ; ; )
unknown's avatar
unknown committed
420
    {
421
      /* Set my_hash_entries to the next bigger 2 power */
422
      if ((keycache->hash_entries= next_power(blocks)) < blocks * 5/4)
unknown's avatar
unknown committed
423
        keycache->hash_entries<<= 1;
424
      hash_links= 2 * blocks;
425 426
#if defined(MAX_THREADS)
      if (hash_links < MAX_THREADS + blocks - 1)
427
        hash_links= MAX_THREADS + blocks - 1;
428
#endif
429 430
      while ((length= (ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)) +
		       ALIGN_SIZE(hash_links * sizeof(HASH_LINK)) +
431
		       ALIGN_SIZE(sizeof(HASH_LINK*) *
432
                                  keycache->hash_entries))) +
433
	     ((size_t) blocks * keycache->key_cache_block_size) > use_mem)
434 435
        blocks--;
      /* Allocate memory for cache page buffers */
436
      if ((keycache->block_mem=
437
	   my_large_malloc((size_t) blocks * keycache->key_cache_block_size,
438
			  MYF(0))))
439
      {
440
        /*
441 442
	  Allocate memory for blocks, hash_links and hash entries;
	  For each block 2 hash links are allocated
443
        */
444
        if ((keycache->block_root= (BLOCK_LINK*) my_malloc(length,
unknown's avatar
unknown committed
445
                                                           MYF(0))))
446
          break;
447
        my_large_free(keycache->block_mem, MYF(0));
448
        keycache->block_mem= 0;
449
      }
450
      if (blocks < 8)
unknown's avatar
unknown committed
451
      {
unknown's avatar
unknown committed
452
        my_errno= ENOMEM;
453
        my_error(EE_OUTOFMEMORY, MYF(0), blocks * keycache->key_cache_block_size);
454
        goto err;
unknown's avatar
unknown committed
455
      }
456
      blocks= blocks / 4*3;
unknown's avatar
unknown committed
457
    }
458
    keycache->blocks_unused= blocks;
unknown's avatar
unknown committed
459 460 461 462 463 464
    keycache->disk_blocks= (int) blocks;
    keycache->hash_links= hash_links;
    keycache->hash_root= (HASH_LINK**) ((char*) keycache->block_root +
				        ALIGN_SIZE(blocks*sizeof(BLOCK_LINK)));
    keycache->hash_link_root= (HASH_LINK*) ((char*) keycache->hash_root +
				            ALIGN_SIZE((sizeof(HASH_LINK*) *
465
							keycache->hash_entries)));
466
    bzero((uchar*) keycache->block_root,
467
	  keycache->disk_blocks * sizeof(BLOCK_LINK));
468
    bzero((uchar*) keycache->hash_root,
469
          keycache->hash_entries * sizeof(HASH_LINK*));
470
    bzero((uchar*) keycache->hash_link_root,
471
	  keycache->hash_links * sizeof(HASH_LINK));
unknown's avatar
unknown committed
472 473 474
    keycache->hash_links_used= 0;
    keycache->free_hash_list= NULL;
    keycache->blocks_used= keycache->blocks_changed= 0;
unknown's avatar
unknown committed
475

476
    keycache->global_blocks_changed= 0;
unknown's avatar
unknown committed
477 478
    keycache->blocks_available=0;		/* For debugging */

479
    /* The LRU chain is empty after initialization */
480 481
    keycache->used_last= NULL;
    keycache->used_ins= NULL;
482
    keycache->free_block_list= NULL;
483 484
    keycache->keycache_time= 0;
    keycache->warm_blocks= 0;
unknown's avatar
unknown committed
485 486
    keycache->min_warm_blocks= (division_limit ?
				blocks * division_limit / 100 + 1 :
487
				blocks);
unknown's avatar
unknown committed
488 489
    keycache->age_threshold= (age_threshold ?
			      blocks * age_threshold / 100 :
490
			      blocks);
491

unknown's avatar
unknown committed
492 493
    keycache->can_be_used= 1;

unknown's avatar
unknown committed
494 495
    keycache->waiting_for_hash_link.last_thread= NULL;
    keycache->waiting_for_block.last_thread= NULL;
496
    DBUG_PRINT("exit",
497 498
	       ("disk_blocks: %d  block_root: 0x%lx  hash_entries: %d\
 hash_root: 0x%lx  hash_links: %d  hash_link_root: 0x%lx",
unknown's avatar
unknown committed
499 500 501
		keycache->disk_blocks,  (long) keycache->block_root,
		keycache->hash_entries, (long) keycache->hash_root,
		keycache->hash_links,   (long) keycache->hash_link_root));
502
    bzero((uchar*) keycache->changed_blocks,
unknown's avatar
unknown committed
503
	  sizeof(keycache->changed_blocks[0]) * CHANGED_BLOCKS_HASH);
504
    bzero((uchar*) keycache->file_blocks,
unknown's avatar
unknown committed
505
	  sizeof(keycache->file_blocks[0]) * CHANGED_BLOCKS_HASH);
unknown's avatar
unknown committed
506
  }
507 508 509 510 511
  else
  {
    /* key_buffer_size is specified too small. Disable the cache. */
    keycache->can_be_used= 0;
  }
unknown's avatar
unknown committed
512 513

  keycache->blocks= keycache->disk_blocks > 0 ? keycache->disk_blocks : 0;
514
  DBUG_RETURN((int) keycache->disk_blocks);
515

unknown's avatar
unknown committed
516
err:
unknown's avatar
unknown committed
517
  error= my_errno;
518
  keycache->disk_blocks= 0;
unknown's avatar
unknown committed
519
  keycache->blocks=  0;
unknown's avatar
unknown committed
520
  if (keycache->block_mem)
521
  {
522
    my_large_free((uchar*) keycache->block_mem, MYF(0));
523 524 525 526
    keycache->block_mem= NULL;
  }
  if (keycache->block_root)
  {
527
    my_free((uchar*) keycache->block_root, MYF(0));
528 529
    keycache->block_root= NULL;
  }
unknown's avatar
unknown committed
530
  my_errno= error;
unknown's avatar
unknown committed
531
  keycache->can_be_used= 0;
unknown's avatar
unknown committed
532
  DBUG_RETURN(0);
533
}
unknown's avatar
unknown committed
534 535


unknown's avatar
unknown committed
536
/*
537 538 539 540
  Resize a key cache

  SYNOPSIS
    resize_key_cache()
unknown's avatar
unknown committed
541 542
    keycache     	        pointer to a key cache data structure
    key_cache_block_size        size of blocks to keep cached data
unknown's avatar
unknown committed
543 544 545
    use_mem			total memory to use for the new key cache
    division_limit		new division limit (if not zero)
    age_threshold		new age threshold (if not zero)
546 547 548 549 550 551 552

  RETURN VALUE
    number of blocks in the key cache, if successful,
    0 - otherwise.

  NOTES.
    The function first compares the memory size and the block size parameters
unknown's avatar
unknown committed
553 554 555 556 557 558
    with the key cache values.

    If they differ the function free the the memory allocated for the
    old key cache blocks by calling the end_key_cache function and
    then rebuilds the key cache with new blocks by calling
    init_key_cache.
unknown's avatar
unknown committed
559 560 561 562

    The function starts the operation only when all other threads
    performing operations with the key cache let her to proceed
    (when cnt_for_resize=0).
unknown's avatar
unknown committed
563
*/
564

unknown's avatar
unknown committed
565
int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
566 567
                     size_t use_mem, uint division_limit,
                     uint age_threshold)
unknown's avatar
unknown committed
568
{
569
  int blocks;
570
  DBUG_ENTER("resize_key_cache");
unknown's avatar
unknown committed
571

unknown's avatar
unknown committed
572
  if (!keycache->key_cache_inited)
unknown's avatar
unknown committed
573
    DBUG_RETURN(keycache->disk_blocks);
574

unknown's avatar
unknown committed
575 576 577 578 579
  if(key_cache_block_size == keycache->key_cache_block_size &&
     use_mem == keycache->key_cache_mem_size)
  {
    change_key_cache_param(keycache, division_limit, age_threshold);
    DBUG_RETURN(keycache->disk_blocks);
580
  }
581

unknown's avatar
unknown committed
582
  keycache_pthread_mutex_lock(&keycache->cache_lock);
unknown's avatar
unknown committed
583

584
#ifdef THREAD
585 586 587 588 589 590 591
  /*
    We may need to wait for another thread which is doing a resize
    already. This cannot happen in the MySQL server though. It allows
    one resizer only. In set_var.cc keycache->in_init is used to block
    multiple attempts.
  */
  while (keycache->in_resize)
unknown's avatar
unknown committed
592
  {
593 594 595
    /* purecov: begin inspected */
    wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
    /* purecov: end */
unknown's avatar
unknown committed
596
  }
597
#endif
unknown's avatar
unknown committed
598

599 600 601 602 603 604 605 606 607
  /*
    Mark the operation in progress. This blocks other threads from doing
    a resize in parallel. It prohibits new blocks to enter the cache.
    Read/write requests can bypass the cache during the flush phase.
  */
  keycache->in_resize= 1;

  /* Need to flush only if keycache is enabled. */
  if (keycache->can_be_used)
unknown's avatar
unknown committed
608
  {
609 610 611 612 613 614 615 616 617 618 619
    /* Start the flush phase. */
    keycache->resize_in_flush= 1;

    if (flush_all_key_blocks(keycache))
    {
      /* TODO: if this happens, we should write a warning in the log file ! */
      keycache->resize_in_flush= 0;
      blocks= 0;
      keycache->can_be_used= 0;
      goto finish;
    }
620
    DBUG_ASSERT(cache_empty(keycache));
621 622

    /* End the flush phase. */
unknown's avatar
unknown committed
623
    keycache->resize_in_flush= 0;
unknown's avatar
unknown committed
624
  }
625

626
#ifdef THREAD
627 628 629 630 631 632 633 634 635 636 637
  /*
    Some direct read/write operations (bypassing the cache) may still be
    unfinished. Wait until they are done. If the key cache can be used,
    direct I/O is done in increments of key_cache_block_size. That is,
    every block is checked if it is in the cache. We need to wait for
    pending I/O before re-initializing the cache, because we may change
    the block size. Otherwise they could check for blocks at file
    positions where the new block division has none. We do also want to
    wait for I/O done when (if) the cache was disabled. It must not
    run in parallel with normal cache operation.
  */
unknown's avatar
unknown committed
638
  while (keycache->cnt_for_resize_op)
639
    wait_on_queue(&keycache->waiting_for_resize_cnt, &keycache->cache_lock);
640 641 642
#else
  KEYCACHE_DBUG_ASSERT(keycache->cnt_for_resize_op == 0);
#endif
unknown's avatar
unknown committed
643

644 645 646 647 648 649
  /*
    Free old cache structures, allocate new structures, and initialize
    them. Note that the cache_lock mutex and the resize_queue are left
    untouched. We do not lose the cache_lock and will release it only at
    the end of this function.
  */
unknown's avatar
unknown committed
650
  end_key_cache(keycache, 0);			/* Don't free mutex */
unknown's avatar
unknown committed
651
  /* The following will work even if use_mem is 0 */
unknown's avatar
unknown committed
652 653
  blocks= init_key_cache(keycache, key_cache_block_size, use_mem,
			 division_limit, age_threshold);
unknown's avatar
unknown committed
654 655

finish:
656 657 658 659 660 661 662 663 664
  /*
    Mark the resize finished. This allows other threads to start a
    resize or to request new cache blocks.
  */
  keycache->in_resize= 0;

  /* Signal waiting threads. */
  release_whole_queue(&keycache->resize_queue);

unknown's avatar
unknown committed
665
  keycache_pthread_mutex_unlock(&keycache->cache_lock);
unknown's avatar
unknown committed
666
  DBUG_RETURN(blocks);
unknown's avatar
unknown committed
667 668 669
}


unknown's avatar
unknown committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
/*
  Increment counter blocking resize key cache operation
*/
static inline void inc_counter_for_resize_op(KEY_CACHE *keycache)
{
  keycache->cnt_for_resize_op++;
}


/*
  Decrement counter blocking resize key cache operation;
  Signal the operation to proceed when counter becomes equal zero
*/
static inline void dec_counter_for_resize_op(KEY_CACHE *keycache)
{
685 686
  if (!--keycache->cnt_for_resize_op)
    release_whole_queue(&keycache->waiting_for_resize_cnt);
unknown's avatar
unknown committed
687 688
}

689
/*
690
  Change the key cache parameters
691 692 693

  SYNOPSIS
    change_key_cache_param()
694
    keycache			pointer to a key cache data structure
unknown's avatar
unknown committed
695 696
    division_limit		new division limit (if not zero)
    age_threshold		new age threshold (if not zero)
697 698 699 700 701 702 703

  RETURN VALUE
    none

  NOTES.
    Presently the function resets the key cache parameters
    concerning midpoint insertion strategy - division_limit and
unknown's avatar
unknown committed
704
    age_threshold.
705 706
*/

unknown's avatar
unknown committed
707 708
void change_key_cache_param(KEY_CACHE *keycache, uint division_limit,
			    uint age_threshold)
709
{
unknown's avatar
unknown committed
710
  DBUG_ENTER("change_key_cache_param");
711

unknown's avatar
unknown committed
712
  keycache_pthread_mutex_lock(&keycache->cache_lock);
unknown's avatar
unknown committed
713 714 715 716 717 718
  if (division_limit)
    keycache->min_warm_blocks= (keycache->disk_blocks *
				division_limit / 100 + 1);
  if (age_threshold)
    keycache->age_threshold=   (keycache->disk_blocks *
				age_threshold / 100);
unknown's avatar
unknown committed
719
  keycache_pthread_mutex_unlock(&keycache->cache_lock);
unknown's avatar
unknown committed
720
  DBUG_VOID_RETURN;
721 722 723
}


724
/*
725
  Remove key_cache from memory
726 727 728

  SYNOPSIS
    end_key_cache()
unknown's avatar
unknown committed
729 730
    keycache		key cache handle
    cleanup		Complete free (Free also mutex for key cache)
731 732 733

  RETURN VALUE
    none
734
*/
735

unknown's avatar
unknown committed
736
void end_key_cache(KEY_CACHE *keycache, my_bool cleanup)
unknown's avatar
unknown committed
737 738
{
  DBUG_ENTER("end_key_cache");
unknown's avatar
unknown committed
739
  DBUG_PRINT("enter", ("key_cache: 0x%lx", (long) keycache));
740

unknown's avatar
unknown committed
741
  if (!keycache->key_cache_inited)
742
    DBUG_VOID_RETURN;
unknown's avatar
unknown committed
743

unknown's avatar
unknown committed
744
  if (keycache->disk_blocks > 0)
unknown's avatar
unknown committed
745
  {
unknown's avatar
unknown committed
746
    if (keycache->block_mem)
unknown's avatar
unknown committed
747
    {
748
      my_large_free((uchar*) keycache->block_mem, MYF(0));
749
      keycache->block_mem= NULL;
750
      my_free((uchar*) keycache->block_root, MYF(0));
751
      keycache->block_root= NULL;
unknown's avatar
unknown committed
752
    }
unknown's avatar
unknown committed
753
    keycache->disk_blocks= -1;
unknown's avatar
unknown committed
754 755
    /* Reset blocks_changed to be safe if flush_all_key_blocks is called */
    keycache->blocks_changed= 0;
unknown's avatar
unknown committed
756
  }
unknown's avatar
unknown committed
757

unknown's avatar
unknown committed
758
  DBUG_PRINT("status", ("used: %lu  changed: %lu  w_requests: %lu  "
759 760 761 762 763 764
                        "writes: %lu  r_requests: %lu  reads: %lu",
                        keycache->blocks_used, keycache->global_blocks_changed,
                        (ulong) keycache->global_cache_w_requests,
                        (ulong) keycache->global_cache_write,
                        (ulong) keycache->global_cache_r_requests,
                        (ulong) keycache->global_cache_read));
unknown's avatar
unknown committed
765

766 767 768 769 770 771 772
  /*
    Reset these values to be able to detect a disabled key cache.
    See Bug#44068 (RESTORE can disable the MyISAM Key Cache).
  */
  keycache->blocks_used= 0;
  keycache->blocks_unused= 0;

unknown's avatar
unknown committed
773 774
  if (cleanup)
  {
unknown's avatar
unknown committed
775
    pthread_mutex_destroy(&keycache->cache_lock);
776
    keycache->key_cache_inited= keycache->can_be_used= 0;
unknown's avatar
unknown committed
777
    KEYCACHE_DEBUG_CLOSE;
unknown's avatar
unknown committed
778
  }
unknown's avatar
unknown committed
779 780 781 782
  DBUG_VOID_RETURN;
} /* end_key_cache */


783
#ifdef THREAD
784

785
/*
786 787 788 789
  Link a thread into double-linked queue of waiting threads.

  SYNOPSIS
    link_into_queue()
790 791
      wqueue              pointer to the queue structure
      thread              pointer to the thread to be added to the queue
792 793 794 795 796 797 798 799

  RETURN VALUE
    none

  NOTES.
    Queue is represented by a circular list of the thread structures
    The list is double-linked of the type (**prev,*next), accessed by
    a pointer to the last element.
800
*/
801

802
static void link_into_queue(KEYCACHE_WQUEUE *wqueue,
803
                                   struct st_my_thread_var *thread)
804
{
805
  struct st_my_thread_var *last;
806 807

  DBUG_ASSERT(!thread->next && !thread->prev);
808
  if (! (last= wqueue->last_thread))
809 810
  {
    /* Queue is empty */
811 812
    thread->next= thread;
    thread->prev= &thread->next;
813 814
  }
  else
815
  {
816 817 818 819
    thread->prev= last->next->prev;
    last->next->prev= &thread->next;
    thread->next= last->next;
    last->next= thread;
820
  }
821
  wqueue->last_thread= thread;
822 823 824
}

/*
825
  Unlink a thread from double-linked queue of waiting threads
826 827 828

  SYNOPSIS
    unlink_from_queue()
829 830
      wqueue              pointer to the queue structure
      thread              pointer to the thread to be removed from the queue
831 832 833 834 835 836

  RETURN VALUE
    none

  NOTES.
    See NOTES for link_into_queue
837
*/
838

839
static void unlink_from_queue(KEYCACHE_WQUEUE *wqueue,
840
                                     struct st_my_thread_var *thread)
841
{
842
  KEYCACHE_DBUG_PRINT("unlink_from_queue", ("thread %ld", thread->id));
843
  DBUG_ASSERT(thread->next && thread->prev);
844 845
  if (thread->next == thread)
    /* The queue contains only one member */
846
    wqueue->last_thread= NULL;
847
  else
848
  {
849
    thread->next->prev= thread->prev;
850 851
    *thread->prev=thread->next;
    if (wqueue->last_thread == thread)
852 853
      wqueue->last_thread= STRUCT_PTR(struct st_my_thread_var, next,
                                      thread->prev);
854
  }
855
  thread->next= NULL;
856 857 858 859 860 861 862
#if !defined(DBUG_OFF)
  /*
    This makes it easier to see it's not in a chain during debugging.
    And some DBUG_ASSERT() rely on it.
  */
  thread->prev= NULL;
#endif
863 864 865 866
}


/*
867
  Add a thread to single-linked queue of waiting threads
868 869

  SYNOPSIS
870 871 872
    wait_on_queue()
      wqueue            Pointer to the queue structure.
      mutex             Cache_lock to acquire after awake.
873 874 875 876 877 878 879 880

  RETURN VALUE
    none

  NOTES.
    Queue is represented by a circular list of the thread structures
    The list is single-linked of the type (*next), accessed by a pointer
    to the last element.
881 882 883 884 885 886

    The function protects against stray signals by verifying that the
    current thread is unlinked from the queue when awaking. However,
    since several threads can wait for the same event, it might be
    necessary for the caller of the function to check again if the
    condition for awake is indeed matched.
887
*/
888

889 890
static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
                          pthread_mutex_t *mutex)
891
{
892
  struct st_my_thread_var *last;
893 894 895 896 897
  struct st_my_thread_var *thread= my_thread_var;

  /* Add to queue. */
  DBUG_ASSERT(!thread->next);
  DBUG_ASSERT(!thread->prev); /* Not required, but must be true anyway. */
898 899
  if (! (last= wqueue->last_thread))
    thread->next= thread;
900
  else
901
  {
902 903
    thread->next= last->next;
    last->next= thread;
904
  }
905
  wqueue->last_thread= thread;
906 907 908 909 910 911 912 913 914 915

  /*
    Wait until thread is removed from queue by the signalling thread.
    The loop protects against stray signals.
  */
  do
  {
    KEYCACHE_DBUG_PRINT("wait", ("suspend thread %ld", thread->id));
    keycache_pthread_cond_wait(&thread->suspend, mutex);
  }
916
  while (thread->next);
917 918 919 920
}


/*
921
  Remove all threads from queue signaling them to proceed
922 923

  SYNOPSIS
924 925
    release_whole_queue()
      wqueue            pointer to the queue structure
926 927 928 929 930

  RETURN VALUE
    none

  NOTES.
931
    See notes for wait_on_queue().
932
    When removed from the queue each thread is signaled via condition
933
    variable thread->suspend.
934
*/
935

936
static void release_whole_queue(KEYCACHE_WQUEUE *wqueue)
937
{
938 939
  struct st_my_thread_var *last;
  struct st_my_thread_var *next;
940
  struct st_my_thread_var *thread;
941 942 943 944 945 946

  /* Queue may be empty. */
  if (!(last= wqueue->last_thread))
    return;

  next= last->next;
947 948 949
  do
  {
    thread=next;
950 951 952
    KEYCACHE_DBUG_PRINT("release_whole_queue: signal",
                        ("thread %ld", thread->id));
    /* Signal the thread. */
953
    keycache_pthread_cond_signal(&thread->suspend);
954
    /* Take thread from queue. */
955
    next=thread->next;
956
    thread->next= NULL;
957 958
  }
  while (thread != last);
959 960

  /* Now queue is definitely empty. */
961
  wqueue->last_thread= NULL;
962
}
963 964

#endif /* THREAD */
965 966 967


/*
968
  Unlink a block from the chain of dirty/clean blocks
969
*/
970

971
static inline void unlink_changed(BLOCK_LINK *block)
unknown's avatar
unknown committed
972
{
973
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
974
  if (block->next_changed)
975 976
    block->next_changed->prev_changed= block->prev_changed;
  *block->prev_changed= block->next_changed;
977 978 979 980 981 982 983 984 985

#if !defined(DBUG_OFF)
  /*
    This makes it easier to see it's not in a chain during debugging.
    And some DBUG_ASSERT() rely on it.
  */
  block->next_changed= NULL;
  block->prev_changed= NULL;
#endif
unknown's avatar
unknown committed
986 987 988
}


989
/*
990
  Link a block into the chain of dirty/clean blocks
991
*/
992

993
static inline void link_changed(BLOCK_LINK *block, BLOCK_LINK **phead)
unknown's avatar
unknown committed
994
{
995 996
  DBUG_ASSERT(!block->next_changed);
  DBUG_ASSERT(!block->prev_changed);
997 998
  block->prev_changed= phead;
  if ((block->next_changed= *phead))
999
    (*phead)->prev_changed= &block->next_changed;
1000
  *phead= block;
unknown's avatar
unknown committed
1001 1002
}

1003 1004

/*
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
  Link a block in a chain of clean blocks of a file.

  SYNOPSIS
    link_to_file_list()
      keycache		Key cache handle
      block             Block to relink
      file              File to be linked to
      unlink            If to unlink first

  DESCRIPTION
    Unlink a block from whichever chain it is linked in, if it's
    asked for, and link it to the chain of clean blocks of the
    specified file.

  NOTE
    Please do never set/clear BLOCK_CHANGED outside of
    link_to_file_list() or link_to_changed_list().
    You would risk to damage correct counting of changed blocks
    and to find blocks in the wrong hash.

  RETURN
    void
1027
*/
1028

unknown's avatar
unknown committed
1029
static void link_to_file_list(KEY_CACHE *keycache,
1030 1031
                              BLOCK_LINK *block, int file,
                              my_bool unlink_block)
unknown's avatar
unknown committed
1032
{
1033 1034 1035
  DBUG_ASSERT(block->status & BLOCK_IN_USE);
  DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  DBUG_ASSERT(block->hash_link->file == file);
1036
  if (unlink_block)
1037
    unlink_changed(block);
1038
  link_changed(block, &keycache->file_blocks[FILE_HASH(file)]);
1039 1040
  if (block->status & BLOCK_CHANGED)
  {
1041
    block->status&= ~BLOCK_CHANGED;
unknown's avatar
unknown committed
1042
    keycache->blocks_changed--;
unknown's avatar
unknown committed
1043
    keycache->global_blocks_changed--;
1044
  }
unknown's avatar
unknown committed
1045 1046
}

1047

1048
/*
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  Re-link a block from the clean chain to the dirty chain of a file.

  SYNOPSIS
    link_to_changed_list()
      keycache		key cache handle
      block             block to relink

  DESCRIPTION
    Unlink a block from the chain of clean blocks of a file
    and link it to the chain of dirty blocks of the same file.

  NOTE
    Please do never set/clear BLOCK_CHANGED outside of
    link_to_file_list() or link_to_changed_list().
    You would risk to damage correct counting of changed blocks
    and to find blocks in the wrong hash.

  RETURN
    void
1068
*/
1069

1070 1071
static void link_to_changed_list(KEY_CACHE *keycache,
                                 BLOCK_LINK *block)
unknown's avatar
unknown committed
1072
{
1073 1074 1075 1076
  DBUG_ASSERT(block->status & BLOCK_IN_USE);
  DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  DBUG_ASSERT(block->hash_link && block->hash_link->block == block);

1077
  unlink_changed(block);
unknown's avatar
unknown committed
1078 1079
  link_changed(block,
               &keycache->changed_blocks[FILE_HASH(block->hash_link->file)]);
1080
  block->status|=BLOCK_CHANGED;
unknown's avatar
unknown committed
1081
  keycache->blocks_changed++;
unknown's avatar
unknown committed
1082
  keycache->global_blocks_changed++;
unknown's avatar
unknown committed
1083 1084 1085
}


1086
/*
1087 1088 1089 1090 1091
  Link a block to the LRU chain at the beginning or at the end of
  one of two parts.

  SYNOPSIS
    link_block()
1092
      keycache            pointer to a key cache data structure
1093 1094 1095 1096 1097 1098 1099 1100
      block               pointer to the block to link to the LRU chain
      hot                 <-> to link the block into the hot subchain
      at_end              <-> to link the block at the end of the subchain

  RETURN VALUE
    none

  NOTES.
1101
    The LRU ring is represented by a circular list of block structures.
1102
    The list is double-linked of the type (**prev,*next) type.
1103
    The LRU ring is divided into two parts - hot and warm.
1104
    There are two pointers to access the last blocks of these two
1105
    parts. The beginning of the warm part follows right after the
1106
    end of the hot part.
1107
    Only blocks of the warm part can be used for eviction.
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    The first block from the beginning of this subchain is always
    taken for eviction (keycache->last_used->next)

    LRU chain:       +------+   H O T    +------+
                +----| end  |----...<----| beg  |----+
                |    +------+last        +------+    |
                v<-link in latest hot (new end)      |
                |     link in latest warm (new end)->^
                |    +------+  W A R M   +------+    |
                +----| beg  |---->...----| end  |----+
                     +------+            +------+ins
1119
                  first for eviction
1120 1121 1122

    It is also possible that the block is selected for eviction and thus
    not linked in the LRU ring.
1123
*/
1124

1125 1126
static void link_block(KEY_CACHE *keycache, BLOCK_LINK *block, my_bool hot,
                       my_bool at_end)
1127
{
1128 1129 1130
  BLOCK_LINK *ins;
  BLOCK_LINK **pins;

1131 1132 1133 1134 1135 1136
  DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  DBUG_ASSERT(!block->requests);
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  DBUG_ASSERT(!block->next_used);
  DBUG_ASSERT(!block->prev_used);
1137
#ifdef THREAD
1138 1139
  if (!hot && keycache->waiting_for_block.last_thread)
  {
1140
    /* Signal that in the LRU warm sub-chain an available block has appeared */
unknown's avatar
unknown committed
1141 1142 1143 1144
    struct st_my_thread_var *last_thread=
                               keycache->waiting_for_block.last_thread;
    struct st_my_thread_var *first_thread= last_thread->next;
    struct st_my_thread_var *next_thread= first_thread;
1145 1146 1147 1148
    HASH_LINK *hash_link= (HASH_LINK *) first_thread->opt_info;
    struct st_my_thread_var *thread;
    do
    {
1149 1150
      thread= next_thread;
      next_thread= thread->next;
1151
      /*
1152 1153 1154 1155 1156
         We notify about the event all threads that ask
         for the same page as the first thread in the queue
      */
      if ((HASH_LINK *) thread->opt_info == hash_link)
      {
1157
        KEYCACHE_DBUG_PRINT("link_block: signal", ("thread %ld", thread->id));
1158
        keycache_pthread_cond_signal(&thread->suspend);
unknown's avatar
unknown committed
1159
        unlink_from_queue(&keycache->waiting_for_block, thread);
1160 1161
        block->requests++;
      }
1162
    }
1163
    while (thread != last_thread);
unknown's avatar
unknown committed
1164
    hash_link->block= block;
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    /*
      NOTE: We assigned the block to the hash_link and signalled the
      requesting thread(s). But it is possible that other threads runs
      first. These threads see the hash_link assigned to a block which
      is assigned to another hash_link and not marked BLOCK_IN_SWITCH.
      This can be a problem for functions that do not select the block
      via its hash_link: flush and free. They do only see a block which
      is in a "normal" state and don't know that it will be evicted soon.

      We cannot set BLOCK_IN_SWITCH here because only one of the
      requesting threads must handle the eviction. All others must wait
      for it to complete. If we set the flag here, the threads would not
      know who is in charge of the eviction. Without the flag, the first
      thread takes the stick and sets the flag.

      But we need to note in the block that is has been selected for
      eviction. It must not be freed. The evicting thread will not
      expect the block in the free list. Before freeing we could also
      check if block->requests > 1. But I think including another flag
      in the check of block->status is slightly more efficient and
      probably easier to read.
    */
    block->status|= BLOCK_IN_EVICTION;
1188 1189
    KEYCACHE_THREAD_TRACE("link_block: after signaling");
#if defined(KEYCACHE_DEBUG)
1190
    KEYCACHE_DBUG_PRINT("link_block",
1191
        ("linked,unlinked block %u  status=%x  #requests=%u  #available=%u",
unknown's avatar
unknown committed
1192
         BLOCK_NUMBER(block), block->status,
unknown's avatar
unknown committed
1193
         block->requests, keycache->blocks_available));
unknown's avatar
unknown committed
1194
#endif
1195 1196
    return;
  }
1197 1198 1199 1200
#else /* THREAD */
  KEYCACHE_DBUG_ASSERT(! (!hot && keycache->waiting_for_block.last_thread));
      /* Condition not transformed using DeMorgan, to keep the text identical */
#endif /* THREAD */
1201
  pins= hot ? &keycache->used_ins : &keycache->used_last;
1202
  ins= *pins;
1203
  if (ins)
1204
  {
1205 1206 1207 1208
    ins->next_used->prev_used= &block->next_used;
    block->next_used= ins->next_used;
    block->prev_used= &ins->next_used;
    ins->next_used= block;
1209
    if (at_end)
1210
      *pins= block;
1211 1212 1213
  }
  else
  {
1214
    /* The LRU ring is empty. Let the block point to itself. */
1215
    keycache->used_last= keycache->used_ins= block->next_used= block;
unknown's avatar
unknown committed
1216
    block->prev_used= &block->next_used;
1217 1218 1219
  }
  KEYCACHE_THREAD_TRACE("link_block");
#if defined(KEYCACHE_DEBUG)
unknown's avatar
unknown committed
1220
  keycache->blocks_available++;
1221
  KEYCACHE_DBUG_PRINT("link_block",
1222
      ("linked block %u:%1u  status=%x  #requests=%u  #available=%u",
1223
       BLOCK_NUMBER(block), at_end, block->status,
unknown's avatar
unknown committed
1224
       block->requests, keycache->blocks_available));
unknown's avatar
unknown committed
1225 1226
  KEYCACHE_DBUG_ASSERT((ulong) keycache->blocks_available <=
                       keycache->blocks_used);
1227 1228
#endif
}
unknown's avatar
unknown committed
1229

1230 1231

/*
1232
  Unlink a block from the LRU chain
1233 1234 1235

  SYNOPSIS
    unlink_block()
1236
      keycache            pointer to a key cache data structure
1237 1238 1239 1240 1241 1242 1243
      block               pointer to the block to unlink from the LRU chain

  RETURN VALUE
    none

  NOTES.
    See NOTES for link_block
1244
*/
1245

unknown's avatar
unknown committed
1246
static void unlink_block(KEY_CACHE *keycache, BLOCK_LINK *block)
1247
{
1248 1249 1250 1251 1252 1253 1254
  DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  DBUG_ASSERT(!block->requests);
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  DBUG_ASSERT(block->next_used && block->prev_used &&
              (block->next_used->prev_used == &block->next_used) &&
              (*block->prev_used == block));
1255 1256
  if (block->next_used == block)
    /* The list contains only one member */
1257
    keycache->used_last= keycache->used_ins= NULL;
1258
  else
1259
  {
unknown's avatar
unknown committed
1260 1261 1262 1263
    block->next_used->prev_used= block->prev_used;
    *block->prev_used= block->next_used;
    if (keycache->used_last == block)
      keycache->used_last= STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
1264 1265
    if (keycache->used_ins == block)
      keycache->used_ins=STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
1266
  }
unknown's avatar
unknown committed
1267
  block->next_used= NULL;
1268 1269 1270 1271 1272 1273 1274
#if !defined(DBUG_OFF)
  /*
    This makes it easier to see it's not in a chain during debugging.
    And some DBUG_ASSERT() rely on it.
  */
  block->prev_used= NULL;
#endif
1275

1276 1277
  KEYCACHE_THREAD_TRACE("unlink_block");
#if defined(KEYCACHE_DEBUG)
1278
  KEYCACHE_DBUG_ASSERT(keycache->blocks_available != 0);
unknown's avatar
unknown committed
1279
  keycache->blocks_available--;
1280
  KEYCACHE_DBUG_PRINT("unlink_block",
1281
    ("unlinked block %u  status=%x   #requests=%u  #available=%u",
1282
     BLOCK_NUMBER(block), block->status,
unknown's avatar
unknown committed
1283
     block->requests, keycache->blocks_available));
1284 1285 1286 1287 1288
#endif
}


/*
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  Register requests for a block.

  SYNOPSIS
    reg_requests()
      keycache          Pointer to a key cache data structure.
      block             Pointer to the block to register a request on.
      count             Number of requests. Always 1.

  NOTE
    The first request unlinks the block from the LRU ring. This means
    that it is protected against eveiction.

  RETURN
    void
1303
*/
unknown's avatar
unknown committed
1304
static void reg_requests(KEY_CACHE *keycache, BLOCK_LINK *block, int count)
1305
{
1306 1307 1308 1309
  DBUG_ASSERT(block->status & BLOCK_IN_USE);
  DBUG_ASSERT(block->hash_link);

  if (!block->requests)
unknown's avatar
unknown committed
1310
    unlink_block(keycache, block);
1311 1312 1313 1314
  block->requests+=count;
}


1315 1316 1317
/*
  Unregister request for a block
  linking it to the LRU chain if it's the last request
1318 1319

  SYNOPSIS
1320 1321 1322 1323
    unreg_request()
    keycache            pointer to a key cache data structure
    block               pointer to the block to link to the LRU chain
    at_end              <-> to link the block at the end of the LRU chain
1324 1325 1326 1327

  RETURN VALUE
    none

1328
  NOTES.
1329
    Every linking to the LRU ring decrements by one a special block
1330 1331
    counter (if it's positive). If the at_end parameter is TRUE the block is
    added either at the end of warm sub-chain or at the end of hot sub-chain.
1332 1333
    It is added to the hot subchain if its counter is zero and number of
    blocks in warm sub-chain is not less than some low limit (determined by
1334 1335
    the division_limit parameter). Otherwise the block is added to the warm
    sub-chain. If the at_end parameter is FALSE the block is always added
1336
    at beginning of the warm sub-chain.
1337 1338 1339 1340
    Thus a warm block can be promoted to the hot sub-chain when its counter
    becomes zero for the first time.
    At the same time  the block at the very beginning of the hot subchain
    might be moved to the beginning of the warm subchain if it stays untouched
1341
    for a too long time (this time is determined by parameter age_threshold).
1342 1343 1344

    It is also possible that the block is selected for eviction and thus
    not linked in the LRU ring.
1345
*/
1346

1347 1348
static void unreg_request(KEY_CACHE *keycache,
                          BLOCK_LINK *block, int at_end)
1349
{
1350 1351 1352 1353 1354 1355
  DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  DBUG_ASSERT(block->requests);
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  DBUG_ASSERT(!block->next_used);
  DBUG_ASSERT(!block->prev_used);
1356 1357 1358 1359 1360
  /*
    Unregister the request, but do not link erroneous blocks into the
    LRU ring.
  */
  if (!--block->requests && !(block->status & BLOCK_ERROR))
1361 1362 1363 1364 1365 1366 1367 1368
  {
    my_bool hot;
    if (block->hits_left)
      block->hits_left--;
    hot= !block->hits_left && at_end &&
      keycache->warm_blocks > keycache->min_warm_blocks;
    if (hot)
    {
1369 1370 1371
      if (block->temperature == BLOCK_WARM)
        keycache->warm_blocks--;
      block->temperature= BLOCK_HOT;
unknown's avatar
unknown committed
1372
      KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
1373 1374 1375 1376
                           keycache->warm_blocks));
    }
    link_block(keycache, block, hot, (my_bool)at_end);
    block->last_hit_time= keycache->keycache_time;
1377
    keycache->keycache_time++;
1378 1379 1380 1381 1382
    /*
      At this place, the block might be in the LRU ring or not. If an
      evicter was waiting for a block, it was selected for eviction and
      not linked in the LRU ring.
    */
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392
    /*
      Check if we should link a hot block to the warm block sub-chain.
      It is possible that we select the same block as above. But it can
      also be another block. In any case a block from the LRU ring is
      selected. In other words it works even if the above block was
      selected for eviction and not linked in the LRU ring. Since this
      happens only if the LRU ring is empty, the block selected below
      would be NULL and the rest of the function skipped.
    */
1393 1394
    block= keycache->used_ins;
    if (block && keycache->keycache_time - block->last_hit_time >
1395 1396 1397 1398
	keycache->age_threshold)
    {
      unlink_block(keycache, block);
      link_block(keycache, block, 0, 0);
1399 1400 1401 1402 1403
      if (block->temperature != BLOCK_WARM)
      {
        keycache->warm_blocks++;
        block->temperature= BLOCK_WARM;
      }
unknown's avatar
unknown committed
1404
      KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
1405 1406 1407
                           keycache->warm_blocks));
    }
  }
1408 1409 1410
}

/*
1411
  Remove a reader of the page in block
1412
*/
1413

1414
static void remove_reader(BLOCK_LINK *block)
1415
{
1416 1417 1418 1419 1420 1421
  DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  DBUG_ASSERT(!block->next_used);
  DBUG_ASSERT(!block->prev_used);
  DBUG_ASSERT(block->hash_link->requests);
unknown's avatar
unknown committed
1422
#ifdef THREAD
1423 1424
  if (! --block->hash_link->requests && block->condvar)
    keycache_pthread_cond_signal(block->condvar);
unknown's avatar
unknown committed
1425 1426 1427
#else
  --block->hash_link->requests;
#endif
1428 1429 1430 1431
}


/*
1432 1433
  Wait until the last reader of the page in block
  signals on its termination
1434
*/
1435

1436 1437
static void wait_for_readers(KEY_CACHE *keycache,
                             BLOCK_LINK *block)
1438
{
1439
#ifdef THREAD
unknown's avatar
unknown committed
1440
  struct st_my_thread_var *thread= my_thread_var;
1441
  DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
1442
  DBUG_ASSERT(!(block->status & (BLOCK_IN_FLUSH | BLOCK_CHANGED)));
1443 1444 1445 1446 1447 1448 1449
  DBUG_ASSERT(block->hash_link);
  DBUG_ASSERT(block->hash_link->block == block);
  /* Linked in file_blocks or changed_blocks hash. */
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  /* Not linked in LRU ring. */
  DBUG_ASSERT(!block->next_used);
  DBUG_ASSERT(!block->prev_used);
1450 1451
  while (block->hash_link->requests)
  {
1452 1453 1454
    KEYCACHE_DBUG_PRINT("wait_for_readers: wait",
                        ("suspend thread %ld  block %u",
                         thread->id, BLOCK_NUMBER(block)));
1455 1456
    /* There must be no other waiter. We have no queue here. */
    DBUG_ASSERT(!block->condvar);
1457
    block->condvar= &thread->suspend;
unknown's avatar
unknown committed
1458
    keycache_pthread_cond_wait(&thread->suspend, &keycache->cache_lock);
1459
    block->condvar= NULL;
1460
  }
1461 1462 1463
#else
  KEYCACHE_DBUG_ASSERT(block->hash_link->requests == 0);
#endif
1464 1465 1466 1467
}


/*
1468
  Add a hash link to a bucket in the hash_table
1469
*/
1470

1471 1472 1473
static inline void link_hash(HASH_LINK **start, HASH_LINK *hash_link)
{
  if (*start)
unknown's avatar
unknown committed
1474 1475 1476 1477
    (*start)->prev= &hash_link->next;
  hash_link->next= *start;
  hash_link->prev= start;
  *start= hash_link;
1478 1479 1480 1481
}


/*
1482
  Remove a hash link from the hash table
1483
*/
1484

unknown's avatar
unknown committed
1485
static void unlink_hash(KEY_CACHE *keycache, HASH_LINK *hash_link)
1486
{
1487
  KEYCACHE_DBUG_PRINT("unlink_hash", ("fd: %u  pos_ %lu  #requests=%u",
1488 1489
      (uint) hash_link->file,(ulong) hash_link->diskpos, hash_link->requests));
  KEYCACHE_DBUG_ASSERT(hash_link->requests == 0);
unknown's avatar
unknown committed
1490 1491 1492
  if ((*hash_link->prev= hash_link->next))
    hash_link->next->prev= hash_link->prev;
  hash_link->block= NULL;
1493
#ifdef THREAD
unknown's avatar
unknown committed
1494
  if (keycache->waiting_for_hash_link.last_thread)
1495
  {
unknown's avatar
unknown committed
1496
    /* Signal that a free hash link has appeared */
unknown's avatar
unknown committed
1497 1498 1499 1500
    struct st_my_thread_var *last_thread=
                               keycache->waiting_for_hash_link.last_thread;
    struct st_my_thread_var *first_thread= last_thread->next;
    struct st_my_thread_var *next_thread= first_thread;
1501 1502 1503
    KEYCACHE_PAGE *first_page= (KEYCACHE_PAGE *) (first_thread->opt_info);
    struct st_my_thread_var *thread;

unknown's avatar
unknown committed
1504 1505
    hash_link->file= first_page->file;
    hash_link->diskpos= first_page->filepos;
1506 1507 1508
    do
    {
      KEYCACHE_PAGE *page;
unknown's avatar
unknown committed
1509
      thread= next_thread;
1510
      page= (KEYCACHE_PAGE *) thread->opt_info;
unknown's avatar
unknown committed
1511
      next_thread= thread->next;
1512
      /*
1513 1514 1515 1516 1517
         We notify about the event all threads that ask
         for the same page as the first thread in the queue
      */
      if (page->file == hash_link->file && page->filepos == hash_link->diskpos)
      {
1518
        KEYCACHE_DBUG_PRINT("unlink_hash: signal", ("thread %ld", thread->id));
1519
        keycache_pthread_cond_signal(&thread->suspend);
unknown's avatar
unknown committed
1520
        unlink_from_queue(&keycache->waiting_for_hash_link, thread);
1521 1522 1523
      }
    }
    while (thread != last_thread);
unknown's avatar
unknown committed
1524 1525 1526
    link_hash(&keycache->hash_root[KEYCACHE_HASH(hash_link->file,
					         hash_link->diskpos)],
              hash_link);
1527
    return;
1528
  }
1529 1530 1531
#else /* THREAD */
  KEYCACHE_DBUG_ASSERT(! (keycache->waiting_for_hash_link.last_thread));
#endif /* THREAD */
unknown's avatar
unknown committed
1532 1533
  hash_link->next= keycache->free_hash_list;
  keycache->free_hash_list= hash_link;
1534 1535
}

1536

1537
/*
1538
  Get the hash link for a page
1539
*/
1540

1541
static HASH_LINK *get_hash_link(KEY_CACHE *keycache,
unknown's avatar
unknown committed
1542
                                int file, my_off_t filepos)
1543 1544 1545 1546 1547 1548
{
  reg1 HASH_LINK *hash_link, **start;
#if defined(KEYCACHE_DEBUG)
  int cnt;
#endif

1549
  KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u  pos: %lu",
1550 1551 1552 1553 1554 1555 1556 1557
                      (uint) file,(ulong) filepos));

restart:
  /*
     Find the bucket in the hash table for the pair (file, filepos);
     start contains the head of the bucket list,
     hash_link points to the first member of the list
  */
unknown's avatar
unknown committed
1558
  hash_link= *(start= &keycache->hash_root[KEYCACHE_HASH(file, filepos)]);
1559
#if defined(KEYCACHE_DEBUG)
unknown's avatar
unknown committed
1560
  cnt= 0;
1561 1562 1563 1564 1565 1566 1567 1568
#endif
  /* Look for an element for the pair (file, filepos) in the bucket chain */
  while (hash_link &&
         (hash_link->diskpos != filepos || hash_link->file != file))
  {
    hash_link= hash_link->next;
#if defined(KEYCACHE_DEBUG)
    cnt++;
unknown's avatar
unknown committed
1569
    if (! (cnt <= keycache->hash_links_used))
1570 1571
    {
      int i;
unknown's avatar
unknown committed
1572 1573
      for (i=0, hash_link= *start ;
           i < cnt ; i++, hash_link= hash_link->next)
1574
      {
1575
        KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u  pos: %lu",
1576 1577 1578
            (uint) hash_link->file,(ulong) hash_link->diskpos));
      }
    }
unknown's avatar
unknown committed
1579
    KEYCACHE_DBUG_ASSERT(cnt <= keycache->hash_links_used);
1580 1581 1582
#endif
  }
  if (! hash_link)
1583 1584
  {
    /* There is no hash link in the hash table for the pair (file, filepos) */
unknown's avatar
unknown committed
1585
    if (keycache->free_hash_list)
1586
    {
unknown's avatar
unknown committed
1587
      hash_link= keycache->free_hash_list;
1588
      keycache->free_hash_list= hash_link->next;
1589
    }
unknown's avatar
unknown committed
1590
    else if (keycache->hash_links_used < keycache->hash_links)
1591
    {
unknown's avatar
unknown committed
1592
      hash_link= &keycache->hash_link_root[keycache->hash_links_used++];
1593 1594
    }
    else
1595
    {
1596
#ifdef THREAD
1597
      /* Wait for a free hash link */
unknown's avatar
unknown committed
1598
      struct st_my_thread_var *thread= my_thread_var;
unknown's avatar
unknown committed
1599
      KEYCACHE_PAGE page;
1600
      KEYCACHE_DBUG_PRINT("get_hash_link", ("waiting"));
1601 1602
      page.file= file;
      page.filepos= filepos;
1603
      thread->opt_info= (void *) &page;
unknown's avatar
unknown committed
1604
      link_into_queue(&keycache->waiting_for_hash_link, thread);
1605 1606
      KEYCACHE_DBUG_PRINT("get_hash_link: wait",
                        ("suspend thread %ld", thread->id));
unknown's avatar
unknown committed
1607
      keycache_pthread_cond_wait(&thread->suspend,
unknown's avatar
unknown committed
1608
                                 &keycache->cache_lock);
unknown's avatar
unknown committed
1609
      thread->opt_info= NULL;
1610 1611 1612
#else
      KEYCACHE_DBUG_ASSERT(0);
#endif
1613 1614
      goto restart;
    }
unknown's avatar
unknown committed
1615 1616
    hash_link->file= file;
    hash_link->diskpos= filepos;
1617 1618 1619 1620
    link_hash(start, hash_link);
  }
  /* Register the request for the page */
  hash_link->requests++;
1621

1622 1623 1624 1625 1626
  return hash_link;
}


/*
1627 1628
  Get a block for the file page requested by a keycache read/write operation;
  If the page is not in the cache return a free block, if there is none
1629
  return the lru block after saving its buffer if the page is dirty.
1630

1631 1632 1633
  SYNOPSIS

    find_key_block()
1634
      keycache            pointer to a key cache data structure
1635 1636 1637 1638
      file                handler for the file to read page from
      filepos             position of the page in the file
      init_hits_left      how initialize the block counter for the page
      wrmode              <-> get for writing
1639
      page_st        out  {PAGE_READ,PAGE_TO_BE_READ,PAGE_WAIT_TO_BE_READ}
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650

  RETURN VALUE
    Pointer to the found block if successful, 0 - otherwise

  NOTES.
    For the page from file positioned at filepos the function checks whether
    the page is in the key cache specified by the first parameter.
    If this is the case it immediately returns the block.
    If not, the function first chooses  a block for this page. If there is
    no not used blocks in the key cache yet, the function takes the block
    at the very beginning of the warm sub-chain. It saves the page in that
1651
    block if it's dirty before returning the pointer to it.
1652 1653 1654
    The function returns in the page_st parameter the following values:
      PAGE_READ         - if page already in the block,
      PAGE_TO_BE_READ   - if it is to be read yet by the current thread
1655
      WAIT_TO_BE_READ   - if it is to be read by another thread
1656 1657 1658
    If an error occurs THE BLOCK_ERROR bit is set in the block status.
    It might happen that there are no blocks in LRU chain (in warm part) -
    all blocks  are unlinked for some read/write operations. Then the function
1659
    waits until first of this operations links any block back.
1660 1661
*/

unknown's avatar
unknown committed
1662
static BLOCK_LINK *find_key_block(KEY_CACHE *keycache,
1663 1664
                                  File file, my_off_t filepos,
                                  int init_hits_left,
1665 1666 1667 1668
                                  int wrmode, int *page_st)
{
  HASH_LINK *hash_link;
  BLOCK_LINK *block;
unknown's avatar
unknown committed
1669
  int error= 0;
1670
  int page_status;
1671

1672 1673
  DBUG_ENTER("find_key_block");
  KEYCACHE_THREAD_TRACE("find_key_block:begin");
unknown's avatar
unknown committed
1674 1675 1676 1677 1678
  DBUG_PRINT("enter", ("fd: %d  pos: %lu  wrmode: %d",
                       file, (ulong) filepos, wrmode));
  KEYCACHE_DBUG_PRINT("find_key_block", ("fd: %d  pos: %lu  wrmode: %d",
                                         file, (ulong) filepos,
                                         wrmode));
1679
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
unknown's avatar
unknown committed
1680 1681
  DBUG_EXECUTE("check_keycache2",
               test_key_cache(keycache, "start of find_key_block", 0););
unknown's avatar
unknown committed
1682
#endif
1683

1684
restart:
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
  /*
    If the flush phase of a resize operation fails, the cache is left
    unusable. This will be detected only after "goto restart".
  */
  if (!keycache->can_be_used)
    DBUG_RETURN(0);

  /*
    Find the hash_link for the requested file block (file, filepos). We
    do always get a hash_link here. It has registered our request so
    that no other thread can use it for another file block until we
    release the request (which is done by remove_reader() usually). The
    hash_link can have a block assigned to it or not. If there is a
    block, it may be assigned to this hash_link or not. In cases where a
    block is evicted from the cache, it is taken from the LRU ring and
    referenced by the new hash_link. But the block can still be assigned
    to its old hash_link for some time if it needs to be flushed first,
    or if there are other threads still reading it.

    Summary:
      hash_link is always returned.
      hash_link->block can be:
      - NULL or
      - not assigned to this hash_link or
      - assigned to this hash_link. If assigned, the block can have
        - invalid data (when freshly assigned) or
        - valid data. Valid data can be
          - changed over the file contents (dirty) or
          - not changed (clean).
  */
unknown's avatar
unknown committed
1715
  hash_link= get_hash_link(keycache, file, filepos);
1716
  DBUG_ASSERT((hash_link->file == file) && (hash_link->diskpos == filepos));
1717

unknown's avatar
unknown committed
1718 1719
  page_status= -1;
  if ((block= hash_link->block) &&
1720
      block->hash_link == hash_link && (block->status & BLOCK_READ))
1721 1722
  {
    /* Assigned block with valid (changed or unchanged) contents. */
unknown's avatar
unknown committed
1723
    page_status= PAGE_READ;
1724 1725 1726 1727 1728 1729 1730
  }
  /*
    else (page_status == -1)
      - block == NULL or
      - block not assigned to this hash_link or
      - block assigned but not yet read from file (invalid data).
  */
1731

Joerg Bruehe's avatar
Joerg Bruehe committed
1732
#ifdef THREAD
1733
  if (keycache->in_resize)
unknown's avatar
unknown committed
1734
  {
1735
    /* This is a request during a resize operation */
unknown's avatar
unknown committed
1736

1737
    if (!block)
unknown's avatar
unknown committed
1738
    {
1739 1740 1741 1742 1743 1744 1745 1746 1747
      struct st_my_thread_var *thread;

      /*
        The file block is not in the cache. We don't need it in the
        cache: we are going to read or write directly to file. Cancel
        the request. We can simply decrement hash_link->requests because
        we did not release cache_lock since increasing it. So no other
        thread can wait for our request to become released.
      */
1748
      if (hash_link->requests == 1)
1749 1750 1751 1752 1753
      {
        /*
          We are the only one to request this hash_link (this file/pos).
          Free the hash_link.
        */
1754
        hash_link->requests--;
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        unlink_hash(keycache, hash_link);
        DBUG_RETURN(0);
      }

      /*
        More requests on the hash_link. Someone tries to evict a block
        for this hash_link (could have started before resizing started).
        This means that the LRU ring is empty. Otherwise a block could
        be assigned immediately. Behave like a thread that wants to
        evict a block for this file/pos. Add to the queue of threads
        waiting for a block. Wait until there is one assigned.

        Refresh the request on the hash-link so that it cannot be reused
        for another file/pos.
      */
      thread= my_thread_var;
      thread->opt_info= (void *) hash_link;
      link_into_queue(&keycache->waiting_for_block, thread);
      do
      {
        KEYCACHE_DBUG_PRINT("find_key_block: wait",
                            ("suspend thread %ld", thread->id));
        keycache_pthread_cond_wait(&thread->suspend,
                                   &keycache->cache_lock);
      } while (thread->next);
      thread->opt_info= NULL;
      /*
        A block should now be assigned to the hash_link. But it may
        still need to be evicted. Anyway, we should re-check the
        situation. page_status must be set correctly.
      */
unknown's avatar
unknown committed
1786
      hash_link->requests--;
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
      goto restart;
    } /* end of if (!block) */

    /*
      There is a block for this file/pos in the cache. Register a
      request on it. This unlinks it from the LRU ring (if it is there)
      and hence protects it against eviction (if not already in
      eviction). We need this for returning the block to the caller, for
      calling remove_reader() (for debugging purposes), and for calling
      free_block(). The only case where we don't need the request is if
      the block is in eviction. In that case we have to unregister the
      request later.
    */
    reg_requests(keycache, block, 1);

    if (page_status != PAGE_READ)
    {
      /*
        - block not assigned to this hash_link or
        - block assigned but not yet read from file (invalid data).

        This must be a block in eviction. It will be read soon. We need
        to wait here until this happened. Otherwise the caller could
        access a wrong block or a block which is in read. While waiting
        we cannot lose hash_link nor block. We have registered a request
        on the hash_link. Everything can happen to the block but changes
        in the hash_link -> block relationship. In other words:
        everything can happen to the block but free or another completed
        eviction.

        Note that we bahave like a secondary requestor here. We just
        cannot return with PAGE_WAIT_TO_BE_READ. This would work for
        read requests and writes on dirty blocks that are not in flush
        only. Waiting here on COND_FOR_REQUESTED works in all
        situations.
      */
      DBUG_ASSERT(((block->hash_link != hash_link) &&
                   (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
                  ((block->hash_link == hash_link) &&
                   !(block->status & BLOCK_READ)));
      wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
      /*
        Here we can trust that the block has been assigned to this
        hash_link (block->hash_link == hash_link) and read into the
        buffer (BLOCK_READ). The worst things possible here are that the
        block is in free (BLOCK_REASSIGNED). But the block is still
        assigned to the hash_link. The freeing thread waits until we
        release our request on the hash_link. The block must not be
        again in eviction because we registered an request on it before
        starting to wait.
      */
      DBUG_ASSERT(block->hash_link == hash_link);
      DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
      DBUG_ASSERT(!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)));
unknown's avatar
unknown committed
1841
    }
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
    /*
      The block is in the cache. Assigned to the hash_link. Valid data.
      Note that in case of page_st == PAGE_READ, the block can be marked
      for eviction. In any case it can be marked for freeing.
    */

    if (!wrmode)
    {
      /* A reader can just read the block. */
      *page_st= PAGE_READ;
      DBUG_ASSERT((hash_link->file == file) &&
                  (hash_link->diskpos == filepos) &&
                  (block->hash_link == hash_link));
      DBUG_RETURN(block);
    }

    /*
      This is a writer. No two writers for the same block can exist.
      This must be assured by locks outside of the key cache.
    */
    DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));

    while (block->status & BLOCK_IN_FLUSH)
    {
      /*
        Wait until the block is flushed to file. Do not release the
        request on the hash_link yet to prevent that the block is freed
        or reassigned while we wait. While we wait, several things can
        happen to the block, including another flush. But the block
        cannot be reassigned to another hash_link until we release our
        request on it. But it can be marked BLOCK_REASSIGNED from free
        or eviction, while they wait for us to release the hash_link.
      */
      wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
      /*
        If the flush phase failed, the resize could have finished while
        we waited here.
      */
      if (!keycache->in_resize)
      {
        remove_reader(block);
        unreg_request(keycache, block, 1);
        goto restart;
      }
      DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
      DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
      DBUG_ASSERT(block->hash_link == hash_link);
    }

    if (block->status & BLOCK_CHANGED)
    {
      /*
        We want to write a block with changed contents. If the cache
        block size is bigger than the callers block size (e.g. MyISAM),
        the caller may replace part of the block only. Changes of the
        other part of the block must be preserved. Since the block has
        not yet been selected for flush, we can still add our changes.
      */
      *page_st= PAGE_READ;
      DBUG_ASSERT((hash_link->file == file) &&
                  (hash_link->diskpos == filepos) &&
                  (block->hash_link == hash_link));
      DBUG_RETURN(block);
    }

    /*
      This is a write request for a clean block. We do not want to have
      new dirty blocks in the cache while resizing. We will free the
      block and write directly to file. If the block is in eviction or
      in free, we just let it go.

      Unregister from the hash_link. This must be done before freeing
      the block. And it must be done if not freeing the block. Because
      we could have waited above, we need to call remove_reader(). Other
      threads could wait for us to release our request on the hash_link.
    */
    remove_reader(block);

    /* If the block is not in eviction and not in free, we can free it. */
    if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                           BLOCK_REASSIGNED)))
1923
    {
unknown's avatar
unknown committed
1924
      /*
1925 1926 1927
        Free block as we are going to write directly to file.
        Although we have an exlusive lock for the updated key part,
        the control can be yielded by the current thread as we might
unknown's avatar
unknown committed
1928 1929 1930
        have unfinished readers of other key parts in the block
        buffer. Still we are guaranteed not to have any readers
        of the key part we are writing into until the block is
1931
        removed from the cache as we set the BLOCK_REASSIGNED
1932
        flag (see the code below that handles reading requests).
unknown's avatar
unknown committed
1933
      */
1934
      free_block(keycache, block);
unknown's avatar
unknown committed
1935
    }
1936
    else
unknown's avatar
unknown committed
1937
    {
1938
      /*
1939 1940
        The block will be evicted/freed soon. Don't touch it in any way.
        Unregister the request that we registered above.
1941
      */
1942 1943 1944 1945
      unreg_request(keycache, block, 1);

      /*
        The block is still assigned to the hash_link (the file/pos that
1946
        we are going to write to). Wait until the eviction/free is
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
        complete. Otherwise the direct write could complete before all
        readers are done with the block. So they could read outdated
        data.

        Since we released our request on the hash_link, it can be reused
        for another file/pos. Hence we cannot just check for
        block->hash_link == hash_link. As long as the resize is
        proceeding the block cannot be reassigned to the same file/pos
        again. So we can terminate the loop when the block is no longer
        assigned to this file/pos.
      */
      do
      {
        wait_on_queue(&block->wqueue[COND_FOR_SAVED],
                      &keycache->cache_lock);
        /*
          If the flush phase failed, the resize could have finished
          while we waited here.
        */
        if (!keycache->in_resize)
          goto restart;
      } while (block->hash_link &&
               (block->hash_link->file == file) &&
               (block->hash_link->diskpos == filepos));
unknown's avatar
unknown committed
1971
    }
1972
    DBUG_RETURN(0);
unknown's avatar
unknown committed
1973
  }
1974 1975 1976
#else /* THREAD */
  DBUG_ASSERT(!keycache->in_resize);
#endif
1977

unknown's avatar
unknown committed
1978
  if (page_status == PAGE_READ &&
1979 1980
      (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                        BLOCK_REASSIGNED)))
1981
  {
1982 1983 1984 1985 1986 1987 1988 1989 1990
    /*
      This is a request for a block to be removed from cache. The block
      is assigned to this hash_link and contains valid data, but is
      marked for eviction or to be freed. Possible reasons why it has
      not yet been evicted/freed can be a flush before reassignment
      (BLOCK_IN_SWITCH), readers of the block have not finished yet
      (BLOCK_REASSIGNED), or the evicting thread did not yet awake after
      the block has been selected for it (BLOCK_IN_EVICTION).
    */
unknown's avatar
unknown committed
1991

1992
    KEYCACHE_DBUG_PRINT("find_key_block",
1993 1994 1995
                        ("request for old page in block %u "
                         "wrmode: %d  block->status: %d",
                         BLOCK_NUMBER(block), wrmode, block->status));
1996
    /*
1997 1998 1999 2000
       Only reading requests can proceed until the old dirty page is flushed,
       all others are to be suspended, then resubmitted
    */
    if (!wrmode && !(block->status & BLOCK_REASSIGNED))
2001 2002 2003 2004 2005 2006
    {
      /*
        This is a read request and the block not yet reassigned. We can
        register our request and proceed. This unlinks the block from
        the LRU ring and protects it against eviction.
      */
2007
      reg_requests(keycache, block, 1);
2008
    }
2009 2010
    else
    {
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
      /*
        Either this is a write request for a block that is in eviction
        or in free. We must not use it any more. Instead we must evict
        another block. But we cannot do this before the eviction/free is
        done. Otherwise we would find the same hash_link + block again
        and again.

        Or this is a read request for a block in eviction/free that does
        not require a flush, but waits for readers to finish with the
        block. We do not read this block to let the eviction/free happen
        as soon as possible. Again we must wait so that we don't find
        the same hash_link + block again and again.
      */
      DBUG_ASSERT(hash_link->requests);
2025
      hash_link->requests--;
2026
      KEYCACHE_DBUG_PRINT("find_key_block",
2027
                          ("request waiting for old page to be saved"));
2028
      wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
2029
      KEYCACHE_DBUG_PRINT("find_key_block",
2030
                          ("request for old page resubmitted"));
2031 2032 2033 2034
      /*
        The block is no longer assigned to this hash_link.
        Get another one.
      */
2035 2036 2037 2038
      goto restart;
    }
  }
  else
2039
  {
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    /*
      This is a request for a new block or for a block not to be removed.
      Either
      - block == NULL or
      - block not assigned to this hash_link or
      - block assigned but not yet read from file,
      or
      - block assigned with valid (changed or unchanged) data and
      - it will not be reassigned/freed.
    */
2050
    if (! block)
2051
    {
2052
      /* No block is assigned to the hash_link yet. */
2053
      if (keycache->blocks_unused)
2054
      {
2055 2056 2057 2058 2059 2060 2061 2062 2063
        if (keycache->free_block_list)
        {
          /* There is a block in the free list. */
          block= keycache->free_block_list;
          keycache->free_block_list= block->next_used;
          block->next_used= NULL;
        }
        else
        {
2064
          size_t block_mem_offset;
2065
          /* There are some never used blocks, take first of them */
2066 2067
          DBUG_ASSERT(keycache->blocks_used <
                      (ulong) keycache->disk_blocks);
2068
          block= &keycache->block_root[keycache->blocks_used];
2069 2070
          block_mem_offset= 
           ((size_t) keycache->blocks_used) * keycache->key_cache_block_size;
2071
          block->buffer= ADD_TO_PTR(keycache->block_mem,
2072
                                    block_mem_offset,
2073
                                    uchar*);
2074
          keycache->blocks_used++;
2075
          DBUG_ASSERT(!block->next_used);
2076
        }
2077 2078 2079 2080 2081 2082
        DBUG_ASSERT(!block->prev_used);
        DBUG_ASSERT(!block->next_changed);
        DBUG_ASSERT(!block->prev_changed);
        DBUG_ASSERT(!block->hash_link);
        DBUG_ASSERT(!block->status);
        DBUG_ASSERT(!block->requests);
2083
        keycache->blocks_unused--;
2084
        block->status= BLOCK_IN_USE;
unknown's avatar
unknown committed
2085 2086 2087
        block->length= 0;
        block->offset= keycache->key_cache_block_size;
        block->requests= 1;
2088
        block->temperature= BLOCK_COLD;
2089 2090
        block->hits_left= init_hits_left;
        block->last_hit_time= 0;
unknown's avatar
unknown committed
2091
        block->hash_link= hash_link;
2092
        hash_link->block= block;
2093
        link_to_file_list(keycache, block, file, 0);
unknown's avatar
unknown committed
2094
        page_status= PAGE_TO_BE_READ;
2095
        KEYCACHE_DBUG_PRINT("find_key_block",
2096 2097
                            ("got free or never used block %u",
                             BLOCK_NUMBER(block)));
2098 2099
      }
      else
2100
      {
2101 2102 2103
	/*
          There are no free blocks and no never used blocks, use a block
          from the LRU ring.
2104
        */
2105

2106
#ifdef THREAD
unknown's avatar
unknown committed
2107
        if (! keycache->used_last)
2108
        {
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
          /*
            The LRU ring is empty. Wait until a new block is added to
            it. Several threads might wait here for the same hash_link,
            all of them must get the same block. While waiting for a
            block, after a block is selected for this hash_link, other
            threads can run first before this one awakes. During this
            time interval other threads find this hash_link pointing to
            the block, which is still assigned to another hash_link. In
            this case the block is not marked BLOCK_IN_SWITCH yet, but
            it is marked BLOCK_IN_EVICTION.
          */

unknown's avatar
unknown committed
2121 2122 2123
          struct st_my_thread_var *thread= my_thread_var;
          thread->opt_info= (void *) hash_link;
          link_into_queue(&keycache->waiting_for_block, thread);
2124
          do
2125
          {
2126 2127
            KEYCACHE_DBUG_PRINT("find_key_block: wait",
                                ("suspend thread %ld", thread->id));
unknown's avatar
unknown committed
2128
            keycache_pthread_cond_wait(&thread->suspend,
unknown's avatar
unknown committed
2129
                                       &keycache->cache_lock);
2130 2131
          }
          while (thread->next);
unknown's avatar
unknown committed
2132
          thread->opt_info= NULL;
2133 2134 2135 2136 2137
          /* Assert that block has a request registered. */
          DBUG_ASSERT(hash_link->block->requests);
          /* Assert that block is not in LRU ring. */
          DBUG_ASSERT(!hash_link->block->next_used);
          DBUG_ASSERT(!hash_link->block->prev_used);
2138
        }
2139 2140 2141
#else
        KEYCACHE_DBUG_ASSERT(keycache->used_last);
#endif
2142 2143 2144 2145 2146
        /*
          If we waited above, hash_link->block has been assigned by
          link_block(). Otherwise it is still NULL. In the latter case
          we need to grab a block from the LRU ring ourselves.
        */
unknown's avatar
unknown committed
2147
        block= hash_link->block;
2148 2149
        if (! block)
        {
2150
          /* Select the last block from the LRU ring. */
unknown's avatar
unknown committed
2151
          block= keycache->used_last->next_used;
2152 2153
          block->hits_left= init_hits_left;
          block->last_hit_time= 0;
unknown's avatar
unknown committed
2154
          hash_link->block= block;
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
          /*
            Register a request on the block. This unlinks it from the
            LRU ring and protects it against eviction.
          */
          DBUG_ASSERT(!block->requests);
          reg_requests(keycache, block,1);
          /*
            We do not need to set block->status|= BLOCK_IN_EVICTION here
            because we will set block->status|= BLOCK_IN_SWITCH
            immediately without releasing the lock in between. This does
            also support debugging. When looking at the block, one can
            see if the block has been selected by link_block() after the
            LRU ring was empty, or if it was grabbed directly from the
            LRU ring in this branch.
          */
2170
        }
2171

2172 2173 2174 2175 2176
        /*
          If we had to wait above, there is a small chance that another
          thread grabbed this block for the same file block already. But
          in most cases the first condition is true.
        */
2177 2178 2179 2180
        if (block->hash_link != hash_link &&
	    ! (block->status & BLOCK_IN_SWITCH) )
        {
	  /* this is a primary request for a new page */
2181
          block->status|= BLOCK_IN_SWITCH;
2182 2183

          KEYCACHE_DBUG_PRINT("find_key_block",
unknown's avatar
unknown committed
2184
                        ("got block %u for new page", BLOCK_NUMBER(block)));
2185

2186
          if (block->status & BLOCK_CHANGED)
2187 2188 2189
          {
	    /* The block contains a dirty page - push it out of the cache */

unknown's avatar
unknown committed
2190
            KEYCACHE_DBUG_PRINT("find_key_block", ("block is dirty"));
2191 2192 2193 2194 2195 2196 2197
            if (block->status & BLOCK_IN_FLUSH)
            {
              /*
                The block is marked for flush. If we do not wait here,
                it could happen that we write the block, reassign it to
                another file block, then, before the new owner can read
                the new file block, the flusher writes the cache block
2198
                (which still has the old contents) to the new file block!
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
              */
              wait_on_queue(&block->wqueue[COND_FOR_SAVED],
                            &keycache->cache_lock);
              /*
                The block is marked BLOCK_IN_SWITCH. It should be left
                alone except for reading. No free, no write.
              */
              DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
              DBUG_ASSERT(!(block->status & (BLOCK_REASSIGNED |
                                             BLOCK_CHANGED |
                                             BLOCK_FOR_UPDATE)));
            }
            else
            {
              block->status|= BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE;
              /*
                BLOCK_IN_EVICTION may be true or not. Other flags must
                have a fixed value.
              */
              DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
                          (BLOCK_READ | BLOCK_IN_SWITCH |
                           BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
                           BLOCK_CHANGED | BLOCK_IN_USE));
              DBUG_ASSERT(block->hash_link);
2223

2224 2225 2226 2227 2228 2229
              keycache_pthread_mutex_unlock(&keycache->cache_lock);
              /*
                The call is thread safe because only the current
                thread might change the block->hash_link value
              */
              error= my_pwrite(block->hash_link->file,
2230
                               block->buffer + block->offset,
2231
                               block->length - block->offset,
2232
                               block->hash_link->diskpos + block->offset,
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
                               MYF(MY_NABP | MY_WAIT_IF_FULL));
              keycache_pthread_mutex_lock(&keycache->cache_lock);

              /* Block status must not have changed. */
              DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
                          (BLOCK_READ | BLOCK_IN_SWITCH |
                           BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
                           BLOCK_CHANGED | BLOCK_IN_USE) || fail_block(block));
              keycache->global_cache_write++;
            }
2243
          }
2244

unknown's avatar
unknown committed
2245
          block->status|= BLOCK_REASSIGNED;
2246 2247 2248 2249 2250
          /*
            The block comes from the LRU ring. It must have a hash_link
            assigned.
          */
          DBUG_ASSERT(block->hash_link);
2251 2252
          if (block->hash_link)
          {
2253
            /*
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
              All pending requests for this page must be resubmitted.
              This must be done before waiting for readers. They could
              wait for the flush to complete. And we must also do it
              after the wait. Flushers might try to free the block while
              we wait. They would wait until the reassignment is
              complete. Also the block status must reflect the correct
              situation: The block is not changed nor in flush any more.
              Note that we must not change the BLOCK_CHANGED flag
              outside of link_to_file_list() so that it is always in the
              correct queue and the *blocks_changed counters are
              correct.
            */
            block->status&= ~(BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE);
            link_to_file_list(keycache, block, block->hash_link->file, 1);
            release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
            /*
              The block is still assigned to its old hash_link.
2271 2272 2273 2274
	      Wait until all pending read requests
	      for this page are executed
	      (we could have avoided this waiting, if we had read
	      a page in the cache in a sweep, without yielding control)
2275
            */
unknown's avatar
unknown committed
2276
            wait_for_readers(keycache, block);
2277 2278 2279 2280 2281 2282 2283
            DBUG_ASSERT(block->hash_link && block->hash_link->block == block &&
                        block->prev_changed);
            /* The reader must not have been a writer. */
            DBUG_ASSERT(!(block->status & BLOCK_CHANGED));

            /* Wake flushers that might have found the block in between. */
            release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
2284

2285
            /* Remove the hash link for the old file block from the hash. */
unknown's avatar
unknown committed
2286
            unlink_hash(keycache, block->hash_link);
2287 2288 2289 2290 2291 2292 2293 2294 2295

            /*
              For sanity checks link_to_file_list() asserts that block
              and hash_link refer to each other. Hence we need to assign
              the hash_link first, but then we would not know if it was
              linked before. Hence we would not know if to unlink it. So
              unlink it here and call link_to_file_list(..., FALSE).
            */
            unlink_changed(block);
2296
          }
2297
          block->status= error ? BLOCK_ERROR : BLOCK_IN_USE ;
unknown's avatar
unknown committed
2298 2299 2300
          block->length= 0;
          block->offset= keycache->key_cache_block_size;
          block->hash_link= hash_link;
2301
          link_to_file_list(keycache, block, file, 0);
unknown's avatar
unknown committed
2302
          page_status= PAGE_TO_BE_READ;
2303

2304 2305 2306 2307 2308
          KEYCACHE_DBUG_ASSERT(block->hash_link->block == block);
          KEYCACHE_DBUG_ASSERT(hash_link->block->hash_link == hash_link);
        }
        else
        {
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
          /*
            Either (block->hash_link == hash_link),
	    or     (block->status & BLOCK_IN_SWITCH).

            This is for secondary requests for a new file block only.
            Either it is already assigned to the new hash_link meanwhile
            (if we had to wait due to empty LRU), or it is already in
            eviction by another thread. Since this block has been
            grabbed from the LRU ring and attached to this hash_link,
            another thread cannot grab the same block from the LRU ring
            anymore. If the block is in eviction already, it must become
            attached to the same hash_link and as such destined for the
            same file block.
          */
2323 2324 2325 2326 2327 2328 2329
          KEYCACHE_DBUG_PRINT("find_key_block",
                              ("block->hash_link: %p  hash_link: %p  "
                               "block->status: %u", block->hash_link,
                               hash_link, block->status ));
          page_status= (((block->hash_link == hash_link) &&
                         (block->status & BLOCK_READ)) ?
                        PAGE_READ : PAGE_WAIT_TO_BE_READ);
2330 2331 2332 2333 2334
        }
      }
    }
    else
    {
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
      /*
        Block is not NULL. This hash_link points to a block.
        Either
        - block not assigned to this hash_link (yet) or
        - block assigned but not yet read from file,
        or
        - block assigned with valid (changed or unchanged) data and
        - it will not be reassigned/freed.

        The first condition means hash_link points to a block in
        eviction. This is not necessarily marked by BLOCK_IN_SWITCH yet.
        But then it is marked BLOCK_IN_EVICTION. See the NOTE in
        link_block(). In both cases it is destined for this hash_link
        and its file block address. When this hash_link got its block
        address, the block was removed from the LRU ring and cannot be
        selected for eviction (for another hash_link) again.

        Register a request on the block. This is another protection
        against eviction.
      */
      DBUG_ASSERT(((block->hash_link != hash_link) &&
                   (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
                  ((block->hash_link == hash_link) &&
                   !(block->status & BLOCK_READ)) ||
                  ((block->status & BLOCK_READ) &&
                   !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))));
unknown's avatar
unknown committed
2361
      reg_requests(keycache, block, 1);
2362 2363 2364 2365 2366 2367 2368
      KEYCACHE_DBUG_PRINT("find_key_block",
                          ("block->hash_link: %p  hash_link: %p  "
                           "block->status: %u", block->hash_link,
                           hash_link, block->status ));
      page_status= (((block->hash_link == hash_link) &&
                     (block->status & BLOCK_READ)) ?
                    PAGE_READ : PAGE_WAIT_TO_BE_READ);
2369 2370
    }
  }
2371

2372
  KEYCACHE_DBUG_ASSERT(page_status != -1);
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
  /* Same assert basically, but be very sure. */
  KEYCACHE_DBUG_ASSERT(block);
  /* Assert that block has a request and is not in LRU ring. */
  DBUG_ASSERT(block->requests);
  DBUG_ASSERT(!block->next_used);
  DBUG_ASSERT(!block->prev_used);
  /* Assert that we return the correct block. */
  DBUG_ASSERT((page_status == PAGE_WAIT_TO_BE_READ) ||
              ((block->hash_link->file == file) &&
               (block->hash_link->diskpos == filepos)));
2383
  *page_st=page_status;
unknown's avatar
unknown committed
2384
  KEYCACHE_DBUG_PRINT("find_key_block",
2385
                      ("fd: %d  pos: %lu  block->status: %u  page_status: %d",
unknown's avatar
unknown committed
2386
                       file, (ulong) filepos, block->status,
2387
                       page_status));
2388

2389
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
unknown's avatar
unknown committed
2390 2391
  DBUG_EXECUTE("check_keycache2",
               test_key_cache(keycache, "end of find_key_block",0););
2392 2393 2394 2395
#endif
  KEYCACHE_THREAD_TRACE("find_key_block:end");
  DBUG_RETURN(block);
}
unknown's avatar
unknown committed
2396 2397


2398
/*
2399 2400 2401 2402 2403
  Read into a key cache block buffer from disk.

  SYNOPSIS

    read_block()
2404
      keycache            pointer to a key cache data structure
2405
      block               block to which buffer the data is to be read
2406 2407 2408 2409
      read_length         size of data to be read
      min_length          at least so much data must be read
      primary             <-> the current thread will read the data

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
  RETURN VALUE
    None

  NOTES.
    The function either reads a page data from file to the block buffer,
    or waits until another thread reads it. What page to read is determined
    by a block parameter - reference to a hash link for this page.
    If an error occurs THE BLOCK_ERROR bit is set in the block status.
    We do not report error when the size of successfully read
    portion is less than read_length, but not less than min_length.
2420
*/
2421

2422
static void read_block(KEY_CACHE *keycache,
unknown's avatar
unknown committed
2423
                       BLOCK_LINK *block, uint read_length,
2424 2425
                       uint min_length, my_bool primary)
{
2426
  size_t got_length;
2427

unknown's avatar
unknown committed
2428
  /* On entry cache_lock is locked */
2429

2430 2431
  KEYCACHE_THREAD_TRACE("read_block");
  if (primary)
2432 2433
  {
    /*
2434 2435 2436 2437
      This code is executed only by threads that submitted primary
      requests. Until block->status contains BLOCK_READ, all other
      request for the block become secondary requests. For a primary
      request the block must be properly initialized.
2438
    */
2439 2440 2441 2442 2443 2444
    DBUG_ASSERT(((block->status & ~BLOCK_FOR_UPDATE) == BLOCK_IN_USE) ||
                fail_block(block));
    DBUG_ASSERT((block->length == 0) || fail_block(block));
    DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
                fail_block(block));
    DBUG_ASSERT((block->requests > 0) || fail_block(block));
2445 2446

    KEYCACHE_DBUG_PRINT("read_block",
2447
                        ("page to be read by primary request"));
2448

2449
    keycache->global_cache_read++;
2450
    /* Page is not in buffer yet, is to be read from disk */
unknown's avatar
unknown committed
2451
    keycache_pthread_mutex_unlock(&keycache->cache_lock);
2452 2453 2454 2455
    /*
      Here other threads may step in and register as secondary readers.
      They will register in block->wqueue[COND_FOR_REQUESTED].
    */
unknown's avatar
unknown committed
2456 2457
    got_length= my_pread(block->hash_link->file, block->buffer,
                         read_length, block->hash_link->diskpos, MYF(0));
unknown's avatar
unknown committed
2458
    keycache_pthread_mutex_lock(&keycache->cache_lock);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
    /*
      The block can now have been marked for free (in case of
      FLUSH_RELEASE). Otherwise the state must be unchanged.
    */
    DBUG_ASSERT(((block->status & ~(BLOCK_REASSIGNED |
                                    BLOCK_FOR_UPDATE)) == BLOCK_IN_USE) ||
                fail_block(block));
    DBUG_ASSERT((block->length == 0) || fail_block(block));
    DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
                fail_block(block));
    DBUG_ASSERT((block->requests > 0) || fail_block(block));

2471
    if (got_length < min_length)
unknown's avatar
unknown committed
2472
      block->status|= BLOCK_ERROR;
2473 2474
    else
    {
2475
      block->status|= BLOCK_READ;
unknown's avatar
unknown committed
2476
      block->length= got_length;
2477 2478 2479 2480 2481 2482
      /*
        Do not set block->offset here. If this block is marked
        BLOCK_CHANGED later, we want to flush only the modified part. So
        only a writer may set block->offset down from
        keycache->key_cache_block_size.
      */
2483
    }
2484
    KEYCACHE_DBUG_PRINT("read_block",
2485 2486
                        ("primary request: new page in cache"));
    /* Signal that all pending requests for this page now can be processed */
2487
    release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
2488
  }
2489 2490 2491
  else
  {
    /*
2492 2493 2494 2495 2496 2497 2498
      This code is executed only by threads that submitted secondary
      requests. At this point it could happen that the cache block is
      not yet assigned to the hash_link for the requested file block.
      But at awake from the wait this should be the case. Unfortunately
      we cannot assert this here because we do not know the hash_link
      for the requested file block nor the file and position. So we have
      to assert this in the caller.
2499
    */
2500
    KEYCACHE_DBUG_PRINT("read_block",
2501
                      ("secondary request waiting for new page to be read"));
2502
    wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
2503
    KEYCACHE_DBUG_PRINT("read_block",
2504 2505 2506 2507 2508 2509
                        ("secondary request: new page in cache"));
  }
}


/*
2510
  Read a block of data from a cached file into a buffer;
2511 2512 2513 2514

  SYNOPSIS

    key_cache_read()
2515
      keycache            pointer to a key cache data structure
2516 2517 2518
      file                handler for the file for the block of data to be read
      filepos             position of the block of data in the file
      level               determines the weight of the data
2519
      buff                buffer to where the data must be placed
2520
      length              length of the buffer
2521 2522 2523
      block_length        length of the block in the key cache buffer
      return_buffer       return pointer to the key cache buffer with the data

2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
  RETURN VALUE
    Returns address from where the data is placed if sucessful, 0 - otherwise.

  NOTES.
    The function ensures that a block of data of size length from file
    positioned at filepos is in the buffers for some key cache blocks.
    Then the function either copies the data into the buffer buff, or,
    if return_buffer is TRUE, it just returns the pointer to the key cache
    buffer with the data.
    Filepos must be a multiple of 'block_length', but it doesn't
    have to be a multiple of key_cache_block_size;
2535
*/
unknown's avatar
unknown committed
2536

2537
uchar *key_cache_read(KEY_CACHE *keycache,
2538 2539 2540 2541
                      File file, my_off_t filepos, int level,
                      uchar *buff, uint length,
                      uint block_length __attribute__((unused)),
                      int return_buffer __attribute__((unused)))
unknown's avatar
unknown committed
2542
{
2543
  my_bool locked_and_incremented= FALSE;
unknown's avatar
unknown committed
2544
  int error=0;
2545
  uchar *start= buff;
unknown's avatar
unknown committed
2546
  DBUG_ENTER("key_cache_read");
2547
  DBUG_PRINT("enter", ("fd: %u  pos: %lu  length: %u",
2548
               (uint) file, (ulong) filepos, length));
2549

2550
  if (keycache->key_cache_inited)
2551 2552
  {
    /* Key cache is used */
2553
    reg1 BLOCK_LINK *block;
unknown's avatar
unknown committed
2554
    uint read_length;
2555
    uint offset;
2556
    int page_st;
2557

2558
    /*
2559 2560 2561 2562
      When the key cache is once initialized, we use the cache_lock to
      reliably distinguish the cases of normal operation, resizing, and
      disabled cache. We always increment and decrement
      'cnt_for_resize_op' so that a resizer can wait for pending I/O.
2563
    */
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
    keycache_pthread_mutex_lock(&keycache->cache_lock);
    /*
      Cache resizing has two phases: Flushing and re-initializing. In
      the flush phase read requests are allowed to bypass the cache for
      blocks not in the cache. find_key_block() returns NULL in this
      case.

      After the flush phase new I/O requests must wait until the
      re-initialization is done. The re-initialization can be done only
      if no I/O request is in progress. The reason is that
      key_cache_block_size can change. With enabled cache, I/O is done
      in chunks of key_cache_block_size. Every chunk tries to use a
      cache block first. If the block size changes in the middle, a
      block could be missed and old data could be read.
    */
    while (keycache->in_resize && !keycache->resize_in_flush)
      wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
    /* Register the I/O for the next resize. */
    inc_counter_for_resize_op(keycache);
2583
    locked_and_incremented= TRUE;
2584
    /* Requested data may not always be aligned to cache blocks. */
2585
    offset= (uint) (filepos % keycache->key_cache_block_size);
2586
    /* Read data in key_cache_block_size increments */
unknown's avatar
unknown committed
2587 2588
    do
    {
2589
      /* Cache could be disabled in a later iteration. */
2590
      if (!keycache->can_be_used)
unknown's avatar
unknown committed
2591
      {
2592 2593
        KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache cannot be used"));
        goto no_key_cache;
unknown's avatar
unknown committed
2594
      }
2595
      /* Start reading at the beginning of the cache block. */
unknown's avatar
unknown committed
2596
      filepos-= offset;
2597
      /* Do not read beyond the end of the cache block. */
unknown's avatar
unknown committed
2598 2599 2600 2601
      read_length= length;
      set_if_smaller(read_length, keycache->key_cache_block_size-offset);
      KEYCACHE_DBUG_ASSERT(read_length > 0);

unknown's avatar
unknown committed
2602 2603 2604 2605 2606
#ifndef THREAD
      if (block_length > keycache->key_cache_block_size || offset)
	return_buffer=0;
#endif

2607
      /* Request the cache block that matches file/pos. */
unknown's avatar
unknown committed
2608
      keycache->global_cache_r_requests++;
2609
      block=find_key_block(keycache, file, filepos, level, 0, &page_st);
2610
      if (!block)
2611 2612
      {
        /*
2613 2614 2615
          This happens only for requests submitted during key cache
          resize. The block is not in the cache and shall not go in.
          Read directly from file.
2616
        */
2617 2618
        keycache->global_cache_read++;
        keycache_pthread_mutex_unlock(&keycache->cache_lock);
2619
        error= (my_pread(file, (uchar*) buff, read_length,
2620
                         filepos + offset, MYF(MY_NABP)) != 0);
2621 2622 2623
        keycache_pthread_mutex_lock(&keycache->cache_lock);
        goto next_block;
      }
2624
      if (!(block->status & BLOCK_ERROR))
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
      {
        if (page_st != PAGE_READ)
        {
          /* The requested page is to be read into the block buffer */
          read_block(keycache, block,
                     keycache->key_cache_block_size, read_length+offset,
                     (my_bool)(page_st == PAGE_TO_BE_READ));
          /*
            A secondary request must now have the block assigned to the
            requested file block. It does not hurt to check it for
            primary requests too.
          */
          DBUG_ASSERT(keycache->can_be_used);
          DBUG_ASSERT(block->hash_link->file == file);
          DBUG_ASSERT(block->hash_link->diskpos == filepos);
          DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
        }
        else if (block->length < read_length + offset)
        {
          /*
            Impossible if nothing goes wrong:
            this could only happen if we are using a file with
            small key blocks and are trying to read outside the file
          */
          my_errno= -1;
          block->status|= BLOCK_ERROR;
        }
unknown's avatar
unknown committed
2652
      }
2653

2654
      /* block status may have added BLOCK_ERROR in the above 'if'. */
2655
      if (!(block->status & BLOCK_ERROR))
unknown's avatar
unknown committed
2656
      {
2657
#ifndef THREAD
2658
        if (! return_buffer)
2659 2660
#endif
        {
2661
          DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2662
#if !defined(SERIALIZED_READ_FROM_CACHE)
unknown's avatar
unknown committed
2663
          keycache_pthread_mutex_unlock(&keycache->cache_lock);
2664
#endif
2665

2666 2667
          /* Copy data from the cache buffer */
          if (!(read_length & 511))
unknown's avatar
unknown committed
2668
            bmove512(buff, block->buffer+offset, read_length);
2669
          else
unknown's avatar
unknown committed
2670
            memcpy(buff, block->buffer+offset, (size_t) read_length);
2671 2672

#if !defined(SERIALIZED_READ_FROM_CACHE)
unknown's avatar
unknown committed
2673
          keycache_pthread_mutex_lock(&keycache->cache_lock);
2674
          DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2675 2676
#endif
        }
unknown's avatar
unknown committed
2677
      }
2678

2679
      remove_reader(block);
2680

2681 2682 2683
      /* Error injection for coverage testing. */
      DBUG_EXECUTE_IF("key_cache_read_block_error",
                      block->status|= BLOCK_ERROR;);
2684

2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
      /* Do not link erroneous blocks into the LRU ring, but free them. */
      if (!(block->status & BLOCK_ERROR))
      {
        /*
          Link the block into the LRU ring if it's the last submitted
          request for the block. This enables eviction for the block.
        */
        unreg_request(keycache, block, 1);
      }
      else
2695
      {
2696
        free_block(keycache, block);
2697 2698 2699
        error= 1;
        break;
      }
2700

2701
#ifndef THREAD
unknown's avatar
unknown committed
2702
      /* This is only true if we where able to read everything in one block */
2703
      if (return_buffer)
2704
	DBUG_RETURN(block->buffer);
unknown's avatar
unknown committed
2705
#endif
2706
    next_block:
unknown's avatar
unknown committed
2707
      buff+= read_length;
unknown's avatar
unknown committed
2708
      filepos+= read_length+offset;
unknown's avatar
unknown committed
2709
      offset= 0;
2710

unknown's avatar
unknown committed
2711
    } while ((length-= read_length));
2712
    goto end;
unknown's avatar
unknown committed
2713
  }
2714
  KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache not initialized"));
2715

2716 2717
no_key_cache:
  /* Key cache is not used */
unknown's avatar
unknown committed
2718 2719 2720

  keycache->global_cache_r_requests++;
  keycache->global_cache_read++;
2721

2722
  if (locked_and_incremented)
2723
    keycache_pthread_mutex_unlock(&keycache->cache_lock);
2724
  if (my_pread(file, (uchar*) buff, length, filepos, MYF(MY_NABP)))
unknown's avatar
unknown committed
2725
    error= 1;
2726
  if (locked_and_incremented)
2727 2728 2729
    keycache_pthread_mutex_lock(&keycache->cache_lock);

end:
2730
  if (locked_and_incremented)
2731 2732 2733 2734
  {
    dec_counter_for_resize_op(keycache);
    keycache_pthread_mutex_unlock(&keycache->cache_lock);
  }
2735
  DBUG_PRINT("exit", ("error: %d", error ));
2736
  DBUG_RETURN(error ? (uchar*) 0 : start);
2737
}
unknown's avatar
unknown committed
2738 2739


unknown's avatar
unknown committed
2740 2741 2742 2743
/*
  Insert a block of file data from a buffer into key cache

  SYNOPSIS
2744
    key_cache_insert()
unknown's avatar
unknown committed
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
    keycache            pointer to a key cache data structure
    file                handler for the file to insert data from
    filepos             position of the block of data in the file to insert
    level               determines the weight of the data
    buff                buffer to read data from
    length              length of the data in the buffer

  NOTES
    This is used by MyISAM to move all blocks from a index file to the key
    cache
2755

unknown's avatar
unknown committed
2756
  RETURN VALUE
2757
    0 if a success, 1 - otherwise.
unknown's avatar
unknown committed
2758 2759
*/

unknown's avatar
unknown committed
2760
int key_cache_insert(KEY_CACHE *keycache,
2761
                     File file, my_off_t filepos, int level,
2762
                     uchar *buff, uint length)
unknown's avatar
unknown committed
2763
{
2764
  int error= 0;
unknown's avatar
unknown committed
2765
  DBUG_ENTER("key_cache_insert");
2766
  DBUG_PRINT("enter", ("fd: %u  pos: %lu  length: %u",
unknown's avatar
unknown committed
2767 2768
               (uint) file,(ulong) filepos, length));

2769
  if (keycache->key_cache_inited)
unknown's avatar
unknown committed
2770 2771 2772 2773
  {
    /* Key cache is used */
    reg1 BLOCK_LINK *block;
    uint read_length;
unknown's avatar
unknown committed
2774
    uint offset;
2775
    int page_st;
2776
    my_bool locked_and_incremented= FALSE;
unknown's avatar
unknown committed
2777

2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
    /*
      When the keycache is once initialized, we use the cache_lock to
      reliably distinguish the cases of normal operation, resizing, and
      disabled cache. We always increment and decrement
      'cnt_for_resize_op' so that a resizer can wait for pending I/O.
    */
    keycache_pthread_mutex_lock(&keycache->cache_lock);
    /*
      We do not load index data into a disabled cache nor into an
      ongoing resize.
    */
    if (!keycache->can_be_used || keycache->in_resize)
	goto no_key_cache;
    /* Register the pseudo I/O for the next resize. */
    inc_counter_for_resize_op(keycache);
2793
    locked_and_incremented= TRUE;
2794
    /* Loaded data may not always be aligned to cache blocks. */
2795
    offset= (uint) (filepos % keycache->key_cache_block_size);
2796
    /* Load data in key_cache_block_size increments. */
unknown's avatar
unknown committed
2797 2798
    do
    {
2799 2800 2801 2802
      /* Cache could be disabled or resizing in a later iteration. */
      if (!keycache->can_be_used || keycache->in_resize)
	goto no_key_cache;
      /* Start loading at the beginning of the cache block. */
unknown's avatar
unknown committed
2803
      filepos-= offset;
2804
      /* Do not load beyond the end of the cache block. */
unknown's avatar
unknown committed
2805 2806 2807
      read_length= length;
      set_if_smaller(read_length, keycache->key_cache_block_size-offset);
      KEYCACHE_DBUG_ASSERT(read_length > 0);
unknown's avatar
unknown committed
2808

2809 2810 2811
      /* The block has been read by the caller already. */
      keycache->global_cache_read++;
      /* Request the cache block that matches file/pos. */
unknown's avatar
unknown committed
2812
      keycache->global_cache_r_requests++;
2813
      block= find_key_block(keycache, file, filepos, level, 0, &page_st);
2814
      if (!block)
unknown's avatar
unknown committed
2815
      {
2816
        /*
2817 2818 2819
          This happens only for requests submitted during key cache
          resize. The block is not in the cache and shall not go in.
          Stop loading index data.
2820
        */
2821 2822
        goto no_key_cache;
      }
2823
      if (!(block->status & BLOCK_ERROR))
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
      {
        if ((page_st == PAGE_WAIT_TO_BE_READ) ||
            ((page_st == PAGE_TO_BE_READ) &&
             (offset || (read_length < keycache->key_cache_block_size))))
        {
          /*
            Either

            this is a secondary request for a block to be read into the
            cache. The block is in eviction. It is not yet assigned to
            the requested file block (It does not point to the right
            hash_link). So we cannot call remove_reader() on the block.
            And we cannot access the hash_link directly here. We need to
            wait until the assignment is complete. read_block() executes
            the correct wait when called with primary == FALSE.

            Or

            this is a primary request for a block to be read into the
            cache and the supplied data does not fill the whole block.

            This function is called on behalf of a LOAD INDEX INTO CACHE
            statement, which is a read-only task and allows other
            readers. It is possible that a parallel running reader tries
            to access this block. If it needs more data than has been
            supplied here, it would report an error. To be sure that we
            have all data in the block that is available in the file, we
            read the block ourselves.

            Though reading again what the caller did read already is an
            expensive operation, we need to do this for correctness.
          */
          read_block(keycache, block, keycache->key_cache_block_size,
                     read_length + offset, (page_st == PAGE_TO_BE_READ));
          /*
            A secondary request must now have the block assigned to the
            requested file block. It does not hurt to check it for
            primary requests too.
          */
          DBUG_ASSERT(keycache->can_be_used);
          DBUG_ASSERT(block->hash_link->file == file);
          DBUG_ASSERT(block->hash_link->diskpos == filepos);
          DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
        }
        else if (page_st == PAGE_TO_BE_READ)
        {
          /*
            This is a new block in the cache. If we come here, we have
            data for the whole block.
          */
          DBUG_ASSERT(block->hash_link->requests);
          DBUG_ASSERT(block->status & BLOCK_IN_USE);
          DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
                      (block->status & BLOCK_READ));
2878

2879 2880 2881 2882 2883 2884
#if !defined(SERIALIZED_READ_FROM_CACHE)
          keycache_pthread_mutex_unlock(&keycache->cache_lock);
          /*
            Here other threads may step in and register as secondary readers.
            They will register in block->wqueue[COND_FOR_REQUESTED].
          */
unknown's avatar
unknown committed
2885 2886
#endif

2887 2888 2889 2890 2891
          /* Copy data from buff */
          if (!(read_length & 511))
            bmove512(block->buffer+offset, buff, read_length);
          else
            memcpy(block->buffer+offset, buff, (size_t) read_length);
unknown's avatar
unknown committed
2892 2893

#if !defined(SERIALIZED_READ_FROM_CACHE)
2894 2895 2896 2897
          keycache_pthread_mutex_lock(&keycache->cache_lock);
          DBUG_ASSERT(block->status & BLOCK_IN_USE);
          DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
                      (block->status & BLOCK_READ));
unknown's avatar
unknown committed
2898
#endif
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
          /*
            After the data is in the buffer, we can declare the block
            valid. Now other threads do not need to register as
            secondary readers any more. They can immediately access the
            block.
          */
          block->status|= BLOCK_READ;
          block->length= read_length+offset;
          /*
            Do not set block->offset here. If this block is marked
            BLOCK_CHANGED later, we want to flush only the modified part. So
            only a writer may set block->offset down from
            keycache->key_cache_block_size.
          */
          KEYCACHE_DBUG_PRINT("key_cache_insert",
                              ("primary request: new page in cache"));
          /* Signal all pending requests. */
          release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
        }
        else
        {
          /*
            page_st == PAGE_READ. The block is in the buffer. All data
            must already be present. Blocks are always read with all
            data available on file. Assert that the block does not have
            less contents than the preloader supplies. If the caller has
            data beyond block->length, it means that a file write has
            been done while this block was in cache and not extended
            with the new data. If the condition is met, we can simply
            ignore the block.
          */
          DBUG_ASSERT((page_st == PAGE_READ) &&
                      (read_length + offset <= block->length));
        }

        /*
          A secondary request must now have the block assigned to the
          requested file block. It does not hurt to check it for primary
          requests too.
        */
        DBUG_ASSERT(block->hash_link->file == file);
        DBUG_ASSERT(block->hash_link->diskpos == filepos);
        DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
2942
      } /* end of if (!(block->status & BLOCK_ERROR)) */
unknown's avatar
unknown committed
2943 2944

      remove_reader(block);
2945

2946 2947 2948
      /* Error injection for coverage testing. */
      DBUG_EXECUTE_IF("key_cache_insert_block_error",
                      block->status|= BLOCK_ERROR; errno=EIO;);
unknown's avatar
unknown committed
2949

2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
      /* Do not link erroneous blocks into the LRU ring, but free them. */
      if (!(block->status & BLOCK_ERROR))
      {
        /*
          Link the block into the LRU ring if it's the last submitted
          request for the block. This enables eviction for the block.
        */
        unreg_request(keycache, block, 1);
      }
      else
      {
        free_block(keycache, block);
        error= 1;
2963
        break;
2964
      }
unknown's avatar
unknown committed
2965

unknown's avatar
unknown committed
2966
      buff+= read_length;
unknown's avatar
unknown committed
2967
      filepos+= read_length+offset;
unknown's avatar
unknown committed
2968
      offset= 0;
unknown's avatar
unknown committed
2969 2970

    } while ((length-= read_length));
2971 2972

  no_key_cache:
2973
    if (locked_and_incremented)
2974 2975
      dec_counter_for_resize_op(keycache);
    keycache_pthread_mutex_unlock(&keycache->cache_lock);
unknown's avatar
unknown committed
2976
  }
2977
  DBUG_RETURN(error);
unknown's avatar
unknown committed
2978 2979 2980
}


2981
/*
2982 2983
  Write a buffer into a cached file.

2984 2985 2986
  SYNOPSIS

    key_cache_write()
2987
      keycache            pointer to a key cache data structure
2988 2989 2990
      file                handler for the file to write data to
      filepos             position in the file to write data to
      level               determines the weight of the data
2991
      buff                buffer with the data
2992 2993
      length              length of the buffer
      dont_write          if is 0 then all dirty pages involved in writing
2994 2995
                          should have been flushed from key cache

2996 2997 2998 2999 3000 3001 3002
  RETURN VALUE
    0 if a success, 1 - otherwise.

  NOTES.
    The function copies the data of size length from buff into buffers
    for key cache blocks that are  assigned to contain the portion of
    the file starting with position filepos.
3003
    It ensures that this data is flushed to the file if dont_write is FALSE.
3004 3005
    Filepos must be a multiple of 'block_length', but it doesn't
    have to be a multiple of key_cache_block_size;
3006 3007

    dont_write is always TRUE in the server (info->lock_type is never F_UNLCK).
3008
*/
3009

unknown's avatar
unknown committed
3010
int key_cache_write(KEY_CACHE *keycache,
3011
                    File file, my_off_t filepos, int level,
3012
                    uchar *buff, uint length,
3013 3014
                    uint block_length  __attribute__((unused)),
                    int dont_write)
unknown's avatar
unknown committed
3015
{
3016
  my_bool locked_and_incremented= FALSE;
unknown's avatar
unknown committed
3017
  int error=0;
unknown's avatar
unknown committed
3018
  DBUG_ENTER("key_cache_write");
3019
  DBUG_PRINT("enter",
3020 3021 3022 3023
             ("fd: %u  pos: %lu  length: %u  block_length: %u"
              "  key_block_length: %u",
              (uint) file, (ulong) filepos, length, block_length,
              keycache ? keycache->key_cache_block_size : 0));
unknown's avatar
unknown committed
3024 3025

  if (!dont_write)
3026
  {
3027 3028 3029 3030
    /* purecov: begin inspected */
    /* Not used in the server. */
    /* Force writing from buff into disk. */
    keycache->global_cache_w_requests++;
unknown's avatar
unknown committed
3031
    keycache->global_cache_write++;
unknown's avatar
unknown committed
3032
    if (my_pwrite(file, buff, length, filepos, MYF(MY_NABP | MY_WAIT_IF_FULL)))
unknown's avatar
unknown committed
3033
      DBUG_RETURN(1);
3034
    /* purecov: end */
unknown's avatar
unknown committed
3035
  }
3036

unknown's avatar
unknown committed
3037
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
unknown's avatar
unknown committed
3038 3039
  DBUG_EXECUTE("check_keycache",
               test_key_cache(keycache, "start of key_cache_write", 1););
unknown's avatar
unknown committed
3040
#endif
3041

3042
  if (keycache->key_cache_inited)
3043 3044
  {
    /* Key cache is used */
3045
    reg1 BLOCK_LINK *block;
unknown's avatar
unknown committed
3046
    uint read_length;
unknown's avatar
unknown committed
3047
    uint offset;
3048
    int page_st;
3049

3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
    /*
      When the key cache is once initialized, we use the cache_lock to
      reliably distinguish the cases of normal operation, resizing, and
      disabled cache. We always increment and decrement
      'cnt_for_resize_op' so that a resizer can wait for pending I/O.
    */
    keycache_pthread_mutex_lock(&keycache->cache_lock);
    /*
      Cache resizing has two phases: Flushing and re-initializing. In
      the flush phase write requests can modify dirty blocks that are
      not yet in flush. Otherwise they are allowed to bypass the cache.
      find_key_block() returns NULL in both cases (clean blocks and
      non-cached blocks).

      After the flush phase new I/O requests must wait until the
      re-initialization is done. The re-initialization can be done only
      if no I/O request is in progress. The reason is that
      key_cache_block_size can change. With enabled cache I/O is done in
      chunks of key_cache_block_size. Every chunk tries to use a cache
      block first. If the block size changes in the middle, a block
      could be missed and data could be written below a cached block.
    */
    while (keycache->in_resize && !keycache->resize_in_flush)
      wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
    /* Register the I/O for the next resize. */
    inc_counter_for_resize_op(keycache);
3076
    locked_and_incremented= TRUE;
3077
    /* Requested data may not always be aligned to cache blocks. */
3078
    offset= (uint) (filepos % keycache->key_cache_block_size);
3079
    /* Write data in key_cache_block_size increments. */
unknown's avatar
unknown committed
3080 3081
    do
    {
3082
      /* Cache could be disabled in a later iteration. */
3083
      if (!keycache->can_be_used)
unknown's avatar
unknown committed
3084
	goto no_key_cache;
3085
      /* Start writing at the beginning of the cache block. */
unknown's avatar
unknown committed
3086
      filepos-= offset;
3087
      /* Do not write beyond the end of the cache block. */
unknown's avatar
unknown committed
3088 3089 3090
      read_length= length;
      set_if_smaller(read_length, keycache->key_cache_block_size-offset);
      KEYCACHE_DBUG_ASSERT(read_length > 0);
unknown's avatar
unknown committed
3091

3092
      /* Request the cache block that matches file/pos. */
unknown's avatar
unknown committed
3093
      keycache->global_cache_w_requests++;
3094
      block= find_key_block(keycache, file, filepos, level, 1, &page_st);
unknown's avatar
unknown committed
3095 3096
      if (!block)
      {
3097 3098 3099 3100 3101 3102
        /*
          This happens only for requests submitted during key cache
          resize. The block is not in the cache and shall not go in.
          Write directly to file.
        */
        if (dont_write)
unknown's avatar
unknown committed
3103
        {
3104
          /* Used in the server. */
unknown's avatar
unknown committed
3105
          keycache->global_cache_write++;
3106
          keycache_pthread_mutex_unlock(&keycache->cache_lock);
3107
          if (my_pwrite(file, (uchar*) buff, read_length, filepos + offset,
3108
                        MYF(MY_NABP | MY_WAIT_IF_FULL)))
unknown's avatar
unknown committed
3109
            error=1;
3110 3111
          keycache_pthread_mutex_lock(&keycache->cache_lock);
        }
unknown's avatar
unknown committed
3112 3113
        goto next_block;
      }
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
      /*
        Prevent block from flushing and from being selected for to be
        freed. This must be set when we release the cache_lock.
        However, we must not set the status of the block before it is
        assigned to this file/pos.
      */
      if (page_st != PAGE_WAIT_TO_BE_READ)
        block->status|= BLOCK_FOR_UPDATE;
      /*
        We must read the file block first if it is not yet in the cache
        and we do not replace all of its contents.

        In cases where the cache block is big enough to contain (parts
        of) index blocks of different indexes, our request can be
        secondary (PAGE_WAIT_TO_BE_READ). In this case another thread is
        reading the file block. If the read completes after us, it
        overwrites our new contents with the old contents. So we have to
        wait for the other thread to complete the read of this block.
        read_block() takes care for the wait.
      */
3134
      if (!(block->status & BLOCK_ERROR) &&
3135 3136 3137 3138
          ((page_st == PAGE_TO_BE_READ &&
            (offset || read_length < keycache->key_cache_block_size)) ||
           (page_st == PAGE_WAIT_TO_BE_READ)))
      {
unknown's avatar
unknown committed
3139 3140 3141
        read_block(keycache, block,
                   offset + read_length >= keycache->key_cache_block_size?
                   offset : keycache->key_cache_block_size,
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
                   offset, (page_st == PAGE_TO_BE_READ));
        DBUG_ASSERT(keycache->can_be_used);
        DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
        /*
          Prevent block from flushing and from being selected for to be
          freed. This must be set when we release the cache_lock.
          Here we set it in case we could not set it above.
        */
        block->status|= BLOCK_FOR_UPDATE;
      }
      /*
        The block should always be assigned to the requested file block
        here. It need not be BLOCK_READ when overwriting the whole block.
      */
      DBUG_ASSERT(block->hash_link->file == file);
      DBUG_ASSERT(block->hash_link->diskpos == filepos);
      DBUG_ASSERT(block->status & BLOCK_IN_USE);
      DBUG_ASSERT((page_st == PAGE_TO_BE_READ) || (block->status & BLOCK_READ));
      /*
        The block to be written must not be marked BLOCK_REASSIGNED.
        Otherwise it could be freed in dirty state or reused without
        another flush during eviction. It must also not be in flush.
        Otherwise the old contens may have been flushed already and
        the flusher could clear BLOCK_CHANGED without flushing the
        new changes again.
      */
      DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));

      while (block->status & BLOCK_IN_FLUSHWRITE)
      {
        /*
          Another thread is flushing the block. It was dirty already.
          Wait until the block is flushed to file. Otherwise we could
          modify the buffer contents just while it is written to file.
          An unpredictable file block contents would be the result.
          While we wait, several things can happen to the block,
          including another flush. But the block cannot be reassigned to
          another hash_link until we release our request on it.
        */
        wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
        DBUG_ASSERT(keycache->can_be_used);
        DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
        /* Still must not be marked for free. */
        DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
        DBUG_ASSERT(block->hash_link && (block->hash_link->block == block));
      }

      /*
        We could perhaps release the cache_lock during access of the
        data like in the other functions. Locks outside of the key cache
        assure that readers and a writer do not access the same range of
        data. Parallel accesses should happen only if the cache block
        contains multiple index block(fragment)s. So different parts of
        the buffer would be read/written. An attempt to flush during
        memcpy() is prevented with BLOCK_FOR_UPDATE.
      */
3198
      if (!(block->status & BLOCK_ERROR))
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
      {
#if !defined(SERIALIZED_READ_FROM_CACHE)
        keycache_pthread_mutex_unlock(&keycache->cache_lock);
#endif
        if (!(read_length & 511))
	  bmove512(block->buffer+offset, buff, read_length);
        else
          memcpy(block->buffer+offset, buff, (size_t) read_length);

#if !defined(SERIALIZED_READ_FROM_CACHE)
        keycache_pthread_mutex_lock(&keycache->cache_lock);
#endif
      }
3212

3213
      if (!dont_write)
3214
      {
3215
        /* Not used in the server. buff has been written to disk at start. */
3216
        if ((block->status & BLOCK_CHANGED) &&
unknown's avatar
unknown committed
3217 3218
            (!offset && read_length >= keycache->key_cache_block_size))
             link_to_file_list(keycache, block, block->hash_link->file, 1);
3219 3220
      }
      else if (! (block->status & BLOCK_CHANGED))
unknown's avatar
unknown committed
3221
        link_to_changed_list(keycache, block);
3222 3223 3224 3225 3226 3227 3228
      block->status|=BLOCK_READ;
      /*
        Allow block to be selected for to be freed. Since it is marked
        BLOCK_CHANGED too, it won't be selected for to be freed without
        a flush.
      */
      block->status&= ~BLOCK_FOR_UPDATE;
unknown's avatar
unknown committed
3229
      set_if_smaller(block->offset, offset);
unknown's avatar
unknown committed
3230
      set_if_bigger(block->length, read_length+offset);
3231

3232 3233
      /* Threads may be waiting for the changes to be complete. */
      release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
3234

3235 3236 3237 3238 3239 3240 3241 3242 3243
      /*
        If only a part of the cache block is to be replaced, and the
        rest has been read from file, then the cache lock has been
        released for I/O and it could be possible that another thread
        wants to evict or free the block and waits for it to be
        released. So we must not just decrement hash_link->requests, but
        also wake a waiting thread.
      */
      remove_reader(block);
3244

3245 3246 3247
      /* Error injection for coverage testing. */
      DBUG_EXECUTE_IF("key_cache_write_block_error",
                      block->status|= BLOCK_ERROR;);
3248

3249 3250
      /* Do not link erroneous blocks into the LRU ring, but free them. */
      if (!(block->status & BLOCK_ERROR))
3251
      {
3252 3253 3254 3255 3256 3257 3258
        /*
          Link the block into the LRU ring if it's the last submitted
          request for the block. This enables eviction for the block.
        */
        unreg_request(keycache, block, 1);
      }
      else
3259
      {
3260 3261 3262
        /* Pretend a "clean" block to avoid complications. */
        block->status&= ~(BLOCK_CHANGED);
        free_block(keycache, block);
unknown's avatar
unknown committed
3263
        error= 1;
3264 3265
        break;
      }
3266

unknown's avatar
unknown committed
3267
    next_block:
unknown's avatar
unknown committed
3268
      buff+= read_length;
unknown's avatar
unknown committed
3269
      filepos+= read_length+offset;
unknown's avatar
unknown committed
3270
      offset= 0;
3271

unknown's avatar
unknown committed
3272
    } while ((length-= read_length));
unknown's avatar
unknown committed
3273
    goto end;
unknown's avatar
unknown committed
3274
  }
unknown's avatar
unknown committed
3275 3276 3277 3278

no_key_cache:
  /* Key cache is not used */
  if (dont_write)
3279
  {
3280
    /* Used in the server. */
unknown's avatar
unknown committed
3281 3282
    keycache->global_cache_w_requests++;
    keycache->global_cache_write++;
3283
    if (locked_and_incremented)
3284
      keycache_pthread_mutex_unlock(&keycache->cache_lock);
3285
    if (my_pwrite(file, (uchar*) buff, length, filepos,
unknown's avatar
unknown committed
3286 3287
		  MYF(MY_NABP | MY_WAIT_IF_FULL)))
      error=1;
3288
    if (locked_and_incremented)
3289
      keycache_pthread_mutex_lock(&keycache->cache_lock);
3290
  }
unknown's avatar
unknown committed
3291

unknown's avatar
unknown committed
3292
end:
3293
  if (locked_and_incremented)
3294 3295 3296 3297
  {
    dec_counter_for_resize_op(keycache);
    keycache_pthread_mutex_unlock(&keycache->cache_lock);
  }
unknown's avatar
unknown committed
3298
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
unknown's avatar
unknown committed
3299 3300
  DBUG_EXECUTE("exec",
               test_key_cache(keycache, "end of key_cache_write", 1););
unknown's avatar
unknown committed
3301
#endif
3302 3303
  DBUG_RETURN(error);
}
unknown's avatar
unknown committed
3304 3305


3306
/*
3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
  Free block.

  SYNOPSIS
    free_block()
      keycache          Pointer to a key cache data structure
      block             Pointer to the block to free

  DESCRIPTION
    Remove reference to block from hash table.
    Remove block from the chain of clean blocks.
    Add block to the free list.

  NOTE
    Block must not be free (status == 0).
    Block must not be in free_block_list.
    Block must not be in the LRU ring.
    Block must not be in eviction (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH).
    Block must not be in free (BLOCK_REASSIGNED).
    Block must not be in flush (BLOCK_IN_FLUSH).
    Block must not be dirty (BLOCK_CHANGED).
    Block must not be in changed_blocks (dirty) hash.
    Block must be in file_blocks (clean) hash.
    Block must refer to a hash_link.
    Block must have a request registered on it.
3331 3332
*/

unknown's avatar
unknown committed
3333
static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block)
unknown's avatar
unknown committed
3334
{
3335
  KEYCACHE_THREAD_TRACE("free block");
3336
  KEYCACHE_DBUG_PRINT("free_block",
3337 3338 3339
                      ("block %u to be freed, hash_link %p  status: %u",
                       BLOCK_NUMBER(block), block->hash_link,
                       block->status));
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
  /*
    Assert that the block is not free already. And that it is in a clean
    state. Note that the block might just be assigned to a hash_link and
    not yet read (BLOCK_READ may not be set here). In this case a reader
    is registered in the hash_link and free_block() will wait for it
    below.
  */
  DBUG_ASSERT((block->status & BLOCK_IN_USE) &&
              !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                                 BLOCK_REASSIGNED | BLOCK_IN_FLUSH |
                                 BLOCK_CHANGED | BLOCK_FOR_UPDATE)));
  /* Assert that the block is in a file_blocks chain. */
  DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  /* Assert that the block is not in the LRU ring. */
  DBUG_ASSERT(!block->next_used && !block->prev_used);
  /*
    IMHO the below condition (if()) makes no sense. I can't see how it
    could be possible that free_block() is entered with a NULL hash_link
    pointer. The only place where it can become NULL is in free_block()
    (or before its first use ever, but for those blocks free_block() is
    not called). I don't remove the conditional as it cannot harm, but
    place an DBUG_ASSERT to confirm my hypothesis. Eventually the
    condition (if()) can be removed.
  */
  DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
3365
  if (block->hash_link)
unknown's avatar
unknown committed
3366
  {
3367 3368 3369 3370 3371 3372
    /*
      While waiting for readers to finish, new readers might request the
      block. But since we set block->status|= BLOCK_REASSIGNED, they
      will wait on block->wqueue[COND_FOR_SAVED]. They must be signalled
      later.
    */
unknown's avatar
unknown committed
3373 3374
    block->status|= BLOCK_REASSIGNED;
    wait_for_readers(keycache, block);
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
    /*
      The block must not have been freed by another thread. Repeat some
      checks. An additional requirement is that it must be read now
      (BLOCK_READ).
    */
    DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
    DBUG_ASSERT((block->status & (BLOCK_READ | BLOCK_IN_USE |
                                  BLOCK_REASSIGNED)) &&
                !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                                   BLOCK_IN_FLUSH | BLOCK_CHANGED |
                                   BLOCK_FOR_UPDATE)));
    DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
    DBUG_ASSERT(!block->prev_used);
    /*
      Unset BLOCK_REASSIGNED again. If we hand the block to an evicting
      thread (through unreg_request() below), other threads must not see
      this flag. They could become confused.
    */
    block->status&= ~BLOCK_REASSIGNED;
    /*
      Do not release the hash_link until the block is off all lists.
      At least not if we hand it over for eviction in unreg_request().
    */
unknown's avatar
unknown committed
3398
  }
3399

3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
  /*
    Unregister the block request and link the block into the LRU ring.
    This enables eviction for the block. If the LRU ring was empty and
    threads are waiting for a block, then the block wil be handed over
    for eviction immediately. Otherwise we will unlink it from the LRU
    ring again, without releasing the lock in between. So decrementing
    the request counter and updating statistics are the only relevant
    operation in this case. Assert that there are no other requests
    registered.
  */
  DBUG_ASSERT(block->requests == 1);
unknown's avatar
unknown committed
3411
  unreg_request(keycache, block, 0);
3412 3413 3414 3415 3416 3417 3418 3419
  /*
    Note that even without releasing the cache lock it is possible that
    the block is immediately selected for eviction by link_block() and
    thus not added to the LRU ring. In this case we must not touch the
    block any more.
  */
  if (block->status & BLOCK_IN_EVICTION)
    return;
3420

3421 3422 3423 3424 3425 3426 3427
  /* Error blocks are not put into the LRU ring. */
  if (!(block->status & BLOCK_ERROR))
  {
    /* Here the block must be in the LRU ring. Unlink it again. */
    DBUG_ASSERT(block->next_used && block->prev_used &&
                *block->prev_used == block);
    unlink_block(keycache, block);
unknown's avatar
unknown committed
3428
  }
3429 3430 3431
  if (block->temperature == BLOCK_WARM)
    keycache->warm_blocks--;
  block->temperature= BLOCK_COLD;
3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449

  /* Remove from file_blocks hash. */
  unlink_changed(block);

  /* Remove reference to block from hash table. */
  unlink_hash(keycache, block->hash_link);
  block->hash_link= NULL;

  block->status= 0;
  block->length= 0;
  block->offset= keycache->key_cache_block_size;
  KEYCACHE_THREAD_TRACE("free block");
  KEYCACHE_DBUG_PRINT("free_block", ("block is freed"));

  /* Enforced by unlink_changed(), but just to be sure. */
  DBUG_ASSERT(!block->next_changed && !block->prev_changed);
  /* Enforced by unlink_block(): not in LRU ring nor in free_block_list. */
  DBUG_ASSERT(!block->next_used && !block->prev_used);
3450 3451 3452 3453 3454
  /* Insert the free block in the free list. */
  block->next_used= keycache->free_block_list;
  keycache->free_block_list= block;
  /* Keep track of the number of currently unused blocks. */
  keycache->blocks_unused++;
3455 3456

  /* All pending requests for this page must be resubmitted. */
3457
  release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
unknown's avatar
unknown committed
3458 3459 3460
}


3461
static int cmp_sec_link(BLOCK_LINK **a, BLOCK_LINK **b)
unknown's avatar
unknown committed
3462
{
3463 3464
  return (((*a)->hash_link->diskpos < (*b)->hash_link->diskpos) ? -1 :
      ((*a)->hash_link->diskpos > (*b)->hash_link->diskpos) ? 1 : 0);
unknown's avatar
unknown committed
3465 3466
}

unknown's avatar
unknown committed
3467

3468 3469 3470
/*
  Flush a portion of changed blocks to disk,
  free used blocks if requested
3471
*/
3472

unknown's avatar
unknown committed
3473 3474
static int flush_cached_blocks(KEY_CACHE *keycache,
                               File file, BLOCK_LINK **cache,
3475 3476
                               BLOCK_LINK **end,
                               enum flush_type type)
unknown's avatar
unknown committed
3477
{
3478
  int error;
unknown's avatar
unknown committed
3479
  int last_errno= 0;
3480
  uint count= (uint) (end-cache);
3481

3482
  /* Don't lock the cache during the flush */
unknown's avatar
unknown committed
3483
  keycache_pthread_mutex_unlock(&keycache->cache_lock);
3484 3485 3486
  /*
     As all blocks referred in 'cache' are marked by BLOCK_IN_FLUSH
     we are guarunteed no thread will change them
3487
  */
3488
  my_qsort((uchar*) cache, count, sizeof(*cache), (qsort_cmp) cmp_sec_link);
3489

unknown's avatar
unknown committed
3490
  keycache_pthread_mutex_lock(&keycache->cache_lock);
3491 3492 3493 3494 3495
  /*
    Note: Do not break the loop. We have registered a request on every
    block in 'cache'. These must be unregistered by free_block() or
    unreg_request().
  */
3496
  for ( ; cache != end ; cache++)
unknown's avatar
unknown committed
3497
  {
3498
    BLOCK_LINK *block= *cache;
3499 3500

    KEYCACHE_DBUG_PRINT("flush_cached_blocks",
3501
                        ("block %u to be flushed", BLOCK_NUMBER(block)));
3502 3503 3504 3505 3506 3507
    /*
      If the block contents is going to be changed, we abandon the flush
      for this block. flush_key_blocks_int() will restart its search and
      handle the block properly.
    */
    if (!(block->status & BLOCK_FOR_UPDATE))
unknown's avatar
unknown committed
3508
    {
3509 3510 3511 3512 3513 3514 3515 3516
      /* Blocks coming here must have a certain status. */
      DBUG_ASSERT(block->hash_link);
      DBUG_ASSERT(block->hash_link->block == block);
      DBUG_ASSERT(block->hash_link->file == file);
      DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
                  (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
      block->status|= BLOCK_IN_FLUSHWRITE;
      keycache_pthread_mutex_unlock(&keycache->cache_lock);
3517
      error= my_pwrite(file, block->buffer+block->offset,
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
                       block->length - block->offset,
                       block->hash_link->diskpos+ block->offset,
                       MYF(MY_NABP | MY_WAIT_IF_FULL));
      keycache_pthread_mutex_lock(&keycache->cache_lock);
      keycache->global_cache_write++;
      if (error)
      {
        block->status|= BLOCK_ERROR;
        if (!last_errno)
          last_errno= errno ? errno : -1;
      }
      block->status&= ~BLOCK_IN_FLUSHWRITE;
      /* Block must not have changed status except BLOCK_FOR_UPDATE. */
      DBUG_ASSERT(block->hash_link);
      DBUG_ASSERT(block->hash_link->block == block);
      DBUG_ASSERT(block->hash_link->file == file);
      DBUG_ASSERT((block->status & ~(BLOCK_FOR_UPDATE | BLOCK_IN_EVICTION)) ==
                  (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
      /*
        Set correct status and link in right queue for free or later use.
        free_block() must not see BLOCK_CHANGED and it may need to wait
        for readers of the block. These should not see the block in the
        wrong hash. If not freeing the block, we need to have it in the
        right queue anyway.
      */
      link_to_file_list(keycache, block, file, 1);
3544
    }
3545
    block->status&= ~BLOCK_IN_FLUSH;
3546
    /*
unknown's avatar
unknown committed
3547 3548 3549
      Let to proceed for possible waiting requests to write to the block page.
      It might happen only during an operation to resize the key cache.
    */
3550
    release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
3551
    /* type will never be FLUSH_IGNORE_CHANGED here */
3552 3553 3554
    if (!(type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE) &&
        !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                           BLOCK_FOR_UPDATE)))
3555
    {
3556 3557 3558 3559
      /*
        Note that a request has been registered against the block in
        flush_key_blocks_int().
      */
unknown's avatar
unknown committed
3560
      free_block(keycache, block);
3561
    }
3562
    else
3563
    {
3564 3565 3566 3567 3568 3569
      /*
        Link the block into the LRU ring if it's the last submitted
        request for the block. This enables eviction for the block.
        Note that a request has been registered against the block in
        flush_key_blocks_int().
      */
unknown's avatar
unknown committed
3570
      unreg_request(keycache, block, 1);
unknown's avatar
unknown committed
3571
    }
3572

3573
  } /* end of for ( ; cache != end ; cache++) */
unknown's avatar
unknown committed
3574 3575 3576 3577
  return last_errno;
}


3578
/*
3579
  Flush all key blocks for a file to disk, but don't do any mutex locks.
3580

3581
  SYNOPSIS
unknown's avatar
unknown committed
3582
    flush_key_blocks_int()
3583
      keycache            pointer to a key cache data structure
3584 3585
      file                handler for the file to flush to
      flush_type          type of the flush
3586

3587 3588 3589 3590 3591
  NOTES
    This function doesn't do any mutex locks because it needs to be called both
    from flush_key_blocks and flush_all_key_blocks (the later one does the
    mutex lock in the resize_key_cache() function).

3592 3593 3594 3595
    We do only care about changed blocks that exist when the function is
    entered. We do not guarantee that all changed blocks of the file are
    flushed if more blocks change while this function is running.

3596 3597 3598 3599 3600
  RETURN
    0   ok
    1  error
*/

unknown's avatar
unknown committed
3601
static int flush_key_blocks_int(KEY_CACHE *keycache,
3602
				File file, enum flush_type type)
unknown's avatar
unknown committed
3603
{
3604
  BLOCK_LINK *cache_buff[FLUSH_CACHE],**cache;
unknown's avatar
unknown committed
3605
  int last_errno= 0;
3606
  int last_errcnt= 0;
3607
  DBUG_ENTER("flush_key_blocks_int");
unknown's avatar
unknown committed
3608
  DBUG_PRINT("enter",("file: %d  blocks_used: %lu  blocks_changed: %lu",
unknown's avatar
unknown committed
3609
              file, keycache->blocks_used, keycache->blocks_changed));
3610

unknown's avatar
unknown committed
3611
#if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
3612 3613
  DBUG_EXECUTE("check_keycache",
               test_key_cache(keycache, "start of flush_key_blocks", 0););
unknown's avatar
unknown committed
3614
#endif
3615

unknown's avatar
unknown committed
3616 3617
  cache= cache_buff;
  if (keycache->disk_blocks > 0 &&
3618
      (!my_disable_flush_key_blocks || type != FLUSH_KEEP))
3619 3620
  {
    /* Key cache exists and flush is not disabled */
unknown's avatar
unknown committed
3621
    int error= 0;
3622
    uint count= FLUSH_CACHE;
3623
    BLOCK_LINK **pos,**end;
unknown's avatar
unknown committed
3624
    BLOCK_LINK *first_in_switch= NULL;
3625 3626
    BLOCK_LINK *last_in_flush;
    BLOCK_LINK *last_for_update;
3627 3628 3629 3630
    BLOCK_LINK *block, *next;
#if defined(KEYCACHE_DEBUG)
    uint cnt=0;
#endif
3631

unknown's avatar
unknown committed
3632 3633
    if (type != FLUSH_IGNORE_CHANGED)
    {
3634
      /*
3635 3636 3637
         Count how many key blocks we have to cache to be able
         to flush all dirty pages with minimum seek moves
      */
3638
      count= 0;
unknown's avatar
unknown committed
3639
      for (block= keycache->changed_blocks[FILE_HASH(file)] ;
3640
           block ;
unknown's avatar
unknown committed
3641
           block= block->next_changed)
unknown's avatar
unknown committed
3642
      {
3643 3644
        if ((block->hash_link->file == file) &&
            !(block->status & BLOCK_IN_FLUSH))
3645
        {
3646
          count++;
unknown's avatar
unknown committed
3647
          KEYCACHE_DBUG_ASSERT(count<= keycache->blocks_used);
3648
        }
unknown's avatar
unknown committed
3649
      }
3650 3651 3652 3653 3654
      /*
        Allocate a new buffer only if its bigger than the one we have.
        Assure that we always have some entries for the case that new
        changed blocks appear while we need to wait for something.
      */
3655 3656 3657
      if ((count > FLUSH_CACHE) &&
          !(cache= (BLOCK_LINK**) my_malloc(sizeof(BLOCK_LINK*)*count,
                                            MYF(0))))
unknown's avatar
unknown committed
3658
        cache= cache_buff;
3659 3660 3661 3662 3663
      /*
        After a restart there could be more changed blocks than now.
        So we should not let count become smaller than the fixed buffer.
      */
      if (cache == cache_buff)
3664
        count= FLUSH_CACHE;
unknown's avatar
unknown committed
3665
    }
3666

3667 3668
    /* Retrieve the blocks and write them to a buffer to be flushed */
restart:
3669 3670
    last_in_flush= NULL;
    last_for_update= NULL;
unknown's avatar
unknown committed
3671 3672
    end= (pos= cache)+count;
    for (block= keycache->changed_blocks[FILE_HASH(file)] ;
3673
         block ;
unknown's avatar
unknown committed
3674
         block= next)
unknown's avatar
unknown committed
3675
    {
3676 3677
#if defined(KEYCACHE_DEBUG)
      cnt++;
unknown's avatar
unknown committed
3678
      KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
3679
#endif
unknown's avatar
unknown committed
3680
      next= block->next_changed;
3681
      if (block->hash_link->file == file)
unknown's avatar
unknown committed
3682
      {
3683
        if (!(block->status & (BLOCK_IN_FLUSH | BLOCK_FOR_UPDATE)))
3684
        {
3685 3686 3687 3688
          /*
            Note: The special handling of BLOCK_IN_SWITCH is obsolete
            since we set BLOCK_IN_FLUSH if the eviction includes a
            flush. It can be removed in a later version.
3689
          */
3690
          if (!(block->status & BLOCK_IN_SWITCH))
3691
          {
3692 3693 3694 3695 3696 3697 3698 3699
            /*
              We care only for the blocks for which flushing was not
              initiated by another thread and which are not in eviction.
              Registering a request on the block unlinks it from the LRU
              ring and protects against eviction.
            */
            reg_requests(keycache, block, 1);
            if (type != FLUSH_IGNORE_CHANGED)
3700
            {
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
              /* It's not a temporary file */
              if (pos == end)
              {
                /*
                  This should happen relatively seldom. Remove the
                  request because we won't do anything with the block
                  but restart and pick it again in the next iteration.
                */
                unreg_request(keycache, block, 0);
                /*
                  This happens only if there is not enough
                  memory for the big block
                */
                if ((error= flush_cached_blocks(keycache, file, cache,
                                                end,type)))
                {
3717
                  /* Do not loop infinitely trying to flush in vain. */
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734
                  if ((last_errno == error) && (++last_errcnt > 5))
                    goto err;
                  last_errno= error;
                }
                /*
                  Restart the scan as some other thread might have changed
                  the changed blocks chain: the blocks that were in switch
                  state before the flush started have to be excluded
                */
                goto restart;
              }
              /*
                Mark the block with BLOCK_IN_FLUSH in order not to let
                other threads to use it for new pages and interfere with
                our sequence of flushing dirty file pages. We must not
                set this flag before actually putting the block on the
                write burst array called 'cache'.
3735
              */
3736 3737 3738 3739 3740 3741 3742 3743
              block->status|= BLOCK_IN_FLUSH;
              /* Add block to the array for a write burst. */
              *pos++= block;
            }
            else
            {
              /* It's a temporary file */
              DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
3744
              /*
3745 3746 3747 3748
                free_block() must not be called with BLOCK_CHANGED. Note
                that we must not change the BLOCK_CHANGED flag outside of
                link_to_file_list() so that it is always in the correct
                queue and the *blocks_changed counters are correct.
3749
              */
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
              link_to_file_list(keycache, block, file, 1);
              if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)))
              {
                /* A request has been registered against the block above. */
                free_block(keycache, block);
              }
              else
              {
                /*
                  Link the block into the LRU ring if it's the last
                  submitted request for the block. This enables eviction
                  for the block. A request has been registered against
                  the block above.
                */
                unreg_request(keycache, block, 1);
              }
3766 3767 3768 3769
            }
          }
          else
          {
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780
            /*
              Link the block into a list of blocks 'in switch'.

              WARNING: Here we introduce a place where a changed block
              is not in the changed_blocks hash! This is acceptable for
              a BLOCK_IN_SWITCH. Never try this for another situation.
              Other parts of the key cache code rely on changed blocks
              being in the changed_blocks hash.
            */
            unlink_changed(block);
            link_changed(block, &first_in_switch);
3781 3782
          }
        }
3783
        else if (type != FLUSH_KEEP)
3784
        {
3785 3786 3787 3788 3789 3790 3791 3792
          /*
            During the normal flush at end of statement (FLUSH_KEEP) we
            do not need to ensure that blocks in flush or update by
            other threads are flushed. They will be flushed by them
            later. In all other cases we must assure that we do not have
            any changed block of this file in the cache when this
            function returns.
          */
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
          if (block->status & BLOCK_IN_FLUSH)
          {
            /* Remember the last block found to be in flush. */
            last_in_flush= block;
          }
          else
          {
            /* Remember the last block found to be selected for update. */
            last_for_update= block;
          }
3803
        }
unknown's avatar
unknown committed
3804 3805 3806 3807
      }
    }
    if (pos != cache)
    {
unknown's avatar
unknown committed
3808
      if ((error= flush_cached_blocks(keycache, file, cache, pos, type)))
3809 3810 3811 3812
      {
        /* Do not loop inifnitely trying to flush in vain. */
        if ((last_errno == error) && (++last_errcnt > 5))
          goto err;
unknown's avatar
unknown committed
3813
        last_errno= error;
3814 3815
      }
      /*
3816 3817 3818 3819 3820
        Do not restart here during the normal flush at end of statement
        (FLUSH_KEEP). We have now flushed at least all blocks that were
        changed when entering this function. In all other cases we must
        assure that we do not have any changed block of this file in the
        cache when this function returns.
3821
      */
3822 3823
      if (type != FLUSH_KEEP)
        goto restart;
3824 3825 3826 3827 3828 3829
    }
    if (last_in_flush)
    {
      /*
        There are no blocks to be flushed by this thread, but blocks in
        flush by other threads. Wait until one of the blocks is flushed.
3830 3831 3832 3833 3834 3835 3836
        Re-check the condition for last_in_flush. We may have unlocked
        the cache_lock in flush_cached_blocks(). The state of the block
        could have changed.
      */
      if (last_in_flush->status & BLOCK_IN_FLUSH)
        wait_on_queue(&last_in_flush->wqueue[COND_FOR_SAVED],
                      &keycache->cache_lock);
3837 3838 3839 3840 3841 3842 3843 3844
      /* Be sure not to lose a block. They may be flushed in random order. */
      goto restart;
    }
    if (last_for_update)
    {
      /*
        There are no blocks to be flushed by this thread, but blocks for
        update by other threads. Wait until one of the blocks is updated.
3845 3846 3847 3848 3849 3850 3851
        Re-check the condition for last_for_update. We may have unlocked
        the cache_lock in flush_cached_blocks(). The state of the block
        could have changed.
      */
      if (last_for_update->status & BLOCK_FOR_UPDATE)
        wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
                      &keycache->cache_lock);
3852 3853
      /* The block is now changed. Flush it. */
      goto restart;
3854
    }
3855 3856 3857 3858 3859 3860

    /*
      Wait until the list of blocks in switch is empty. The threads that
      are switching these blocks will relink them to clean file chains
      while we wait and thus empty the 'first_in_switch' chain.
    */
3861 3862 3863
    while (first_in_switch)
    {
#if defined(KEYCACHE_DEBUG)
unknown's avatar
unknown committed
3864
      cnt= 0;
3865
#endif
3866 3867
      wait_on_queue(&first_in_switch->wqueue[COND_FOR_SAVED],
                    &keycache->cache_lock);
3868 3869
#if defined(KEYCACHE_DEBUG)
      cnt++;
unknown's avatar
unknown committed
3870
      KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
3871
#endif
3872 3873 3874 3875 3876 3877
      /*
        Do not restart here. We have flushed all blocks that were
        changed when entering this function and were not marked for
        eviction. Other threads have now flushed all remaining blocks in
        the course of their eviction.
      */
unknown's avatar
unknown committed
3878
    }
3879

3880
    if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE))
unknown's avatar
unknown committed
3881
    {
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
      BLOCK_LINK *last_for_update= NULL;
      BLOCK_LINK *last_in_switch= NULL;
      uint total_found= 0;
      uint found;

      /*
        Finally free all clean blocks for this file.
        During resize this may be run by two threads in parallel.
      */
      do
unknown's avatar
unknown committed
3892
      {
3893 3894 3895 3896
        found= 0;
        for (block= keycache->file_blocks[FILE_HASH(file)] ;
             block ;
             block= next)
3897
        {
3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919
          /* Remember the next block. After freeing we cannot get at it. */
          next= block->next_changed;

          /* Changed blocks cannot appear in the file_blocks hash. */
          DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
          if (block->hash_link->file == file)
          {
            /* We must skip blocks that will be changed. */
            if (block->status & BLOCK_FOR_UPDATE)
            {
              last_for_update= block;
              continue;
            }

            /*
              We must not free blocks in eviction (BLOCK_IN_EVICTION |
              BLOCK_IN_SWITCH) or blocks intended to be freed
              (BLOCK_REASSIGNED).
            */
            if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
                                   BLOCK_REASSIGNED)))
            {
3920 3921 3922 3923 3924
              struct st_hash_link *UNINIT_VAR(next_hash_link);
              my_off_t UNINIT_VAR(next_diskpos);
              File UNINIT_VAR(next_file);
              uint UNINIT_VAR(next_status);
              uint UNINIT_VAR(hash_requests);
3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990

              total_found++;
              found++;
              KEYCACHE_DBUG_ASSERT(found <= keycache->blocks_used);

              /*
                Register a request. This unlinks the block from the LRU
                ring and protects it against eviction. This is required
                by free_block().
              */
              reg_requests(keycache, block, 1);

              /*
                free_block() may need to wait for readers of the block.
                This is the moment where the other thread can move the
                'next' block from the chain. free_block() needs to wait
                if there are requests for the block pending.
              */
              if (next && (hash_requests= block->hash_link->requests))
              {
                /* Copy values from the 'next' block and its hash_link. */
                next_status=    next->status;
                next_hash_link= next->hash_link;
                next_diskpos=   next_hash_link->diskpos;
                next_file=      next_hash_link->file;
                DBUG_ASSERT(next == next_hash_link->block);
              }

              free_block(keycache, block);
              /*
                If we had to wait and the state of the 'next' block
                changed, break the inner loop. 'next' may no longer be
                part of the current chain.

                We do not want to break the loop after every free_block(),
                not even only after waits. The chain might be quite long
                and contain blocks for many files. Traversing it again and
                again to find more blocks for this file could become quite
                inefficient.
              */
              if (next && hash_requests &&
                  ((next_status    != next->status) ||
                   (next_hash_link != next->hash_link) ||
                   (next_file      != next_hash_link->file) ||
                   (next_diskpos   != next_hash_link->diskpos) ||
                   (next           != next_hash_link->block)))
                break;
            }
            else
            {
              last_in_switch= block;
            }
          }
        } /* end for block in file_blocks */
      } while (found);

      /*
        If any clean block has been found, we may have waited for it to
        become free. In this case it could be possible that another clean
        block became dirty. This is possible if the write request existed
        before the flush started (BLOCK_FOR_UPDATE). Re-check the hashes.
      */
      if (total_found)
        goto restart;

      /*
3991
        To avoid an infinite loop, wait until one of the blocks marked
3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
        for update is updated.
      */
      if (last_for_update)
      {
        /* We did not wait. Block must not have changed status. */
        DBUG_ASSERT(last_for_update->status & BLOCK_FOR_UPDATE);
        wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
                      &keycache->cache_lock);
        goto restart;
      }

      /*
        To avoid an infinite loop wait until one of the blocks marked
        for eviction is switched.
      */
      if (last_in_switch)
      {
        /* We did not wait. Block must not have changed status. */
        DBUG_ASSERT(last_in_switch->status & (BLOCK_IN_EVICTION |
                                              BLOCK_IN_SWITCH |
                                              BLOCK_REASSIGNED));
        wait_on_queue(&last_in_switch->wqueue[COND_FOR_SAVED],
                      &keycache->cache_lock);
        goto restart;
unknown's avatar
unknown committed
4016
      }
4017 4018 4019 4020

    } /* if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE)) */

  } /* if (keycache->disk_blocks > 0 */
4021

unknown's avatar
unknown committed
4022
#ifndef DBUG_OFF
unknown's avatar
unknown committed
4023 4024
  DBUG_EXECUTE("check_keycache",
               test_key_cache(keycache, "end of flush_key_blocks", 0););
unknown's avatar
unknown committed
4025
#endif
4026
err:
unknown's avatar
unknown committed
4027
  if (cache != cache_buff)
4028
    my_free((uchar*) cache, MYF(0));
unknown's avatar
unknown committed
4029
  if (last_errno)
4030
    errno=last_errno;                /* Return first error */
unknown's avatar
unknown committed
4031
  DBUG_RETURN(last_errno != 0);
unknown's avatar
unknown committed
4032 4033 4034
}


4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
/*
  Flush all blocks for a file to disk

  SYNOPSIS

    flush_key_blocks()
      keycache            pointer to a key cache data structure
      file                handler for the file to flush to
      flush_type          type of the flush

  RETURN
    0   ok
    1  error
unknown's avatar
unknown committed
4048
*/
4049

unknown's avatar
unknown committed
4050
int flush_key_blocks(KEY_CACHE *keycache,
4051 4052
                     File file, enum flush_type type)
{
4053
  int res= 0;
4054
  DBUG_ENTER("flush_key_blocks");
unknown's avatar
unknown committed
4055
  DBUG_PRINT("enter", ("keycache: 0x%lx", (long) keycache));
4056

4057
  if (!keycache->key_cache_inited)
4058
    DBUG_RETURN(0);
4059

unknown's avatar
unknown committed
4060
  keycache_pthread_mutex_lock(&keycache->cache_lock);
4061 4062 4063 4064 4065 4066 4067
  /* While waiting for lock, keycache could have been ended. */
  if (keycache->disk_blocks > 0)
  {
    inc_counter_for_resize_op(keycache);
    res= flush_key_blocks_int(keycache, file, type);
    dec_counter_for_resize_op(keycache);
  }
unknown's avatar
unknown committed
4068
  keycache_pthread_mutex_unlock(&keycache->cache_lock);
4069 4070 4071 4072
  DBUG_RETURN(res);
}


4073
/*
4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
  Flush all blocks in the key cache to disk.

  SYNOPSIS
    flush_all_key_blocks()
      keycache                  pointer to key cache root structure

  DESCRIPTION

    Flushing of the whole key cache is done in two phases.

    1. Flush all changed blocks, waiting for them if necessary. Loop
    until there is no changed block left in the cache.

    2. Free all clean blocks. Normally this means free all blocks. The
    changed blocks were flushed in phase 1 and became clean. However we
    may need to wait for blocks that are read by other threads. While we
    wait, a clean block could become changed if that operation started
    before the resize operation started. To be safe we must restart at
    phase 1.

    When we can run through the changed_blocks and file_blocks hashes
    without finding a block any more, then we are done.

    Note that we hold keycache->cache_lock all the time unless we need
    to wait for something.

  RETURN
    0           OK
    != 0        Error
4103
*/
4104

unknown's avatar
unknown committed
4105
static int flush_all_key_blocks(KEY_CACHE *keycache)
4106
{
4107 4108 4109 4110 4111 4112 4113
  BLOCK_LINK    *block;
  uint          total_found;
  uint          found;
  uint          idx;
  DBUG_ENTER("flush_all_key_blocks");

  do
4114
  {
4115
    safe_mutex_assert_owner(&keycache->cache_lock);
4116 4117
    total_found= 0;

4118 4119 4120 4121
    /*
      Phase1: Flush all changed blocks, waiting for them if necessary.
      Loop until there is no changed block left in the cache.
    */
4122
    do
4123
    {
4124 4125 4126
      found= 0;
      /* Step over the whole changed_blocks hash array. */
      for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
4127
      {
4128 4129
        /*
          If an array element is non-empty, use the first block from its
4130 4131 4132 4133 4134 4135
          chain to find a file for flush. All changed blocks for this
          file are flushed. So the same block will not appear at this
          place again with the next iteration. New writes for blocks are
          not accepted during the flush. If multiple files share the
          same hash bucket, one of them will be flushed per iteration
          of the outer loop of phase 1.
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
        */
        if ((block= keycache->changed_blocks[idx]))
        {
          found++;
          /*
            Flush dirty blocks but do not free them yet. They can be used
            for reading until all other blocks are flushed too.
          */
          if (flush_key_blocks_int(keycache, block->hash_link->file,
                                   FLUSH_FORCE_WRITE))
            DBUG_RETURN(1);
        }
4148
      }
4149 4150 4151

    } while (found);

4152 4153 4154 4155 4156 4157 4158 4159
    /*
      Phase 2: Free all clean blocks. Normally this means free all
      blocks. The changed blocks were flushed in phase 1 and became
      clean. However we may need to wait for blocks that are read by
      other threads. While we wait, a clean block could become changed
      if that operation started before the resize operation started. To
      be safe we must restart at phase 1.
    */
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
    do
    {
      found= 0;
      /* Step over the whole file_blocks hash array. */
      for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
      {
        /*
          If an array element is non-empty, use the first block from its
          chain to find a file for flush. All blocks for this file are
          freed. So the same block will not appear at this place again
4170 4171 4172
          with the next iteration. If multiple files share the
          same hash bucket, one of them will be flushed per iteration
          of the outer loop of phase 2.
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199
        */
        if ((block= keycache->file_blocks[idx]))
        {
          total_found++;
          found++;
          if (flush_key_blocks_int(keycache, block->hash_link->file,
                                   FLUSH_RELEASE))
            DBUG_RETURN(1);
        }
      }

    } while (found);

    /*
      If any clean block has been found, we may have waited for it to
      become free. In this case it could be possible that another clean
      block became dirty. This is possible if the write request existed
      before the resize started (BLOCK_FOR_UPDATE). Re-check the hashes.
    */
  } while (total_found);

#ifndef DBUG_OFF
  /* Now there should not exist any block any more. */
  for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
  {
    DBUG_ASSERT(!keycache->changed_blocks[idx]);
    DBUG_ASSERT(!keycache->file_blocks[idx]);
4200
  }
4201 4202 4203
#endif

  DBUG_RETURN(0);
4204
}
unknown's avatar
unknown committed
4205 4206


unknown's avatar
unknown committed
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222
/*
  Reset the counters of a key cache.

  SYNOPSIS
    reset_key_cache_counters()
    name       the name of a key cache
    key_cache  pointer to the key kache to be reset

  DESCRIPTION
   This procedure is used by process_key_caches() to reset the counters of all
   currently used key caches, both the default one and the named ones.

  RETURN
    0 on success (always because it can't fail)
*/

unknown's avatar
unknown committed
4223 4224
int reset_key_cache_counters(const char *name __attribute__((unused)),
                             KEY_CACHE *key_cache)
unknown's avatar
unknown committed
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
{
  DBUG_ENTER("reset_key_cache_counters");
  if (!key_cache->key_cache_inited)
  {
    DBUG_PRINT("info", ("Key cache %s not initialized.", name));
    DBUG_RETURN(0);
  }
  DBUG_PRINT("info", ("Resetting counters for key cache %s.", name));

  key_cache->global_blocks_changed= 0;   /* Key_blocks_not_flushed */
  key_cache->global_cache_r_requests= 0; /* Key_read_requests */
  key_cache->global_cache_read= 0;       /* Key_reads */
  key_cache->global_cache_w_requests= 0; /* Key_write_requests */
  key_cache->global_cache_write= 0;      /* Key_writes */
  DBUG_RETURN(0);
}


4243 4244
#ifndef DBUG_OFF
/*
4245
  Test if disk-cache is ok
unknown's avatar
unknown committed
4246
*/
unknown's avatar
unknown committed
4247
static void test_key_cache(KEY_CACHE *keycache __attribute__((unused)),
unknown's avatar
unknown committed
4248
                           const char *where __attribute__((unused)),
4249 4250 4251
                           my_bool lock __attribute__((unused)))
{
  /* TODO */
4252
}
4253
#endif
unknown's avatar
unknown committed
4254

4255 4256 4257 4258 4259 4260
#if defined(KEYCACHE_TIMEOUT)

#define KEYCACHE_DUMP_FILE  "keycache_dump.txt"
#define MAX_QUEUE_LEN  100


unknown's avatar
unknown committed
4261
static void keycache_dump(KEY_CACHE *keycache)
unknown's avatar
unknown committed
4262
{
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287
  FILE *keycache_dump_file=fopen(KEYCACHE_DUMP_FILE, "w");
  struct st_my_thread_var *last;
  struct st_my_thread_var *thread;
  BLOCK_LINK *block;
  HASH_LINK *hash_link;
  KEYCACHE_PAGE *page;
  uint i;

  fprintf(keycache_dump_file, "thread:%u\n", thread->id);

  i=0;
  thread=last=waiting_for_hash_link.last_thread;
  fprintf(keycache_dump_file, "queue of threads waiting for hash link\n");
  if (thread)
    do
    {
      thread=thread->next;
      page= (KEYCACHE_PAGE *) thread->opt_info;
      fprintf(keycache_dump_file,
              "thread:%u, (file,filepos)=(%u,%lu)\n",
              thread->id,(uint) page->file,(ulong) page->filepos);
      if (++i == MAX_QUEUE_LEN)
        break;
    }
    while (thread != last);
4288

4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305
  i=0;
  thread=last=waiting_for_block.last_thread;
  fprintf(keycache_dump_file, "queue of threads waiting for block\n");
  if (thread)
    do
    {
      thread=thread->next;
      hash_link= (HASH_LINK *) thread->opt_info;
      fprintf(keycache_dump_file,
        "thread:%u hash_link:%u (file,filepos)=(%u,%lu)\n",
        thread->id, (uint) HASH_LINK_NUMBER(hash_link),
        (uint) hash_link->file,(ulong) hash_link->diskpos);
      if (++i == MAX_QUEUE_LEN)
        break;
    }
    while (thread != last);

unknown's avatar
unknown committed
4306
  for (i=0 ; i< keycache->blocks_used ; i++)
4307 4308
  {
    int j;
unknown's avatar
unknown committed
4309
    block= &keycache->block_root[i];
4310
    hash_link= block->hash_link;
4311 4312 4313 4314 4315 4316 4317
    fprintf(keycache_dump_file,
            "block:%u hash_link:%d status:%x #requests=%u waiting_for_readers:%d\n",
            i, (int) (hash_link ? HASH_LINK_NUMBER(hash_link) : -1),
            block->status, block->requests, block->condvar ? 1 : 0);
    for (j=0 ; j < 2; j++)
    {
      KEYCACHE_WQUEUE *wqueue=&block->wqueue[j];
4318
      thread= last= wqueue->last_thread;
4319 4320
      fprintf(keycache_dump_file, "queue #%d\n", j);
      if (thread)
4321
      {
4322 4323 4324 4325 4326 4327 4328 4329 4330
        do
        {
          thread=thread->next;
          fprintf(keycache_dump_file,
                  "thread:%u\n", thread->id);
          if (++i == MAX_QUEUE_LEN)
            break;
        }
        while (thread != last);
4331
      }
4332 4333 4334
    }
  }
  fprintf(keycache_dump_file, "LRU chain:");
unknown's avatar
unknown committed
4335
  block= keycache= used_last;
4336
  if (block)
4337
  {
4338 4339
    do
    {
unknown's avatar
unknown committed
4340
      block= block->next_used;
4341 4342 4343
      fprintf(keycache_dump_file,
              "block:%u, ", BLOCK_NUMBER(block));
    }
unknown's avatar
unknown committed
4344
    while (block != keycache->used_last);
4345
  }
4346
  fprintf(keycache_dump_file, "\n");
4347

4348
  fclose(keycache_dump_file);
unknown's avatar
unknown committed
4349 4350
}

4351
#endif /* defined(KEYCACHE_TIMEOUT) */
unknown's avatar
unknown committed
4352

4353
#if defined(KEYCACHE_TIMEOUT) && !defined(__WIN__)
unknown's avatar
unknown committed
4354 4355


4356
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
4357 4358 4359 4360 4361 4362 4363 4364 4365
                                      pthread_mutex_t *mutex)
{
  int rc;
  struct timeval  now;            /* time when we started waiting        */
  struct timespec timeout;        /* timeout value for the wait function */
  struct timezone tz;
#if defined(KEYCACHE_DEBUG)
  int cnt=0;
#endif
4366 4367

  /* Get current time */
4368 4369
  gettimeofday(&now, &tz);
  /* Prepare timeout value */
4370
  timeout.tv_sec= now.tv_sec + KEYCACHE_TIMEOUT;
unknown's avatar
unknown committed
4371 4372 4373 4374 4375 4376
 /*
   timeval uses microseconds.
   timespec uses nanoseconds.
   1 nanosecond = 1000 micro seconds
 */
  timeout.tv_nsec= now.tv_usec * 1000;
4377 4378 4379 4380 4381 4382 4383
  KEYCACHE_THREAD_TRACE_END("started waiting");
#if defined(KEYCACHE_DEBUG)
  cnt++;
  if (cnt % 100 == 0)
    fprintf(keycache_debug_log, "waiting...\n");
    fflush(keycache_debug_log);
#endif
4384
  rc= pthread_cond_timedwait(cond, mutex, &timeout);
4385
  KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
unknown's avatar
unknown committed
4386
  if (rc == ETIMEDOUT || rc == ETIME)
4387
  {
unknown's avatar
unknown committed
4388
#if defined(KEYCACHE_DEBUG)
4389 4390 4391 4392 4393
    fprintf(keycache_debug_log,"aborted by keycache timeout\n");
    fclose(keycache_debug_log);
    abort();
#endif
    keycache_dump();
unknown's avatar
unknown committed
4394
  }
4395

4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409
#if defined(KEYCACHE_DEBUG)
  KEYCACHE_DBUG_ASSERT(rc != ETIMEDOUT);
#else
  assert(rc != ETIMEDOUT);
#endif
  return rc;
}
#else
#if defined(KEYCACHE_DEBUG)
static int keycache_pthread_cond_wait(pthread_cond_t *cond,
                                      pthread_mutex_t *mutex)
{
  int rc;
  KEYCACHE_THREAD_TRACE_END("started waiting");
4410
  rc= pthread_cond_wait(cond, mutex);
4411 4412 4413 4414 4415
  KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
  return rc;
}
#endif
#endif /* defined(KEYCACHE_TIMEOUT) && !defined(__WIN__) */
unknown's avatar
unknown committed
4416

4417
#if defined(KEYCACHE_DEBUG)
unknown's avatar
unknown committed
4418 4419


4420
static int keycache_pthread_mutex_lock(pthread_mutex_t *mutex)
unknown's avatar
unknown committed
4421
{
4422
  int rc;
4423
  rc= pthread_mutex_lock(mutex);
4424 4425
  KEYCACHE_THREAD_TRACE_BEGIN("");
  return rc;
unknown's avatar
unknown committed
4426
}
unknown's avatar
unknown committed
4427 4428


4429 4430 4431 4432 4433
static void keycache_pthread_mutex_unlock(pthread_mutex_t *mutex)
{
  KEYCACHE_THREAD_TRACE_END("");
  pthread_mutex_unlock(mutex);
}
unknown's avatar
unknown committed
4434 4435


4436
static int keycache_pthread_cond_signal(pthread_cond_t *cond)
unknown's avatar
unknown committed
4437
{
4438 4439
  int rc;
  KEYCACHE_THREAD_TRACE("signal");
4440
  rc= pthread_cond_signal(cond);
4441 4442
  return rc;
}
unknown's avatar
unknown committed
4443 4444


4445
#if defined(KEYCACHE_DEBUG_LOG)
unknown's avatar
unknown committed
4446 4447


4448 4449 4450 4451 4452
static void keycache_debug_print(const char * fmt,...)
{
  va_list args;
  va_start(args,fmt);
  if (keycache_debug_log)
unknown's avatar
unknown committed
4453
  {
4454 4455
    (void) vfprintf(keycache_debug_log, fmt, args);
    (void) fputc('\n',keycache_debug_log);
unknown's avatar
unknown committed
4456
  }
4457 4458 4459
  va_end(args);
}
#endif /* defined(KEYCACHE_DEBUG_LOG) */
unknown's avatar
unknown committed
4460

4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471
#if defined(KEYCACHE_DEBUG_LOG)


void keycache_debug_log_close(void)
{
  if (keycache_debug_log)
    fclose(keycache_debug_log);
}
#endif /* defined(KEYCACHE_DEBUG_LOG) */

#endif /* defined(KEYCACHE_DEBUG) */
4472 4473

#if !defined(DBUG_OFF)
4474
#define F_B_PRT(_f_, _v_) DBUG_PRINT("assert_fail", (_f_, _v_))
4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519

static int fail_block(BLOCK_LINK *block)
{
  F_B_PRT("block->next_used:    %lx\n", (ulong) block->next_used);
  F_B_PRT("block->prev_used:    %lx\n", (ulong) block->prev_used);
  F_B_PRT("block->next_changed: %lx\n", (ulong) block->next_changed);
  F_B_PRT("block->prev_changed: %lx\n", (ulong) block->prev_changed);
  F_B_PRT("block->hash_link:    %lx\n", (ulong) block->hash_link);
  F_B_PRT("block->status:       %u\n", block->status);
  F_B_PRT("block->length:       %u\n", block->length);
  F_B_PRT("block->offset:       %u\n", block->offset);
  F_B_PRT("block->requests:     %u\n", block->requests);
  F_B_PRT("block->temperature:  %u\n", block->temperature);
  return 0; /* Let the assert fail. */
}

static int fail_hlink(HASH_LINK *hlink)
{
  F_B_PRT("hlink->next:    %lx\n", (ulong) hlink->next);
  F_B_PRT("hlink->prev:    %lx\n", (ulong) hlink->prev);
  F_B_PRT("hlink->block:   %lx\n", (ulong) hlink->block);
  F_B_PRT("hlink->diskpos: %lu\n", (ulong) hlink->diskpos);
  F_B_PRT("hlink->file:    %d\n", hlink->file);
  return 0; /* Let the assert fail. */
}

static int cache_empty(KEY_CACHE *keycache)
{
  int errcnt= 0;
  int idx;
  if (keycache->disk_blocks <= 0)
    return 1;
  for (idx= 0; idx < keycache->disk_blocks; idx++)
  {
    BLOCK_LINK *block= keycache->block_root + idx;
    if (block->status || block->requests || block->hash_link)
    {
      fprintf(stderr, "block index: %u\n", idx);
      fail_block(block);
      errcnt++;
    }
  }
  for (idx= 0; idx < keycache->hash_links; idx++)
  {
    HASH_LINK *hash_link= keycache->hash_link_root + idx;
4520
    if (hash_link->requests || hash_link->block)
4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538
    {
      fprintf(stderr, "hash_link index: %u\n", idx);
      fail_hlink(hash_link);
      errcnt++;
    }
  }
  if (errcnt)
  {
    fprintf(stderr, "blocks: %d  used: %lu\n",
            keycache->disk_blocks, keycache->blocks_used);
    fprintf(stderr, "hash_links: %d  used: %d\n",
            keycache->hash_links, keycache->hash_links_used);
    fprintf(stderr, "\n");
  }
  return !errcnt;
}
#endif