dscache.c 33.6 KB
Newer Older
1 2 3 4 5 6 7
#include "redis.h"

#include <fcntl.h>
#include <pthread.h>
#include <math.h>
#include <signal.h>

8 9 10 11 12 13 14 15 16 17 18 19 20
/* dscache.c - Disk store cache for disk store backend.
 *
 * When Redis is configured for using disk as backend instead of memory, the
 * memory is used as a cache, so that recently accessed keys are taken in
 * memory for fast read and write operations.
 *
 * Modified keys are marked to be flushed on disk, and will be flushed
 * as long as the maxium configured flush time elapsed.
 *
 * This file implements the whole caching subsystem and contains further
 * documentation. */

/* TODO:
A
antirez 已提交
21 22 23 24
 *
 * WARNING: most of the following todo items and design issues are no
 * longer relevant with the new design. Here as a checklist to see if
 * some old ideas still apply.
25 26 27 28 29 30 31 32
 *
 * - The WATCH helper will be used to signal the cache system
 *   we need to flush a given key/dbid into disk, adding this key/dbid
 *   pair into a server.ds_cache_dirty linked list AND hash table (so that we
 *   don't add the same thing multiple times).
 *
 * - cron() checks if there are elements on this list. When there are things
 *   to flush, we create an IO Job for the I/O thread.
33 34 35
 *   NOTE: We disalbe object sharing when server.ds_enabled == 1 so objects
 *   that are referenced an IO job for flushing on disk are marked as
 *   o->storage == REDIS_DS_SAVING.
36 37
 *
 * - This is what we do on key lookup:
38 39
 *   1) The key already exists in memory. object->storage == REDIS_DS_MEMORY
 *      or it is object->storage == REDIS_DS_DIRTY:
40 41
 *      We don't do nothing special, lookup, return value object pointer.
 *   2) The key is in memory but object->storage == REDIS_DS_SAVING.
42 43
 *      When this happens we block waiting for the I/O thread to process
 *      this object. Then continue.
44 45 46 47 48 49 50 51 52 53
 *   3) The key is not in memory. We block to load the key from disk.
 *      Of course the key may not be present at all on the disk store as well,
 *      in such case we just detect this condition and continue, returning
 *      NULL from lookup.
 *
 * - Preloading of needed keys:
 *   1) As it was done with VM, also with this new system we try preloading
 *      keys a client is going to use. We block the client, load keys
 *      using the I/O thread, unblock the client. Same code as VM more or less.
 *
54 55 56 57
 * - Reclaiming memory.
 *   In cron() we detect our memory limit was reached. What we
 *   do is deleting keys that are REDIS_DS_MEMORY, using LRU.
 *
58 59
 *   If this is not enough to return again under the memory limits we also
 *   start to flush keys that need to be synched on disk synchronously,
60 61
 *   removing it from the memory. We do this blocking as memory limit is a
 *   much "harder" barrirer in the new design.
62 63
 *
 * - IO thread operations are no longer stopped for sync loading/saving of
64 65
 *   things. When a key is found to be in the process of being saved
 *   we simply wait for the IO thread to end its work.
66 67 68
 *
 *   Otherwise if there is to load a key without any IO thread operation
 *   just started it is blocking-loaded in the lookup function.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
 *
 * - What happens when an object is destroyed?
 *
 *   If o->storage == REDIS_DS_MEMORY then we simply destory the object.
 *   If o->storage == REDIS_DS_DIRTY we can still remove the object. It had
 *                    changes not flushed on disk, but is being removed so
 *                    who cares.
 *   if o->storage == REDIS_DS_SAVING then the object is being saved so
 *                    it is impossible that its refcount == 1, must be at
 *                    least two. When the object is saved the storage will
 *                    be set back to DS_MEMORY.
 *
 * - What happens when keys are deleted?
 *
 *   We simply schedule a key flush operation as usually, but when the
 *   IO thread will be created the object pointer will be set to NULL
 *   so the IO thread will know that the work to do is to delete the key
 *   from the disk store.
 *
 * - What happens with MULTI/EXEC?
 *
 *   Good question.
91 92 93
 *
 * - If dsSet() fails on the write thread log the error and reschedule the
 *   key for flush.
94 95
 *
 * - Check why INCR will not update the LRU info for the object.
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
 *
 * - Fix/Check the following race condition: a key gets a DEL so there is
 *   a write operation scheduled against this key. Later the same key will
 *   be the argument of a GET, but the write operation was still not
 *   completed (to delete the file). If the GET will be for some reason
 *   a blocking loading (via lookup) we can load the old value on memory.
 *
 *   This problems can be fixed with negative caching. We can use it
 *   to optimize the system, but also when a key is deleted we mark
 *   it as non existing on disk as well (in a way that this cache
 *   entry can't be evicted, setting time to 0), then we avoid looking at
 *   the disk at all if the key can't be there. When an IO Job complete
 *   a deletion, we set the time of the negative caching to a non zero
 *   value so it will be evicted later.
 *
 *   Are there other patterns like this where we load stale data?
A
antirez 已提交
112 113 114 115
 *
 *   Also, make sure that key preloading is ONLY done for keys that are
 *   not marked as cacheKeyDoesNotExist(), otherwise, again, we can load
 *   data from disk that should instead be deleted.
A
antirez 已提交
116 117
 *
 * - dsSet() use rename(2) in order to avoid corruptions.
A
antirez 已提交
118 119 120
 *
 * - Don't add a LOAD if there is already a LOADINPROGRESS, or is this
 *   impossible since anyway the io_keys stuff will work as lock?
121 122
 */

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
/* Virtual Memory is composed mainly of two subsystems:
 * - Blocking Virutal Memory
 * - Threaded Virtual Memory I/O
 * The two parts are not fully decoupled, but functions are split among two
 * different sections of the source code (delimited by comments) in order to
 * make more clear what functionality is about the blocking VM and what about
 * the threaded (not blocking) VM.
 *
 * Redis VM design:
 *
 * Redis VM is a blocking VM (one that blocks reading swapped values from
 * disk into memory when a value swapped out is needed in memory) that is made
 * unblocking by trying to examine the command argument vector in order to
 * load in background values that will likely be needed in order to exec
 * the command. The command is executed only once all the relevant keys
 * are loaded into memory.
 *
 * This basically is almost as simple of a blocking VM, but almost as parallel
 * as a fully non-blocking VM.
 */

A
antirez 已提交
144 145
void spawnIOThread(void);

146 147
/* =================== Virtual Memory - Blocking Side  ====================== */

148
void dsInit(void) {
149 150 151
    int pipefds[2];
    size_t stacksize;

152
    zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
153

A
antirez 已提交
154
    redisLog(REDIS_NOTICE,"Opening Disk Store: %s", server.ds_path);
155 156 157
    /* Open Disk Store */
    if (dsOpen() != REDIS_OK) {
        redisLog(REDIS_WARNING,"Fatal error opening disk store. Exiting.");
158
        exit(1);
159
    };
160

161
    /* Initialize threaded I/O for Object Cache */
162 163 164 165 166
    server.io_newjobs = listCreate();
    server.io_processing = listCreate();
    server.io_processed = listCreate();
    server.io_ready_clients = listCreate();
    pthread_mutex_init(&server.io_mutex,NULL);
167
    pthread_cond_init(&server.io_condvar,NULL);
168 169
    server.io_active_threads = 0;
    if (pipe(pipefds) == -1) {
170
        redisLog(REDIS_WARNING,"Unable to intialized DS: pipe(2): %s. Exiting."
171 172 173 174 175 176 177 178 179
            ,strerror(errno));
        exit(1);
    }
    server.io_ready_pipe_read = pipefds[0];
    server.io_ready_pipe_write = pipefds[1];
    redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
    /* LZF requires a lot of stack */
    pthread_attr_init(&server.io_threads_attr);
    pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
180 181 182 183 184

    /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
     * multiplying it by 2 in the while loop later will not really help ;) */
    if (!stacksize) stacksize = 1;

185 186 187 188 189 190 191
    while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
    pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
    /* Listen for events in the threaded I/O pipe */
    if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
        vmThreadedIOCompletedJob, NULL) == AE_ERR)
        oom("creating file event");

192 193
    /* Spawn our I/O thread */
    spawnIOThread();
194 195
}

196 197
/* Compute how good candidate the specified object is for eviction.
 * An higher number means a better candidate. */
198 199 200
double computeObjectSwappability(robj *o) {
    /* actual age can be >= minage, but not < minage. As we use wrapping
     * 21 bit clocks with minutes resolution for the LRU. */
201
    return (double) estimateObjectIdleTime(o);
202 203
}

204 205
/* Try to free one entry from the diskstore object cache */
int cacheFreeOneEntry(void) {
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    int j, i;
    struct dictEntry *best = NULL;
    double best_swappability = 0;
    redisDb *best_db = NULL;
    robj *val;
    sds key;

    for (j = 0; j < server.dbnum; j++) {
        redisDb *db = server.db+j;
        /* Why maxtries is set to 100?
         * Because this way (usually) we'll find 1 object even if just 1% - 2%
         * are swappable objects */
        int maxtries = 100;

        if (dictSize(db->dict) == 0) continue;
        for (i = 0; i < 5; i++) {
            dictEntry *de;
            double swappability;
224 225
            robj keyobj;
            sds keystr;
226 227 228

            if (maxtries) maxtries--;
            de = dictGetRandomKey(db->dict);
229
            keystr = dictGetEntryKey(de);
230
            val = dictGetEntryVal(de);
231 232 233 234 235
            initStaticStringObject(keyobj,keystr);

            /* Don't remove objects that are currently target of a
             * read or write operation. */
            if (cacheScheduleIOGetFlags(db,&keyobj) != 0) {
236 237 238 239 240 241 242 243 244 245 246
                if (maxtries) i--; /* don't count this try */
                continue;
            }
            swappability = computeObjectSwappability(val);
            if (!best || swappability > best_swappability) {
                best = de;
                best_swappability = swappability;
                best_db = db;
            }
        }
    }
247 248 249 250 251 252 253
    if (best == NULL) {
        /* FIXME: If there are objects marked as DS_DIRTY or DS_SAVING
         * let's wait for this objects to be clear and retry...
         *
         * Object cache vm limit is considered an hard limit. */
        return REDIS_ERR;
    }
254 255 256
    key = dictGetEntryKey(best);
    val = dictGetEntryVal(best);

257
    redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f",
258 259
        key, best_swappability);

260 261 262 263 264
    /* Delete this key from memory */
    {
        robj *kobj = createStringObject(key,sdslen(key));
        dbDelete(best_db,kobj);
        decrRefCount(kobj);
265
    }
266
    return REDIS_OK;
267 268 269 270 271
}

/* Return true if it's safe to swap out objects in a given moment.
 * Basically we don't want to swap objects out while there is a BGSAVE
 * or a BGAEOREWRITE running in backgroud. */
272
int dsCanTouchDiskStore(void) {
273 274 275
    return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
}

A
antirez 已提交
276 277 278 279 280
/* ==================== Disk store negative caching  ========================
 *
 * When disk store is enabled, we need negative caching, that is, to remember
 * keys that are for sure *not* on the disk key-value store.
 *
281 282
 * This is usefuls because without negative caching cache misses will cost us
 * a disk lookup, even if the same non existing key is accessed again and again.
A
antirez 已提交
283
 *
284 285 286 287
 * With negative caching we remember that the key is not on disk, so if it's
 * not in memory and we have a negative cache entry, we don't try a disk
 * access at all.
 */
A
antirez 已提交
288

289 290
/* Returns true if the specified key may exists on disk, that is, we don't
 * have an entry in our negative cache for this key */
A
antirez 已提交
291 292 293 294
int cacheKeyMayExist(redisDb *db, robj *key) {
    return dictFind(db->io_negcache,key) == NULL;
}

295 296
/* Set the specified key as an entry that may possibily exist on disk, that is,
 * remove the negative cache entry for this key if any. */
A
antirez 已提交
297 298 299 300
void cacheSetKeyMayExist(redisDb *db, robj *key) {
    dictDelete(db->io_negcache,key);
}

301 302
/* Set the specified key as non existing on disk, that is, create a negative
 * cache entry for this key. */
A
antirez 已提交
303 304 305 306 307 308 309
void cacheSetKeyDoesNotExist(redisDb *db, robj *key) {
    if (dictReplace(db->io_negcache,key,(void*)time(NULL))) {
        incrRefCount(key);
    }
}

/* ================== Disk store cache - Threaded I/O  ====================== */
310 311 312

void freeIOJob(iojob *j) {
    decrRefCount(j->key);
313 314
    /* j->val can be NULL if the job is about deleting the key from disk. */
    if (j->val) decrRefCount(j->val);
315 316 317 318 319
    zfree(j);
}

/* Every time a thread finished a Job, it writes a byte into the write side
 * of an unix pipe in order to "awake" the main thread, and this function
A
antirez 已提交
320
 * is called. */
321 322 323 324
void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
            int mask)
{
    char buf[1];
A
antirez 已提交
325
    int retval, processed = 0, toprocess = -1;
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    REDIS_NOTUSED(privdata);

    /* For every byte we read in the read side of the pipe, there is one
     * I/O job completed to process. */
    while((retval = read(fd,buf,1)) == 1) {
        iojob *j;
        listNode *ln;

        redisLog(REDIS_DEBUG,"Processing I/O completed job");

        /* Get the processed element (the oldest one) */
        lockThreadedIO();
        redisAssert(listLength(server.io_processed) != 0);
        if (toprocess == -1) {
            toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
            if (toprocess <= 0) toprocess = 1;
        }
        ln = listFirst(server.io_processed);
        j = ln->value;
        listDelNode(server.io_processed,ln);
        unlockThreadedIO();
A
antirez 已提交
349

350 351
        /* Post process it in the main thread, as there are things we
         * can do just here to avoid race conditions and/or invasive locks */
352 353 354
        redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s",
            (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
            (unsigned char*)j->key->ptr);
355
        if (j->type == REDIS_IOJOB_LOAD) {
356
            /* Create the key-value pair in the in-memory database */
357
            if (j->val != NULL) {
358 359 360
                /* Note: it's possible that the key is already in memory
                 * due to a blocking load operation. */
                if (dbAdd(j->db,j->key,j->val) == REDIS_OK) {
361 362 363
                    incrRefCount(j->val);
                    if (j->expire != -1) setExpire(j->db,j->key,j->expire);
                }
364 365 366
            } else {
                /* The key does not exist. Create a negative cache entry
                 * for this key. */
A
antirez 已提交
367
                cacheSetKeyDoesNotExist(j->db,j->key);
368
            }
369
            cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_LOADINPROG);
370
            handleClientsBlockedOnSwappedKey(j->db,j->key);
371
            freeIOJob(j);
A
antirez 已提交
372
        } else if (j->type == REDIS_IOJOB_SAVE) {
373
            if (j->val) {
A
antirez 已提交
374 375
                cacheSetKeyMayExist(j->db,j->key);
            } else {
376
                cacheSetKeyDoesNotExist(j->db,j->key);
377
            }
378
            cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_SAVEINPROG);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
            freeIOJob(j);
        }
        processed++;
        if (processed == toprocess) return;
    }
    if (retval < 0 && errno != EAGAIN) {
        redisLog(REDIS_WARNING,
            "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
            strerror(errno));
    }
}

void lockThreadedIO(void) {
    pthread_mutex_lock(&server.io_mutex);
}

void unlockThreadedIO(void) {
    pthread_mutex_unlock(&server.io_mutex);
}

void *IOThreadEntryPoint(void *arg) {
    iojob *j;
    listNode *ln;
    REDIS_NOTUSED(arg);

    pthread_detach(pthread_self());
405
    lockThreadedIO();
406 407 408
    while(1) {
        /* Get a new job to process */
        if (listLength(server.io_newjobs) == 0) {
A
antirez 已提交
409 410
            /* Wait for more work to do */
            pthread_cond_wait(&server.io_condvar,&server.io_mutex);
411
            continue;
412
        }
413 414
        redisLog(REDIS_DEBUG,"%ld IO jobs to process",
            listLength(server.io_newjobs));
415 416 417 418 419 420 421
        ln = listFirst(server.io_newjobs);
        j = ln->value;
        listDelNode(server.io_newjobs,ln);
        /* Add the job in the processing queue */
        listAddNodeTail(server.io_processing,j);
        ln = listLast(server.io_processing); /* We use ln later to remove it */
        unlockThreadedIO();
422

423 424 425 426
        redisLog(REDIS_DEBUG,"Thread %ld: new job type %s: %p about key '%s'",
            (long) pthread_self(),
            (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
            (void*)j, (char*)j->key->ptr);
427 428 429

        /* Process the Job */
        if (j->type == REDIS_IOJOB_LOAD) {
430 431 432 433
            time_t expire;

            j->val = dsGet(j->db,j->key,&expire);
            if (j->val) j->expire = expire;
434
        } else if (j->type == REDIS_IOJOB_SAVE) {
435
            if (j->val) {
436
                dsSet(j->db,j->key,j->val);
437
            } else {
438
                dsDel(j->db,j->key);
439
            }
440 441 442 443 444
        }

        /* Done: insert the job into the processed queue */
        redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
            (long) pthread_self(), (void*)j, (char*)j->key->ptr);
445

446 447 448 449 450 451 452
        lockThreadedIO();
        listDelNode(server.io_processing,ln);
        listAddNodeTail(server.io_processed,j);

        /* Signal the main thread there is new stuff to process */
        redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
    }
453 454 455
    /* never reached, but that's the full pattern... */
    unlockThreadedIO();
    return NULL;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
}

void spawnIOThread(void) {
    pthread_t thread;
    sigset_t mask, omask;
    int err;

    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigaddset(&mask,SIGHUP);
    sigaddset(&mask,SIGPIPE);
    pthread_sigmask(SIG_SETMASK, &mask, &omask);
    while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
        redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
            strerror(err));
        usleep(1000000);
    }
    pthread_sigmask(SIG_SETMASK, &omask, NULL);
    server.io_active_threads++;
}

A
antirez 已提交
477
/* Wait that all the pending IO Jobs are processed */
478 479 480 481 482 483
void waitEmptyIOJobsQueue(void) {
    while(1) {
        int io_processed_len;

        lockThreadedIO();
        if (listLength(server.io_newjobs) == 0 &&
A
antirez 已提交
484
            listLength(server.io_processing) == 0)
485 486 487 488
        {
            unlockThreadedIO();
            return;
        }
A
antirez 已提交
489 490 491 492 493 494 495 496 497 498
        /* If there are new jobs we need to signal the thread to
         * process the next one. */
        redisLog(REDIS_DEBUG,"waitEmptyIOJobsQueue: new %d, processing %d",
            listLength(server.io_newjobs),
            listLength(server.io_processing));
            /*
        if (listLength(server.io_newjobs)) {
            pthread_cond_signal(&server.io_condvar);
        }
        */
499 500 501 502 503 504 505
        /* While waiting for empty jobs queue condition we post-process some
         * finshed job, as I/O threads may be hanging trying to write against
         * the io_ready_pipe_write FD but there are so much pending jobs that
         * it's blocking. */
        io_processed_len = listLength(server.io_processed);
        unlockThreadedIO();
        if (io_processed_len) {
506 507
            vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
                                                        (void*)0xdeadbeef,0);
508 509 510 511 512 513 514
            usleep(1000); /* 1 millisecond */
        } else {
            usleep(10000); /* 10 milliseconds */
        }
    }
}

A
antirez 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
/* Process all the IO Jobs already completed by threads but still waiting
 * processing from the main thread. */
void processAllPendingIOJobs(void) {
    while(1) {
        int io_processed_len;

        lockThreadedIO();
        io_processed_len = listLength(server.io_processed);
        unlockThreadedIO();
        if (io_processed_len == 0) return;
        vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
                                                    (void*)0xdeadbeef,0);
    }
}

530 531 532 533 534 535 536 537 538
/* This function must be called while with threaded IO locked */
void queueIOJob(iojob *j) {
    redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
        (void*)j, j->type, (char*)j->key->ptr);
    listAddNodeTail(server.io_newjobs,j);
    if (server.io_active_threads < server.vm_max_threads)
        spawnIOThread();
}

539
void dsCreateIOJob(int type, redisDb *db, robj *key, robj *val) {
540 541 542
    iojob *j;

    j = zmalloc(sizeof(*j));
543
    j->type = type;
544 545 546
    j->db = db;
    j->key = key;
    incrRefCount(key);
547
    j->val = val;
548
    if (val) incrRefCount(val);
549 550 551

    lockThreadedIO();
    queueIOJob(j);
552
    pthread_cond_signal(&server.io_condvar);
553 554 555
    unlockThreadedIO();
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
/* ============= Disk store cache - Scheduling of IO operations ============= 
 *
 * We use a queue and an hash table to hold the state of IO operations
 * so that's fast to lookup if there is already an IO operation in queue
 * for a given key.
 *
 * There are two types of IO operations for a given key:
 * REDIS_IO_LOAD and REDIS_IO_SAVE.
 *
 * The function cacheScheduleIO() function pushes the specified IO operation
 * in the queue, but avoid adding the same key for the same operation
 * multiple times, thanks to the associated hash table.
 *
 * We take a set of flags per every key, so when the scheduled IO operation
 * gets moved from the scheduled queue to the actual IO Jobs queue that
 * is processed by the IO thread, we flag it as IO_LOADINPROG or
 * IO_SAVEINPROG.
 *
 * So for every given key we always know if there is some IO operation
 * scheduled, or in progress, for this key.
 *
 * NOTE: all this is very important in order to guarantee correctness of
 * the Disk Store Cache. Jobs are always queued here. Load jobs are
 * queued at the head for faster execution only in the case there is not
 * already a write operation of some kind for this job.
 *
 * So we have ordering, but can do exceptions when there are no already
 * operations for a given key. Also when we need to block load a given
 * key, for an immediate lookup operation, we can check if the key can
 * be accessed synchronously without race conditions (no IN PROGRESS
 * operations for this key), otherwise we blocking wait for completion. */

#define REDIS_IO_LOAD 1
#define REDIS_IO_SAVE 2
#define REDIS_IO_LOADINPROG 4
#define REDIS_IO_SAVEINPROG 8

void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag) {
    struct dictEntry *de = dictFind(db->io_queued,key);

    if (!de) {
        dictAdd(db->io_queued,key,(void*)flag);
        incrRefCount(key);
        return;
    } else {
        long flags = (long) dictGetEntryVal(de);
A
antirez 已提交
602 603 604 605 606

        if (flags & flag) {
            redisLog(REDIS_WARNING,"Adding the same flag again: was: %ld, addede: %ld",flags,flag);
            redisAssert(!(flags & flag));
        }
607 608
        flags |= flag;
        dictGetEntryVal(de) = (void*) flags;
609
    }
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
}

void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag) {
    struct dictEntry *de = dictFind(db->io_queued,key);
    long flags;

    redisAssert(de != NULL);
    flags = (long) dictGetEntryVal(de);
    redisAssert(flags & flag);
    flags &= ~flag;
    if (flags == 0) {
        dictDelete(db->io_queued,key);
    } else {
        dictGetEntryVal(de) = (void*) flags;
    }
}
626

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
int cacheScheduleIOGetFlags(redisDb *db, robj *key) {
    struct dictEntry *de = dictFind(db->io_queued,key);

    return (de == NULL) ? 0 : ((long) dictGetEntryVal(de));
}

void cacheScheduleIO(redisDb *db, robj *key, int type) {
    ioop *op;
    long flags;

    if ((flags = cacheScheduleIOGetFlags(db,key)) & type) return;
    
    redisLog(REDIS_DEBUG,"Scheduling key %s for %s",
        key->ptr, type == REDIS_IO_LOAD ? "loading" : "saving");
    cacheScheduleIOAddFlag(db,key,type);
    op = zmalloc(sizeof(*op));
    op->type = type;
    op->db = db;
    op->key = key;
646
    incrRefCount(key);
647 648 649 650 651 652 653 654 655 656 657 658
    op->ctime = time(NULL);

    /* Give priority to load operations if there are no save already
     * in queue for the same key. */
    if (type == REDIS_IO_LOAD && !(flags & REDIS_IO_SAVE)) {
        listAddNodeHead(server.cache_io_queue, op);
    } else {
        /* FIXME: probably when this happens we want to at least move
         * the write job about this queue on top, and set the creation time
         * to a value that will force processing ASAP. */
        listAddNodeTail(server.cache_io_queue, op);
    }
659 660 661 662 663
}

void cacheCron(void) {
    time_t now = time(NULL);
    listNode *ln;
664 665 666 667 668 669 670 671 672
    int jobs, topush = 0;

    /* Sync stuff on disk, but only if we have less than 100 IO jobs */
    lockThreadedIO();
    jobs = listLength(server.io_newjobs);
    unlockThreadedIO();

    topush = 100-jobs;
    if (topush < 0) topush = 0;
A
antirez 已提交
673 674
    if (topush > (signed)listLength(server.cache_io_queue))
        topush = listLength(server.cache_io_queue);
675

676 677
    while((ln = listFirst(server.cache_io_queue)) != NULL) {
        ioop *op = ln->value;
678

679 680 681
        if (!topush) break;
        topush--;

682 683 684
        if (op->type == REDIS_IO_LOAD ||
            (now - op->ctime) >= server.cache_flush_delay)
        {
685 686 687
            struct dictEntry *de;
            robj *val;

A
antirez 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
            /* Don't add a SAVE job in queue if there is already
             * a save in progress for the same key. */
            if (op->type == REDIS_IO_SAVE && 
                cacheScheduleIOGetFlags(op->db,op->key) & REDIS_IO_SAVEINPROG)
            {
                /* Move the operation at the end of the list of there
                 * are other operations. Otherwise break, nothing to do
                 * here. */
                if (listLength(server.cache_io_queue) > 1) {
                    listDelNode(server.cache_io_queue,ln);
                    listAddNodeTail(server.cache_io_queue,op);
                    continue;
                } else {
                    break;
                }
            }

705 706 707 708 709
            redisLog(REDIS_DEBUG,"Creating IO %s Job for key %s",
                op->type == REDIS_IO_LOAD ? "load" : "save", op->key->ptr);

            if (op->type == REDIS_IO_LOAD) {
                dsCreateIOJob(REDIS_IOJOB_LOAD,op->db,op->key,NULL);
710
            } else {
711 712 713 714 715 716 717 718 719 720 721 722
                /* Lookup the key, in order to put the current value in the IO
                 * Job. Otherwise if the key does not exists we schedule a disk
                 * store delete operation, setting the value to NULL. */
                de = dictFind(op->db->dict,op->key->ptr);
                if (de) {
                    val = dictGetEntryVal(de);
                } else {
                    /* Setting the value to NULL tells the IO thread to delete
                     * the key on disk. */
                    val = NULL;
                }
                dsCreateIOJob(REDIS_IOJOB_SAVE,op->db,op->key,val);
723
            }
724 725 726 727 728 729 730 731 732 733
            /* Mark the operation as in progress. */
            cacheScheduleIODelFlag(op->db,op->key,op->type);
            cacheScheduleIOAddFlag(op->db,op->key,
                (op->type == REDIS_IO_LOAD) ? REDIS_IO_LOADINPROG :
                                              REDIS_IO_SAVEINPROG);
            /* Finally remove the operation from the queue.
             * But we'll have trace of it in the hash table. */
            listDelNode(server.cache_io_queue,ln);
            decrRefCount(op->key);
            zfree(op);
734 735 736 737 738 739 740 741 742 743
        } else {
            break; /* too early */
        }
    }

    /* Reclaim memory from the object cache */
    while (server.ds_enabled && zmalloc_used_memory() >
            server.cache_max_memory)
    {
        if (cacheFreeOneEntry() == REDIS_ERR) break;
744
        /* FIXME: also free negative cache entries here. */
745 746 747
    }
}

748
/* ========== Disk store cache - Blocking clients on missing keys =========== */
749 750

/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
751
 * If the key is already in memory we don't need to block.
752
 *
753 754 755 756 757 758 759 760
 *   FIXME: we should try if it's actually better to suspend the client
 *   accessing an object that is being saved, and awake it only when
 *   the saving was completed.
 *
 * Otherwise if the key is not in memory, we block the client and start
 * an IO Job to load it:
 *
 * the key is added to the io_keys list in the client structure, and also
761 762 763 764 765 766
 * in the hash table mapping swapped keys to waiting clients, that is,
 * server.io_waited_keys. */
int waitForSwappedKey(redisClient *c, robj *key) {
    struct dictEntry *de;
    list *l;

767
    /* Return ASAP if the key is in memory */
768
    de = dictFind(c->db->dict,key->ptr);
769
    if (de != NULL) return 0;
770

A
antirez 已提交
771 772 773
    /* Don't wait for keys we are sure are not on disk either */
    if (!cacheKeyMayExist(c->db,key)) return 0;

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    /* Add the key to the list of keys this client is waiting for.
     * This maps clients to keys they are waiting for. */
    listAddNodeTail(c->io_keys,key);
    incrRefCount(key);

    /* Add the client to the swapped keys => clients waiting map. */
    de = dictFind(c->db->io_keys,key);
    if (de == NULL) {
        int retval;

        /* For every key we take a list of clients blocked for it */
        l = listCreate();
        retval = dictAdd(c->db->io_keys,key,l);
        incrRefCount(key);
        redisAssert(retval == DICT_OK);
    } else {
        l = dictGetEntryVal(de);
    }
    listAddNodeTail(l,c);

    /* Are we already loading the key from disk? If not create a job */
795
    if (de == NULL)
796
        cacheScheduleIO(c->db,key,REDIS_IO_LOAD);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
    return 1;
}

/* Preload keys for any command with first, last and step values for
 * the command keys prototype, as defined in the command table. */
void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
    int j, last;
    if (cmd->vm_firstkey == 0) return;
    last = cmd->vm_lastkey;
    if (last < 0) last = argc+last;
    for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
        redisAssert(j < argc);
        waitForSwappedKey(c,argv[j]);
    }
}

/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
 * Note that the number of keys to preload is user-defined, so we need to
 * apply a sanity check against argc. */
void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
    int i, num;
    REDIS_NOTUSED(cmd);

    num = atoi(argv[2]->ptr);
    if (num > (argc-3)) return;
    for (i = 0; i < num; i++) {
        waitForSwappedKey(c,argv[3+i]);
    }
}

/* Preload keys needed to execute the entire MULTI/EXEC block.
 *
 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
 * and will block the client when any command requires a swapped out value. */
void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
    int i, margc;
    struct redisCommand *mcmd;
    robj **margv;
    REDIS_NOTUSED(cmd);
    REDIS_NOTUSED(argc);
    REDIS_NOTUSED(argv);

    if (!(c->flags & REDIS_MULTI)) return;
    for (i = 0; i < c->mstate.count; i++) {
        mcmd = c->mstate.commands[i].cmd;
        margc = c->mstate.commands[i].argc;
        margv = c->mstate.commands[i].argv;

        if (mcmd->vm_preload_proc != NULL) {
            mcmd->vm_preload_proc(c,mcmd,margc,margv);
        } else {
            waitForMultipleSwappedKeys(c,mcmd,margc,margv);
        }
    }
}

/* Is this client attempting to run a command against swapped keys?
 * If so, block it ASAP, load the keys in background, then resume it.
 *
 * The important idea about this function is that it can fail! If keys will
 * still be swapped when the client is resumed, this key lookups will
 * just block loading keys from disk. In practical terms this should only
 * happen with SORT BY command or if there is a bug in this function.
 *
 * Return 1 if the client is marked as blocked, 0 if the client can
 * continue as the keys it is going to access appear to be in memory. */
int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
    if (cmd->vm_preload_proc != NULL) {
        cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
    } else {
        waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
    }

    /* If the client was blocked for at least one key, mark it as blocked. */
    if (listLength(c->io_keys)) {
        c->flags |= REDIS_IO_WAIT;
        aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
874
        server.cache_blocked_clients++;
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
        return 1;
    } else {
        return 0;
    }
}

/* Remove the 'key' from the list of blocked keys for a given client.
 *
 * The function returns 1 when there are no longer blocking keys after
 * the current one was removed (and the client can be unblocked). */
int dontWaitForSwappedKey(redisClient *c, robj *key) {
    list *l;
    listNode *ln;
    listIter li;
    struct dictEntry *de;

891 892 893 894 895
    /* The key object might be destroyed when deleted from the c->io_keys
     * list (and the "key" argument is physically the same object as the
     * object inside the list), so we need to protect it. */
    incrRefCount(key);

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    /* Remove the key from the list of keys this client is waiting for. */
    listRewind(c->io_keys,&li);
    while ((ln = listNext(&li)) != NULL) {
        if (equalStringObjects(ln->value,key)) {
            listDelNode(c->io_keys,ln);
            break;
        }
    }
    redisAssert(ln != NULL);

    /* Remove the client form the key => waiting clients map. */
    de = dictFind(c->db->io_keys,key);
    redisAssert(de != NULL);
    l = dictGetEntryVal(de);
    ln = listSearchKey(l,c);
    redisAssert(ln != NULL);
    listDelNode(l,ln);
    if (listLength(l) == 0)
        dictDelete(c->db->io_keys,key);

916
    decrRefCount(key);
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    return listLength(c->io_keys) == 0;
}

/* Every time we now a key was loaded back in memory, we handle clients
 * waiting for this key if any. */
void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
    struct dictEntry *de;
    list *l;
    listNode *ln;
    int len;

    de = dictFind(db->io_keys,key);
    if (!de) return;

    l = dictGetEntryVal(de);
    len = listLength(l);
    /* Note: we can't use something like while(listLength(l)) as the list
     * can be freed by the calling function when we remove the last element. */
    while (len--) {
        ln = listFirst(l);
        redisClient *c = ln->value;

        if (dontWaitForSwappedKey(c,key)) {
            /* Put the client in the list of clients ready to go as we
             * loaded all the keys about it. */
            listAddNodeTail(server.io_ready_clients,c);
        }
    }
}