]> git.saurik.com Git - redis.git/blame - src/dscache.c
diskstore race condition fixed
[redis.git] / src / dscache.c
CommitLineData
e2641e09 1#include "redis.h"
2
3#include <fcntl.h>
4#include <pthread.h>
5#include <math.h>
6#include <signal.h>
7
33388d43 8/* dscache.c - Disk store cache for disk store backend.
9 *
10 * When Redis is configured for using disk as backend instead of memory, the
11 * memory is used as a cache, so that recently accessed keys are taken in
12 * memory for fast read and write operations.
13 *
14 * Modified keys are marked to be flushed on disk, and will be flushed
15 * as long as the maxium configured flush time elapsed.
16 *
17 * This file implements the whole caching subsystem and contains further
18 * documentation. */
19
20/* TODO:
133cf28e 21 *
22 * WARNING: most of the following todo items and design issues are no
23 * longer relevant with the new design. Here as a checklist to see if
24 * some old ideas still apply.
33388d43 25 *
26 * - The WATCH helper will be used to signal the cache system
27 * we need to flush a given key/dbid into disk, adding this key/dbid
28 * pair into a server.ds_cache_dirty linked list AND hash table (so that we
29 * don't add the same thing multiple times).
30 *
31 * - cron() checks if there are elements on this list. When there are things
32 * to flush, we create an IO Job for the I/O thread.
16d77878 33 * NOTE: We disalbe object sharing when server.ds_enabled == 1 so objects
34 * that are referenced an IO job for flushing on disk are marked as
35 * o->storage == REDIS_DS_SAVING.
33388d43 36 *
37 * - This is what we do on key lookup:
16d77878 38 * 1) The key already exists in memory. object->storage == REDIS_DS_MEMORY
39 * or it is object->storage == REDIS_DS_DIRTY:
33388d43 40 * We don't do nothing special, lookup, return value object pointer.
41 * 2) The key is in memory but object->storage == REDIS_DS_SAVING.
16d77878 42 * When this happens we block waiting for the I/O thread to process
43 * this object. Then continue.
33388d43 44 * 3) The key is not in memory. We block to load the key from disk.
45 * Of course the key may not be present at all on the disk store as well,
46 * in such case we just detect this condition and continue, returning
47 * NULL from lookup.
48 *
49 * - Preloading of needed keys:
50 * 1) As it was done with VM, also with this new system we try preloading
51 * keys a client is going to use. We block the client, load keys
52 * using the I/O thread, unblock the client. Same code as VM more or less.
53 *
16d77878 54 * - Reclaiming memory.
55 * In cron() we detect our memory limit was reached. What we
56 * do is deleting keys that are REDIS_DS_MEMORY, using LRU.
57 *
33388d43 58 * If this is not enough to return again under the memory limits we also
59 * start to flush keys that need to be synched on disk synchronously,
16d77878 60 * removing it from the memory. We do this blocking as memory limit is a
61 * much "harder" barrirer in the new design.
33388d43 62 *
63 * - IO thread operations are no longer stopped for sync loading/saving of
16d77878 64 * things. When a key is found to be in the process of being saved
65 * we simply wait for the IO thread to end its work.
33388d43 66 *
67 * Otherwise if there is to load a key without any IO thread operation
68 * just started it is blocking-loaded in the lookup function.
16d77878 69 *
70 * - What happens when an object is destroyed?
71 *
72 * If o->storage == REDIS_DS_MEMORY then we simply destory the object.
73 * If o->storage == REDIS_DS_DIRTY we can still remove the object. It had
74 * changes not flushed on disk, but is being removed so
75 * who cares.
76 * if o->storage == REDIS_DS_SAVING then the object is being saved so
77 * it is impossible that its refcount == 1, must be at
78 * least two. When the object is saved the storage will
79 * be set back to DS_MEMORY.
80 *
81 * - What happens when keys are deleted?
82 *
83 * We simply schedule a key flush operation as usually, but when the
84 * IO thread will be created the object pointer will be set to NULL
85 * so the IO thread will know that the work to do is to delete the key
86 * from the disk store.
87 *
88 * - What happens with MULTI/EXEC?
89 *
90 * Good question.
4ab98823 91 *
92 * - If dsSet() fails on the write thread log the error and reschedule the
93 * key for flush.
98a9abb6 94 *
95 * - Check why INCR will not update the LRU info for the object.
8e6bb671 96 *
97 * - Fix/Check the following race condition: a key gets a DEL so there is
98 * a write operation scheduled against this key. Later the same key will
99 * be the argument of a GET, but the write operation was still not
100 * completed (to delete the file). If the GET will be for some reason
101 * a blocking loading (via lookup) we can load the old value on memory.
102 *
103 * This problems can be fixed with negative caching. We can use it
104 * to optimize the system, but also when a key is deleted we mark
105 * it as non existing on disk as well (in a way that this cache
106 * entry can't be evicted, setting time to 0), then we avoid looking at
107 * the disk at all if the key can't be there. When an IO Job complete
108 * a deletion, we set the time of the negative caching to a non zero
109 * value so it will be evicted later.
110 *
111 * Are there other patterns like this where we load stale data?
d934e1e8 112 *
113 * Also, make sure that key preloading is ONLY done for keys that are
114 * not marked as cacheKeyDoesNotExist(), otherwise, again, we can load
115 * data from disk that should instead be deleted.
aa81e4d5 116 *
117 * - dsSet() use rename(2) in order to avoid corruptions.
33388d43 118 */
119
e2641e09 120/* Virtual Memory is composed mainly of two subsystems:
121 * - Blocking Virutal Memory
122 * - Threaded Virtual Memory I/O
123 * The two parts are not fully decoupled, but functions are split among two
124 * different sections of the source code (delimited by comments) in order to
125 * make more clear what functionality is about the blocking VM and what about
126 * the threaded (not blocking) VM.
127 *
128 * Redis VM design:
129 *
130 * Redis VM is a blocking VM (one that blocks reading swapped values from
131 * disk into memory when a value swapped out is needed in memory) that is made
132 * unblocking by trying to examine the command argument vector in order to
133 * load in background values that will likely be needed in order to exec
134 * the command. The command is executed only once all the relevant keys
135 * are loaded into memory.
136 *
137 * This basically is almost as simple of a blocking VM, but almost as parallel
138 * as a fully non-blocking VM.
139 */
140
f34a6cd8 141void spawnIOThread(void);
142
e2641e09 143/* =================== Virtual Memory - Blocking Side ====================== */
144
f2da3a62 145void dsInit(void) {
e2641e09 146 int pipefds[2];
147 size_t stacksize;
e2641e09 148
f2da3a62 149 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
e2641e09 150
67b0b41c 151 redisLog(REDIS_NOTICE,"Opening Disk Store: %s", server.ds_path);
f2da3a62 152 /* Open Disk Store */
153 if (dsOpen() != REDIS_OK) {
154 redisLog(REDIS_WARNING,"Fatal error opening disk store. Exiting.");
e2641e09 155 exit(1);
f2da3a62 156 };
e2641e09 157
f2da3a62 158 /* Initialize threaded I/O for Object Cache */
e2641e09 159 server.io_newjobs = listCreate();
160 server.io_processing = listCreate();
161 server.io_processed = listCreate();
162 server.io_ready_clients = listCreate();
163 pthread_mutex_init(&server.io_mutex,NULL);
98a9abb6 164 pthread_cond_init(&server.io_condvar,NULL);
e2641e09 165 server.io_active_threads = 0;
166 if (pipe(pipefds) == -1) {
f2da3a62 167 redisLog(REDIS_WARNING,"Unable to intialized DS: pipe(2): %s. Exiting."
e2641e09 168 ,strerror(errno));
169 exit(1);
170 }
171 server.io_ready_pipe_read = pipefds[0];
172 server.io_ready_pipe_write = pipefds[1];
173 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
174 /* LZF requires a lot of stack */
175 pthread_attr_init(&server.io_threads_attr);
176 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
556bdfba 177
178 /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
179 * multiplying it by 2 in the while loop later will not really help ;) */
180 if (!stacksize) stacksize = 1;
181
e2641e09 182 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
183 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
184 /* Listen for events in the threaded I/O pipe */
185 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
186 vmThreadedIOCompletedJob, NULL) == AE_ERR)
187 oom("creating file event");
e2641e09 188
f2da3a62 189 /* Spawn our I/O thread */
190 spawnIOThread();
e2641e09 191}
192
f2da3a62 193/* Compute how good candidate the specified object is for eviction.
194 * An higher number means a better candidate. */
e2641e09 195double computeObjectSwappability(robj *o) {
196 /* actual age can be >= minage, but not < minage. As we use wrapping
197 * 21 bit clocks with minutes resolution for the LRU. */
f081eaf1 198 return (double) estimateObjectIdleTime(o);
e2641e09 199}
200
f2da3a62 201/* Try to free one entry from the diskstore object cache */
202int cacheFreeOneEntry(void) {
e2641e09 203 int j, i;
204 struct dictEntry *best = NULL;
205 double best_swappability = 0;
206 redisDb *best_db = NULL;
207 robj *val;
208 sds key;
209
210 for (j = 0; j < server.dbnum; j++) {
211 redisDb *db = server.db+j;
212 /* Why maxtries is set to 100?
213 * Because this way (usually) we'll find 1 object even if just 1% - 2%
214 * are swappable objects */
215 int maxtries = 100;
216
217 if (dictSize(db->dict) == 0) continue;
218 for (i = 0; i < 5; i++) {
219 dictEntry *de;
220 double swappability;
3be00d7e 221 robj keyobj;
222 sds keystr;
e2641e09 223
224 if (maxtries) maxtries--;
225 de = dictGetRandomKey(db->dict);
3be00d7e 226 keystr = dictGetEntryKey(de);
e2641e09 227 val = dictGetEntryVal(de);
3be00d7e 228 initStaticStringObject(keyobj,keystr);
229
230 /* Don't remove objects that are currently target of a
231 * read or write operation. */
232 if (cacheScheduleIOGetFlags(db,&keyobj) != 0) {
e2641e09 233 if (maxtries) i--; /* don't count this try */
234 continue;
235 }
236 swappability = computeObjectSwappability(val);
237 if (!best || swappability > best_swappability) {
238 best = de;
239 best_swappability = swappability;
240 best_db = db;
241 }
242 }
243 }
f2da3a62 244 if (best == NULL) {
245 /* FIXME: If there are objects marked as DS_DIRTY or DS_SAVING
246 * let's wait for this objects to be clear and retry...
247 *
248 * Object cache vm limit is considered an hard limit. */
249 return REDIS_ERR;
250 }
e2641e09 251 key = dictGetEntryKey(best);
252 val = dictGetEntryVal(best);
253
f2da3a62 254 redisLog(REDIS_DEBUG,"Key selected for cache eviction: %s swappability:%f",
e2641e09 255 key, best_swappability);
256
f2da3a62 257 /* Delete this key from memory */
258 {
259 robj *kobj = createStringObject(key,sdslen(key));
260 dbDelete(best_db,kobj);
261 decrRefCount(kobj);
e2641e09 262 }
5ef64098 263 return REDIS_OK;
e2641e09 264}
265
e2641e09 266/* Return true if it's safe to swap out objects in a given moment.
267 * Basically we don't want to swap objects out while there is a BGSAVE
268 * or a BGAEOREWRITE running in backgroud. */
f2da3a62 269int dsCanTouchDiskStore(void) {
e2641e09 270 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
271}
272
d934e1e8 273/* ==================== Disk store negative caching ========================
274 *
275 * When disk store is enabled, we need negative caching, that is, to remember
276 * keys that are for sure *not* on the disk key-value store.
277 *
3be00d7e 278 * This is usefuls because without negative caching cache misses will cost us
279 * a disk lookup, even if the same non existing key is accessed again and again.
d934e1e8 280 *
3be00d7e 281 * With negative caching we remember that the key is not on disk, so if it's
282 * not in memory and we have a negative cache entry, we don't try a disk
283 * access at all.
284 */
d934e1e8 285
3be00d7e 286/* Returns true if the specified key may exists on disk, that is, we don't
287 * have an entry in our negative cache for this key */
d934e1e8 288int cacheKeyMayExist(redisDb *db, robj *key) {
289 return dictFind(db->io_negcache,key) == NULL;
290}
291
3be00d7e 292/* Set the specified key as an entry that may possibily exist on disk, that is,
293 * remove the negative cache entry for this key if any. */
d934e1e8 294void cacheSetKeyMayExist(redisDb *db, robj *key) {
295 dictDelete(db->io_negcache,key);
296}
297
3be00d7e 298/* Set the specified key as non existing on disk, that is, create a negative
299 * cache entry for this key. */
d934e1e8 300void cacheSetKeyDoesNotExist(redisDb *db, robj *key) {
d934e1e8 301 if (dictReplace(db->io_negcache,key,(void*)time(NULL))) {
302 incrRefCount(key);
303 }
304}
305
d934e1e8 306/* ================== Disk store cache - Threaded I/O ====================== */
e2641e09 307
308void freeIOJob(iojob *j) {
e2641e09 309 decrRefCount(j->key);
5ef64098 310 /* j->val can be NULL if the job is about deleting the key from disk. */
311 if (j->val) decrRefCount(j->val);
e2641e09 312 zfree(j);
313}
314
315/* Every time a thread finished a Job, it writes a byte into the write side
316 * of an unix pipe in order to "awake" the main thread, and this function
f34a6cd8 317 * is called. */
e2641e09 318void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
319 int mask)
320{
321 char buf[1];
f34a6cd8 322 int retval, processed = 0, toprocess = -1;
e2641e09 323 REDIS_NOTUSED(el);
324 REDIS_NOTUSED(mask);
325 REDIS_NOTUSED(privdata);
326
327 /* For every byte we read in the read side of the pipe, there is one
328 * I/O job completed to process. */
329 while((retval = read(fd,buf,1)) == 1) {
330 iojob *j;
331 listNode *ln;
e2641e09 332
333 redisLog(REDIS_DEBUG,"Processing I/O completed job");
334
335 /* Get the processed element (the oldest one) */
336 lockThreadedIO();
337 redisAssert(listLength(server.io_processed) != 0);
338 if (toprocess == -1) {
339 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
340 if (toprocess <= 0) toprocess = 1;
341 }
342 ln = listFirst(server.io_processed);
343 j = ln->value;
344 listDelNode(server.io_processed,ln);
345 unlockThreadedIO();
f34a6cd8 346
e2641e09 347 /* Post process it in the main thread, as there are things we
348 * can do just here to avoid race conditions and/or invasive locks */
5ef64098 349 redisLog(REDIS_DEBUG,"COMPLETED Job type %s, key: %s",
350 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
351 (unsigned char*)j->key->ptr);
e2641e09 352 if (j->type == REDIS_IOJOB_LOAD) {
5ef64098 353 /* Create the key-value pair in the in-memory database */
4ab98823 354 if (j->val != NULL) {
3be00d7e 355 /* Note: it's possible that the key is already in memory
356 * due to a blocking load operation. */
357 if (dbAdd(j->db,j->key,j->val) == REDIS_OK) {
ad01a255 358 incrRefCount(j->val);
359 if (j->expire != -1) setExpire(j->db,j->key,j->expire);
360 }
4ab98823 361 } else {
362 /* The key does not exist. Create a negative cache entry
363 * for this key. */
d934e1e8 364 cacheSetKeyDoesNotExist(j->db,j->key);
4ab98823 365 }
3be00d7e 366 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_LOADINPROG);
5ef64098 367 handleClientsBlockedOnSwappedKey(j->db,j->key);
e2641e09 368 freeIOJob(j);
5f6e1183 369 } else if (j->type == REDIS_IOJOB_SAVE) {
31222292 370 if (j->val) {
d934e1e8 371 cacheSetKeyMayExist(j->db,j->key);
372 } else {
3be00d7e 373 cacheSetKeyDoesNotExist(j->db,j->key);
31222292 374 }
3be00d7e 375 cacheScheduleIODelFlag(j->db,j->key,REDIS_IO_SAVEINPROG);
e2641e09 376 freeIOJob(j);
e2641e09 377 }
378 processed++;
379 if (processed == toprocess) return;
380 }
381 if (retval < 0 && errno != EAGAIN) {
382 redisLog(REDIS_WARNING,
383 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
384 strerror(errno));
385 }
386}
387
388void lockThreadedIO(void) {
389 pthread_mutex_lock(&server.io_mutex);
390}
391
392void unlockThreadedIO(void) {
393 pthread_mutex_unlock(&server.io_mutex);
394}
395
e2641e09 396void *IOThreadEntryPoint(void *arg) {
397 iojob *j;
398 listNode *ln;
399 REDIS_NOTUSED(arg);
400
401 pthread_detach(pthread_self());
98a9abb6 402 lockThreadedIO();
e2641e09 403 while(1) {
404 /* Get a new job to process */
e2641e09 405 if (listLength(server.io_newjobs) == 0) {
a440ecf0 406 /* Wait for more work to do */
407 pthread_cond_wait(&server.io_condvar,&server.io_mutex);
1609a1c4 408 continue;
e2641e09 409 }
c4b64a13 410 redisLog(REDIS_DEBUG,"%ld IO jobs to process",
411 listLength(server.io_newjobs));
e2641e09 412 ln = listFirst(server.io_newjobs);
413 j = ln->value;
414 listDelNode(server.io_newjobs,ln);
415 /* Add the job in the processing queue */
e2641e09 416 listAddNodeTail(server.io_processing,j);
417 ln = listLast(server.io_processing); /* We use ln later to remove it */
418 unlockThreadedIO();
98a9abb6 419
5ef64098 420 redisLog(REDIS_DEBUG,"Thread %ld: new job type %s: %p about key '%s'",
421 (long) pthread_self(),
422 (j->type == REDIS_IOJOB_LOAD) ? "load" : "save",
423 (void*)j, (char*)j->key->ptr);
e2641e09 424
425 /* Process the Job */
426 if (j->type == REDIS_IOJOB_LOAD) {
4ab98823 427 time_t expire;
428
429 j->val = dsGet(j->db,j->key,&expire);
430 if (j->val) j->expire = expire;
5ef64098 431 } else if (j->type == REDIS_IOJOB_SAVE) {
31222292 432 if (j->val) {
5ef64098 433 dsSet(j->db,j->key,j->val);
31222292 434 } else {
5ef64098 435 dsDel(j->db,j->key);
31222292 436 }
e2641e09 437 }
438
439 /* Done: insert the job into the processed queue */
440 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
441 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
98a9abb6 442
e2641e09 443 lockThreadedIO();
444 listDelNode(server.io_processing,ln);
445 listAddNodeTail(server.io_processed,j);
e2641e09 446
447 /* Signal the main thread there is new stuff to process */
448 redisAssert(write(server.io_ready_pipe_write,"x",1) == 1);
449 }
98a9abb6 450 /* never reached, but that's the full pattern... */
451 unlockThreadedIO();
452 return NULL;
e2641e09 453}
454
455void spawnIOThread(void) {
456 pthread_t thread;
457 sigset_t mask, omask;
458 int err;
459
460 sigemptyset(&mask);
461 sigaddset(&mask,SIGCHLD);
462 sigaddset(&mask,SIGHUP);
463 sigaddset(&mask,SIGPIPE);
464 pthread_sigmask(SIG_SETMASK, &mask, &omask);
465 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
466 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
467 strerror(err));
468 usleep(1000000);
469 }
470 pthread_sigmask(SIG_SETMASK, &omask, NULL);
471 server.io_active_threads++;
472}
473
8d51fb6a 474/* Wait that all the pending IO Jobs are processed */
e2641e09 475void waitEmptyIOJobsQueue(void) {
476 while(1) {
477 int io_processed_len;
478
479 lockThreadedIO();
480 if (listLength(server.io_newjobs) == 0 &&
8d51fb6a 481 listLength(server.io_processing) == 0)
e2641e09 482 {
483 unlockThreadedIO();
484 return;
485 }
a440ecf0 486 /* If there are new jobs we need to signal the thread to
487 * process the next one. */
488 redisLog(REDIS_DEBUG,"waitEmptyIOJobsQueue: new %d, processing %d",
489 listLength(server.io_newjobs),
490 listLength(server.io_processing));
491 /*
492 if (listLength(server.io_newjobs)) {
493 pthread_cond_signal(&server.io_condvar);
494 }
495 */
e2641e09 496 /* While waiting for empty jobs queue condition we post-process some
497 * finshed job, as I/O threads may be hanging trying to write against
498 * the io_ready_pipe_write FD but there are so much pending jobs that
499 * it's blocking. */
500 io_processed_len = listLength(server.io_processed);
501 unlockThreadedIO();
502 if (io_processed_len) {
c1ae36ae 503 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
504 (void*)0xdeadbeef,0);
e2641e09 505 usleep(1000); /* 1 millisecond */
506 } else {
507 usleep(10000); /* 10 milliseconds */
508 }
509 }
510}
511
8d51fb6a 512/* Process all the IO Jobs already completed by threads but still waiting
513 * processing from the main thread. */
514void processAllPendingIOJobs(void) {
515 while(1) {
516 int io_processed_len;
517
518 lockThreadedIO();
519 io_processed_len = listLength(server.io_processed);
520 unlockThreadedIO();
521 if (io_processed_len == 0) return;
522 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,
523 (void*)0xdeadbeef,0);
524 }
525}
526
e2641e09 527/* This function must be called while with threaded IO locked */
528void queueIOJob(iojob *j) {
529 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
530 (void*)j, j->type, (char*)j->key->ptr);
531 listAddNodeTail(server.io_newjobs,j);
532 if (server.io_active_threads < server.vm_max_threads)
533 spawnIOThread();
534}
535
5ef64098 536void dsCreateIOJob(int type, redisDb *db, robj *key, robj *val) {
e2641e09 537 iojob *j;
538
539 j = zmalloc(sizeof(*j));
5ef64098 540 j->type = type;
e2641e09 541 j->db = db;
542 j->key = key;
543 incrRefCount(key);
5ef64098 544 j->val = val;
1609a1c4 545 if (val) incrRefCount(val);
e2641e09 546
547 lockThreadedIO();
548 queueIOJob(j);
98a9abb6 549 pthread_cond_signal(&server.io_condvar);
e2641e09 550 unlockThreadedIO();
e2641e09 551}
552
3be00d7e 553/* ============= Disk store cache - Scheduling of IO operations =============
554 *
555 * We use a queue and an hash table to hold the state of IO operations
556 * so that's fast to lookup if there is already an IO operation in queue
557 * for a given key.
558 *
559 * There are two types of IO operations for a given key:
560 * REDIS_IO_LOAD and REDIS_IO_SAVE.
561 *
562 * The function cacheScheduleIO() function pushes the specified IO operation
563 * in the queue, but avoid adding the same key for the same operation
564 * multiple times, thanks to the associated hash table.
565 *
566 * We take a set of flags per every key, so when the scheduled IO operation
567 * gets moved from the scheduled queue to the actual IO Jobs queue that
568 * is processed by the IO thread, we flag it as IO_LOADINPROG or
569 * IO_SAVEINPROG.
570 *
571 * So for every given key we always know if there is some IO operation
572 * scheduled, or in progress, for this key.
573 *
574 * NOTE: all this is very important in order to guarantee correctness of
575 * the Disk Store Cache. Jobs are always queued here. Load jobs are
576 * queued at the head for faster execution only in the case there is not
577 * already a write operation of some kind for this job.
578 *
579 * So we have ordering, but can do exceptions when there are no already
580 * operations for a given key. Also when we need to block load a given
581 * key, for an immediate lookup operation, we can check if the key can
582 * be accessed synchronously without race conditions (no IN PROGRESS
583 * operations for this key), otherwise we blocking wait for completion. */
584
585#define REDIS_IO_LOAD 1
586#define REDIS_IO_SAVE 2
587#define REDIS_IO_LOADINPROG 4
588#define REDIS_IO_SAVEINPROG 8
589
590void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag) {
591 struct dictEntry *de = dictFind(db->io_queued,key);
592
593 if (!de) {
594 dictAdd(db->io_queued,key,(void*)flag);
595 incrRefCount(key);
596 return;
597 } else {
598 long flags = (long) dictGetEntryVal(de);
e37efb0d 599
600 if (flags & flag) {
601 redisLog(REDIS_WARNING,"Adding the same flag again: was: %ld, addede: %ld",flags,flag);
602 redisAssert(!(flags & flag));
603 }
3be00d7e 604 flags |= flag;
605 dictGetEntryVal(de) = (void*) flags;
f63f0928 606 }
3be00d7e 607}
608
609void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag) {
610 struct dictEntry *de = dictFind(db->io_queued,key);
611 long flags;
612
613 redisAssert(de != NULL);
614 flags = (long) dictGetEntryVal(de);
615 redisAssert(flags & flag);
616 flags &= ~flag;
617 if (flags == 0) {
618 dictDelete(db->io_queued,key);
619 } else {
620 dictGetEntryVal(de) = (void*) flags;
621 }
622}
f63f0928 623
3be00d7e 624int cacheScheduleIOGetFlags(redisDb *db, robj *key) {
625 struct dictEntry *de = dictFind(db->io_queued,key);
626
627 return (de == NULL) ? 0 : ((long) dictGetEntryVal(de));
628}
629
630void cacheScheduleIO(redisDb *db, robj *key, int type) {
631 ioop *op;
632 long flags;
633
634 if ((flags = cacheScheduleIOGetFlags(db,key)) & type) return;
635
636 redisLog(REDIS_DEBUG,"Scheduling key %s for %s",
637 key->ptr, type == REDIS_IO_LOAD ? "loading" : "saving");
638 cacheScheduleIOAddFlag(db,key,type);
639 op = zmalloc(sizeof(*op));
640 op->type = type;
641 op->db = db;
642 op->key = key;
f63f0928 643 incrRefCount(key);
3be00d7e 644 op->ctime = time(NULL);
645
646 /* Give priority to load operations if there are no save already
647 * in queue for the same key. */
648 if (type == REDIS_IO_LOAD && !(flags & REDIS_IO_SAVE)) {
649 listAddNodeHead(server.cache_io_queue, op);
650 } else {
651 /* FIXME: probably when this happens we want to at least move
652 * the write job about this queue on top, and set the creation time
653 * to a value that will force processing ASAP. */
654 listAddNodeTail(server.cache_io_queue, op);
655 }
f63f0928 656}
657
658void cacheCron(void) {
659 time_t now = time(NULL);
660 listNode *ln;
c4b64a13 661 int jobs, topush = 0;
662
663 /* Sync stuff on disk, but only if we have less than 100 IO jobs */
664 lockThreadedIO();
665 jobs = listLength(server.io_newjobs);
666 unlockThreadedIO();
667
668 topush = 100-jobs;
669 if (topush < 0) topush = 0;
e37efb0d 670 if (topush > (signed)listLength(server.cache_io_queue))
671 topush = listLength(server.cache_io_queue);
f63f0928 672
3be00d7e 673 while((ln = listFirst(server.cache_io_queue)) != NULL) {
674 ioop *op = ln->value;
f63f0928 675
c4b64a13 676 if (!topush) break;
677 topush--;
678
3be00d7e 679 if (op->type == REDIS_IO_LOAD ||
680 (now - op->ctime) >= server.cache_flush_delay)
681 {
f63f0928 682 struct dictEntry *de;
683 robj *val;
684
e37efb0d 685 /* Don't add a SAVE job in queue if there is already
686 * a save in progress for the same key. */
687 if (op->type == REDIS_IO_SAVE &&
688 cacheScheduleIOGetFlags(op->db,op->key) & REDIS_IO_SAVEINPROG)
689 {
690 /* Move the operation at the end of the list of there
691 * are other operations. Otherwise break, nothing to do
692 * here. */
693 if (listLength(server.cache_io_queue) > 1) {
694 listDelNode(server.cache_io_queue,ln);
695 listAddNodeTail(server.cache_io_queue,op);
696 continue;
697 } else {
698 break;
699 }
700 }
701
3be00d7e 702 redisLog(REDIS_DEBUG,"Creating IO %s Job for key %s",
703 op->type == REDIS_IO_LOAD ? "load" : "save", op->key->ptr);
704
705 if (op->type == REDIS_IO_LOAD) {
706 dsCreateIOJob(REDIS_IOJOB_LOAD,op->db,op->key,NULL);
f63f0928 707 } else {
3be00d7e 708 /* Lookup the key, in order to put the current value in the IO
709 * Job. Otherwise if the key does not exists we schedule a disk
710 * store delete operation, setting the value to NULL. */
711 de = dictFind(op->db->dict,op->key->ptr);
712 if (de) {
713 val = dictGetEntryVal(de);
714 } else {
715 /* Setting the value to NULL tells the IO thread to delete
716 * the key on disk. */
717 val = NULL;
718 }
719 dsCreateIOJob(REDIS_IOJOB_SAVE,op->db,op->key,val);
f63f0928 720 }
3be00d7e 721 /* Mark the operation as in progress. */
722 cacheScheduleIODelFlag(op->db,op->key,op->type);
723 cacheScheduleIOAddFlag(op->db,op->key,
724 (op->type == REDIS_IO_LOAD) ? REDIS_IO_LOADINPROG :
725 REDIS_IO_SAVEINPROG);
726 /* Finally remove the operation from the queue.
727 * But we'll have trace of it in the hash table. */
728 listDelNode(server.cache_io_queue,ln);
729 decrRefCount(op->key);
730 zfree(op);
f63f0928 731 } else {
732 break; /* too early */
733 }
734 }
735
736 /* Reclaim memory from the object cache */
737 while (server.ds_enabled && zmalloc_used_memory() >
738 server.cache_max_memory)
739 {
740 if (cacheFreeOneEntry() == REDIS_ERR) break;
3be00d7e 741 /* FIXME: also free negative cache entries here. */
f63f0928 742 }
743}
744
3be00d7e 745/* ========== Disk store cache - Blocking clients on missing keys =========== */
e2641e09 746
747/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
3be00d7e 748 * If the key is already in memory we don't need to block.
f63f0928 749 *
5ef64098 750 * FIXME: we should try if it's actually better to suspend the client
751 * accessing an object that is being saved, and awake it only when
752 * the saving was completed.
753 *
754 * Otherwise if the key is not in memory, we block the client and start
755 * an IO Job to load it:
756 *
757 * the key is added to the io_keys list in the client structure, and also
e2641e09 758 * in the hash table mapping swapped keys to waiting clients, that is,
759 * server.io_waited_keys. */
760int waitForSwappedKey(redisClient *c, robj *key) {
761 struct dictEntry *de;
e2641e09 762 list *l;
763
5ef64098 764 /* Return ASAP if the key is in memory */
e2641e09 765 de = dictFind(c->db->dict,key->ptr);
5ef64098 766 if (de != NULL) return 0;
e2641e09 767
d934e1e8 768 /* Don't wait for keys we are sure are not on disk either */
769 if (!cacheKeyMayExist(c->db,key)) return 0;
770
e2641e09 771 /* Add the key to the list of keys this client is waiting for.
772 * This maps clients to keys they are waiting for. */
773 listAddNodeTail(c->io_keys,key);
774 incrRefCount(key);
775
776 /* Add the client to the swapped keys => clients waiting map. */
777 de = dictFind(c->db->io_keys,key);
778 if (de == NULL) {
779 int retval;
780
781 /* For every key we take a list of clients blocked for it */
782 l = listCreate();
783 retval = dictAdd(c->db->io_keys,key,l);
784 incrRefCount(key);
785 redisAssert(retval == DICT_OK);
786 } else {
787 l = dictGetEntryVal(de);
788 }
789 listAddNodeTail(l,c);
790
791 /* Are we already loading the key from disk? If not create a job */
5ef64098 792 if (de == NULL)
3be00d7e 793 cacheScheduleIO(c->db,key,REDIS_IO_LOAD);
e2641e09 794 return 1;
795}
796
797/* Preload keys for any command with first, last and step values for
798 * the command keys prototype, as defined in the command table. */
799void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
800 int j, last;
801 if (cmd->vm_firstkey == 0) return;
802 last = cmd->vm_lastkey;
803 if (last < 0) last = argc+last;
804 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
805 redisAssert(j < argc);
806 waitForSwappedKey(c,argv[j]);
807 }
808}
809
810/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
811 * Note that the number of keys to preload is user-defined, so we need to
812 * apply a sanity check against argc. */
813void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
814 int i, num;
815 REDIS_NOTUSED(cmd);
816
817 num = atoi(argv[2]->ptr);
818 if (num > (argc-3)) return;
819 for (i = 0; i < num; i++) {
820 waitForSwappedKey(c,argv[3+i]);
821 }
822}
823
824/* Preload keys needed to execute the entire MULTI/EXEC block.
825 *
826 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
827 * and will block the client when any command requires a swapped out value. */
828void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
829 int i, margc;
830 struct redisCommand *mcmd;
831 robj **margv;
832 REDIS_NOTUSED(cmd);
833 REDIS_NOTUSED(argc);
834 REDIS_NOTUSED(argv);
835
836 if (!(c->flags & REDIS_MULTI)) return;
837 for (i = 0; i < c->mstate.count; i++) {
838 mcmd = c->mstate.commands[i].cmd;
839 margc = c->mstate.commands[i].argc;
840 margv = c->mstate.commands[i].argv;
841
842 if (mcmd->vm_preload_proc != NULL) {
843 mcmd->vm_preload_proc(c,mcmd,margc,margv);
844 } else {
845 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
846 }
847 }
848}
849
850/* Is this client attempting to run a command against swapped keys?
851 * If so, block it ASAP, load the keys in background, then resume it.
852 *
853 * The important idea about this function is that it can fail! If keys will
854 * still be swapped when the client is resumed, this key lookups will
855 * just block loading keys from disk. In practical terms this should only
856 * happen with SORT BY command or if there is a bug in this function.
857 *
858 * Return 1 if the client is marked as blocked, 0 if the client can
859 * continue as the keys it is going to access appear to be in memory. */
860int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
861 if (cmd->vm_preload_proc != NULL) {
862 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
863 } else {
864 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
865 }
866
867 /* If the client was blocked for at least one key, mark it as blocked. */
868 if (listLength(c->io_keys)) {
869 c->flags |= REDIS_IO_WAIT;
870 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
5ef64098 871 server.cache_blocked_clients++;
e2641e09 872 return 1;
873 } else {
874 return 0;
875 }
876}
877
878/* Remove the 'key' from the list of blocked keys for a given client.
879 *
880 * The function returns 1 when there are no longer blocking keys after
881 * the current one was removed (and the client can be unblocked). */
882int dontWaitForSwappedKey(redisClient *c, robj *key) {
883 list *l;
884 listNode *ln;
885 listIter li;
886 struct dictEntry *de;
887
c8a10631
PN
888 /* The key object might be destroyed when deleted from the c->io_keys
889 * list (and the "key" argument is physically the same object as the
890 * object inside the list), so we need to protect it. */
891 incrRefCount(key);
892
e2641e09 893 /* Remove the key from the list of keys this client is waiting for. */
894 listRewind(c->io_keys,&li);
895 while ((ln = listNext(&li)) != NULL) {
896 if (equalStringObjects(ln->value,key)) {
897 listDelNode(c->io_keys,ln);
898 break;
899 }
900 }
901 redisAssert(ln != NULL);
902
903 /* Remove the client form the key => waiting clients map. */
904 de = dictFind(c->db->io_keys,key);
905 redisAssert(de != NULL);
906 l = dictGetEntryVal(de);
907 ln = listSearchKey(l,c);
908 redisAssert(ln != NULL);
909 listDelNode(l,ln);
910 if (listLength(l) == 0)
911 dictDelete(c->db->io_keys,key);
912
c8a10631 913 decrRefCount(key);
e2641e09 914 return listLength(c->io_keys) == 0;
915}
916
917/* Every time we now a key was loaded back in memory, we handle clients
918 * waiting for this key if any. */
919void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
920 struct dictEntry *de;
921 list *l;
922 listNode *ln;
923 int len;
924
925 de = dictFind(db->io_keys,key);
926 if (!de) return;
927
928 l = dictGetEntryVal(de);
929 len = listLength(l);
930 /* Note: we can't use something like while(listLength(l)) as the list
931 * can be freed by the calling function when we remove the last element. */
932 while (len--) {
933 ln = listFirst(l);
934 redisClient *c = ln->value;
935
936 if (dontWaitForSwappedKey(c,key)) {
937 /* Put the client in the list of clients ready to go as we
938 * loaded all the keys about it. */
939 listAddNodeTail(server.io_ready_clients,c);
940 }
941 }
942}