2  * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> 
   5  * Redistribution and use in source and binary forms, with or without 
   6  * modification, are permitted provided that the following conditions are met: 
   8  *   * Redistributions of source code must retain the above copyright notice, 
   9  *     this list of conditions and the following disclaimer. 
  10  *   * Redistributions in binary form must reproduce the above copyright 
  11  *     notice, this list of conditions and the following disclaimer in the 
  12  *     documentation and/or other materials provided with the distribution. 
  13  *   * Neither the name of Redis nor the names of its contributors may be used 
  14  *     to endorse or promote products derived from this software without 
  15  *     specific prior written permission. 
  17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  27  * POSSIBILITY OF SUCH DAMAGE. 
  30 #define REDIS_VERSION "1.3.4" 
  40 #define __USE_POSIX199309 
  47 #endif /* HAVE_BACKTRACE */ 
  55 #include <arpa/inet.h> 
  59 #include <sys/resource.h> 
  66 #include "solarisfixes.h" 
  70 #include "ae.h"     /* Event driven programming library */ 
  71 #include "sds.h"    /* Dynamic safe strings */ 
  72 #include "anet.h"   /* Networking the easy way */ 
  73 #include "dict.h"   /* Hash tables */ 
  74 #include "adlist.h" /* Linked lists */ 
  75 #include "zmalloc.h" /* total memory usage aware version of malloc/free */ 
  76 #include "lzf.h"    /* LZF compression library */ 
  77 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */ 
  84 /* Static server configuration */ 
  85 #define REDIS_SERVERPORT        6379    /* TCP port */ 
  86 #define REDIS_MAXIDLETIME       (60*5)  /* default client timeout */ 
  87 #define REDIS_IOBUF_LEN         1024 
  88 #define REDIS_LOADBUF_LEN       1024 
  89 #define REDIS_STATIC_ARGS       4 
  90 #define REDIS_DEFAULT_DBNUM     16 
  91 #define REDIS_CONFIGLINE_MAX    1024 
  92 #define REDIS_OBJFREELIST_MAX   1000000 /* Max number of objects to cache */ 
  93 #define REDIS_MAX_SYNC_TIME     60      /* Slave can't take more to sync */ 
  94 #define REDIS_EXPIRELOOKUPS_PER_CRON    100 /* try to expire 100 keys/second */ 
  95 #define REDIS_MAX_WRITE_PER_EVENT (1024*64) 
  96 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */ 
  98 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */ 
  99 #define REDIS_WRITEV_THRESHOLD      3 
 100 /* Max number of iovecs used for each writev call */ 
 101 #define REDIS_WRITEV_IOVEC_COUNT    256 
 103 /* Hash table parameters */ 
 104 #define REDIS_HT_MINFILL        10      /* Minimal hash table fill 10% */ 
 107 #define REDIS_CMD_BULK          1       /* Bulk write command */ 
 108 #define REDIS_CMD_INLINE        2       /* Inline command */ 
 109 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with 
 110    this flags will return an error when the 'maxmemory' option is set in the 
 111    config file and the server is using more than maxmemory bytes of memory. 
 112    In short this commands are denied on low memory conditions. */ 
 113 #define REDIS_CMD_DENYOOM       4 
 116 #define REDIS_STRING 0 
 122 /* Objects encoding. Some kind of objects like Strings and Hashes can be 
 123  * internally represented in multiple ways. The 'encoding' field of the object 
 124  * is set to one of this fields for this object. */ 
 125 #define REDIS_ENCODING_RAW 0    /* Raw representation */ 
 126 #define REDIS_ENCODING_INT 1    /* Encoded as integer */ 
 127 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */ 
 128 #define REDIS_ENCODING_HT 3     /* Encoded as an hash table */ 
 130 /* Object types only used for dumping to disk */ 
 131 #define REDIS_EXPIRETIME 253 
 132 #define REDIS_SELECTDB 254 
 133 #define REDIS_EOF 255 
 135 /* Defines related to the dump file format. To store 32 bits lengths for short 
 136  * keys requires a lot of space, so we check the most significant 2 bits of 
 137  * the first byte to interpreter the length: 
 139  * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte 
 140  * 01|000000 00000000 =>  01, the len is 14 byes, 6 bits + 8 bits of next byte 
 141  * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow 
 142  * 11|000000 this means: specially encoded object will follow. The six bits 
 143  *           number specify the kind of object that follows. 
 144  *           See the REDIS_RDB_ENC_* defines. 
 146  * Lenghts up to 63 are stored using a single byte, most DB keys, and may 
 147  * values, will fit inside. */ 
 148 #define REDIS_RDB_6BITLEN 0 
 149 #define REDIS_RDB_14BITLEN 1 
 150 #define REDIS_RDB_32BITLEN 2 
 151 #define REDIS_RDB_ENCVAL 3 
 152 #define REDIS_RDB_LENERR UINT_MAX 
 154 /* When a length of a string object stored on disk has the first two bits 
 155  * set, the remaining two bits specify a special encoding for the object 
 156  * accordingly to the following defines: */ 
 157 #define REDIS_RDB_ENC_INT8 0        /* 8 bit signed integer */ 
 158 #define REDIS_RDB_ENC_INT16 1       /* 16 bit signed integer */ 
 159 #define REDIS_RDB_ENC_INT32 2       /* 32 bit signed integer */ 
 160 #define REDIS_RDB_ENC_LZF 3         /* string compressed with FASTLZ */ 
 162 /* Virtual memory object->where field. */ 
 163 #define REDIS_VM_MEMORY 0       /* The object is on memory */ 
 164 #define REDIS_VM_SWAPPED 1      /* The object is on disk */ 
 165 #define REDIS_VM_SWAPPING 2     /* Redis is swapping this object on disk */ 
 166 #define REDIS_VM_LOADING 3      /* Redis is loading this object from disk */ 
 168 /* Virtual memory static configuration stuff. 
 169  * Check vmFindContiguousPages() to know more about this magic numbers. */ 
 170 #define REDIS_VM_MAX_NEAR_PAGES 65536 
 171 #define REDIS_VM_MAX_RANDOM_JUMP 4096 
 172 #define REDIS_VM_MAX_THREADS 32 
 173 #define REDIS_THREAD_STACK_SIZE (1024*1024*4) 
 174 /* The following is the *percentage* of completed I/O jobs to process when the 
 175  * handelr is called. While Virtual Memory I/O operations are performed by 
 176  * threads, this operations must be processed by the main thread when completed 
 177  * in order to take effect. */ 
 178 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1 
 181 #define REDIS_SLAVE 1       /* This client is a slave server */ 
 182 #define REDIS_MASTER 2      /* This client is a master server */ 
 183 #define REDIS_MONITOR 4     /* This client is a slave monitor, see MONITOR */ 
 184 #define REDIS_MULTI 8       /* This client is in a MULTI context */ 
 185 #define REDIS_BLOCKED 16    /* The client is waiting in a blocking operation */ 
 186 #define REDIS_IO_WAIT 32    /* The client is waiting for Virtual Memory I/O */ 
 188 /* Slave replication state - slave side */ 
 189 #define REDIS_REPL_NONE 0   /* No active replication */ 
 190 #define REDIS_REPL_CONNECT 1    /* Must connect to master */ 
 191 #define REDIS_REPL_CONNECTED 2  /* Connected to master */ 
 193 /* Slave replication state - from the point of view of master 
 194  * Note that in SEND_BULK and ONLINE state the slave receives new updates 
 195  * in its output queue. In the WAIT_BGSAVE state instead the server is waiting 
 196  * to start the next background saving in order to send updates to it. */ 
 197 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */ 
 198 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */ 
 199 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */ 
 200 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */ 
 202 /* List related stuff */ 
 206 /* Sort operations */ 
 207 #define REDIS_SORT_GET 0 
 208 #define REDIS_SORT_ASC 1 
 209 #define REDIS_SORT_DESC 2 
 210 #define REDIS_SORTKEY_MAX 1024 
 213 #define REDIS_DEBUG 0 
 214 #define REDIS_VERBOSE 1 
 215 #define REDIS_NOTICE 2 
 216 #define REDIS_WARNING 3 
 218 /* Anti-warning macro... */ 
 219 #define REDIS_NOTUSED(V) ((void) V) 
 221 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */ 
 222 #define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */ 
 224 /* Append only defines */ 
 225 #define APPENDFSYNC_NO 0 
 226 #define APPENDFSYNC_ALWAYS 1 
 227 #define APPENDFSYNC_EVERYSEC 2 
 229 /* Hashes related defaults */ 
 230 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64 
 231 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512 
 233 /* We can print the stacktrace, so our assert is defined this way: */ 
 234 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1))) 
 235 static void _redisAssert(char *estr
, char *file
, int line
); 
 237 /*================================= Data types ============================== */ 
 239 /* A redis object, that is a type able to hold a string / list / set */ 
 241 /* The VM object structure */ 
 242 struct redisObjectVM 
{ 
 243     off_t page
;         /* the page at witch the object is stored on disk */ 
 244     off_t usedpages
;    /* number of pages used on disk */ 
 245     time_t atime
;       /* Last access time */ 
 248 /* The actual Redis Object */ 
 249 typedef struct redisObject 
{ 
 252     unsigned char encoding
; 
 253     unsigned char storage
;  /* If this object is a key, where is the value? 
 254                              * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */ 
 255     unsigned char vtype
; /* If this object is a key, and value is swapped out, 
 256                           * this is the type of the swapped out object. */ 
 258     /* VM fields, this are only allocated if VM is active, otherwise the 
 259      * object allocation function will just allocate 
 260      * sizeof(redisObjct) minus sizeof(redisObjectVM), so using 
 261      * Redis without VM active will not have any overhead. */ 
 262     struct redisObjectVM vm
; 
 265 /* Macro used to initalize a Redis object allocated on the stack. 
 266  * Note that this macro is taken near the structure definition to make sure 
 267  * we'll update it when the structure is changed, to avoid bugs like 
 268  * bug #85 introduced exactly in this way. */ 
 269 #define initStaticStringObject(_var,_ptr) do { \ 
 271     _var.type = REDIS_STRING; \ 
 272     _var.encoding = REDIS_ENCODING_RAW; \ 
 274     if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \ 
 277 typedef struct redisDb 
{ 
 278     dict 
*dict
;                 /* The keyspace for this DB */ 
 279     dict 
*expires
;              /* Timeout of keys with a timeout set */ 
 280     dict 
*blockingkeys
;         /* Keys with clients waiting for data (BLPOP) */ 
 281     dict 
*io_keys
;              /* Keys with clients waiting for VM I/O */ 
 285 /* Client MULTI/EXEC state */ 
 286 typedef struct multiCmd 
{ 
 289     struct redisCommand 
*cmd
; 
 292 typedef struct multiState 
{ 
 293     multiCmd 
*commands
;     /* Array of MULTI commands */ 
 294     int count
;              /* Total number of MULTI commands */ 
 297 /* With multiplexing we need to take per-clinet state. 
 298  * Clients are taken in a liked list. */ 
 299 typedef struct redisClient 
{ 
 304     robj 
**argv
, **mbargv
; 
 306     int bulklen
;            /* bulk read len. -1 if not in bulk read mode */ 
 307     int multibulk
;          /* multi bulk command format active */ 
 310     time_t lastinteraction
; /* time of the last interaction, used for timeout */ 
 311     int flags
;              /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */ 
 312     int slaveseldb
;         /* slave selected db, if this client is a slave */ 
 313     int authenticated
;      /* when requirepass is non-NULL */ 
 314     int replstate
;          /* replication state if this is a slave */ 
 315     int repldbfd
;           /* replication DB file descriptor */ 
 316     long repldboff
;         /* replication DB file offset */ 
 317     off_t repldbsize
;       /* replication DB file size */ 
 318     multiState mstate
;      /* MULTI/EXEC state */ 
 319     robj 
**blockingkeys
;    /* The key we are waiting to terminate a blocking 
 320                              * operation such as BLPOP. Otherwise NULL. */ 
 321     int blockingkeysnum
;    /* Number of blocking keys */ 
 322     time_t blockingto
;      /* Blocking operation timeout. If UNIX current time 
 323                              * is >= blockingto then the operation timed out. */ 
 324     list 
*io_keys
;          /* Keys this client is waiting to be loaded from the 
 325                              * swap file in order to continue. */ 
 333 /* Global server state structure */ 
 338     dict 
*sharingpool
;          /* Poll used for object sharing */ 
 339     unsigned int sharingpoolsize
; 
 340     long long dirty
;            /* changes to DB from the last save */ 
 342     list 
*slaves
, *monitors
; 
 343     char neterr
[ANET_ERR_LEN
]; 
 345     int cronloops
;              /* number of times the cron function run */ 
 346     list 
*objfreelist
;          /* A list of freed objects to avoid malloc() */ 
 347     time_t lastsave
;            /* Unix time of last save succeeede */ 
 348     /* Fields used only for stats */ 
 349     time_t stat_starttime
;         /* server start time */ 
 350     long long stat_numcommands
;    /* number of processed commands */ 
 351     long long stat_numconnections
; /* number of connections received */ 
 364     pid_t bgsavechildpid
; 
 365     pid_t bgrewritechildpid
; 
 366     sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */ 
 367     struct saveparam 
*saveparams
; 
 372     char *appendfilename
; 
 376     /* Replication related */ 
 381     redisClient 
*master
;    /* client that is master for this slave */ 
 383     unsigned int maxclients
; 
 384     unsigned long long maxmemory
; 
 385     unsigned int blpop_blocked_clients
; 
 386     unsigned int vm_blocked_clients
; 
 387     /* Sort parameters - qsort_r() is only available under BSD so we 
 388      * have to take this state global, in order to pass it to sortCompare() */ 
 392     /* Virtual memory configuration */ 
 397     unsigned long long vm_max_memory
; 
 399     size_t hash_max_zipmap_entries
; 
 400     size_t hash_max_zipmap_value
; 
 401     /* Virtual memory state */ 
 404     off_t vm_next_page
; /* Next probably empty page */ 
 405     off_t vm_near_pages
; /* Number of pages allocated sequentially */ 
 406     unsigned char *vm_bitmap
; /* Bitmap of free/used pages */ 
 407     time_t unixtime
;    /* Unix time sampled every second. */ 
 408     /* Virtual memory I/O threads stuff */ 
 409     /* An I/O thread process an element taken from the io_jobs queue and 
 410      * put the result of the operation in the io_done list. While the 
 411      * job is being processed, it's put on io_processing queue. */ 
 412     list 
*io_newjobs
; /* List of VM I/O jobs yet to be processed */ 
 413     list 
*io_processing
; /* List of VM I/O jobs being processed */ 
 414     list 
*io_processed
; /* List of VM I/O jobs already processed */ 
 415     list 
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */ 
 416     pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */ 
 417     pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */ 
 418     pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */ 
 419     pthread_attr_t io_threads_attr
; /* attributes for threads creation */ 
 420     int io_active_threads
; /* Number of running I/O threads */ 
 421     int vm_max_threads
; /* Max number of I/O threads running at the same time */ 
 422     /* Our main thread is blocked on the event loop, locking for sockets ready 
 423      * to be read or written, so when a threaded I/O operation is ready to be 
 424      * processed by the main thread, the I/O thread will use a unix pipe to 
 425      * awake the main thread. The followings are the two pipe FDs. */ 
 426     int io_ready_pipe_read
; 
 427     int io_ready_pipe_write
; 
 428     /* Virtual memory stats */ 
 429     unsigned long long vm_stats_used_pages
; 
 430     unsigned long long vm_stats_swapped_objects
; 
 431     unsigned long long vm_stats_swapouts
; 
 432     unsigned long long vm_stats_swapins
; 
 436 typedef void redisCommandProc(redisClient 
*c
); 
 437 struct redisCommand 
{ 
 439     redisCommandProc 
*proc
; 
 442     /* What keys should be loaded in background when calling this command? */ 
 443     int vm_firstkey
; /* The first argument that's a key (0 = no keys) */ 
 444     int vm_lastkey
;  /* THe last argument that's a key */ 
 445     int vm_keystep
;  /* The step between first and last key */ 
 448 struct redisFunctionSym 
{ 
 450     unsigned long pointer
; 
 453 typedef struct _redisSortObject 
{ 
 461 typedef struct _redisSortOperation 
{ 
 464 } redisSortOperation
; 
 466 /* ZSETs use a specialized version of Skiplists */ 
 468 typedef struct zskiplistNode 
{ 
 469     struct zskiplistNode 
**forward
; 
 470     struct zskiplistNode 
*backward
; 
 476 typedef struct zskiplist 
{ 
 477     struct zskiplistNode 
*header
, *tail
; 
 478     unsigned long length
; 
 482 typedef struct zset 
{ 
 487 /* Our shared "common" objects */ 
 489 struct sharedObjectsStruct 
{ 
 490     robj 
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
, 
 491     *colon
, *nullbulk
, *nullmultibulk
, *queued
, 
 492     *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
, 
 493     *outofrangeerr
, *plus
, 
 494     *select0
, *select1
, *select2
, *select3
, *select4
, 
 495     *select5
, *select6
, *select7
, *select8
, *select9
; 
 498 /* Global vars that are actally used as constants. The following double 
 499  * values are used for double on-disk serialization, and are initialized 
 500  * at runtime to avoid strange compiler optimizations. */ 
 502 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
; 
 504 /* VM threaded I/O request message */ 
 505 #define REDIS_IOJOB_LOAD 0          /* Load from disk to memory */ 
 506 #define REDIS_IOJOB_PREPARE_SWAP 1  /* Compute needed pages */ 
 507 #define REDIS_IOJOB_DO_SWAP 2       /* Swap from memory to disk */ 
 508 typedef struct iojob 
{ 
 509     int type
;   /* Request type, REDIS_IOJOB_* */ 
 510     redisDb 
*db
;/* Redis database */ 
 511     robj 
*key
;  /* This I/O request is about swapping this key */ 
 512     robj 
*val
;  /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this 
 513                  * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */ 
 514     off_t page
; /* Swap page where to read/write the object */ 
 515     off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */ 
 516     int canceled
; /* True if this command was canceled by blocking side of VM */ 
 517     pthread_t thread
; /* ID of the thread processing this entry */ 
 520 /*================================ Prototypes =============================== */ 
 522 static void freeStringObject(robj 
*o
); 
 523 static void freeListObject(robj 
*o
); 
 524 static void freeSetObject(robj 
*o
); 
 525 static void decrRefCount(void *o
); 
 526 static robj 
*createObject(int type
, void *ptr
); 
 527 static void freeClient(redisClient 
*c
); 
 528 static int rdbLoad(char *filename
); 
 529 static void addReply(redisClient 
*c
, robj 
*obj
); 
 530 static void addReplySds(redisClient 
*c
, sds s
); 
 531 static void incrRefCount(robj 
*o
); 
 532 static int rdbSaveBackground(char *filename
); 
 533 static robj 
*createStringObject(char *ptr
, size_t len
); 
 534 static robj 
*dupStringObject(robj 
*o
); 
 535 static void replicationFeedSlaves(list 
*slaves
, struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
); 
 536 static void feedAppendOnlyFile(struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
); 
 537 static int syncWithMaster(void); 
 538 static robj 
*tryObjectSharing(robj 
*o
); 
 539 static int tryObjectEncoding(robj 
*o
); 
 540 static robj 
*getDecodedObject(robj 
*o
); 
 541 static int removeExpire(redisDb 
*db
, robj 
*key
); 
 542 static int expireIfNeeded(redisDb 
*db
, robj 
*key
); 
 543 static int deleteIfVolatile(redisDb 
*db
, robj 
*key
); 
 544 static int deleteIfSwapped(redisDb 
*db
, robj 
*key
); 
 545 static int deleteKey(redisDb 
*db
, robj 
*key
); 
 546 static time_t getExpire(redisDb 
*db
, robj 
*key
); 
 547 static int setExpire(redisDb 
*db
, robj 
*key
, time_t when
); 
 548 static void updateSlavesWaitingBgsave(int bgsaveerr
); 
 549 static void freeMemoryIfNeeded(void); 
 550 static int processCommand(redisClient 
*c
); 
 551 static void setupSigSegvAction(void); 
 552 static void rdbRemoveTempFile(pid_t childpid
); 
 553 static void aofRemoveTempFile(pid_t childpid
); 
 554 static size_t stringObjectLen(robj 
*o
); 
 555 static void processInputBuffer(redisClient 
*c
); 
 556 static zskiplist 
*zslCreate(void); 
 557 static void zslFree(zskiplist 
*zsl
); 
 558 static void zslInsert(zskiplist 
*zsl
, double score
, robj 
*obj
); 
 559 static void sendReplyToClientWritev(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
); 
 560 static void initClientMultiState(redisClient 
*c
); 
 561 static void freeClientMultiState(redisClient 
*c
); 
 562 static void queueMultiCommand(redisClient 
*c
, struct redisCommand 
*cmd
); 
 563 static void unblockClientWaitingData(redisClient 
*c
); 
 564 static int handleClientsWaitingListPush(redisClient 
*c
, robj 
*key
, robj 
*ele
); 
 565 static void vmInit(void); 
 566 static void vmMarkPagesFree(off_t page
, off_t count
); 
 567 static robj 
*vmLoadObject(robj 
*key
); 
 568 static robj 
*vmPreviewObject(robj 
*key
); 
 569 static int vmSwapOneObjectBlocking(void); 
 570 static int vmSwapOneObjectThreaded(void); 
 571 static int vmCanSwapOut(void); 
 572 static int tryFreeOneObjectFromFreelist(void); 
 573 static void acceptHandler(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
); 
 574 static void vmThreadedIOCompletedJob(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
); 
 575 static void vmCancelThreadedIOJob(robj 
*o
); 
 576 static void lockThreadedIO(void); 
 577 static void unlockThreadedIO(void); 
 578 static int vmSwapObjectThreaded(robj 
*key
, robj 
*val
, redisDb 
*db
); 
 579 static void freeIOJob(iojob 
*j
); 
 580 static void queueIOJob(iojob 
*j
); 
 581 static int vmWriteObjectOnSwap(robj 
*o
, off_t page
); 
 582 static robj 
*vmReadObjectFromSwap(off_t page
, int type
); 
 583 static void waitEmptyIOJobsQueue(void); 
 584 static void vmReopenSwapFile(void); 
 585 static int vmFreePage(off_t page
); 
 586 static int blockClientOnSwappedKeys(struct redisCommand 
*cmd
, redisClient 
*c
); 
 587 static int dontWaitForSwappedKey(redisClient 
*c
, robj 
*key
); 
 588 static void handleClientsBlockedOnSwappedKey(redisDb 
*db
, robj 
*key
); 
 589 static void readQueryFromClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
); 
 590 static struct redisCommand 
*lookupCommand(char *name
); 
 591 static void call(redisClient 
*c
, struct redisCommand 
*cmd
); 
 592 static void resetClient(redisClient 
*c
); 
 593 static void convertToRealHash(robj 
*o
); 
 595 static void authCommand(redisClient 
*c
); 
 596 static void pingCommand(redisClient 
*c
); 
 597 static void echoCommand(redisClient 
*c
); 
 598 static void setCommand(redisClient 
*c
); 
 599 static void setnxCommand(redisClient 
*c
); 
 600 static void getCommand(redisClient 
*c
); 
 601 static void delCommand(redisClient 
*c
); 
 602 static void existsCommand(redisClient 
*c
); 
 603 static void incrCommand(redisClient 
*c
); 
 604 static void decrCommand(redisClient 
*c
); 
 605 static void incrbyCommand(redisClient 
*c
); 
 606 static void decrbyCommand(redisClient 
*c
); 
 607 static void selectCommand(redisClient 
*c
); 
 608 static void randomkeyCommand(redisClient 
*c
); 
 609 static void keysCommand(redisClient 
*c
); 
 610 static void dbsizeCommand(redisClient 
*c
); 
 611 static void lastsaveCommand(redisClient 
*c
); 
 612 static void saveCommand(redisClient 
*c
); 
 613 static void bgsaveCommand(redisClient 
*c
); 
 614 static void bgrewriteaofCommand(redisClient 
*c
); 
 615 static void shutdownCommand(redisClient 
*c
); 
 616 static void moveCommand(redisClient 
*c
); 
 617 static void renameCommand(redisClient 
*c
); 
 618 static void renamenxCommand(redisClient 
*c
); 
 619 static void lpushCommand(redisClient 
*c
); 
 620 static void rpushCommand(redisClient 
*c
); 
 621 static void lpopCommand(redisClient 
*c
); 
 622 static void rpopCommand(redisClient 
*c
); 
 623 static void llenCommand(redisClient 
*c
); 
 624 static void lindexCommand(redisClient 
*c
); 
 625 static void lrangeCommand(redisClient 
*c
); 
 626 static void ltrimCommand(redisClient 
*c
); 
 627 static void typeCommand(redisClient 
*c
); 
 628 static void lsetCommand(redisClient 
*c
); 
 629 static void saddCommand(redisClient 
*c
); 
 630 static void sremCommand(redisClient 
*c
); 
 631 static void smoveCommand(redisClient 
*c
); 
 632 static void sismemberCommand(redisClient 
*c
); 
 633 static void scardCommand(redisClient 
*c
); 
 634 static void spopCommand(redisClient 
*c
); 
 635 static void srandmemberCommand(redisClient 
*c
); 
 636 static void sinterCommand(redisClient 
*c
); 
 637 static void sinterstoreCommand(redisClient 
*c
); 
 638 static void sunionCommand(redisClient 
*c
); 
 639 static void sunionstoreCommand(redisClient 
*c
); 
 640 static void sdiffCommand(redisClient 
*c
); 
 641 static void sdiffstoreCommand(redisClient 
*c
); 
 642 static void syncCommand(redisClient 
*c
); 
 643 static void flushdbCommand(redisClient 
*c
); 
 644 static void flushallCommand(redisClient 
*c
); 
 645 static void sortCommand(redisClient 
*c
); 
 646 static void lremCommand(redisClient 
*c
); 
 647 static void rpoplpushcommand(redisClient 
*c
); 
 648 static void infoCommand(redisClient 
*c
); 
 649 static void mgetCommand(redisClient 
*c
); 
 650 static void monitorCommand(redisClient 
*c
); 
 651 static void expireCommand(redisClient 
*c
); 
 652 static void expireatCommand(redisClient 
*c
); 
 653 static void getsetCommand(redisClient 
*c
); 
 654 static void ttlCommand(redisClient 
*c
); 
 655 static void slaveofCommand(redisClient 
*c
); 
 656 static void debugCommand(redisClient 
*c
); 
 657 static void msetCommand(redisClient 
*c
); 
 658 static void msetnxCommand(redisClient 
*c
); 
 659 static void zaddCommand(redisClient 
*c
); 
 660 static void zincrbyCommand(redisClient 
*c
); 
 661 static void zrangeCommand(redisClient 
*c
); 
 662 static void zrangebyscoreCommand(redisClient 
*c
); 
 663 static void zcountCommand(redisClient 
*c
); 
 664 static void zrevrangeCommand(redisClient 
*c
); 
 665 static void zcardCommand(redisClient 
*c
); 
 666 static void zremCommand(redisClient 
*c
); 
 667 static void zscoreCommand(redisClient 
*c
); 
 668 static void zremrangebyscoreCommand(redisClient 
*c
); 
 669 static void multiCommand(redisClient 
*c
); 
 670 static void execCommand(redisClient 
*c
); 
 671 static void discardCommand(redisClient 
*c
); 
 672 static void blpopCommand(redisClient 
*c
); 
 673 static void brpopCommand(redisClient 
*c
); 
 674 static void appendCommand(redisClient 
*c
); 
 675 static void substrCommand(redisClient 
*c
); 
 676 static void zrankCommand(redisClient 
*c
); 
 677 static void zrevrankCommand(redisClient 
*c
); 
 678 static void hsetCommand(redisClient 
*c
); 
 679 static void hgetCommand(redisClient 
*c
); 
 680 static void zremrangebyrankCommand(redisClient 
*c
); 
 681 static void zunionCommand(redisClient 
*c
); 
 682 static void zinterCommand(redisClient 
*c
); 
 684 /*================================= Globals ================================= */ 
 687 static struct redisServer server
; /* server global state */ 
 688 static struct redisCommand cmdTable
[] = { 
 689     {"get",getCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 690     {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0}, 
 691     {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0}, 
 692     {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 693     {"substr",substrCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 694     {"del",delCommand
,-2,REDIS_CMD_INLINE
,0,0,0}, 
 695     {"exists",existsCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 696     {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1}, 
 697     {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1}, 
 698     {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,1,-1,1}, 
 699     {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 700     {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 701     {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 702     {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 703     {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1}, 
 704     {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1}, 
 705     {"llen",llenCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 706     {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 707     {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 708     {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 709     {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 710     {"lrem",lremCommand
,4,REDIS_CMD_BULK
,1,1,1}, 
 711     {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,2,1}, 
 712     {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 713     {"srem",sremCommand
,3,REDIS_CMD_BULK
,1,1,1}, 
 714     {"smove",smoveCommand
,4,REDIS_CMD_BULK
,1,2,1}, 
 715     {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,1,1,1}, 
 716     {"scard",scardCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 717     {"spop",spopCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 718     {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 719     {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1}, 
 720     {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1}, 
 721     {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1}, 
 722     {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1}, 
 723     {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1}, 
 724     {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1}, 
 725     {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 726     {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 727     {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 728     {"zrem",zremCommand
,3,REDIS_CMD_BULK
,1,1,1}, 
 729     {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 730     {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 731     {"zunion",zunionCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,0,0,0}, 
 732     {"zinter",zinterCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,0,0,0}, 
 733     {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1}, 
 734     {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,1,1,1}, 
 735     {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,1,1,1}, 
 736     {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1}, 
 737     {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 738     {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 739     {"zrank",zrankCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 740     {"zrevrank",zrevrankCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 741     {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 742     {"hget",hgetCommand
,3,REDIS_CMD_BULK
,1,1,1}, 
 743     {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1}, 
 744     {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1}, 
 745     {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1}, 
 746     {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2}, 
 747     {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2}, 
 748     {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 749     {"select",selectCommand
,2,REDIS_CMD_INLINE
,0,0,0}, 
 750     {"move",moveCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 751     {"rename",renameCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 752     {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,1,1,1}, 
 753     {"expire",expireCommand
,3,REDIS_CMD_INLINE
,0,0,0}, 
 754     {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,0,0,0}, 
 755     {"keys",keysCommand
,2,REDIS_CMD_INLINE
,0,0,0}, 
 756     {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 757     {"auth",authCommand
,2,REDIS_CMD_INLINE
,0,0,0}, 
 758     {"ping",pingCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 759     {"echo",echoCommand
,2,REDIS_CMD_BULK
,0,0,0}, 
 760     {"save",saveCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 761     {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 762     {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 763     {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 764     {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 765     {"type",typeCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 766     {"multi",multiCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 767     {"exec",execCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 768     {"discard",discardCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 769     {"sync",syncCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 770     {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 771     {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 772     {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1}, 
 773     {"info",infoCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 774     {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,0,0,0}, 
 775     {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,1,1,1}, 
 776     {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,0,0,0}, 
 777     {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,0,0,0}, 
 778     {NULL
,NULL
,0,0,0,0,0} 
 781 /*============================ Utility functions ============================ */ 
 783 /* Glob-style pattern matching. */ 
 784 int stringmatchlen(const char *pattern
, int patternLen
, 
 785         const char *string
, int stringLen
, int nocase
) 
 790             while (pattern
[1] == '*') { 
 795                 return 1; /* match */ 
 797                 if (stringmatchlen(pattern
+1, patternLen
-1, 
 798                             string
, stringLen
, nocase
)) 
 799                     return 1; /* match */ 
 803             return 0; /* no match */ 
 807                 return 0; /* no match */ 
 817             not = pattern
[0] == '^'; 
 824                 if (pattern
[0] == '\\') { 
 827                     if (pattern
[0] == string
[0]) 
 829                 } else if (pattern
[0] == ']') { 
 831                 } else if (patternLen 
== 0) { 
 835                 } else if (pattern
[1] == '-' && patternLen 
>= 3) { 
 836                     int start 
= pattern
[0]; 
 837                     int end 
= pattern
[2]; 
 845                         start 
= tolower(start
); 
 851                     if (c 
>= start 
&& c 
<= end
) 
 855                         if (pattern
[0] == string
[0]) 
 858                         if (tolower((int)pattern
[0]) == tolower((int)string
[0])) 
 868                 return 0; /* no match */ 
 874             if (patternLen 
>= 2) { 
 881                 if (pattern
[0] != string
[0]) 
 882                     return 0; /* no match */ 
 884                 if (tolower((int)pattern
[0]) != tolower((int)string
[0])) 
 885                     return 0; /* no match */ 
 893         if (stringLen 
== 0) { 
 894             while(*pattern 
== '*') { 
 901     if (patternLen 
== 0 && stringLen 
== 0) 
 906 static void redisLog(int level
, const char *fmt
, ...) { 
 910     fp 
= (server
.logfile 
== NULL
) ? stdout 
: fopen(server
.logfile
,"a"); 
 914     if (level 
>= server
.verbosity
) { 
 920         strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
)); 
 921         fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]); 
 922         vfprintf(fp
, fmt
, ap
); 
 928     if (server
.logfile
) fclose(fp
); 
 931 /*====================== Hash table type implementation  ==================== */ 
 933 /* This is an hash table type that uses the SDS dynamic strings libary as 
 934  * keys and radis objects as values (objects can hold SDS strings, 
 937 static void dictVanillaFree(void *privdata
, void *val
) 
 939     DICT_NOTUSED(privdata
); 
 943 static void dictListDestructor(void *privdata
, void *val
) 
 945     DICT_NOTUSED(privdata
); 
 946     listRelease((list
*)val
); 
 949 static int sdsDictKeyCompare(void *privdata
, const void *key1
, 
 953     DICT_NOTUSED(privdata
); 
 955     l1 
= sdslen((sds
)key1
); 
 956     l2 
= sdslen((sds
)key2
); 
 957     if (l1 
!= l2
) return 0; 
 958     return memcmp(key1
, key2
, l1
) == 0; 
 961 static void dictRedisObjectDestructor(void *privdata
, void *val
) 
 963     DICT_NOTUSED(privdata
); 
 965     if (val 
== NULL
) return; /* Values of swapped out keys as set to NULL */ 
 969 static int dictObjKeyCompare(void *privdata
, const void *key1
, 
 972     const robj 
*o1 
= key1
, *o2 
= key2
; 
 973     return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 976 static unsigned int dictObjHash(const void *key
) { 
 978     return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 981 static int dictEncObjKeyCompare(void *privdata
, const void *key1
, 
 984     robj 
*o1 
= (robj
*) key1
, *o2 
= (robj
*) key2
; 
 987     o1 
= getDecodedObject(o1
); 
 988     o2 
= getDecodedObject(o2
); 
 989     cmp 
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 995 static unsigned int dictEncObjHash(const void *key
) { 
 996     robj 
*o 
= (robj
*) key
; 
 998     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
 999         return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
1001         if (o
->encoding 
== REDIS_ENCODING_INT
) { 
1005             len 
= snprintf(buf
,32,"%ld",(long)o
->ptr
); 
1006             return dictGenHashFunction((unsigned char*)buf
, len
); 
1010             o 
= getDecodedObject(o
); 
1011             hash 
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
1018 /* Sets type and expires */ 
1019 static dictType setDictType 
= { 
1020     dictEncObjHash
,            /* hash function */ 
1023     dictEncObjKeyCompare
,      /* key compare */ 
1024     dictRedisObjectDestructor
, /* key destructor */ 
1025     NULL                       
/* val destructor */ 
1028 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ 
1029 static dictType zsetDictType 
= { 
1030     dictEncObjHash
,            /* hash function */ 
1033     dictEncObjKeyCompare
,      /* key compare */ 
1034     dictRedisObjectDestructor
, /* key destructor */ 
1035     dictVanillaFree            
/* val destructor of malloc(sizeof(double)) */ 
1039 static dictType dbDictType 
= { 
1040     dictObjHash
,                /* hash function */ 
1043     dictObjKeyCompare
,          /* key compare */ 
1044     dictRedisObjectDestructor
,  /* key destructor */ 
1045     dictRedisObjectDestructor   
/* val destructor */ 
1049 static dictType keyptrDictType 
= { 
1050     dictObjHash
,               /* hash function */ 
1053     dictObjKeyCompare
,         /* key compare */ 
1054     dictRedisObjectDestructor
, /* key destructor */ 
1055     NULL                       
/* val destructor */ 
1058 /* Hash type hash table (note that small hashes are represented with zimpaps) */ 
1059 static dictType hashDictType 
= { 
1060     dictEncObjHash
,             /* hash function */ 
1063     dictEncObjKeyCompare
,       /* key compare */ 
1064     dictRedisObjectDestructor
,  /* key destructor */ 
1065     dictRedisObjectDestructor   
/* val destructor */ 
1068 /* Keylist hash table type has unencoded redis objects as keys and 
1069  * lists as values. It's used for blocking operations (BLPOP) and to 
1070  * map swapped keys to a list of clients waiting for this keys to be loaded. */ 
1071 static dictType keylistDictType 
= { 
1072     dictObjHash
,                /* hash function */ 
1075     dictObjKeyCompare
,          /* key compare */ 
1076     dictRedisObjectDestructor
,  /* key destructor */ 
1077     dictListDestructor          
/* val destructor */ 
1080 /* ========================= Random utility functions ======================= */ 
1082 /* Redis generally does not try to recover from out of memory conditions 
1083  * when allocating objects or strings, it is not clear if it will be possible 
1084  * to report this condition to the client since the networking layer itself 
1085  * is based on heap allocation for send buffers, so we simply abort. 
1086  * At least the code will be simpler to read... */ 
1087 static void oom(const char *msg
) { 
1088     redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
); 
1093 /* ====================== Redis server networking stuff ===================== */ 
1094 static void closeTimedoutClients(void) { 
1097     time_t now 
= time(NULL
); 
1100     listRewind(server
.clients
,&li
); 
1101     while ((ln 
= listNext(&li
)) != NULL
) { 
1102         c 
= listNodeValue(ln
); 
1103         if (server
.maxidletime 
&& 
1104             !(c
->flags 
& REDIS_SLAVE
) &&    /* no timeout for slaves */ 
1105             !(c
->flags 
& REDIS_MASTER
) &&   /* no timeout for masters */ 
1106              (now 
- c
->lastinteraction 
> server
.maxidletime
)) 
1108             redisLog(REDIS_VERBOSE
,"Closing idle client"); 
1110         } else if (c
->flags 
& REDIS_BLOCKED
) { 
1111             if (c
->blockingto 
!= 0 && c
->blockingto 
< now
) { 
1112                 addReply(c
,shared
.nullmultibulk
); 
1113                 unblockClientWaitingData(c
); 
1119 static int htNeedsResize(dict 
*dict
) { 
1120     long long size
, used
; 
1122     size 
= dictSlots(dict
); 
1123     used 
= dictSize(dict
); 
1124     return (size 
&& used 
&& size 
> DICT_HT_INITIAL_SIZE 
&& 
1125             (used
*100/size 
< REDIS_HT_MINFILL
)); 
1128 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL 
1129  * we resize the hash table to save memory */ 
1130 static void tryResizeHashTables(void) { 
1133     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1134         if (htNeedsResize(server
.db
[j
].dict
)) { 
1135             redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
); 
1136             dictResize(server
.db
[j
].dict
); 
1137             redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
); 
1139         if (htNeedsResize(server
.db
[j
].expires
)) 
1140             dictResize(server
.db
[j
].expires
); 
1144 /* A background saving child (BGSAVE) terminated its work. Handle this. */ 
1145 void backgroundSaveDoneHandler(int statloc
) { 
1146     int exitcode 
= WEXITSTATUS(statloc
); 
1147     int bysignal 
= WIFSIGNALED(statloc
); 
1149     if (!bysignal 
&& exitcode 
== 0) { 
1150         redisLog(REDIS_NOTICE
, 
1151             "Background saving terminated with success"); 
1153         server
.lastsave 
= time(NULL
); 
1154     } else if (!bysignal 
&& exitcode 
!= 0) { 
1155         redisLog(REDIS_WARNING
, "Background saving error"); 
1157         redisLog(REDIS_WARNING
, 
1158             "Background saving terminated by signal"); 
1159         rdbRemoveTempFile(server
.bgsavechildpid
); 
1161     server
.bgsavechildpid 
= -1; 
1162     /* Possibly there are slaves waiting for a BGSAVE in order to be served 
1163      * (the first stage of SYNC is a bulk transfer of dump.rdb) */ 
1164     updateSlavesWaitingBgsave(exitcode 
== 0 ? REDIS_OK 
: REDIS_ERR
); 
1167 /* A background append only file rewriting (BGREWRITEAOF) terminated its work. 
1169 void backgroundRewriteDoneHandler(int statloc
) { 
1170     int exitcode 
= WEXITSTATUS(statloc
); 
1171     int bysignal 
= WIFSIGNALED(statloc
); 
1173     if (!bysignal 
&& exitcode 
== 0) { 
1177         redisLog(REDIS_NOTICE
, 
1178             "Background append only file rewriting terminated with success"); 
1179         /* Now it's time to flush the differences accumulated by the parent */ 
1180         snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
); 
1181         fd 
= open(tmpfile
,O_WRONLY
|O_APPEND
); 
1183             redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
)); 
1186         /* Flush our data... */ 
1187         if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) != 
1188                 (signed) sdslen(server
.bgrewritebuf
)) { 
1189             redisLog(REDIS_WARNING
, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno
)); 
1193         redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
)); 
1194         /* Now our work is to rename the temp file into the stable file. And 
1195          * switch the file descriptor used by the server for append only. */ 
1196         if (rename(tmpfile
,server
.appendfilename
) == -1) { 
1197             redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
)); 
1201         /* Mission completed... almost */ 
1202         redisLog(REDIS_NOTICE
,"Append only file successfully rewritten."); 
1203         if (server
.appendfd 
!= -1) { 
1204             /* If append only is actually enabled... */ 
1205             close(server
.appendfd
); 
1206             server
.appendfd 
= fd
; 
1208             server
.appendseldb 
= -1; /* Make sure it will issue SELECT */ 
1209             redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends."); 
1211             /* If append only is disabled we just generate a dump in this 
1212              * format. Why not? */ 
1215     } else if (!bysignal 
&& exitcode 
!= 0) { 
1216         redisLog(REDIS_WARNING
, "Background append only file rewriting error"); 
1218         redisLog(REDIS_WARNING
, 
1219             "Background append only file rewriting terminated by signal"); 
1222     sdsfree(server
.bgrewritebuf
); 
1223     server
.bgrewritebuf 
= sdsempty(); 
1224     aofRemoveTempFile(server
.bgrewritechildpid
); 
1225     server
.bgrewritechildpid 
= -1; 
1228 static int serverCron(struct aeEventLoop 
*eventLoop
, long long id
, void *clientData
) { 
1229     int j
, loops 
= server
.cronloops
++; 
1230     REDIS_NOTUSED(eventLoop
); 
1232     REDIS_NOTUSED(clientData
); 
1234     /* We take a cached value of the unix time in the global state because 
1235      * with virtual memory and aging there is to store the current time 
1236      * in objects at every object access, and accuracy is not needed. 
1237      * To access a global var is faster than calling time(NULL) */ 
1238     server
.unixtime 
= time(NULL
); 
1240     /* Show some info about non-empty databases */ 
1241     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1242         long long size
, used
, vkeys
; 
1244         size 
= dictSlots(server
.db
[j
].dict
); 
1245         used 
= dictSize(server
.db
[j
].dict
); 
1246         vkeys 
= dictSize(server
.db
[j
].expires
); 
1247         if (!(loops 
% 5) && (used 
|| vkeys
)) { 
1248             redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
); 
1249             /* dictPrintStats(server.dict); */ 
1253     /* We don't want to resize the hash tables while a bacground saving 
1254      * is in progress: the saving child is created using fork() that is 
1255      * implemented with a copy-on-write semantic in most modern systems, so 
1256      * if we resize the HT while there is the saving child at work actually 
1257      * a lot of memory movements in the parent will cause a lot of pages 
1259     if (server
.bgsavechildpid 
== -1) tryResizeHashTables(); 
1261     /* Show information about connected clients */ 
1263         redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects", 
1264             listLength(server
.clients
)-listLength(server
.slaves
), 
1265             listLength(server
.slaves
), 
1266             zmalloc_used_memory(), 
1267             dictSize(server
.sharingpool
)); 
1270     /* Close connections of timedout clients */ 
1271     if ((server
.maxidletime 
&& !(loops 
% 10)) || server
.blpop_blocked_clients
) 
1272         closeTimedoutClients(); 
1274     /* Check if a background saving or AOF rewrite in progress terminated */ 
1275     if (server
.bgsavechildpid 
!= -1 || server
.bgrewritechildpid 
!= -1) { 
1279         if ((pid 
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) { 
1280             if (pid 
== server
.bgsavechildpid
) { 
1281                 backgroundSaveDoneHandler(statloc
); 
1283                 backgroundRewriteDoneHandler(statloc
); 
1287         /* If there is not a background saving in progress check if 
1288          * we have to save now */ 
1289          time_t now 
= time(NULL
); 
1290          for (j 
= 0; j 
< server
.saveparamslen
; j
++) { 
1291             struct saveparam 
*sp 
= server
.saveparams
+j
; 
1293             if (server
.dirty 
>= sp
->changes 
&& 
1294                 now
-server
.lastsave 
> sp
->seconds
) { 
1295                 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...", 
1296                     sp
->changes
, sp
->seconds
); 
1297                 rdbSaveBackground(server
.dbfilename
); 
1303     /* Try to expire a few timed out keys. The algorithm used is adaptive and 
1304      * will use few CPU cycles if there are few expiring keys, otherwise 
1305      * it will get more aggressive to avoid that too much memory is used by 
1306      * keys that can be removed from the keyspace. */ 
1307     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1309         redisDb 
*db 
= server
.db
+j
; 
1311         /* Continue to expire if at the end of the cycle more than 25% 
1312          * of the keys were expired. */ 
1314             long num 
= dictSize(db
->expires
); 
1315             time_t now 
= time(NULL
); 
1318             if (num 
> REDIS_EXPIRELOOKUPS_PER_CRON
) 
1319                 num 
= REDIS_EXPIRELOOKUPS_PER_CRON
; 
1324                 if ((de 
= dictGetRandomKey(db
->expires
)) == NULL
) break; 
1325                 t 
= (time_t) dictGetEntryVal(de
); 
1327                     deleteKey(db
,dictGetEntryKey(de
)); 
1331         } while (expired 
> REDIS_EXPIRELOOKUPS_PER_CRON
/4); 
1334     /* Swap a few keys on disk if we are over the memory limit and VM 
1335      * is enbled. Try to free objects from the free list first. */ 
1336     if (vmCanSwapOut()) { 
1337         while (server
.vm_enabled 
&& zmalloc_used_memory() > 
1338                 server
.vm_max_memory
) 
1342             if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue; 
1343             retval 
= (server
.vm_max_threads 
== 0) ? 
1344                         vmSwapOneObjectBlocking() : 
1345                         vmSwapOneObjectThreaded(); 
1346             if (retval 
== REDIS_ERR 
&& (loops 
% 30) == 0 && 
1347                 zmalloc_used_memory() > 
1348                 (server
.vm_max_memory
+server
.vm_max_memory
/10)) 
1350                 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); 
1352             /* Note that when using threade I/O we free just one object, 
1353              * because anyway when the I/O thread in charge to swap this 
1354              * object out will finish, the handler of completed jobs 
1355              * will try to swap more objects if we are still out of memory. */ 
1356             if (retval 
== REDIS_ERR 
|| server
.vm_max_threads 
> 0) break; 
1360     /* Check if we should connect to a MASTER */ 
1361     if (server
.replstate 
== REDIS_REPL_CONNECT
) { 
1362         redisLog(REDIS_NOTICE
,"Connecting to MASTER..."); 
1363         if (syncWithMaster() == REDIS_OK
) { 
1364             redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded"); 
1370 /* This function gets called every time Redis is entering the 
1371  * main loop of the event driven library, that is, before to sleep 
1372  * for ready file descriptors. */ 
1373 static void beforeSleep(struct aeEventLoop 
*eventLoop
) { 
1374     REDIS_NOTUSED(eventLoop
); 
1376     if (server
.vm_enabled 
&& listLength(server
.io_ready_clients
)) { 
1380         listRewind(server
.io_ready_clients
,&li
); 
1381         while((ln 
= listNext(&li
))) { 
1382             redisClient 
*c 
= ln
->value
; 
1383             struct redisCommand 
*cmd
; 
1385             /* Resume the client. */ 
1386             listDelNode(server
.io_ready_clients
,ln
); 
1387             c
->flags 
&= (~REDIS_IO_WAIT
); 
1388             server
.vm_blocked_clients
--; 
1389             aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, 
1390                 readQueryFromClient
, c
); 
1391             cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
1392             assert(cmd 
!= NULL
); 
1395             /* There may be more data to process in the input buffer. */ 
1396             if (c
->querybuf 
&& sdslen(c
->querybuf
) > 0) 
1397                 processInputBuffer(c
); 
1402 static void createSharedObjects(void) { 
1403     shared
.crlf 
= createObject(REDIS_STRING
,sdsnew("\r\n")); 
1404     shared
.ok 
= createObject(REDIS_STRING
,sdsnew("+OK\r\n")); 
1405     shared
.err 
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n")); 
1406     shared
.emptybulk 
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n")); 
1407     shared
.czero 
= createObject(REDIS_STRING
,sdsnew(":0\r\n")); 
1408     shared
.cone 
= createObject(REDIS_STRING
,sdsnew(":1\r\n")); 
1409     shared
.nullbulk 
= createObject(REDIS_STRING
,sdsnew("$-1\r\n")); 
1410     shared
.nullmultibulk 
= createObject(REDIS_STRING
,sdsnew("*-1\r\n")); 
1411     shared
.emptymultibulk 
= createObject(REDIS_STRING
,sdsnew("*0\r\n")); 
1412     shared
.pong 
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n")); 
1413     shared
.queued 
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n")); 
1414     shared
.wrongtypeerr 
= createObject(REDIS_STRING
,sdsnew( 
1415         "-ERR Operation against a key holding the wrong kind of value\r\n")); 
1416     shared
.nokeyerr 
= createObject(REDIS_STRING
,sdsnew( 
1417         "-ERR no such key\r\n")); 
1418     shared
.syntaxerr 
= createObject(REDIS_STRING
,sdsnew( 
1419         "-ERR syntax error\r\n")); 
1420     shared
.sameobjecterr 
= createObject(REDIS_STRING
,sdsnew( 
1421         "-ERR source and destination objects are the same\r\n")); 
1422     shared
.outofrangeerr 
= createObject(REDIS_STRING
,sdsnew( 
1423         "-ERR index out of range\r\n")); 
1424     shared
.space 
= createObject(REDIS_STRING
,sdsnew(" ")); 
1425     shared
.colon 
= createObject(REDIS_STRING
,sdsnew(":")); 
1426     shared
.plus 
= createObject(REDIS_STRING
,sdsnew("+")); 
1427     shared
.select0 
= createStringObject("select 0\r\n",10); 
1428     shared
.select1 
= createStringObject("select 1\r\n",10); 
1429     shared
.select2 
= createStringObject("select 2\r\n",10); 
1430     shared
.select3 
= createStringObject("select 3\r\n",10); 
1431     shared
.select4 
= createStringObject("select 4\r\n",10); 
1432     shared
.select5 
= createStringObject("select 5\r\n",10); 
1433     shared
.select6 
= createStringObject("select 6\r\n",10); 
1434     shared
.select7 
= createStringObject("select 7\r\n",10); 
1435     shared
.select8 
= createStringObject("select 8\r\n",10); 
1436     shared
.select9 
= createStringObject("select 9\r\n",10); 
1439 static void appendServerSaveParams(time_t seconds
, int changes
) { 
1440     server
.saveparams 
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1)); 
1441     server
.saveparams
[server
.saveparamslen
].seconds 
= seconds
; 
1442     server
.saveparams
[server
.saveparamslen
].changes 
= changes
; 
1443     server
.saveparamslen
++; 
1446 static void resetServerSaveParams() { 
1447     zfree(server
.saveparams
); 
1448     server
.saveparams 
= NULL
; 
1449     server
.saveparamslen 
= 0; 
1452 static void initServerConfig() { 
1453     server
.dbnum 
= REDIS_DEFAULT_DBNUM
; 
1454     server
.port 
= REDIS_SERVERPORT
; 
1455     server
.verbosity 
= REDIS_VERBOSE
; 
1456     server
.maxidletime 
= REDIS_MAXIDLETIME
; 
1457     server
.saveparams 
= NULL
; 
1458     server
.logfile 
= NULL
; /* NULL = log on standard output */ 
1459     server
.bindaddr 
= NULL
; 
1460     server
.glueoutputbuf 
= 1; 
1461     server
.daemonize 
= 0; 
1462     server
.appendonly 
= 0; 
1463     server
.appendfsync 
= APPENDFSYNC_ALWAYS
; 
1464     server
.lastfsync 
= time(NULL
); 
1465     server
.appendfd 
= -1; 
1466     server
.appendseldb 
= -1; /* Make sure the first time will not match */ 
1467     server
.pidfile 
= "/var/run/redis.pid"; 
1468     server
.dbfilename 
= "dump.rdb"; 
1469     server
.appendfilename 
= "appendonly.aof"; 
1470     server
.requirepass 
= NULL
; 
1471     server
.shareobjects 
= 0; 
1472     server
.rdbcompression 
= 1; 
1473     server
.sharingpoolsize 
= 1024; 
1474     server
.maxclients 
= 0; 
1475     server
.blpop_blocked_clients 
= 0; 
1476     server
.maxmemory 
= 0; 
1477     server
.vm_enabled 
= 0; 
1478     server
.vm_swap_file 
= zstrdup("/tmp/redis-%p.vm"); 
1479     server
.vm_page_size 
= 256;          /* 256 bytes per page */ 
1480     server
.vm_pages 
= 1024*1024*100;    /* 104 millions of pages */ 
1481     server
.vm_max_memory 
= 1024LL*1024*1024*1; /* 1 GB of RAM */ 
1482     server
.vm_max_threads 
= 4; 
1483     server
.vm_blocked_clients 
= 0; 
1484     server
.hash_max_zipmap_entries 
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
; 
1485     server
.hash_max_zipmap_value 
= REDIS_HASH_MAX_ZIPMAP_VALUE
; 
1487     resetServerSaveParams(); 
1489     appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */ 
1490     appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */ 
1491     appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ 
1492     /* Replication related */ 
1494     server
.masterauth 
= NULL
; 
1495     server
.masterhost 
= NULL
; 
1496     server
.masterport 
= 6379; 
1497     server
.master 
= NULL
; 
1498     server
.replstate 
= REDIS_REPL_NONE
; 
1500     /* Double constants initialization */ 
1502     R_PosInf 
= 1.0/R_Zero
; 
1503     R_NegInf 
= -1.0/R_Zero
; 
1504     R_Nan 
= R_Zero
/R_Zero
; 
1507 static void initServer() { 
1510     signal(SIGHUP
, SIG_IGN
); 
1511     signal(SIGPIPE
, SIG_IGN
); 
1512     setupSigSegvAction(); 
1514     server
.devnull 
= fopen("/dev/null","w"); 
1515     if (server
.devnull 
== NULL
) { 
1516         redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
); 
1519     server
.clients 
= listCreate(); 
1520     server
.slaves 
= listCreate(); 
1521     server
.monitors 
= listCreate(); 
1522     server
.objfreelist 
= listCreate(); 
1523     createSharedObjects(); 
1524     server
.el 
= aeCreateEventLoop(); 
1525     server
.db 
= zmalloc(sizeof(redisDb
)*server
.dbnum
); 
1526     server
.sharingpool 
= dictCreate(&setDictType
,NULL
); 
1527     server
.fd 
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
); 
1528     if (server
.fd 
== -1) { 
1529         redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
); 
1532     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1533         server
.db
[j
].dict 
= dictCreate(&dbDictType
,NULL
); 
1534         server
.db
[j
].expires 
= dictCreate(&keyptrDictType
,NULL
); 
1535         server
.db
[j
].blockingkeys 
= dictCreate(&keylistDictType
,NULL
); 
1536         if (server
.vm_enabled
) 
1537             server
.db
[j
].io_keys 
= dictCreate(&keylistDictType
,NULL
); 
1538         server
.db
[j
].id 
= j
; 
1540     server
.cronloops 
= 0; 
1541     server
.bgsavechildpid 
= -1; 
1542     server
.bgrewritechildpid 
= -1; 
1543     server
.bgrewritebuf 
= sdsempty(); 
1544     server
.lastsave 
= time(NULL
); 
1546     server
.stat_numcommands 
= 0; 
1547     server
.stat_numconnections 
= 0; 
1548     server
.stat_starttime 
= time(NULL
); 
1549     server
.unixtime 
= time(NULL
); 
1550     aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
); 
1551     if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
, 
1552         acceptHandler
, NULL
) == AE_ERR
) oom("creating file event"); 
1554     if (server
.appendonly
) { 
1555         server
.appendfd 
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644); 
1556         if (server
.appendfd 
== -1) { 
1557             redisLog(REDIS_WARNING
, "Can't open the append-only file: %s", 
1563     if (server
.vm_enabled
) vmInit(); 
1566 /* Empty the whole database */ 
1567 static long long emptyDb() { 
1569     long long removed 
= 0; 
1571     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1572         removed 
+= dictSize(server
.db
[j
].dict
); 
1573         dictEmpty(server
.db
[j
].dict
); 
1574         dictEmpty(server
.db
[j
].expires
); 
1579 static int yesnotoi(char *s
) { 
1580     if (!strcasecmp(s
,"yes")) return 1; 
1581     else if (!strcasecmp(s
,"no")) return 0; 
1585 /* I agree, this is a very rudimental way to load a configuration... 
1586    will improve later if the config gets more complex */ 
1587 static void loadServerConfig(char *filename
) { 
1589     char buf
[REDIS_CONFIGLINE_MAX
+1], *err 
= NULL
; 
1593     if (filename
[0] == '-' && filename
[1] == '\0') 
1596         if ((fp 
= fopen(filename
,"r")) == NULL
) { 
1597             redisLog(REDIS_WARNING
,"Fatal error, can't open config file"); 
1602     while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) { 
1608         line 
= sdstrim(line
," \t\r\n"); 
1610         /* Skip comments and blank lines*/ 
1611         if (line
[0] == '#' || line
[0] == '\0') { 
1616         /* Split into arguments */ 
1617         argv 
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
); 
1618         sdstolower(argv
[0]); 
1620         /* Execute config directives */ 
1621         if (!strcasecmp(argv
[0],"timeout") && argc 
== 2) { 
1622             server
.maxidletime 
= atoi(argv
[1]); 
1623             if (server
.maxidletime 
< 0) { 
1624                 err 
= "Invalid timeout value"; goto loaderr
; 
1626         } else if (!strcasecmp(argv
[0],"port") && argc 
== 2) { 
1627             server
.port 
= atoi(argv
[1]); 
1628             if (server
.port 
< 1 || server
.port 
> 65535) { 
1629                 err 
= "Invalid port"; goto loaderr
; 
1631         } else if (!strcasecmp(argv
[0],"bind") && argc 
== 2) { 
1632             server
.bindaddr 
= zstrdup(argv
[1]); 
1633         } else if (!strcasecmp(argv
[0],"save") && argc 
== 3) { 
1634             int seconds 
= atoi(argv
[1]); 
1635             int changes 
= atoi(argv
[2]); 
1636             if (seconds 
< 1 || changes 
< 0) { 
1637                 err 
= "Invalid save parameters"; goto loaderr
; 
1639             appendServerSaveParams(seconds
,changes
); 
1640         } else if (!strcasecmp(argv
[0],"dir") && argc 
== 2) { 
1641             if (chdir(argv
[1]) == -1) { 
1642                 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s", 
1643                     argv
[1], strerror(errno
)); 
1646         } else if (!strcasecmp(argv
[0],"loglevel") && argc 
== 2) { 
1647             if (!strcasecmp(argv
[1],"debug")) server
.verbosity 
= REDIS_DEBUG
; 
1648             else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity 
= REDIS_VERBOSE
; 
1649             else if (!strcasecmp(argv
[1],"notice")) server
.verbosity 
= REDIS_NOTICE
; 
1650             else if (!strcasecmp(argv
[1],"warning")) server
.verbosity 
= REDIS_WARNING
; 
1652                 err 
= "Invalid log level. Must be one of debug, notice, warning"; 
1655         } else if (!strcasecmp(argv
[0],"logfile") && argc 
== 2) { 
1658             server
.logfile 
= zstrdup(argv
[1]); 
1659             if (!strcasecmp(server
.logfile
,"stdout")) { 
1660                 zfree(server
.logfile
); 
1661                 server
.logfile 
= NULL
; 
1663             if (server
.logfile
) { 
1664                 /* Test if we are able to open the file. The server will not 
1665                  * be able to abort just for this problem later... */ 
1666                 logfp 
= fopen(server
.logfile
,"a"); 
1667                 if (logfp 
== NULL
) { 
1668                     err 
= sdscatprintf(sdsempty(), 
1669                         "Can't open the log file: %s", strerror(errno
)); 
1674         } else if (!strcasecmp(argv
[0],"databases") && argc 
== 2) { 
1675             server
.dbnum 
= atoi(argv
[1]); 
1676             if (server
.dbnum 
< 1) { 
1677                 err 
= "Invalid number of databases"; goto loaderr
; 
1679         } else if (!strcasecmp(argv
[0],"maxclients") && argc 
== 2) { 
1680             server
.maxclients 
= atoi(argv
[1]); 
1681         } else if (!strcasecmp(argv
[0],"maxmemory") && argc 
== 2) { 
1682             server
.maxmemory 
= strtoll(argv
[1], NULL
, 10); 
1683         } else if (!strcasecmp(argv
[0],"slaveof") && argc 
== 3) { 
1684             server
.masterhost 
= sdsnew(argv
[1]); 
1685             server
.masterport 
= atoi(argv
[2]); 
1686             server
.replstate 
= REDIS_REPL_CONNECT
; 
1687         } else if (!strcasecmp(argv
[0],"masterauth") && argc 
== 2) { 
1688                 server
.masterauth 
= zstrdup(argv
[1]); 
1689         } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc 
== 2) { 
1690             if ((server
.glueoutputbuf 
= yesnotoi(argv
[1])) == -1) { 
1691                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1693         } else if (!strcasecmp(argv
[0],"shareobjects") && argc 
== 2) { 
1694             if ((server
.shareobjects 
= yesnotoi(argv
[1])) == -1) { 
1695                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1697         } else if (!strcasecmp(argv
[0],"rdbcompression") && argc 
== 2) { 
1698             if ((server
.rdbcompression 
= yesnotoi(argv
[1])) == -1) { 
1699                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1701         } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc 
== 2) { 
1702             server
.sharingpoolsize 
= atoi(argv
[1]); 
1703             if (server
.sharingpoolsize 
< 1) { 
1704                 err 
= "invalid object sharing pool size"; goto loaderr
; 
1706         } else if (!strcasecmp(argv
[0],"daemonize") && argc 
== 2) { 
1707             if ((server
.daemonize 
= yesnotoi(argv
[1])) == -1) { 
1708                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1710         } else if (!strcasecmp(argv
[0],"appendonly") && argc 
== 2) { 
1711             if ((server
.appendonly 
= yesnotoi(argv
[1])) == -1) { 
1712                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1714         } else if (!strcasecmp(argv
[0],"appendfsync") && argc 
== 2) { 
1715             if (!strcasecmp(argv
[1],"no")) { 
1716                 server
.appendfsync 
= APPENDFSYNC_NO
; 
1717             } else if (!strcasecmp(argv
[1],"always")) { 
1718                 server
.appendfsync 
= APPENDFSYNC_ALWAYS
; 
1719             } else if (!strcasecmp(argv
[1],"everysec")) { 
1720                 server
.appendfsync 
= APPENDFSYNC_EVERYSEC
; 
1722                 err 
= "argument must be 'no', 'always' or 'everysec'"; 
1725         } else if (!strcasecmp(argv
[0],"requirepass") && argc 
== 2) { 
1726             server
.requirepass 
= zstrdup(argv
[1]); 
1727         } else if (!strcasecmp(argv
[0],"pidfile") && argc 
== 2) { 
1728             server
.pidfile 
= zstrdup(argv
[1]); 
1729         } else if (!strcasecmp(argv
[0],"dbfilename") && argc 
== 2) { 
1730             server
.dbfilename 
= zstrdup(argv
[1]); 
1731         } else if (!strcasecmp(argv
[0],"vm-enabled") && argc 
== 2) { 
1732             if ((server
.vm_enabled 
= yesnotoi(argv
[1])) == -1) { 
1733                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1735         } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc 
== 2) { 
1736             zfree(server
.vm_swap_file
); 
1737             server
.vm_swap_file 
= zstrdup(argv
[1]); 
1738         } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc 
== 2) { 
1739             server
.vm_max_memory 
= strtoll(argv
[1], NULL
, 10); 
1740         } else if (!strcasecmp(argv
[0],"vm-page-size") && argc 
== 2) { 
1741             server
.vm_page_size 
= strtoll(argv
[1], NULL
, 10); 
1742         } else if (!strcasecmp(argv
[0],"vm-pages") && argc 
== 2) { 
1743             server
.vm_pages 
= strtoll(argv
[1], NULL
, 10); 
1744         } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc 
== 2) { 
1745             server
.vm_max_threads 
= strtoll(argv
[1], NULL
, 10); 
1746         } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc 
== 2){ 
1747             server
.hash_max_zipmap_entries 
= strtol(argv
[1], NULL
, 10); 
1748         } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc 
== 2){ 
1749             server
.hash_max_zipmap_value 
= strtol(argv
[1], NULL
, 10); 
1750         } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc 
== 2) { 
1751             server
.vm_max_threads 
= strtoll(argv
[1], NULL
, 10); 
1753             err 
= "Bad directive or wrong number of arguments"; goto loaderr
; 
1755         for (j 
= 0; j 
< argc
; j
++) 
1760     if (fp 
!= stdin
) fclose(fp
); 
1764     fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n"); 
1765     fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
); 
1766     fprintf(stderr
, ">>> '%s'\n", line
); 
1767     fprintf(stderr
, "%s\n", err
); 
1771 static void freeClientArgv(redisClient 
*c
) { 
1774     for (j 
= 0; j 
< c
->argc
; j
++) 
1775         decrRefCount(c
->argv
[j
]); 
1776     for (j 
= 0; j 
< c
->mbargc
; j
++) 
1777         decrRefCount(c
->mbargv
[j
]); 
1782 static void freeClient(redisClient 
*c
) { 
1785     /* Note that if the client we are freeing is blocked into a blocking 
1786      * call, we have to set querybuf to NULL *before* to call 
1787      * unblockClientWaitingData() to avoid processInputBuffer() will get 
1788      * called. Also it is important to remove the file events after 
1789      * this, because this call adds the READABLE event. */ 
1790     sdsfree(c
->querybuf
); 
1792     if (c
->flags 
& REDIS_BLOCKED
) 
1793         unblockClientWaitingData(c
); 
1795     aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
); 
1796     aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
1797     listRelease(c
->reply
); 
1800     /* Remove from the list of clients */ 
1801     ln 
= listSearchKey(server
.clients
,c
); 
1802     redisAssert(ln 
!= NULL
); 
1803     listDelNode(server
.clients
,ln
); 
1804     /* Remove from the list of clients waiting for swapped keys */ 
1805     if (c
->flags 
& REDIS_IO_WAIT 
&& listLength(c
->io_keys
) == 0) { 
1806         ln 
= listSearchKey(server
.io_ready_clients
,c
); 
1808             listDelNode(server
.io_ready_clients
,ln
); 
1809             server
.vm_blocked_clients
--; 
1812     while (server
.vm_enabled 
&& listLength(c
->io_keys
)) { 
1813         ln 
= listFirst(c
->io_keys
); 
1814         dontWaitForSwappedKey(c
,ln
->value
); 
1816     listRelease(c
->io_keys
); 
1818     if (c
->flags 
& REDIS_SLAVE
) { 
1819         if (c
->replstate 
== REDIS_REPL_SEND_BULK 
&& c
->repldbfd 
!= -1) 
1821         list 
*l 
= (c
->flags 
& REDIS_MONITOR
) ? server
.monitors 
: server
.slaves
; 
1822         ln 
= listSearchKey(l
,c
); 
1823         redisAssert(ln 
!= NULL
); 
1826     if (c
->flags 
& REDIS_MASTER
) { 
1827         server
.master 
= NULL
; 
1828         server
.replstate 
= REDIS_REPL_CONNECT
; 
1832     freeClientMultiState(c
); 
1836 #define GLUEREPLY_UP_TO (1024) 
1837 static void glueReplyBuffersIfNeeded(redisClient 
*c
) { 
1839     char buf
[GLUEREPLY_UP_TO
]; 
1844     listRewind(c
->reply
,&li
); 
1845     while((ln 
= listNext(&li
))) { 
1849         objlen 
= sdslen(o
->ptr
); 
1850         if (copylen 
+ objlen 
<= GLUEREPLY_UP_TO
) { 
1851             memcpy(buf
+copylen
,o
->ptr
,objlen
); 
1853             listDelNode(c
->reply
,ln
); 
1855             if (copylen 
== 0) return; 
1859     /* Now the output buffer is empty, add the new single element */ 
1860     o 
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
)); 
1861     listAddNodeHead(c
->reply
,o
); 
1864 static void sendReplyToClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
1865     redisClient 
*c 
= privdata
; 
1866     int nwritten 
= 0, totwritten 
= 0, objlen
; 
1869     REDIS_NOTUSED(mask
); 
1871     /* Use writev() if we have enough buffers to send */ 
1872     if (!server
.glueoutputbuf 
&& 
1873         listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD 
&&  
1874         !(c
->flags 
& REDIS_MASTER
)) 
1876         sendReplyToClientWritev(el
, fd
, privdata
, mask
); 
1880     while(listLength(c
->reply
)) { 
1881         if (server
.glueoutputbuf 
&& listLength(c
->reply
) > 1) 
1882             glueReplyBuffersIfNeeded(c
); 
1884         o 
= listNodeValue(listFirst(c
->reply
)); 
1885         objlen 
= sdslen(o
->ptr
); 
1888             listDelNode(c
->reply
,listFirst(c
->reply
)); 
1892         if (c
->flags 
& REDIS_MASTER
) { 
1893             /* Don't reply to a master */ 
1894             nwritten 
= objlen 
- c
->sentlen
; 
1896             nwritten 
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen 
- c
->sentlen
); 
1897             if (nwritten 
<= 0) break; 
1899         c
->sentlen 
+= nwritten
; 
1900         totwritten 
+= nwritten
; 
1901         /* If we fully sent the object on head go to the next one */ 
1902         if (c
->sentlen 
== objlen
) { 
1903             listDelNode(c
->reply
,listFirst(c
->reply
)); 
1906         /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT 
1907          * bytes, in a single threaded server it's a good idea to serve 
1908          * other clients as well, even if a very large request comes from 
1909          * super fast link that is always able to accept data (in real world 
1910          * scenario think about 'KEYS *' against the loopback interfae) */ 
1911         if (totwritten 
> REDIS_MAX_WRITE_PER_EVENT
) break; 
1913     if (nwritten 
== -1) { 
1914         if (errno 
== EAGAIN
) { 
1917             redisLog(REDIS_VERBOSE
, 
1918                 "Error writing to client: %s", strerror(errno
)); 
1923     if (totwritten 
> 0) c
->lastinteraction 
= time(NULL
); 
1924     if (listLength(c
->reply
) == 0) { 
1926         aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
1930 static void sendReplyToClientWritev(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) 
1932     redisClient 
*c 
= privdata
; 
1933     int nwritten 
= 0, totwritten 
= 0, objlen
, willwrite
; 
1935     struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
]; 
1936     int offset
, ion 
= 0; 
1938     REDIS_NOTUSED(mask
); 
1941     while (listLength(c
->reply
)) { 
1942         offset 
= c
->sentlen
; 
1946         /* fill-in the iov[] array */ 
1947         for(node 
= listFirst(c
->reply
); node
; node 
= listNextNode(node
)) { 
1948             o 
= listNodeValue(node
); 
1949             objlen 
= sdslen(o
->ptr
); 
1951             if (totwritten 
+ objlen 
- offset 
> REDIS_MAX_WRITE_PER_EVENT
)  
1954             if(ion 
== REDIS_WRITEV_IOVEC_COUNT
) 
1955                 break; /* no more iovecs */ 
1957             iov
[ion
].iov_base 
= ((char*)o
->ptr
) + offset
; 
1958             iov
[ion
].iov_len 
= objlen 
- offset
; 
1959             willwrite 
+= objlen 
- offset
; 
1960             offset 
= 0; /* just for the first item */ 
1967         /* write all collected blocks at once */ 
1968         if((nwritten 
= writev(fd
, iov
, ion
)) < 0) { 
1969             if (errno 
!= EAGAIN
) { 
1970                 redisLog(REDIS_VERBOSE
, 
1971                          "Error writing to client: %s", strerror(errno
)); 
1978         totwritten 
+= nwritten
; 
1979         offset 
= c
->sentlen
; 
1981         /* remove written robjs from c->reply */ 
1982         while (nwritten 
&& listLength(c
->reply
)) { 
1983             o 
= listNodeValue(listFirst(c
->reply
)); 
1984             objlen 
= sdslen(o
->ptr
); 
1986             if(nwritten 
>= objlen 
- offset
) { 
1987                 listDelNode(c
->reply
, listFirst(c
->reply
)); 
1988                 nwritten 
-= objlen 
- offset
; 
1992                 c
->sentlen 
+= nwritten
; 
2000         c
->lastinteraction 
= time(NULL
); 
2002     if (listLength(c
->reply
) == 0) { 
2004         aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
2008 static struct redisCommand 
*lookupCommand(char *name
) { 
2010     while(cmdTable
[j
].name 
!= NULL
) { 
2011         if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
]; 
2017 /* resetClient prepare the client to process the next command */ 
2018 static void resetClient(redisClient 
*c
) { 
2024 /* Call() is the core of Redis execution of a command */ 
2025 static void call(redisClient 
*c
, struct redisCommand 
*cmd
) { 
2028     dirty 
= server
.dirty
; 
2030     if (server
.appendonly 
&& server
.dirty
-dirty
) 
2031         feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
2032     if (server
.dirty
-dirty 
&& listLength(server
.slaves
)) 
2033         replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
2034     if (listLength(server
.monitors
)) 
2035         replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
2036     server
.stat_numcommands
++; 
2039 /* If this function gets called we already read a whole 
2040  * command, argments are in the client argv/argc fields. 
2041  * processCommand() execute the command or prepare the 
2042  * server for a bulk read from the client. 
2044  * If 1 is returned the client is still alive and valid and 
2045  * and other operations can be performed by the caller. Otherwise 
2046  * if 0 is returned the client was destroied (i.e. after QUIT). */ 
2047 static int processCommand(redisClient 
*c
) { 
2048     struct redisCommand 
*cmd
; 
2050     /* Free some memory if needed (maxmemory setting) */ 
2051     if (server
.maxmemory
) freeMemoryIfNeeded(); 
2053     /* Handle the multi bulk command type. This is an alternative protocol 
2054      * supported by Redis in order to receive commands that are composed of 
2055      * multiple binary-safe "bulk" arguments. The latency of processing is 
2056      * a bit higher but this allows things like multi-sets, so if this 
2057      * protocol is used only for MSET and similar commands this is a big win. */ 
2058     if (c
->multibulk 
== 0 && c
->argc 
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') { 
2059         c
->multibulk 
= atoi(((char*)c
->argv
[0]->ptr
)+1); 
2060         if (c
->multibulk 
<= 0) { 
2064             decrRefCount(c
->argv
[c
->argc
-1]); 
2068     } else if (c
->multibulk
) { 
2069         if (c
->bulklen 
== -1) { 
2070             if (((char*)c
->argv
[0]->ptr
)[0] != '$') { 
2071                 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n")); 
2075                 int bulklen 
= atoi(((char*)c
->argv
[0]->ptr
)+1); 
2076                 decrRefCount(c
->argv
[0]); 
2077                 if (bulklen 
< 0 || bulklen 
> 1024*1024*1024) { 
2079                     addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n")); 
2084                 c
->bulklen 
= bulklen
+2; /* add two bytes for CR+LF */ 
2088             c
->mbargv 
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1)); 
2089             c
->mbargv
[c
->mbargc
] = c
->argv
[0]; 
2093             if (c
->multibulk 
== 0) { 
2097                 /* Here we need to swap the multi-bulk argc/argv with the 
2098                  * normal argc/argv of the client structure. */ 
2100                 c
->argv 
= c
->mbargv
; 
2101                 c
->mbargv 
= auxargv
; 
2104                 c
->argc 
= c
->mbargc
; 
2105                 c
->mbargc 
= auxargc
; 
2107                 /* We need to set bulklen to something different than -1 
2108                  * in order for the code below to process the command without 
2109                  * to try to read the last argument of a bulk command as 
2110                  * a special argument. */ 
2112                 /* continue below and process the command */ 
2119     /* -- end of multi bulk commands processing -- */ 
2121     /* The QUIT command is handled as a special case. Normal command 
2122      * procs are unable to close the client connection safely */ 
2123     if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) { 
2128     /* Now lookup the command and check ASAP about trivial error conditions 
2129      * such wrong arity, bad command name and so forth. */ 
2130     cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
2133             sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n", 
2134                 (char*)c
->argv
[0]->ptr
)); 
2137     } else if ((cmd
->arity 
> 0 && cmd
->arity 
!= c
->argc
) || 
2138                (c
->argc 
< -cmd
->arity
)) { 
2140             sdscatprintf(sdsempty(), 
2141                 "-ERR wrong number of arguments for '%s' command\r\n", 
2145     } else if (server
.maxmemory 
&& cmd
->flags 
& REDIS_CMD_DENYOOM 
&& zmalloc_used_memory() > server
.maxmemory
) { 
2146         addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n")); 
2149     } else if (cmd
->flags 
& REDIS_CMD_BULK 
&& c
->bulklen 
== -1) { 
2150         /* This is a bulk command, we have to read the last argument yet. */ 
2151         int bulklen 
= atoi(c
->argv
[c
->argc
-1]->ptr
); 
2153         decrRefCount(c
->argv
[c
->argc
-1]); 
2154         if (bulklen 
< 0 || bulklen 
> 1024*1024*1024) { 
2156             addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n")); 
2161         c
->bulklen 
= bulklen
+2; /* add two bytes for CR+LF */ 
2162         /* It is possible that the bulk read is already in the 
2163          * buffer. Check this condition and handle it accordingly. 
2164          * This is just a fast path, alternative to call processInputBuffer(). 
2165          * It's a good idea since the code is small and this condition 
2166          * happens most of the times. */ 
2167         if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) { 
2168             c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2); 
2170             c
->querybuf 
= sdsrange(c
->querybuf
,c
->bulklen
,-1); 
2172             /* Otherwise return... there is to read the last argument 
2173              * from the socket. */ 
2177     /* Let's try to share objects on the command arguments vector */ 
2178     if (server
.shareobjects
) { 
2180         for(j 
= 1; j 
< c
->argc
; j
++) 
2181             c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]); 
2183     /* Let's try to encode the bulk object to save space. */ 
2184     if (cmd
->flags 
& REDIS_CMD_BULK
) 
2185         tryObjectEncoding(c
->argv
[c
->argc
-1]); 
2187     /* Check if the user is authenticated */ 
2188     if (server
.requirepass 
&& !c
->authenticated 
&& cmd
->proc 
!= authCommand
) { 
2189         addReplySds(c
,sdsnew("-ERR operation not permitted\r\n")); 
2194     /* Exec the command */ 
2195     if (c
->flags 
& REDIS_MULTI 
&& cmd
->proc 
!= execCommand 
&& cmd
->proc 
!= discardCommand
) { 
2196         queueMultiCommand(c
,cmd
); 
2197         addReply(c
,shared
.queued
); 
2199         if (server
.vm_enabled 
&& server
.vm_max_threads 
> 0 && 
2200             blockClientOnSwappedKeys(cmd
,c
)) return 1; 
2204     /* Prepare the client for the next command */ 
2209 static void replicationFeedSlaves(list 
*slaves
, struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
) { 
2214     /* (args*2)+1 is enough room for args, spaces, newlines */ 
2215     robj 
*static_outv
[REDIS_STATIC_ARGS
*2+1]; 
2217     if (argc 
<= REDIS_STATIC_ARGS
) { 
2220         outv 
= zmalloc(sizeof(robj
*)*(argc
*2+1)); 
2223     for (j 
= 0; j 
< argc
; j
++) { 
2224         if (j 
!= 0) outv
[outc
++] = shared
.space
; 
2225         if ((cmd
->flags 
& REDIS_CMD_BULK
) && j 
== argc
-1) { 
2228             lenobj 
= createObject(REDIS_STRING
, 
2229                 sdscatprintf(sdsempty(),"%lu\r\n", 
2230                     (unsigned long) stringObjectLen(argv
[j
]))); 
2231             lenobj
->refcount 
= 0; 
2232             outv
[outc
++] = lenobj
; 
2234         outv
[outc
++] = argv
[j
]; 
2236     outv
[outc
++] = shared
.crlf
; 
2238     /* Increment all the refcounts at start and decrement at end in order to 
2239      * be sure to free objects if there is no slave in a replication state 
2240      * able to be feed with commands */ 
2241     for (j 
= 0; j 
< outc
; j
++) incrRefCount(outv
[j
]); 
2242     listRewind(slaves
,&li
); 
2243     while((ln 
= listNext(&li
))) { 
2244         redisClient 
*slave 
= ln
->value
; 
2246         /* Don't feed slaves that are still waiting for BGSAVE to start */ 
2247         if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) continue; 
2249         /* Feed all the other slaves, MONITORs and so on */ 
2250         if (slave
->slaveseldb 
!= dictid
) { 
2254             case 0: selectcmd 
= shared
.select0
; break; 
2255             case 1: selectcmd 
= shared
.select1
; break; 
2256             case 2: selectcmd 
= shared
.select2
; break; 
2257             case 3: selectcmd 
= shared
.select3
; break; 
2258             case 4: selectcmd 
= shared
.select4
; break; 
2259             case 5: selectcmd 
= shared
.select5
; break; 
2260             case 6: selectcmd 
= shared
.select6
; break; 
2261             case 7: selectcmd 
= shared
.select7
; break; 
2262             case 8: selectcmd 
= shared
.select8
; break; 
2263             case 9: selectcmd 
= shared
.select9
; break; 
2265                 selectcmd 
= createObject(REDIS_STRING
, 
2266                     sdscatprintf(sdsempty(),"select %d\r\n",dictid
)); 
2267                 selectcmd
->refcount 
= 0; 
2270             addReply(slave
,selectcmd
); 
2271             slave
->slaveseldb 
= dictid
; 
2273         for (j 
= 0; j 
< outc
; j
++) addReply(slave
,outv
[j
]); 
2275     for (j 
= 0; j 
< outc
; j
++) decrRefCount(outv
[j
]); 
2276     if (outv 
!= static_outv
) zfree(outv
); 
2279 static void processInputBuffer(redisClient 
*c
) { 
2281     /* Before to process the input buffer, make sure the client is not 
2282      * waitig for a blocking operation such as BLPOP. Note that the first 
2283      * iteration the client is never blocked, otherwise the processInputBuffer 
2284      * would not be called at all, but after the execution of the first commands 
2285      * in the input buffer the client may be blocked, and the "goto again" 
2286      * will try to reiterate. The following line will make it return asap. */ 
2287     if (c
->flags 
& REDIS_BLOCKED 
|| c
->flags 
& REDIS_IO_WAIT
) return; 
2288     if (c
->bulklen 
== -1) { 
2289         /* Read the first line of the query */ 
2290         char *p 
= strchr(c
->querybuf
,'\n'); 
2297             query 
= c
->querybuf
; 
2298             c
->querybuf 
= sdsempty(); 
2299             querylen 
= 1+(p
-(query
)); 
2300             if (sdslen(query
) > querylen
) { 
2301                 /* leave data after the first line of the query in the buffer */ 
2302                 c
->querybuf 
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
); 
2304             *p 
= '\0'; /* remove "\n" */ 
2305             if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */ 
2306             sdsupdatelen(query
); 
2308             /* Now we can split the query in arguments */ 
2309             argv 
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
); 
2312             if (c
->argv
) zfree(c
->argv
); 
2313             c
->argv 
= zmalloc(sizeof(robj
*)*argc
); 
2315             for (j 
= 0; j 
< argc
; j
++) { 
2316                 if (sdslen(argv
[j
])) { 
2317                     c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]); 
2325                 /* Execute the command. If the client is still valid 
2326                  * after processCommand() return and there is something 
2327                  * on the query buffer try to process the next command. */ 
2328                 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
; 
2330                 /* Nothing to process, argc == 0. Just process the query 
2331                  * buffer if it's not empty or return to the caller */ 
2332                 if (sdslen(c
->querybuf
)) goto again
; 
2335         } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) { 
2336             redisLog(REDIS_VERBOSE
, "Client protocol error"); 
2341         /* Bulk read handling. Note that if we are at this point 
2342            the client already sent a command terminated with a newline, 
2343            we are reading the bulk data that is actually the last 
2344            argument of the command. */ 
2345         int qbl 
= sdslen(c
->querybuf
); 
2347         if (c
->bulklen 
<= qbl
) { 
2348             /* Copy everything but the final CRLF as final argument */ 
2349             c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2); 
2351             c
->querybuf 
= sdsrange(c
->querybuf
,c
->bulklen
,-1); 
2352             /* Process the command. If the client is still valid after 
2353              * the processing and there is more data in the buffer 
2354              * try to parse it. */ 
2355             if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
; 
2361 static void readQueryFromClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
2362     redisClient 
*c 
= (redisClient
*) privdata
; 
2363     char buf
[REDIS_IOBUF_LEN
]; 
2366     REDIS_NOTUSED(mask
); 
2368     nread 
= read(fd
, buf
, REDIS_IOBUF_LEN
); 
2370         if (errno 
== EAGAIN
) { 
2373             redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
)); 
2377     } else if (nread 
== 0) { 
2378         redisLog(REDIS_VERBOSE
, "Client closed connection"); 
2383         c
->querybuf 
= sdscatlen(c
->querybuf
, buf
, nread
); 
2384         c
->lastinteraction 
= time(NULL
); 
2388     if (!(c
->flags 
& REDIS_BLOCKED
)) 
2389         processInputBuffer(c
); 
2392 static int selectDb(redisClient 
*c
, int id
) { 
2393     if (id 
< 0 || id 
>= server
.dbnum
) 
2395     c
->db 
= &server
.db
[id
]; 
2399 static void *dupClientReplyValue(void *o
) { 
2400     incrRefCount((robj
*)o
); 
2404 static redisClient 
*createClient(int fd
) { 
2405     redisClient 
*c 
= zmalloc(sizeof(*c
)); 
2407     anetNonBlock(NULL
,fd
); 
2408     anetTcpNoDelay(NULL
,fd
); 
2409     if (!c
) return NULL
; 
2412     c
->querybuf 
= sdsempty(); 
2421     c
->lastinteraction 
= time(NULL
); 
2422     c
->authenticated 
= 0; 
2423     c
->replstate 
= REDIS_REPL_NONE
; 
2424     c
->reply 
= listCreate(); 
2425     listSetFreeMethod(c
->reply
,decrRefCount
); 
2426     listSetDupMethod(c
->reply
,dupClientReplyValue
); 
2427     c
->blockingkeys 
= NULL
; 
2428     c
->blockingkeysnum 
= 0; 
2429     c
->io_keys 
= listCreate(); 
2430     listSetFreeMethod(c
->io_keys
,decrRefCount
); 
2431     if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, 
2432         readQueryFromClient
, c
) == AE_ERR
) { 
2436     listAddNodeTail(server
.clients
,c
); 
2437     initClientMultiState(c
); 
2441 static void addReply(redisClient 
*c
, robj 
*obj
) { 
2442     if (listLength(c
->reply
) == 0 && 
2443         (c
->replstate 
== REDIS_REPL_NONE 
|| 
2444          c
->replstate 
== REDIS_REPL_ONLINE
) && 
2445         aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
, 
2446         sendReplyToClient
, c
) == AE_ERR
) return; 
2448     if (server
.vm_enabled 
&& obj
->storage 
!= REDIS_VM_MEMORY
) { 
2449         obj 
= dupStringObject(obj
); 
2450         obj
->refcount 
= 0; /* getDecodedObject() will increment the refcount */ 
2452     listAddNodeTail(c
->reply
,getDecodedObject(obj
)); 
2455 static void addReplySds(redisClient 
*c
, sds s
) { 
2456     robj 
*o 
= createObject(REDIS_STRING
,s
); 
2461 static void addReplyDouble(redisClient 
*c
, double d
) { 
2464     snprintf(buf
,sizeof(buf
),"%.17g",d
); 
2465     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n", 
2466         (unsigned long) strlen(buf
),buf
)); 
2469 static void addReplyLong(redisClient 
*c
, long l
) { 
2473     len 
= snprintf(buf
,sizeof(buf
),":%ld\r\n",l
); 
2474     addReplySds(c
,sdsnewlen(buf
,len
)); 
2477 static void addReplyBulkLen(redisClient 
*c
, robj 
*obj
) { 
2480     if (obj
->encoding 
== REDIS_ENCODING_RAW
) { 
2481         len 
= sdslen(obj
->ptr
); 
2483         long n 
= (long)obj
->ptr
; 
2485         /* Compute how many bytes will take this integer as a radix 10 string */ 
2491         while((n 
= n
/10) != 0) { 
2495     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
)); 
2498 static void acceptHandler(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
2503     REDIS_NOTUSED(mask
); 
2504     REDIS_NOTUSED(privdata
); 
2506     cfd 
= anetAccept(server
.neterr
, fd
, cip
, &cport
); 
2507     if (cfd 
== AE_ERR
) { 
2508         redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
); 
2511     redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
); 
2512     if ((c 
= createClient(cfd
)) == NULL
) { 
2513         redisLog(REDIS_WARNING
,"Error allocating resoures for the client"); 
2514         close(cfd
); /* May be already closed, just ingore errors */ 
2517     /* If maxclient directive is set and this is one client more... close the 
2518      * connection. Note that we create the client instead to check before 
2519      * for this condition, since now the socket is already set in nonblocking 
2520      * mode and we can send an error for free using the Kernel I/O */ 
2521     if (server
.maxclients 
&& listLength(server
.clients
) > server
.maxclients
) { 
2522         char *err 
= "-ERR max number of clients reached\r\n"; 
2524         /* That's a best effort error message, don't check write errors */ 
2525         if (write(c
->fd
,err
,strlen(err
)) == -1) { 
2526             /* Nothing to do, Just to avoid the warning... */ 
2531     server
.stat_numconnections
++; 
2534 /* ======================= Redis objects implementation ===================== */ 
2536 static robj 
*createObject(int type
, void *ptr
) { 
2539     if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
); 
2540     if (listLength(server
.objfreelist
)) { 
2541         listNode 
*head 
= listFirst(server
.objfreelist
); 
2542         o 
= listNodeValue(head
); 
2543         listDelNode(server
.objfreelist
,head
); 
2544         if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
2546         if (server
.vm_enabled
) { 
2547             pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
2548             o 
= zmalloc(sizeof(*o
)); 
2550             o 
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
)); 
2554     o
->encoding 
= REDIS_ENCODING_RAW
; 
2557     if (server
.vm_enabled
) { 
2558         /* Note that this code may run in the context of an I/O thread 
2559          * and accessing to server.unixtime in theory is an error 
2560          * (no locks). But in practice this is safe, and even if we read 
2561          * garbage Redis will not fail, as it's just a statistical info */ 
2562         o
->vm
.atime 
= server
.unixtime
; 
2563         o
->storage 
= REDIS_VM_MEMORY
; 
2568 static robj 
*createStringObject(char *ptr
, size_t len
) { 
2569     return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
)); 
2572 static robj 
*dupStringObject(robj 
*o
) { 
2573     assert(o
->encoding 
== REDIS_ENCODING_RAW
); 
2574     return createStringObject(o
->ptr
,sdslen(o
->ptr
)); 
2577 static robj 
*createListObject(void) { 
2578     list 
*l 
= listCreate(); 
2580     listSetFreeMethod(l
,decrRefCount
); 
2581     return createObject(REDIS_LIST
,l
); 
2584 static robj 
*createSetObject(void) { 
2585     dict 
*d 
= dictCreate(&setDictType
,NULL
); 
2586     return createObject(REDIS_SET
,d
); 
2589 static robj 
*createHashObject(void) { 
2590     /* All the Hashes start as zipmaps. Will be automatically converted 
2591      * into hash tables if there are enough elements or big elements 
2593     unsigned char *zm 
= zipmapNew(); 
2594     robj 
*o 
= createObject(REDIS_HASH
,zm
); 
2595     o
->encoding 
= REDIS_ENCODING_ZIPMAP
; 
2599 static robj 
*createZsetObject(void) { 
2600     zset 
*zs 
= zmalloc(sizeof(*zs
)); 
2602     zs
->dict 
= dictCreate(&zsetDictType
,NULL
); 
2603     zs
->zsl 
= zslCreate(); 
2604     return createObject(REDIS_ZSET
,zs
); 
2607 static void freeStringObject(robj 
*o
) { 
2608     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
2613 static void freeListObject(robj 
*o
) { 
2614     listRelease((list
*) o
->ptr
); 
2617 static void freeSetObject(robj 
*o
) { 
2618     dictRelease((dict
*) o
->ptr
); 
2621 static void freeZsetObject(robj 
*o
) { 
2624     dictRelease(zs
->dict
); 
2629 static void freeHashObject(robj 
*o
) { 
2630     switch (o
->encoding
) { 
2631     case REDIS_ENCODING_HT
: 
2632         dictRelease((dict
*) o
->ptr
); 
2634     case REDIS_ENCODING_ZIPMAP
: 
2643 static void incrRefCount(robj 
*o
) { 
2644     redisAssert(!server
.vm_enabled 
|| o
->storage 
== REDIS_VM_MEMORY
); 
2648 static void decrRefCount(void *obj
) { 
2651     /* Object is a key of a swapped out value, or in the process of being 
2653     if (server
.vm_enabled 
&& 
2654         (o
->storage 
== REDIS_VM_SWAPPED 
|| o
->storage 
== REDIS_VM_LOADING
)) 
2656         if (o
->storage 
== REDIS_VM_SWAPPED 
|| o
->storage 
== REDIS_VM_LOADING
) { 
2657             redisAssert(o
->refcount 
== 1); 
2659         if (o
->storage 
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
); 
2660         redisAssert(o
->type 
== REDIS_STRING
); 
2661         freeStringObject(o
); 
2662         vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
); 
2663         pthread_mutex_lock(&server
.obj_freelist_mutex
); 
2664         if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX 
|| 
2665             !listAddNodeHead(server
.objfreelist
,o
)) 
2667         pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
2668         server
.vm_stats_swapped_objects
--; 
2671     /* Object is in memory, or in the process of being swapped out. */ 
2672     if (--(o
->refcount
) == 0) { 
2673         if (server
.vm_enabled 
&& o
->storage 
== REDIS_VM_SWAPPING
) 
2674             vmCancelThreadedIOJob(obj
); 
2676         case REDIS_STRING
: freeStringObject(o
); break; 
2677         case REDIS_LIST
: freeListObject(o
); break; 
2678         case REDIS_SET
: freeSetObject(o
); break; 
2679         case REDIS_ZSET
: freeZsetObject(o
); break; 
2680         case REDIS_HASH
: freeHashObject(o
); break; 
2681         default: redisAssert(0 != 0); break; 
2683         if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
); 
2684         if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX 
|| 
2685             !listAddNodeHead(server
.objfreelist
,o
)) 
2687         if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
2691 static robj 
*lookupKey(redisDb 
*db
, robj 
*key
) { 
2692     dictEntry 
*de 
= dictFind(db
->dict
,key
); 
2694         robj 
*key 
= dictGetEntryKey(de
); 
2695         robj 
*val 
= dictGetEntryVal(de
); 
2697         if (server
.vm_enabled
) { 
2698             if (key
->storage 
== REDIS_VM_MEMORY 
|| 
2699                 key
->storage 
== REDIS_VM_SWAPPING
) 
2701                 /* If we were swapping the object out, stop it, this key 
2703                 if (key
->storage 
== REDIS_VM_SWAPPING
) 
2704                     vmCancelThreadedIOJob(key
); 
2705                 /* Update the access time of the key for the aging algorithm. */ 
2706                 key
->vm
.atime 
= server
.unixtime
; 
2708                 int notify 
= (key
->storage 
== REDIS_VM_LOADING
); 
2710                 /* Our value was swapped on disk. Bring it at home. */ 
2711                 redisAssert(val 
== NULL
); 
2712                 val 
= vmLoadObject(key
); 
2713                 dictGetEntryVal(de
) = val
; 
2715                 /* Clients blocked by the VM subsystem may be waiting for 
2717                 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
); 
2726 static robj 
*lookupKeyRead(redisDb 
*db
, robj 
*key
) { 
2727     expireIfNeeded(db
,key
); 
2728     return lookupKey(db
,key
); 
2731 static robj 
*lookupKeyWrite(redisDb 
*db
, robj 
*key
) { 
2732     deleteIfVolatile(db
,key
); 
2733     return lookupKey(db
,key
); 
2736 static int deleteKey(redisDb 
*db
, robj 
*key
) { 
2739     /* We need to protect key from destruction: after the first dictDelete() 
2740      * it may happen that 'key' is no longer valid if we don't increment 
2741      * it's count. This may happen when we get the object reference directly 
2742      * from the hash table with dictRandomKey() or dict iterators */ 
2744     if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
); 
2745     retval 
= dictDelete(db
->dict
,key
); 
2748     return retval 
== DICT_OK
; 
2751 /* Try to share an object against the shared objects pool */ 
2752 static robj 
*tryObjectSharing(robj 
*o
) { 
2753     struct dictEntry 
*de
; 
2756     if (o 
== NULL 
|| server
.shareobjects 
== 0) return o
; 
2758     redisAssert(o
->type 
== REDIS_STRING
); 
2759     de 
= dictFind(server
.sharingpool
,o
); 
2761         robj 
*shared 
= dictGetEntryKey(de
); 
2763         c 
= ((unsigned long) dictGetEntryVal(de
))+1; 
2764         dictGetEntryVal(de
) = (void*) c
; 
2765         incrRefCount(shared
); 
2769         /* Here we are using a stream algorihtm: Every time an object is 
2770          * shared we increment its count, everytime there is a miss we 
2771          * recrement the counter of a random object. If this object reaches 
2772          * zero we remove the object and put the current object instead. */ 
2773         if (dictSize(server
.sharingpool
) >= 
2774                 server
.sharingpoolsize
) { 
2775             de 
= dictGetRandomKey(server
.sharingpool
); 
2776             redisAssert(de 
!= NULL
); 
2777             c 
= ((unsigned long) dictGetEntryVal(de
))-1; 
2778             dictGetEntryVal(de
) = (void*) c
; 
2780                 dictDelete(server
.sharingpool
,de
->key
); 
2783             c 
= 0; /* If the pool is empty we want to add this object */ 
2788             retval 
= dictAdd(server
.sharingpool
,o
,(void*)1); 
2789             redisAssert(retval 
== DICT_OK
); 
2796 /* Check if the nul-terminated string 's' can be represented by a long 
2797  * (that is, is a number that fits into long without any other space or 
2798  * character before or after the digits). 
2800  * If so, the function returns REDIS_OK and *longval is set to the value 
2801  * of the number. Otherwise REDIS_ERR is returned */ 
2802 static int isStringRepresentableAsLong(sds s
, long *longval
) { 
2803     char buf
[32], *endptr
; 
2807     value 
= strtol(s
, &endptr
, 10); 
2808     if (endptr
[0] != '\0') return REDIS_ERR
; 
2809     slen 
= snprintf(buf
,32,"%ld",value
); 
2811     /* If the number converted back into a string is not identical 
2812      * then it's not possible to encode the string as integer */ 
2813     if (sdslen(s
) != (unsigned)slen 
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
; 
2814     if (longval
) *longval 
= value
; 
2818 /* Try to encode a string object in order to save space */ 
2819 static int tryObjectEncoding(robj 
*o
) { 
2823     if (o
->encoding 
!= REDIS_ENCODING_RAW
) 
2824         return REDIS_ERR
; /* Already encoded */ 
2826     /* It's not save to encode shared objects: shared objects can be shared 
2827      * everywhere in the "object space" of Redis. Encoded objects can only 
2828      * appear as "values" (and not, for instance, as keys) */ 
2829      if (o
->refcount 
> 1) return REDIS_ERR
; 
2831     /* Currently we try to encode only strings */ 
2832     redisAssert(o
->type 
== REDIS_STRING
); 
2834     /* Check if we can represent this string as a long integer */ 
2835     if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
; 
2837     /* Ok, this object can be encoded */ 
2838     o
->encoding 
= REDIS_ENCODING_INT
; 
2840     o
->ptr 
= (void*) value
; 
2844 /* Get a decoded version of an encoded object (returned as a new object). 
2845  * If the object is already raw-encoded just increment the ref count. */ 
2846 static robj 
*getDecodedObject(robj 
*o
) { 
2849     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
2853     if (o
->type 
== REDIS_STRING 
&& o
->encoding 
== REDIS_ENCODING_INT
) { 
2856         snprintf(buf
,32,"%ld",(long)o
->ptr
); 
2857         dec 
= createStringObject(buf
,strlen(buf
)); 
2860         redisAssert(1 != 1); 
2864 /* Compare two string objects via strcmp() or alike. 
2865  * Note that the objects may be integer-encoded. In such a case we 
2866  * use snprintf() to get a string representation of the numbers on the stack 
2867  * and compare the strings, it's much faster than calling getDecodedObject(). 
2869  * Important note: if objects are not integer encoded, but binary-safe strings, 
2870  * sdscmp() from sds.c will apply memcmp() so this function ca be considered 
2872 static int compareStringObjects(robj 
*a
, robj 
*b
) { 
2873     redisAssert(a
->type 
== REDIS_STRING 
&& b
->type 
== REDIS_STRING
); 
2874     char bufa
[128], bufb
[128], *astr
, *bstr
; 
2877     if (a 
== b
) return 0; 
2878     if (a
->encoding 
!= REDIS_ENCODING_RAW
) { 
2879         snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
); 
2885     if (b
->encoding 
!= REDIS_ENCODING_RAW
) { 
2886         snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
); 
2892     return bothsds 
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
); 
2895 static size_t stringObjectLen(robj 
*o
) { 
2896     redisAssert(o
->type 
== REDIS_STRING
); 
2897     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
2898         return sdslen(o
->ptr
); 
2902         return snprintf(buf
,32,"%ld",(long)o
->ptr
); 
2906 /*============================ RDB saving/loading =========================== */ 
2908 static int rdbSaveType(FILE *fp
, unsigned char type
) { 
2909     if (fwrite(&type
,1,1,fp
) == 0) return -1; 
2913 static int rdbSaveTime(FILE *fp
, time_t t
) { 
2914     int32_t t32 
= (int32_t) t
; 
2915     if (fwrite(&t32
,4,1,fp
) == 0) return -1; 
2919 /* check rdbLoadLen() comments for more info */ 
2920 static int rdbSaveLen(FILE *fp
, uint32_t len
) { 
2921     unsigned char buf
[2]; 
2924         /* Save a 6 bit len */ 
2925         buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6); 
2926         if (fwrite(buf
,1,1,fp
) == 0) return -1; 
2927     } else if (len 
< (1<<14)) { 
2928         /* Save a 14 bit len */ 
2929         buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6); 
2931         if (fwrite(buf
,2,1,fp
) == 0) return -1; 
2933         /* Save a 32 bit len */ 
2934         buf
[0] = (REDIS_RDB_32BITLEN
<<6); 
2935         if (fwrite(buf
,1,1,fp
) == 0) return -1; 
2937         if (fwrite(&len
,4,1,fp
) == 0) return -1; 
2942 /* String objects in the form "2391" "-100" without any space and with a 
2943  * range of values that can fit in an 8, 16 or 32 bit signed value can be 
2944  * encoded as integers to save space */ 
2945 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) { 
2947     char *endptr
, buf
[32]; 
2949     /* Check if it's possible to encode this value as a number */ 
2950     value 
= strtoll(s
, &endptr
, 10); 
2951     if (endptr
[0] != '\0') return 0; 
2952     snprintf(buf
,32,"%lld",value
); 
2954     /* If the number converted back into a string is not identical 
2955      * then it's not possible to encode the string as integer */ 
2956     if (strlen(buf
) != len 
|| memcmp(buf
,s
,len
)) return 0; 
2958     /* Finally check if it fits in our ranges */ 
2959     if (value 
>= -(1<<7) && value 
<= (1<<7)-1) { 
2960         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
; 
2961         enc
[1] = value
&0xFF; 
2963     } else if (value 
>= -(1<<15) && value 
<= (1<<15)-1) { 
2964         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
; 
2965         enc
[1] = value
&0xFF; 
2966         enc
[2] = (value
>>8)&0xFF; 
2968     } else if (value 
>= -((long long)1<<31) && value 
<= ((long long)1<<31)-1) { 
2969         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
; 
2970         enc
[1] = value
&0xFF; 
2971         enc
[2] = (value
>>8)&0xFF; 
2972         enc
[3] = (value
>>16)&0xFF; 
2973         enc
[4] = (value
>>24)&0xFF; 
2980 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) { 
2981     size_t comprlen
, outlen
; 
2985     /* We require at least four bytes compression for this to be worth it */ 
2986     if (len 
<= 4) return 0; 
2988     if ((out 
= zmalloc(outlen
+1)) == NULL
) return 0; 
2989     comprlen 
= lzf_compress(s
, len
, out
, outlen
); 
2990     if (comprlen 
== 0) { 
2994     /* Data compressed! Let's save it on disk */ 
2995     byte 
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
; 
2996     if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
; 
2997     if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
; 
2998     if (rdbSaveLen(fp
,len
) == -1) goto writeerr
; 
2999     if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
; 
3008 /* Save a string objet as [len][data] on disk. If the object is a string 
3009  * representation of an integer value we try to safe it in a special form */ 
3010 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) { 
3013     /* Try integer encoding */ 
3015         unsigned char buf
[5]; 
3016         if ((enclen 
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) { 
3017             if (fwrite(buf
,enclen
,1,fp
) == 0) return -1; 
3022     /* Try LZF compression - under 20 bytes it's unable to compress even 
3023      * aaaaaaaaaaaaaaaaaa so skip it */ 
3024     if (server
.rdbcompression 
&& len 
> 20) { 
3027         retval 
= rdbSaveLzfStringObject(fp
,s
,len
); 
3028         if (retval 
== -1) return -1; 
3029         if (retval 
> 0) return 0; 
3030         /* retval == 0 means data can't be compressed, save the old way */ 
3033     /* Store verbatim */ 
3034     if (rdbSaveLen(fp
,len
) == -1) return -1; 
3035     if (len 
&& fwrite(s
,len
,1,fp
) == 0) return -1; 
3039 /* Like rdbSaveStringObjectRaw() but handle encoded objects */ 
3040 static int rdbSaveStringObject(FILE *fp
, robj 
*obj
) { 
3043     /* Avoid incr/decr ref count business when possible. 
3044      * This plays well with copy-on-write given that we are probably 
3045      * in a child process (BGSAVE). Also this makes sure key objects 
3046      * of swapped objects are not incRefCount-ed (an assert does not allow 
3047      * this in order to avoid bugs) */ 
3048     if (obj
->encoding 
!= REDIS_ENCODING_RAW
) { 
3049         obj 
= getDecodedObject(obj
); 
3050         retval 
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
)); 
3053         retval 
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
)); 
3058 /* Save a double value. Doubles are saved as strings prefixed by an unsigned 
3059  * 8 bit integer specifing the length of the representation. 
3060  * This 8 bit integer has special values in order to specify the following 
3066 static int rdbSaveDoubleValue(FILE *fp
, double val
) { 
3067     unsigned char buf
[128]; 
3073     } else if (!isfinite(val
)) { 
3075         buf
[0] = (val 
< 0) ? 255 : 254; 
3077         snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
); 
3078         buf
[0] = strlen((char*)buf
+1); 
3081     if (fwrite(buf
,len
,1,fp
) == 0) return -1; 
3085 /* Save a Redis object. */ 
3086 static int rdbSaveObject(FILE *fp
, robj 
*o
) { 
3087     if (o
->type 
== REDIS_STRING
) { 
3088         /* Save a string value */ 
3089         if (rdbSaveStringObject(fp
,o
) == -1) return -1; 
3090     } else if (o
->type 
== REDIS_LIST
) { 
3091         /* Save a list value */ 
3092         list 
*list 
= o
->ptr
; 
3096         if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1; 
3097         listRewind(list
,&li
); 
3098         while((ln 
= listNext(&li
))) { 
3099             robj 
*eleobj 
= listNodeValue(ln
); 
3101             if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1; 
3103     } else if (o
->type 
== REDIS_SET
) { 
3104         /* Save a set value */ 
3106         dictIterator 
*di 
= dictGetIterator(set
); 
3109         if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1; 
3110         while((de 
= dictNext(di
)) != NULL
) { 
3111             robj 
*eleobj 
= dictGetEntryKey(de
); 
3113             if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1; 
3115         dictReleaseIterator(di
); 
3116     } else if (o
->type 
== REDIS_ZSET
) { 
3117         /* Save a set value */ 
3119         dictIterator 
*di 
= dictGetIterator(zs
->dict
); 
3122         if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1; 
3123         while((de 
= dictNext(di
)) != NULL
) { 
3124             robj 
*eleobj 
= dictGetEntryKey(de
); 
3125             double *score 
= dictGetEntryVal(de
); 
3127             if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1; 
3128             if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1; 
3130         dictReleaseIterator(di
); 
3131     } else if (o
->type 
== REDIS_HASH
) { 
3132         /* Save a hash value */ 
3133         if (o
->encoding 
== REDIS_ENCODING_ZIPMAP
) { 
3134             unsigned char *p 
= zipmapRewind(o
->ptr
); 
3135             unsigned int count 
= zipmapLen(o
->ptr
); 
3136             unsigned char *key
, *val
; 
3137             unsigned int klen
, vlen
; 
3139             if (rdbSaveLen(fp
,count
) == -1) return -1; 
3140             while((p 
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) { 
3141                 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1; 
3142                 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1; 
3145             dictIterator 
*di 
= dictGetIterator(o
->ptr
); 
3148             if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1; 
3149             while((de 
= dictNext(di
)) != NULL
) { 
3150                 robj 
*key 
= dictGetEntryKey(de
); 
3151                 robj 
*val 
= dictGetEntryVal(de
); 
3153                 if (rdbSaveStringObject(fp
,key
) == -1) return -1; 
3154                 if (rdbSaveStringObject(fp
,val
) == -1) return -1; 
3156             dictReleaseIterator(di
); 
3159         redisAssert(0 != 0); 
3164 /* Return the length the object will have on disk if saved with 
3165  * the rdbSaveObject() function. Currently we use a trick to get 
3166  * this length with very little changes to the code. In the future 
3167  * we could switch to a faster solution. */ 
3168 static off_t 
rdbSavedObjectLen(robj 
*o
, FILE *fp
) { 
3169     if (fp 
== NULL
) fp 
= server
.devnull
; 
3171     assert(rdbSaveObject(fp
,o
) != 1); 
3175 /* Return the number of pages required to save this object in the swap file */ 
3176 static off_t 
rdbSavedObjectPages(robj 
*o
, FILE *fp
) { 
3177     off_t bytes 
= rdbSavedObjectLen(o
,fp
); 
3179     return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
; 
3182 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */ 
3183 static int rdbSave(char *filename
) { 
3184     dictIterator 
*di 
= NULL
; 
3189     time_t now 
= time(NULL
); 
3191     /* Wait for I/O therads to terminate, just in case this is a 
3192      * foreground-saving, to avoid seeking the swap file descriptor at the 
3194     if (server
.vm_enabled
) 
3195         waitEmptyIOJobsQueue(); 
3197     snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid()); 
3198     fp 
= fopen(tmpfile
,"w"); 
3200         redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
)); 
3203     if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
; 
3204     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
3205         redisDb 
*db 
= server
.db
+j
; 
3207         if (dictSize(d
) == 0) continue; 
3208         di 
= dictGetIterator(d
); 
3214         /* Write the SELECT DB opcode */ 
3215         if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
; 
3216         if (rdbSaveLen(fp
,j
) == -1) goto werr
; 
3218         /* Iterate this DB writing every entry */ 
3219         while((de 
= dictNext(di
)) != NULL
) { 
3220             robj 
*key 
= dictGetEntryKey(de
); 
3221             robj 
*o 
= dictGetEntryVal(de
); 
3222             time_t expiretime 
= getExpire(db
,key
); 
3224             /* Save the expire time */ 
3225             if (expiretime 
!= -1) { 
3226                 /* If this key is already expired skip it */ 
3227                 if (expiretime 
< now
) continue; 
3228                 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
; 
3229                 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
; 
3231             /* Save the key and associated value. This requires special 
3232              * handling if the value is swapped out. */ 
3233             if (!server
.vm_enabled 
|| key
->storage 
== REDIS_VM_MEMORY 
|| 
3234                                       key
->storage 
== REDIS_VM_SWAPPING
) { 
3235                 /* Save type, key, value */ 
3236                 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
; 
3237                 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
; 
3238                 if (rdbSaveObject(fp
,o
) == -1) goto werr
; 
3240                 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */ 
3242                 /* Get a preview of the object in memory */ 
3243                 po 
= vmPreviewObject(key
); 
3244                 /* Save type, key, value */ 
3245                 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
; 
3246                 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
; 
3247                 if (rdbSaveObject(fp
,po
) == -1) goto werr
; 
3248                 /* Remove the loaded object from memory */ 
3252         dictReleaseIterator(di
); 
3255     if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
; 
3257     /* Make sure data will not remain on the OS's output buffers */ 
3262     /* Use RENAME to make sure the DB file is changed atomically only 
3263      * if the generate DB file is ok. */ 
3264     if (rename(tmpfile
,filename
) == -1) { 
3265         redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
)); 
3269     redisLog(REDIS_NOTICE
,"DB saved on disk"); 
3271     server
.lastsave 
= time(NULL
); 
3277     redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
)); 
3278     if (di
) dictReleaseIterator(di
); 
3282 static int rdbSaveBackground(char *filename
) { 
3285     if (server
.bgsavechildpid 
!= -1) return REDIS_ERR
; 
3286     if (server
.vm_enabled
) waitEmptyIOJobsQueue(); 
3287     if ((childpid 
= fork()) == 0) { 
3289         if (server
.vm_enabled
) vmReopenSwapFile(); 
3291         if (rdbSave(filename
) == REDIS_OK
) { 
3298         if (childpid 
== -1) { 
3299             redisLog(REDIS_WARNING
,"Can't save in background: fork: %s", 
3303         redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
); 
3304         server
.bgsavechildpid 
= childpid
; 
3307     return REDIS_OK
; /* unreached */ 
3310 static void rdbRemoveTempFile(pid_t childpid
) { 
3313     snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
); 
3317 static int rdbLoadType(FILE *fp
) { 
3319     if (fread(&type
,1,1,fp
) == 0) return -1; 
3323 static time_t rdbLoadTime(FILE *fp
) { 
3325     if (fread(&t32
,4,1,fp
) == 0) return -1; 
3326     return (time_t) t32
; 
3329 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top 
3330  * of this file for a description of how this are stored on disk. 
3332  * isencoded is set to 1 if the readed length is not actually a length but 
3333  * an "encoding type", check the above comments for more info */ 
3334 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) { 
3335     unsigned char buf
[2]; 
3339     if (isencoded
) *isencoded 
= 0; 
3340     if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
; 
3341     type 
= (buf
[0]&0xC0)>>6; 
3342     if (type 
== REDIS_RDB_6BITLEN
) { 
3343         /* Read a 6 bit len */ 
3345     } else if (type 
== REDIS_RDB_ENCVAL
) { 
3346         /* Read a 6 bit len encoding type */ 
3347         if (isencoded
) *isencoded 
= 1; 
3349     } else if (type 
== REDIS_RDB_14BITLEN
) { 
3350         /* Read a 14 bit len */ 
3351         if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
; 
3352         return ((buf
[0]&0x3F)<<8)|buf
[1]; 
3354         /* Read a 32 bit len */ 
3355         if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
; 
3360 static robj 
*rdbLoadIntegerObject(FILE *fp
, int enctype
) { 
3361     unsigned char enc
[4]; 
3364     if (enctype 
== REDIS_RDB_ENC_INT8
) { 
3365         if (fread(enc
,1,1,fp
) == 0) return NULL
; 
3366         val 
= (signed char)enc
[0]; 
3367     } else if (enctype 
== REDIS_RDB_ENC_INT16
) { 
3369         if (fread(enc
,2,1,fp
) == 0) return NULL
; 
3370         v 
= enc
[0]|(enc
[1]<<8); 
3372     } else if (enctype 
== REDIS_RDB_ENC_INT32
) { 
3374         if (fread(enc
,4,1,fp
) == 0) return NULL
; 
3375         v 
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24); 
3378         val 
= 0; /* anti-warning */ 
3381     return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
)); 
3384 static robj 
*rdbLoadLzfStringObject(FILE*fp
) { 
3385     unsigned int len
, clen
; 
3386     unsigned char *c 
= NULL
; 
3389     if ((clen 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
3390     if ((len 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
3391     if ((c 
= zmalloc(clen
)) == NULL
) goto err
; 
3392     if ((val 
= sdsnewlen(NULL
,len
)) == NULL
) goto err
; 
3393     if (fread(c
,clen
,1,fp
) == 0) goto err
; 
3394     if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
; 
3396     return createObject(REDIS_STRING
,val
); 
3403 static robj 
*rdbLoadStringObject(FILE*fp
) { 
3408     len 
= rdbLoadLen(fp
,&isencoded
); 
3411         case REDIS_RDB_ENC_INT8
: 
3412         case REDIS_RDB_ENC_INT16
: 
3413         case REDIS_RDB_ENC_INT32
: 
3414             return tryObjectSharing(rdbLoadIntegerObject(fp
,len
)); 
3415         case REDIS_RDB_ENC_LZF
: 
3416             return tryObjectSharing(rdbLoadLzfStringObject(fp
)); 
3422     if (len 
== REDIS_RDB_LENERR
) return NULL
; 
3423     val 
= sdsnewlen(NULL
,len
); 
3424     if (len 
&& fread(val
,len
,1,fp
) == 0) { 
3428     return tryObjectSharing(createObject(REDIS_STRING
,val
)); 
3431 /* For information about double serialization check rdbSaveDoubleValue() */ 
3432 static int rdbLoadDoubleValue(FILE *fp
, double *val
) { 
3436     if (fread(&len
,1,1,fp
) == 0) return -1; 
3438     case 255: *val 
= R_NegInf
; return 0; 
3439     case 254: *val 
= R_PosInf
; return 0; 
3440     case 253: *val 
= R_Nan
; return 0; 
3442         if (fread(buf
,len
,1,fp
) == 0) return -1; 
3444         sscanf(buf
, "%lg", val
); 
3449 /* Load a Redis object of the specified type from the specified file. 
3450  * On success a newly allocated object is returned, otherwise NULL. */ 
3451 static robj 
*rdbLoadObject(int type
, FILE *fp
) { 
3454     redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
)); 
3455     if (type 
== REDIS_STRING
) { 
3456         /* Read string value */ 
3457         if ((o 
= rdbLoadStringObject(fp
)) == NULL
) return NULL
; 
3458         tryObjectEncoding(o
); 
3459     } else if (type 
== REDIS_LIST 
|| type 
== REDIS_SET
) { 
3460         /* Read list/set value */ 
3463         if ((listlen 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
3464         o 
= (type 
== REDIS_LIST
) ? createListObject() : createSetObject(); 
3465         /* It's faster to expand the dict to the right size asap in order 
3466          * to avoid rehashing */ 
3467         if (type 
== REDIS_SET 
&& listlen 
> DICT_HT_INITIAL_SIZE
) 
3468             dictExpand(o
->ptr
,listlen
); 
3469         /* Load every single element of the list/set */ 
3473             if ((ele 
= rdbLoadStringObject(fp
)) == NULL
) return NULL
; 
3474             tryObjectEncoding(ele
); 
3475             if (type 
== REDIS_LIST
) { 
3476                 listAddNodeTail((list
*)o
->ptr
,ele
); 
3478                 dictAdd((dict
*)o
->ptr
,ele
,NULL
); 
3481     } else if (type 
== REDIS_ZSET
) { 
3482         /* Read list/set value */ 
3486         if ((zsetlen 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
3487         o 
= createZsetObject(); 
3489         /* Load every single element of the list/set */ 
3490         redisLog(REDIS_DEBUG
,"SORTED SET LEN: %zu\n", zsetlen
); 
3493             double *score 
= zmalloc(sizeof(double)); 
3495             if ((ele 
= rdbLoadStringObject(fp
)) == NULL
) return NULL
; 
3496             redisLog(REDIS_DEBUG
,"ele %s (%d) (%d)\n", (char*)ele
->ptr
, ftell(fp
), zsetlen
); 
3497             tryObjectEncoding(ele
); 
3498             if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
; 
3499             redisLog(REDIS_DEBUG
,"score %.17g\n", *score
); 
3500             dictAdd(zs
->dict
,ele
,score
); 
3501             zslInsert(zs
->zsl
,*score
,ele
); 
3502             incrRefCount(ele
); /* added to skiplist */ 
3504     } else if (type 
== REDIS_HASH
) { 
3507         if ((hashlen 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
3508         o 
= createHashObject(); 
3509         /* Too many entries? Use an hash table. */ 
3510         if (hashlen 
> server
.hash_max_zipmap_entries
) 
3511             convertToRealHash(o
); 
3512         /* Load every key/value, then set it into the zipmap or hash 
3513          * table, as needed. */ 
3517             if ((key 
= rdbLoadStringObject(fp
)) == NULL
) return NULL
; 
3518             if ((val 
= rdbLoadStringObject(fp
)) == NULL
) return NULL
; 
3519             /* If we are using a zipmap and there are too big values 
3520              * the object is converted to real hash table encoding. */ 
3521             if (o
->encoding 
!= REDIS_ENCODING_HT 
&& 
3522                (sdslen(key
->ptr
) > server
.hash_max_zipmap_value 
|| 
3523                 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)) 
3525                     convertToRealHash(o
); 
3528             if (o
->encoding 
== REDIS_ENCODING_ZIPMAP
) { 
3529                 unsigned char *zm 
= o
->ptr
; 
3531                 zm 
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
), 
3532                                   val
->ptr
,sdslen(val
->ptr
),NULL
); 
3537                 tryObjectEncoding(key
); 
3538                 tryObjectEncoding(val
); 
3539                 dictAdd((dict
*)o
->ptr
,key
,val
); 
3545         redisAssert(0 != 0); 
3547     redisLog(REDIS_DEBUG
,"DONE\n"); 
3551 static int rdbLoad(char *filename
) { 
3553     robj 
*keyobj 
= NULL
; 
3555     int type
, retval
, rdbver
; 
3556     dict 
*d 
= server
.db
[0].dict
; 
3557     redisDb 
*db 
= server
.db
+0; 
3559     time_t expiretime 
= -1, now 
= time(NULL
); 
3560     long long loadedkeys 
= 0; 
3562     fp 
= fopen(filename
,"r"); 
3563     if (!fp
) return REDIS_ERR
; 
3564     if (fread(buf
,9,1,fp
) == 0) goto eoferr
; 
3566     if (memcmp(buf
,"REDIS",5) != 0) { 
3568         redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file"); 
3571     rdbver 
= atoi(buf
+5); 
3574         redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
); 
3581         if ((type 
= rdbLoadType(fp
)) == -1) goto eoferr
; 
3582         if (type 
== REDIS_EXPIRETIME
) { 
3583             if ((expiretime 
= rdbLoadTime(fp
)) == -1) goto eoferr
; 
3584             /* We read the time so we need to read the object type again */ 
3585             if ((type 
= rdbLoadType(fp
)) == -1) goto eoferr
; 
3587         if (type 
== REDIS_EOF
) break; 
3588         /* Handle SELECT DB opcode as a special case */ 
3589         if (type 
== REDIS_SELECTDB
) { 
3590             if ((dbid 
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) 
3592             if (dbid 
>= (unsigned)server
.dbnum
) { 
3593                 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
); 
3596             db 
= server
.db
+dbid
; 
3601         if ((keyobj 
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
; 
3602         redisLog(REDIS_DEBUG
,"KEY: %s\n", (char*)keyobj
->ptr
); 
3604         if ((o 
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
; 
3605         /* Add the new object in the hash table */ 
3606         retval 
= dictAdd(d
,keyobj
,o
); 
3607         if (retval 
== DICT_ERR
) { 
3608             redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
); 
3611         /* Set the expire time if needed */ 
3612         if (expiretime 
!= -1) { 
3613             setExpire(db
,keyobj
,expiretime
); 
3614             /* Delete this key if already expired */ 
3615             if (expiretime 
< now
) deleteKey(db
,keyobj
); 
3619         /* Handle swapping while loading big datasets when VM is on */ 
3621         if (server
.vm_enabled 
&& (loadedkeys 
% 5000) == 0) { 
3622             while (zmalloc_used_memory() > server
.vm_max_memory
) { 
3623                 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break; 
3630 eoferr
: /* unexpected end of file is handled here with a fatal exit */ 
3631     if (keyobj
) decrRefCount(keyobj
); 
3632     redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now."); 
3634     return REDIS_ERR
; /* Just to avoid warning */ 
3637 /*================================== Commands =============================== */ 
3639 static void authCommand(redisClient 
*c
) { 
3640     if (!server
.requirepass 
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) { 
3641       c
->authenticated 
= 1; 
3642       addReply(c
,shared
.ok
); 
3644       c
->authenticated 
= 0; 
3645       addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n")); 
3649 static void pingCommand(redisClient 
*c
) { 
3650     addReply(c
,shared
.pong
); 
3653 static void echoCommand(redisClient 
*c
) { 
3654     addReplyBulkLen(c
,c
->argv
[1]); 
3655     addReply(c
,c
->argv
[1]); 
3656     addReply(c
,shared
.crlf
); 
3659 /*=================================== Strings =============================== */ 
3661 static void setGenericCommand(redisClient 
*c
, int nx
) { 
3664     if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]); 
3665     retval 
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
3666     if (retval 
== DICT_ERR
) { 
3668             /* If the key is about a swapped value, we want a new key object 
3669              * to overwrite the old. So we delete the old key in the database. 
3670              * This will also make sure that swap pages about the old object 
3671              * will be marked as free. */ 
3672             if (server
.vm_enabled 
&& deleteIfSwapped(c
->db
,c
->argv
[1])) 
3673                 incrRefCount(c
->argv
[1]); 
3674             dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
3675             incrRefCount(c
->argv
[2]); 
3677             addReply(c
,shared
.czero
); 
3681         incrRefCount(c
->argv
[1]); 
3682         incrRefCount(c
->argv
[2]); 
3685     removeExpire(c
->db
,c
->argv
[1]); 
3686     addReply(c
, nx 
? shared
.cone 
: shared
.ok
); 
3689 static void setCommand(redisClient 
*c
) { 
3690     setGenericCommand(c
,0); 
3693 static void setnxCommand(redisClient 
*c
) { 
3694     setGenericCommand(c
,1); 
3697 static int getGenericCommand(redisClient 
*c
) { 
3698     robj 
*o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
3701         addReply(c
,shared
.nullbulk
); 
3704         if (o
->type 
!= REDIS_STRING
) { 
3705             addReply(c
,shared
.wrongtypeerr
); 
3708             addReplyBulkLen(c
,o
); 
3710             addReply(c
,shared
.crlf
); 
3716 static void getCommand(redisClient 
*c
) { 
3717     getGenericCommand(c
); 
3720 static void getsetCommand(redisClient 
*c
) { 
3721     if (getGenericCommand(c
) == REDIS_ERR
) return; 
3722     if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) { 
3723         dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
3725         incrRefCount(c
->argv
[1]); 
3727     incrRefCount(c
->argv
[2]); 
3729     removeExpire(c
->db
,c
->argv
[1]); 
3732 static void mgetCommand(redisClient 
*c
) { 
3735     addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1)); 
3736     for (j 
= 1; j 
< c
->argc
; j
++) { 
3737         robj 
*o 
= lookupKeyRead(c
->db
,c
->argv
[j
]); 
3739             addReply(c
,shared
.nullbulk
); 
3741             if (o
->type 
!= REDIS_STRING
) { 
3742                 addReply(c
,shared
.nullbulk
); 
3744                 addReplyBulkLen(c
,o
); 
3746                 addReply(c
,shared
.crlf
); 
3752 static void msetGenericCommand(redisClient 
*c
, int nx
) { 
3753     int j
, busykeys 
= 0; 
3755     if ((c
->argc 
% 2) == 0) { 
3756         addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n")); 
3759     /* Handle the NX flag. The MSETNX semantic is to return zero and don't 
3760      * set nothing at all if at least one already key exists. */ 
3762         for (j 
= 1; j 
< c
->argc
; j 
+= 2) { 
3763             if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) { 
3769         addReply(c
, shared
.czero
); 
3773     for (j 
= 1; j 
< c
->argc
; j 
+= 2) { 
3776         tryObjectEncoding(c
->argv
[j
+1]); 
3777         retval 
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]); 
3778         if (retval 
== DICT_ERR
) { 
3779             dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]); 
3780             incrRefCount(c
->argv
[j
+1]); 
3782             incrRefCount(c
->argv
[j
]); 
3783             incrRefCount(c
->argv
[j
+1]); 
3785         removeExpire(c
->db
,c
->argv
[j
]); 
3787     server
.dirty 
+= (c
->argc
-1)/2; 
3788     addReply(c
, nx 
? shared
.cone 
: shared
.ok
); 
3791 static void msetCommand(redisClient 
*c
) { 
3792     msetGenericCommand(c
,0); 
3795 static void msetnxCommand(redisClient 
*c
) { 
3796     msetGenericCommand(c
,1); 
3799 static void incrDecrCommand(redisClient 
*c
, long long incr
) { 
3804     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
3808         if (o
->type 
!= REDIS_STRING
) { 
3813             if (o
->encoding 
== REDIS_ENCODING_RAW
) 
3814                 value 
= strtoll(o
->ptr
, &eptr
, 10); 
3815             else if (o
->encoding 
== REDIS_ENCODING_INT
) 
3816                 value 
= (long)o
->ptr
; 
3818                 redisAssert(1 != 1); 
3823     o 
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
)); 
3824     tryObjectEncoding(o
); 
3825     retval 
= dictAdd(c
->db
->dict
,c
->argv
[1],o
); 
3826     if (retval 
== DICT_ERR
) { 
3827         dictReplace(c
->db
->dict
,c
->argv
[1],o
); 
3828         removeExpire(c
->db
,c
->argv
[1]); 
3830         incrRefCount(c
->argv
[1]); 
3833     addReply(c
,shared
.colon
); 
3835     addReply(c
,shared
.crlf
); 
3838 static void incrCommand(redisClient 
*c
) { 
3839     incrDecrCommand(c
,1); 
3842 static void decrCommand(redisClient 
*c
) { 
3843     incrDecrCommand(c
,-1); 
3846 static void incrbyCommand(redisClient 
*c
) { 
3847     long long incr 
= strtoll(c
->argv
[2]->ptr
, NULL
, 10); 
3848     incrDecrCommand(c
,incr
); 
3851 static void decrbyCommand(redisClient 
*c
) { 
3852     long long incr 
= strtoll(c
->argv
[2]->ptr
, NULL
, 10); 
3853     incrDecrCommand(c
,-incr
); 
3856 static void appendCommand(redisClient 
*c
) { 
3861     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
3863         /* Create the key */ 
3864         retval 
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
3865         incrRefCount(c
->argv
[1]); 
3866         incrRefCount(c
->argv
[2]); 
3867         totlen 
= stringObjectLen(c
->argv
[2]); 
3871         de 
= dictFind(c
->db
->dict
,c
->argv
[1]); 
3874         o 
= dictGetEntryVal(de
); 
3875         if (o
->type 
!= REDIS_STRING
) { 
3876             addReply(c
,shared
.wrongtypeerr
); 
3879         /* If the object is specially encoded or shared we have to make 
3881         if (o
->refcount 
!= 1 || o
->encoding 
!= REDIS_ENCODING_RAW
) { 
3882             robj 
*decoded 
= getDecodedObject(o
); 
3884             o 
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
)); 
3885             decrRefCount(decoded
); 
3886             dictReplace(c
->db
->dict
,c
->argv
[1],o
); 
3889         if (c
->argv
[2]->encoding 
== REDIS_ENCODING_RAW
) { 
3890             o
->ptr 
= sdscatlen(o
->ptr
, 
3891                 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
)); 
3893             o
->ptr 
= sdscatprintf(o
->ptr
, "%ld", 
3894                 (unsigned long) c
->argv
[2]->ptr
); 
3896         totlen 
= sdslen(o
->ptr
); 
3899     addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
)); 
3902 static void substrCommand(redisClient 
*c
) { 
3904     long start 
= atoi(c
->argv
[2]->ptr
); 
3905     long end 
= atoi(c
->argv
[3]->ptr
); 
3907     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
3909         addReply(c
,shared
.nullbulk
); 
3911         if (o
->type 
!= REDIS_STRING
) { 
3912             addReply(c
,shared
.wrongtypeerr
); 
3914             size_t rangelen
, strlen
; 
3917             o 
= getDecodedObject(o
); 
3918             strlen 
= sdslen(o
->ptr
); 
3920             /* convert negative indexes */ 
3921             if (start 
< 0) start 
= strlen
+start
; 
3922             if (end 
< 0) end 
= strlen
+end
; 
3923             if (start 
< 0) start 
= 0; 
3924             if (end 
< 0) end 
= 0; 
3926             /* indexes sanity checks */ 
3927             if (start 
> end 
|| (size_t)start 
>= strlen
) { 
3928                 /* Out of range start or start > end result in null reply */ 
3929                 addReply(c
,shared
.nullbulk
); 
3933             if ((size_t)end 
>= strlen
) end 
= strlen
-1; 
3934             rangelen 
= (end
-start
)+1; 
3936             /* Return the result */ 
3937             addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",rangelen
)); 
3938             range 
= sdsnewlen((char*)o
->ptr
+start
,rangelen
); 
3939             addReplySds(c
,range
); 
3940             addReply(c
,shared
.crlf
); 
3946 /* ========================= Type agnostic commands ========================= */ 
3948 static void delCommand(redisClient 
*c
) { 
3951     for (j 
= 1; j 
< c
->argc
; j
++) { 
3952         if (deleteKey(c
->db
,c
->argv
[j
])) { 
3959         addReply(c
,shared
.czero
); 
3962         addReply(c
,shared
.cone
); 
3965         addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
)); 
3970 static void existsCommand(redisClient 
*c
) { 
3971     addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone 
: shared
.czero
); 
3974 static void selectCommand(redisClient 
*c
) { 
3975     int id 
= atoi(c
->argv
[1]->ptr
); 
3977     if (selectDb(c
,id
) == REDIS_ERR
) { 
3978         addReplySds(c
,sdsnew("-ERR invalid DB index\r\n")); 
3980         addReply(c
,shared
.ok
); 
3984 static void randomkeyCommand(redisClient 
*c
) { 
3988         de 
= dictGetRandomKey(c
->db
->dict
); 
3989         if (!de 
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break; 
3992         addReply(c
,shared
.plus
); 
3993         addReply(c
,shared
.crlf
); 
3995         addReply(c
,shared
.plus
); 
3996         addReply(c
,dictGetEntryKey(de
)); 
3997         addReply(c
,shared
.crlf
); 
4001 static void keysCommand(redisClient 
*c
) { 
4004     sds pattern 
= c
->argv
[1]->ptr
; 
4005     int plen 
= sdslen(pattern
); 
4006     unsigned long numkeys 
= 0; 
4007     robj 
*lenobj 
= createObject(REDIS_STRING
,NULL
); 
4009     di 
= dictGetIterator(c
->db
->dict
); 
4011     decrRefCount(lenobj
); 
4012     while((de 
= dictNext(di
)) != NULL
) { 
4013         robj 
*keyobj 
= dictGetEntryKey(de
); 
4015         sds key 
= keyobj
->ptr
; 
4016         if ((pattern
[0] == '*' && pattern
[1] == '\0') || 
4017             stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) { 
4018             if (expireIfNeeded(c
->db
,keyobj
) == 0) { 
4019                 addReplyBulkLen(c
,keyobj
); 
4021                 addReply(c
,shared
.crlf
); 
4026     dictReleaseIterator(di
); 
4027     lenobj
->ptr 
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
); 
4030 static void dbsizeCommand(redisClient 
*c
) { 
4032         sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
))); 
4035 static void lastsaveCommand(redisClient 
*c
) { 
4037         sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
)); 
4040 static void typeCommand(redisClient 
*c
) { 
4044     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4049         case REDIS_STRING
: type 
= "+string"; break; 
4050         case REDIS_LIST
: type 
= "+list"; break; 
4051         case REDIS_SET
: type 
= "+set"; break; 
4052         case REDIS_ZSET
: type 
= "+zset"; break; 
4053         case REDIS_HASH
: type 
= "+hash"; break; 
4054         default: type 
= "+unknown"; break; 
4057     addReplySds(c
,sdsnew(type
)); 
4058     addReply(c
,shared
.crlf
); 
4061 static void saveCommand(redisClient 
*c
) { 
4062     if (server
.bgsavechildpid 
!= -1) { 
4063         addReplySds(c
,sdsnew("-ERR background save in progress\r\n")); 
4066     if (rdbSave(server
.dbfilename
) == REDIS_OK
) { 
4067         addReply(c
,shared
.ok
); 
4069         addReply(c
,shared
.err
); 
4073 static void bgsaveCommand(redisClient 
*c
) { 
4074     if (server
.bgsavechildpid 
!= -1) { 
4075         addReplySds(c
,sdsnew("-ERR background save already in progress\r\n")); 
4078     if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) { 
4079         char *status 
= "+Background saving started\r\n"; 
4080         addReplySds(c
,sdsnew(status
)); 
4082         addReply(c
,shared
.err
); 
4086 static void shutdownCommand(redisClient 
*c
) { 
4087     redisLog(REDIS_WARNING
,"User requested shutdown, saving DB..."); 
4088     /* Kill the saving child if there is a background saving in progress. 
4089        We want to avoid race conditions, for instance our saving child may 
4090        overwrite the synchronous saving did by SHUTDOWN. */ 
4091     if (server
.bgsavechildpid 
!= -1) { 
4092         redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!"); 
4093         kill(server
.bgsavechildpid
,SIGKILL
); 
4094         rdbRemoveTempFile(server
.bgsavechildpid
); 
4096     if (server
.appendonly
) { 
4097         /* Append only file: fsync() the AOF and exit */ 
4098         fsync(server
.appendfd
); 
4099         if (server
.vm_enabled
) unlink(server
.vm_swap_file
); 
4102         /* Snapshotting. Perform a SYNC SAVE and exit */ 
4103         if (rdbSave(server
.dbfilename
) == REDIS_OK
) { 
4104             if (server
.daemonize
) 
4105                 unlink(server
.pidfile
); 
4106             redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory()); 
4107             redisLog(REDIS_WARNING
,"Server exit now, bye bye..."); 
4108             if (server
.vm_enabled
) unlink(server
.vm_swap_file
); 
4111             /* Ooops.. error saving! The best we can do is to continue operating. 
4112              * Note that if there was a background saving process, in the next 
4113              * cron() Redis will be notified that the background saving aborted, 
4114              * handling special stuff like slaves pending for synchronization... */ 
4115             redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");  
4116             addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n")); 
4121 static void renameGenericCommand(redisClient 
*c
, int nx
) { 
4124     /* To use the same key as src and dst is probably an error */ 
4125     if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) { 
4126         addReply(c
,shared
.sameobjecterr
); 
4130     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4132         addReply(c
,shared
.nokeyerr
); 
4136     deleteIfVolatile(c
->db
,c
->argv
[2]); 
4137     if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) { 
4140             addReply(c
,shared
.czero
); 
4143         dictReplace(c
->db
->dict
,c
->argv
[2],o
); 
4145         incrRefCount(c
->argv
[2]); 
4147     deleteKey(c
->db
,c
->argv
[1]); 
4149     addReply(c
,nx 
? shared
.cone 
: shared
.ok
); 
4152 static void renameCommand(redisClient 
*c
) { 
4153     renameGenericCommand(c
,0); 
4156 static void renamenxCommand(redisClient 
*c
) { 
4157     renameGenericCommand(c
,1); 
4160 static void moveCommand(redisClient 
*c
) { 
4165     /* Obtain source and target DB pointers */ 
4168     if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) { 
4169         addReply(c
,shared
.outofrangeerr
); 
4173     selectDb(c
,srcid
); /* Back to the source DB */ 
4175     /* If the user is moving using as target the same 
4176      * DB as the source DB it is probably an error. */ 
4178         addReply(c
,shared
.sameobjecterr
); 
4182     /* Check if the element exists and get a reference */ 
4183     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4185         addReply(c
,shared
.czero
); 
4189     /* Try to add the element to the target DB */ 
4190     deleteIfVolatile(dst
,c
->argv
[1]); 
4191     if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) { 
4192         addReply(c
,shared
.czero
); 
4195     incrRefCount(c
->argv
[1]); 
4198     /* OK! key moved, free the entry in the source DB */ 
4199     deleteKey(src
,c
->argv
[1]); 
4201     addReply(c
,shared
.cone
); 
4204 /* =================================== Lists ================================ */ 
4205 static void pushGenericCommand(redisClient 
*c
, int where
) { 
4209     lobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4211         if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) { 
4212             addReply(c
,shared
.cone
); 
4215         lobj 
= createListObject(); 
4217         if (where 
== REDIS_HEAD
) { 
4218             listAddNodeHead(list
,c
->argv
[2]); 
4220             listAddNodeTail(list
,c
->argv
[2]); 
4222         dictAdd(c
->db
->dict
,c
->argv
[1],lobj
); 
4223         incrRefCount(c
->argv
[1]); 
4224         incrRefCount(c
->argv
[2]); 
4226         if (lobj
->type 
!= REDIS_LIST
) { 
4227             addReply(c
,shared
.wrongtypeerr
); 
4230         if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) { 
4231             addReply(c
,shared
.cone
); 
4235         if (where 
== REDIS_HEAD
) { 
4236             listAddNodeHead(list
,c
->argv
[2]); 
4238             listAddNodeTail(list
,c
->argv
[2]); 
4240         incrRefCount(c
->argv
[2]); 
4243     addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(list
))); 
4246 static void lpushCommand(redisClient 
*c
) { 
4247     pushGenericCommand(c
,REDIS_HEAD
); 
4250 static void rpushCommand(redisClient 
*c
) { 
4251     pushGenericCommand(c
,REDIS_TAIL
); 
4254 static void llenCommand(redisClient 
*c
) { 
4258     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4260         addReply(c
,shared
.czero
); 
4263         if (o
->type 
!= REDIS_LIST
) { 
4264             addReply(c
,shared
.wrongtypeerr
); 
4267             addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
))); 
4272 static void lindexCommand(redisClient 
*c
) { 
4274     int index 
= atoi(c
->argv
[2]->ptr
); 
4276     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4278         addReply(c
,shared
.nullbulk
); 
4280         if (o
->type 
!= REDIS_LIST
) { 
4281             addReply(c
,shared
.wrongtypeerr
); 
4283             list 
*list 
= o
->ptr
; 
4286             ln 
= listIndex(list
, index
); 
4288                 addReply(c
,shared
.nullbulk
); 
4290                 robj 
*ele 
= listNodeValue(ln
); 
4291                 addReplyBulkLen(c
,ele
); 
4293                 addReply(c
,shared
.crlf
); 
4299 static void lsetCommand(redisClient 
*c
) { 
4301     int index 
= atoi(c
->argv
[2]->ptr
); 
4303     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4305         addReply(c
,shared
.nokeyerr
); 
4307         if (o
->type 
!= REDIS_LIST
) { 
4308             addReply(c
,shared
.wrongtypeerr
); 
4310             list 
*list 
= o
->ptr
; 
4313             ln 
= listIndex(list
, index
); 
4315                 addReply(c
,shared
.outofrangeerr
); 
4317                 robj 
*ele 
= listNodeValue(ln
); 
4320                 listNodeValue(ln
) = c
->argv
[3]; 
4321                 incrRefCount(c
->argv
[3]); 
4322                 addReply(c
,shared
.ok
); 
4329 static void popGenericCommand(redisClient 
*c
, int where
) { 
4332     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4334         addReply(c
,shared
.nullbulk
); 
4336         if (o
->type 
!= REDIS_LIST
) { 
4337             addReply(c
,shared
.wrongtypeerr
); 
4339             list 
*list 
= o
->ptr
; 
4342             if (where 
== REDIS_HEAD
) 
4343                 ln 
= listFirst(list
); 
4345                 ln 
= listLast(list
); 
4348                 addReply(c
,shared
.nullbulk
); 
4350                 robj 
*ele 
= listNodeValue(ln
); 
4351                 addReplyBulkLen(c
,ele
); 
4353                 addReply(c
,shared
.crlf
); 
4354                 listDelNode(list
,ln
); 
4361 static void lpopCommand(redisClient 
*c
) { 
4362     popGenericCommand(c
,REDIS_HEAD
); 
4365 static void rpopCommand(redisClient 
*c
) { 
4366     popGenericCommand(c
,REDIS_TAIL
); 
4369 static void lrangeCommand(redisClient 
*c
) { 
4371     int start 
= atoi(c
->argv
[2]->ptr
); 
4372     int end 
= atoi(c
->argv
[3]->ptr
); 
4374     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4376         addReply(c
,shared
.nullmultibulk
); 
4378         if (o
->type 
!= REDIS_LIST
) { 
4379             addReply(c
,shared
.wrongtypeerr
); 
4381             list 
*list 
= o
->ptr
; 
4383             int llen 
= listLength(list
); 
4387             /* convert negative indexes */ 
4388             if (start 
< 0) start 
= llen
+start
; 
4389             if (end 
< 0) end 
= llen
+end
; 
4390             if (start 
< 0) start 
= 0; 
4391             if (end 
< 0) end 
= 0; 
4393             /* indexes sanity checks */ 
4394             if (start 
> end 
|| start 
>= llen
) { 
4395                 /* Out of range start or start > end result in empty list */ 
4396                 addReply(c
,shared
.emptymultibulk
); 
4399             if (end 
>= llen
) end 
= llen
-1; 
4400             rangelen 
= (end
-start
)+1; 
4402             /* Return the result in form of a multi-bulk reply */ 
4403             ln 
= listIndex(list
, start
); 
4404             addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
)); 
4405             for (j 
= 0; j 
< rangelen
; j
++) { 
4406                 ele 
= listNodeValue(ln
); 
4407                 addReplyBulkLen(c
,ele
); 
4409                 addReply(c
,shared
.crlf
); 
4416 static void ltrimCommand(redisClient 
*c
) { 
4418     int start 
= atoi(c
->argv
[2]->ptr
); 
4419     int end 
= atoi(c
->argv
[3]->ptr
); 
4421     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4423         addReply(c
,shared
.ok
); 
4425         if (o
->type 
!= REDIS_LIST
) { 
4426             addReply(c
,shared
.wrongtypeerr
); 
4428             list 
*list 
= o
->ptr
; 
4430             int llen 
= listLength(list
); 
4431             int j
, ltrim
, rtrim
; 
4433             /* convert negative indexes */ 
4434             if (start 
< 0) start 
= llen
+start
; 
4435             if (end 
< 0) end 
= llen
+end
; 
4436             if (start 
< 0) start 
= 0; 
4437             if (end 
< 0) end 
= 0; 
4439             /* indexes sanity checks */ 
4440             if (start 
> end 
|| start 
>= llen
) { 
4441                 /* Out of range start or start > end result in empty list */ 
4445                 if (end 
>= llen
) end 
= llen
-1; 
4450             /* Remove list elements to perform the trim */ 
4451             for (j 
= 0; j 
< ltrim
; j
++) { 
4452                 ln 
= listFirst(list
); 
4453                 listDelNode(list
,ln
); 
4455             for (j 
= 0; j 
< rtrim
; j
++) { 
4456                 ln 
= listLast(list
); 
4457                 listDelNode(list
,ln
); 
4460             addReply(c
,shared
.ok
); 
4465 static void lremCommand(redisClient 
*c
) { 
4468     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4470         addReply(c
,shared
.czero
); 
4472         if (o
->type 
!= REDIS_LIST
) { 
4473             addReply(c
,shared
.wrongtypeerr
); 
4475             list 
*list 
= o
->ptr
; 
4476             listNode 
*ln
, *next
; 
4477             int toremove 
= atoi(c
->argv
[2]->ptr
); 
4482                 toremove 
= -toremove
; 
4485             ln 
= fromtail 
? list
->tail 
: list
->head
; 
4487                 robj 
*ele 
= listNodeValue(ln
); 
4489                 next 
= fromtail 
? ln
->prev 
: ln
->next
; 
4490                 if (compareStringObjects(ele
,c
->argv
[3]) == 0) { 
4491                     listDelNode(list
,ln
); 
4494                     if (toremove 
&& removed 
== toremove
) break; 
4498             addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
)); 
4503 /* This is the semantic of this command: 
4504  *  RPOPLPUSH srclist dstlist: 
4505  *   IF LLEN(srclist) > 0 
4506  *     element = RPOP srclist 
4507  *     LPUSH dstlist element 
4514  * The idea is to be able to get an element from a list in a reliable way 
4515  * since the element is not just returned but pushed against another list 
4516  * as well. This command was originally proposed by Ezra Zygmuntowicz. 
4518 static void rpoplpushcommand(redisClient 
*c
) { 
4521     sobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4523         addReply(c
,shared
.nullbulk
); 
4525         if (sobj
->type 
!= REDIS_LIST
) { 
4526             addReply(c
,shared
.wrongtypeerr
); 
4528             list 
*srclist 
= sobj
->ptr
; 
4529             listNode 
*ln 
= listLast(srclist
); 
4532                 addReply(c
,shared
.nullbulk
); 
4534                 robj 
*dobj 
= lookupKeyWrite(c
->db
,c
->argv
[2]); 
4535                 robj 
*ele 
= listNodeValue(ln
); 
4538                 if (dobj 
&& dobj
->type 
!= REDIS_LIST
) { 
4539                     addReply(c
,shared
.wrongtypeerr
); 
4543                 /* Add the element to the target list (unless it's directly 
4544                  * passed to some BLPOP-ing client */ 
4545                 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) { 
4547                         /* Create the list if the key does not exist */ 
4548                         dobj 
= createListObject(); 
4549                         dictAdd(c
->db
->dict
,c
->argv
[2],dobj
); 
4550                         incrRefCount(c
->argv
[2]); 
4552                     dstlist 
= dobj
->ptr
; 
4553                     listAddNodeHead(dstlist
,ele
); 
4557                 /* Send the element to the client as reply as well */ 
4558                 addReplyBulkLen(c
,ele
); 
4560                 addReply(c
,shared
.crlf
); 
4562                 /* Finally remove the element from the source list */ 
4563                 listDelNode(srclist
,ln
); 
4571 /* ==================================== Sets ================================ */ 
4573 static void saddCommand(redisClient 
*c
) { 
4576     set 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4578         set 
= createSetObject(); 
4579         dictAdd(c
->db
->dict
,c
->argv
[1],set
); 
4580         incrRefCount(c
->argv
[1]); 
4582         if (set
->type 
!= REDIS_SET
) { 
4583             addReply(c
,shared
.wrongtypeerr
); 
4587     if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) { 
4588         incrRefCount(c
->argv
[2]); 
4590         addReply(c
,shared
.cone
); 
4592         addReply(c
,shared
.czero
); 
4596 static void sremCommand(redisClient 
*c
) { 
4599     set 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4601         addReply(c
,shared
.czero
); 
4603         if (set
->type 
!= REDIS_SET
) { 
4604             addReply(c
,shared
.wrongtypeerr
); 
4607         if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) { 
4609             if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
); 
4610             addReply(c
,shared
.cone
); 
4612             addReply(c
,shared
.czero
); 
4617 static void smoveCommand(redisClient 
*c
) { 
4618     robj 
*srcset
, *dstset
; 
4620     srcset 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4621     dstset 
= lookupKeyWrite(c
->db
,c
->argv
[2]); 
4623     /* If the source key does not exist return 0, if it's of the wrong type 
4625     if (srcset 
== NULL 
|| srcset
->type 
!= REDIS_SET
) { 
4626         addReply(c
, srcset 
? shared
.wrongtypeerr 
: shared
.czero
); 
4629     /* Error if the destination key is not a set as well */ 
4630     if (dstset 
&& dstset
->type 
!= REDIS_SET
) { 
4631         addReply(c
,shared
.wrongtypeerr
); 
4634     /* Remove the element from the source set */ 
4635     if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) { 
4636         /* Key not found in the src set! return zero */ 
4637         addReply(c
,shared
.czero
); 
4641     /* Add the element to the destination set */ 
4643         dstset 
= createSetObject(); 
4644         dictAdd(c
->db
->dict
,c
->argv
[2],dstset
); 
4645         incrRefCount(c
->argv
[2]); 
4647     if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
) 
4648         incrRefCount(c
->argv
[3]); 
4649     addReply(c
,shared
.cone
); 
4652 static void sismemberCommand(redisClient 
*c
) { 
4655     set 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4657         addReply(c
,shared
.czero
); 
4659         if (set
->type 
!= REDIS_SET
) { 
4660             addReply(c
,shared
.wrongtypeerr
); 
4663         if (dictFind(set
->ptr
,c
->argv
[2])) 
4664             addReply(c
,shared
.cone
); 
4666             addReply(c
,shared
.czero
); 
4670 static void scardCommand(redisClient 
*c
) { 
4674     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4676         addReply(c
,shared
.czero
); 
4679         if (o
->type 
!= REDIS_SET
) { 
4680             addReply(c
,shared
.wrongtypeerr
); 
4683             addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n", 
4689 static void spopCommand(redisClient 
*c
) { 
4693     set 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
4695         addReply(c
,shared
.nullbulk
); 
4697         if (set
->type 
!= REDIS_SET
) { 
4698             addReply(c
,shared
.wrongtypeerr
); 
4701         de 
= dictGetRandomKey(set
->ptr
); 
4703             addReply(c
,shared
.nullbulk
); 
4705             robj 
*ele 
= dictGetEntryKey(de
); 
4707             addReplyBulkLen(c
,ele
); 
4709             addReply(c
,shared
.crlf
); 
4710             dictDelete(set
->ptr
,ele
); 
4711             if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
); 
4717 static void srandmemberCommand(redisClient 
*c
) { 
4721     set 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
4723         addReply(c
,shared
.nullbulk
); 
4725         if (set
->type 
!= REDIS_SET
) { 
4726             addReply(c
,shared
.wrongtypeerr
); 
4729         de 
= dictGetRandomKey(set
->ptr
); 
4731             addReply(c
,shared
.nullbulk
); 
4733             robj 
*ele 
= dictGetEntryKey(de
); 
4735             addReplyBulkLen(c
,ele
); 
4737             addReply(c
,shared
.crlf
); 
4742 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) { 
4743     dict 
**d1 
= (void*) s1
, **d2 
= (void*) s2
; 
4745     return dictSize(*d1
)-dictSize(*d2
); 
4748 static void sinterGenericCommand(redisClient 
*c
, robj 
**setskeys
, unsigned long setsnum
, robj 
*dstkey
) { 
4749     dict 
**dv 
= zmalloc(sizeof(dict
*)*setsnum
); 
4752     robj 
*lenobj 
= NULL
, *dstset 
= NULL
; 
4753     unsigned long j
, cardinality 
= 0; 
4755     for (j 
= 0; j 
< setsnum
; j
++) { 
4759                     lookupKeyWrite(c
->db
,setskeys
[j
]) : 
4760                     lookupKeyRead(c
->db
,setskeys
[j
]); 
4764                 if (deleteKey(c
->db
,dstkey
)) 
4766                 addReply(c
,shared
.czero
); 
4768                 addReply(c
,shared
.nullmultibulk
); 
4772         if (setobj
->type 
!= REDIS_SET
) { 
4774             addReply(c
,shared
.wrongtypeerr
); 
4777         dv
[j
] = setobj
->ptr
; 
4779     /* Sort sets from the smallest to largest, this will improve our 
4780      * algorithm's performace */ 
4781     qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
); 
4783     /* The first thing we should output is the total number of elements... 
4784      * since this is a multi-bulk write, but at this stage we don't know 
4785      * the intersection set size, so we use a trick, append an empty object 
4786      * to the output list and save the pointer to later modify it with the 
4789         lenobj 
= createObject(REDIS_STRING
,NULL
); 
4791         decrRefCount(lenobj
); 
4793         /* If we have a target key where to store the resulting set 
4794          * create this key with an empty set inside */ 
4795         dstset 
= createSetObject(); 
4798     /* Iterate all the elements of the first (smallest) set, and test 
4799      * the element against all the other sets, if at least one set does 
4800      * not include the element it is discarded */ 
4801     di 
= dictGetIterator(dv
[0]); 
4803     while((de 
= dictNext(di
)) != NULL
) { 
4806         for (j 
= 1; j 
< setsnum
; j
++) 
4807             if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break; 
4809             continue; /* at least one set does not contain the member */ 
4810         ele 
= dictGetEntryKey(de
); 
4812             addReplyBulkLen(c
,ele
); 
4814             addReply(c
,shared
.crlf
); 
4817             dictAdd(dstset
->ptr
,ele
,NULL
); 
4821     dictReleaseIterator(di
); 
4824         /* Store the resulting set into the target */ 
4825         deleteKey(c
->db
,dstkey
); 
4826         dictAdd(c
->db
->dict
,dstkey
,dstset
); 
4827         incrRefCount(dstkey
); 
4831         lenobj
->ptr 
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
); 
4833         addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n", 
4834             dictSize((dict
*)dstset
->ptr
))); 
4840 static void sinterCommand(redisClient 
*c
) { 
4841     sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
); 
4844 static void sinterstoreCommand(redisClient 
*c
) { 
4845     sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]); 
4848 #define REDIS_OP_UNION 0 
4849 #define REDIS_OP_DIFF 1 
4850 #define REDIS_OP_INTER 2 
4852 static void sunionDiffGenericCommand(redisClient 
*c
, robj 
**setskeys
, int setsnum
, robj 
*dstkey
, int op
) { 
4853     dict 
**dv 
= zmalloc(sizeof(dict
*)*setsnum
); 
4856     robj 
*dstset 
= NULL
; 
4857     int j
, cardinality 
= 0; 
4859     for (j 
= 0; j 
< setsnum
; j
++) { 
4863                     lookupKeyWrite(c
->db
,setskeys
[j
]) : 
4864                     lookupKeyRead(c
->db
,setskeys
[j
]); 
4869         if (setobj
->type 
!= REDIS_SET
) { 
4871             addReply(c
,shared
.wrongtypeerr
); 
4874         dv
[j
] = setobj
->ptr
; 
4877     /* We need a temp set object to store our union. If the dstkey 
4878      * is not NULL (that is, we are inside an SUNIONSTORE operation) then 
4879      * this set object will be the resulting object to set into the target key*/ 
4880     dstset 
= createSetObject(); 
4882     /* Iterate all the elements of all the sets, add every element a single 
4883      * time to the result set */ 
4884     for (j 
= 0; j 
< setsnum
; j
++) { 
4885         if (op 
== REDIS_OP_DIFF 
&& j 
== 0 && !dv
[j
]) break; /* result set is empty */ 
4886         if (!dv
[j
]) continue; /* non existing keys are like empty sets */ 
4888         di 
= dictGetIterator(dv
[j
]); 
4890         while((de 
= dictNext(di
)) != NULL
) { 
4893             /* dictAdd will not add the same element multiple times */ 
4894             ele 
= dictGetEntryKey(de
); 
4895             if (op 
== REDIS_OP_UNION 
|| j 
== 0) { 
4896                 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) { 
4900             } else if (op 
== REDIS_OP_DIFF
) { 
4901                 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) { 
4906         dictReleaseIterator(di
); 
4908         if (op 
== REDIS_OP_DIFF 
&& cardinality 
== 0) break; /* result set is empty */ 
4911     /* Output the content of the resulting set, if not in STORE mode */ 
4913         addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
)); 
4914         di 
= dictGetIterator(dstset
->ptr
); 
4915         while((de 
= dictNext(di
)) != NULL
) { 
4918             ele 
= dictGetEntryKey(de
); 
4919             addReplyBulkLen(c
,ele
); 
4921             addReply(c
,shared
.crlf
); 
4923         dictReleaseIterator(di
); 
4925         /* If we have a target key where to store the resulting set 
4926          * create this key with the result set inside */ 
4927         deleteKey(c
->db
,dstkey
); 
4928         dictAdd(c
->db
->dict
,dstkey
,dstset
); 
4929         incrRefCount(dstkey
); 
4934         decrRefCount(dstset
); 
4936         addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n", 
4937             dictSize((dict
*)dstset
->ptr
))); 
4943 static void sunionCommand(redisClient 
*c
) { 
4944     sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
); 
4947 static void sunionstoreCommand(redisClient 
*c
) { 
4948     sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
); 
4951 static void sdiffCommand(redisClient 
*c
) { 
4952     sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
); 
4955 static void sdiffstoreCommand(redisClient 
*c
) { 
4956     sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
); 
4959 /* ==================================== ZSets =============================== */ 
4961 /* ZSETs are ordered sets using two data structures to hold the same elements 
4962  * in order to get O(log(N)) INSERT and REMOVE operations into a sorted 
4965  * The elements are added to an hash table mapping Redis objects to scores. 
4966  * At the same time the elements are added to a skip list mapping scores 
4967  * to Redis objects (so objects are sorted by scores in this "view"). */ 
4969 /* This skiplist implementation is almost a C translation of the original 
4970  * algorithm described by William Pugh in "Skip Lists: A Probabilistic 
4971  * Alternative to Balanced Trees", modified in three ways: 
4972  * a) this implementation allows for repeated values. 
4973  * b) the comparison is not just by key (our 'score') but by satellite data. 
4974  * c) there is a back pointer, so it's a doubly linked list with the back 
4975  * pointers being only at "level 1". This allows to traverse the list 
4976  * from tail to head, useful for ZREVRANGE. */ 
4978 static zskiplistNode 
*zslCreateNode(int level
, double score
, robj 
*obj
) { 
4979     zskiplistNode 
*zn 
= zmalloc(sizeof(*zn
)); 
4981     zn
->forward 
= zmalloc(sizeof(zskiplistNode
*) * level
); 
4983         zn
->span 
= zmalloc(sizeof(unsigned int) * (level 
- 1)); 
4989 static zskiplist 
*zslCreate(void) { 
4993     zsl 
= zmalloc(sizeof(*zsl
)); 
4996     zsl
->header 
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
); 
4997     for (j 
= 0; j 
< ZSKIPLIST_MAXLEVEL
; j
++) { 
4998         zsl
->header
->forward
[j
] = NULL
; 
5000         /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */ 
5001         if (j 
< ZSKIPLIST_MAXLEVEL
-1) 
5002             zsl
->header
->span
[j
] = 0; 
5004     zsl
->header
->backward 
= NULL
; 
5009 static void zslFreeNode(zskiplistNode 
*node
) { 
5010     decrRefCount(node
->obj
); 
5011     zfree(node
->forward
); 
5016 static void zslFree(zskiplist 
*zsl
) { 
5017     zskiplistNode 
*node 
= zsl
->header
->forward
[0], *next
; 
5019     zfree(zsl
->header
->forward
); 
5020     zfree(zsl
->header
->span
); 
5023         next 
= node
->forward
[0]; 
5030 static int zslRandomLevel(void) { 
5032     while ((random()&0xFFFF) < (ZSKIPLIST_P 
* 0xFFFF)) 
5037 static void zslInsert(zskiplist 
*zsl
, double score
, robj 
*obj
) { 
5038     zskiplistNode 
*update
[ZSKIPLIST_MAXLEVEL
], *x
; 
5039     unsigned int rank
[ZSKIPLIST_MAXLEVEL
]; 
5043     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5044         /* store rank that is crossed to reach the insert position */ 
5045         rank
[i
] = i 
== (zsl
->level
-1) ? 0 : rank
[i
+1]; 
5047         while (x
->forward
[i
] && 
5048             (x
->forward
[i
]->score 
< score 
|| 
5049                 (x
->forward
[i
]->score 
== score 
&& 
5050                 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) { 
5051             rank
[i
] += i 
> 0 ? x
->span
[i
-1] : 1; 
5056     /* we assume the key is not already inside, since we allow duplicated 
5057      * scores, and the re-insertion of score and redis object should never 
5058      * happpen since the caller of zslInsert() should test in the hash table 
5059      * if the element is already inside or not. */ 
5060     level 
= zslRandomLevel(); 
5061     if (level 
> zsl
->level
) { 
5062         for (i 
= zsl
->level
; i 
< level
; i
++) { 
5064             update
[i
] = zsl
->header
; 
5065             update
[i
]->span
[i
-1] = zsl
->length
; 
5069     x 
= zslCreateNode(level
,score
,obj
); 
5070     for (i 
= 0; i 
< level
; i
++) { 
5071         x
->forward
[i
] = update
[i
]->forward
[i
]; 
5072         update
[i
]->forward
[i
] = x
; 
5074         /* update span covered by update[i] as x is inserted here */ 
5076             x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]); 
5077             update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1; 
5081     /* increment span for untouched levels */ 
5082     for (i 
= level
; i 
< zsl
->level
; i
++) { 
5083         update
[i
]->span
[i
-1]++; 
5086     x
->backward 
= (update
[0] == zsl
->header
) ? NULL 
: update
[0]; 
5088         x
->forward
[0]->backward 
= x
; 
5094 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */ 
5095 void zslDeleteNode(zskiplist 
*zsl
, zskiplistNode 
*x
, zskiplistNode 
**update
) { 
5097     for (i 
= 0; i 
< zsl
->level
; i
++) { 
5098         if (update
[i
]->forward
[i
] == x
) { 
5100                 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1; 
5102             update
[i
]->forward
[i
] = x
->forward
[i
]; 
5104             /* invariant: i > 0, because update[0]->forward[0] 
5105              * is always equal to x */ 
5106             update
[i
]->span
[i
-1] -= 1; 
5109     if (x
->forward
[0]) { 
5110         x
->forward
[0]->backward 
= x
->backward
; 
5112         zsl
->tail 
= x
->backward
; 
5114     while(zsl
->level 
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
) 
5119 /* Delete an element with matching score/object from the skiplist. */ 
5120 static int zslDelete(zskiplist 
*zsl
, double score
, robj 
*obj
) { 
5121     zskiplistNode 
*update
[ZSKIPLIST_MAXLEVEL
], *x
; 
5125     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5126         while (x
->forward
[i
] && 
5127             (x
->forward
[i
]->score 
< score 
|| 
5128                 (x
->forward
[i
]->score 
== score 
&& 
5129                 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) 
5133     /* We may have multiple elements with the same score, what we need 
5134      * is to find the element with both the right score and object. */ 
5136     if (x 
&& score 
== x
->score 
&& compareStringObjects(x
->obj
,obj
) == 0) { 
5137         zslDeleteNode(zsl
, x
, update
); 
5141         return 0; /* not found */ 
5143     return 0; /* not found */ 
5146 /* Delete all the elements with score between min and max from the skiplist. 
5147  * Min and mx are inclusive, so a score >= min || score <= max is deleted. 
5148  * Note that this function takes the reference to the hash table view of the 
5149  * sorted set, in order to remove the elements from the hash table too. */ 
5150 static unsigned long zslDeleteRangeByScore(zskiplist 
*zsl
, double min
, double max
, dict 
*dict
) { 
5151     zskiplistNode 
*update
[ZSKIPLIST_MAXLEVEL
], *x
; 
5152     unsigned long removed 
= 0; 
5156     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5157         while (x
->forward
[i
] && x
->forward
[i
]->score 
< min
) 
5161     /* We may have multiple elements with the same score, what we need 
5162      * is to find the element with both the right score and object. */ 
5164     while (x 
&& x
->score 
<= max
) { 
5165         zskiplistNode 
*next 
= x
->forward
[0]; 
5166         zslDeleteNode(zsl
, x
, update
); 
5167         dictDelete(dict
,x
->obj
); 
5172     return removed
; /* not found */ 
5175 /* Delete all the elements with rank between start and end from the skiplist. 
5176  * Start and end are inclusive. Note that start and end need to be 1-based */ 
5177 static unsigned long zslDeleteRangeByRank(zskiplist 
*zsl
, unsigned int start
, unsigned int end
, dict 
*dict
) { 
5178     zskiplistNode 
*update
[ZSKIPLIST_MAXLEVEL
], *x
; 
5179     unsigned long traversed 
= 0, removed 
= 0; 
5183     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5184         while (x
->forward
[i
] && (traversed 
+ (i 
> 0 ? x
->span
[i
-1] : 1)) < start
) { 
5185             traversed 
+= i 
> 0 ? x
->span
[i
-1] : 1; 
5193     while (x 
&& traversed 
<= end
) { 
5194         zskiplistNode 
*next 
= x
->forward
[0]; 
5195         zslDeleteNode(zsl
, x
, update
); 
5196         dictDelete(dict
,x
->obj
); 
5205 /* Find the first node having a score equal or greater than the specified one. 
5206  * Returns NULL if there is no match. */ 
5207 static zskiplistNode 
*zslFirstWithScore(zskiplist 
*zsl
, double score
) { 
5212     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5213         while (x
->forward
[i
] && x
->forward
[i
]->score 
< score
) 
5216     /* We may have multiple elements with the same score, what we need 
5217      * is to find the element with both the right score and object. */ 
5218     return x
->forward
[0]; 
5221 /* Find the rank for an element by both score and key. 
5222  * Returns 0 when the element cannot be found, rank otherwise. 
5223  * Note that the rank is 1-based due to the span of zsl->header to the 
5225 static unsigned long zslGetRank(zskiplist 
*zsl
, double score
, robj 
*o
) { 
5227     unsigned long rank 
= 0; 
5231     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5232         while (x
->forward
[i
] && 
5233             (x
->forward
[i
]->score 
< score 
|| 
5234                 (x
->forward
[i
]->score 
== score 
&& 
5235                 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) { 
5236             rank 
+= i 
> 0 ? x
->span
[i
-1] : 1; 
5240         /* x might be equal to zsl->header, so test if obj is non-NULL */ 
5241         if (x
->obj 
&& compareStringObjects(x
->obj
,o
) == 0) { 
5248 /* Finds an element by its rank. The rank argument needs to be 1-based. */ 
5249 zskiplistNode
* zslGetElementByRank(zskiplist 
*zsl
, unsigned long rank
) { 
5251     unsigned long traversed 
= 0; 
5255     for (i 
= zsl
->level
-1; i 
>= 0; i
--) { 
5256         while (x
->forward
[i
] && (traversed 
+ (i 
> 0 ? x
->span
[i
-1] : 1)) <= rank
) { 
5257             traversed 
+= i 
> 0 ? x
->span
[i
-1] : 1; 
5261         if (traversed 
== rank
) { 
5268 /* The actual Z-commands implementations */ 
5270 /* This generic command implements both ZADD and ZINCRBY. 
5271  * scoreval is the score if the operation is a ZADD (doincrement == 0) or 
5272  * the increment if the operation is a ZINCRBY (doincrement == 1). */ 
5273 static void zaddGenericCommand(redisClient 
*c
, robj 
*key
, robj 
*ele
, double scoreval
, int doincrement
) { 
5278     zsetobj 
= lookupKeyWrite(c
->db
,key
); 
5279     if (zsetobj 
== NULL
) { 
5280         zsetobj 
= createZsetObject(); 
5281         dictAdd(c
->db
->dict
,key
,zsetobj
); 
5284         if (zsetobj
->type 
!= REDIS_ZSET
) { 
5285             addReply(c
,shared
.wrongtypeerr
); 
5291     /* Ok now since we implement both ZADD and ZINCRBY here the code 
5292      * needs to handle the two different conditions. It's all about setting 
5293      * '*score', that is, the new score to set, to the right value. */ 
5294     score 
= zmalloc(sizeof(double)); 
5298         /* Read the old score. If the element was not present starts from 0 */ 
5299         de 
= dictFind(zs
->dict
,ele
); 
5301             double *oldscore 
= dictGetEntryVal(de
); 
5302             *score 
= *oldscore 
+ scoreval
; 
5310     /* What follows is a simple remove and re-insert operation that is common 
5311      * to both ZADD and ZINCRBY... */ 
5312     if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) { 
5313         /* case 1: New element */ 
5314         incrRefCount(ele
); /* added to hash */ 
5315         zslInsert(zs
->zsl
,*score
,ele
); 
5316         incrRefCount(ele
); /* added to skiplist */ 
5319             addReplyDouble(c
,*score
); 
5321             addReply(c
,shared
.cone
); 
5326         /* case 2: Score update operation */ 
5327         de 
= dictFind(zs
->dict
,ele
); 
5328         redisAssert(de 
!= NULL
); 
5329         oldscore 
= dictGetEntryVal(de
); 
5330         if (*score 
!= *oldscore
) { 
5333             /* Remove and insert the element in the skip list with new score */ 
5334             deleted 
= zslDelete(zs
->zsl
,*oldscore
,ele
); 
5335             redisAssert(deleted 
!= 0); 
5336             zslInsert(zs
->zsl
,*score
,ele
); 
5338             /* Update the score in the hash table */ 
5339             dictReplace(zs
->dict
,ele
,score
); 
5345             addReplyDouble(c
,*score
); 
5347             addReply(c
,shared
.czero
); 
5351 static void zaddCommand(redisClient 
*c
) { 
5354     scoreval 
= strtod(c
->argv
[2]->ptr
,NULL
); 
5355     zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0); 
5358 static void zincrbyCommand(redisClient 
*c
) { 
5361     scoreval 
= strtod(c
->argv
[2]->ptr
,NULL
); 
5362     zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1); 
5365 static void zremCommand(redisClient 
*c
) { 
5369     zsetobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
5370     if (zsetobj 
== NULL
) { 
5371         addReply(c
,shared
.czero
); 
5377         if (zsetobj
->type 
!= REDIS_ZSET
) { 
5378             addReply(c
,shared
.wrongtypeerr
); 
5382         de 
= dictFind(zs
->dict
,c
->argv
[2]); 
5384             addReply(c
,shared
.czero
); 
5387         /* Delete from the skiplist */ 
5388         oldscore 
= dictGetEntryVal(de
); 
5389         deleted 
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]); 
5390         redisAssert(deleted 
!= 0); 
5392         /* Delete from the hash table */ 
5393         dictDelete(zs
->dict
,c
->argv
[2]); 
5394         if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
); 
5396         addReply(c
,shared
.cone
); 
5400 static void zremrangebyscoreCommand(redisClient 
*c
) { 
5401     double min 
= strtod(c
->argv
[2]->ptr
,NULL
); 
5402     double max 
= strtod(c
->argv
[3]->ptr
,NULL
); 
5406     zsetobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
5407     if (zsetobj 
== NULL
) { 
5408         addReply(c
,shared
.czero
); 
5412         if (zsetobj
->type 
!= REDIS_ZSET
) { 
5413             addReply(c
,shared
.wrongtypeerr
); 
5417         deleted 
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
); 
5418         if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
); 
5419         server
.dirty 
+= deleted
; 
5420         addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
)); 
5424 static void zremrangebyrankCommand(redisClient 
*c
) { 
5425     int start 
= atoi(c
->argv
[2]->ptr
); 
5426     int end 
= atoi(c
->argv
[3]->ptr
); 
5430     zsetobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
5431     if (zsetobj 
== NULL
) { 
5432         addReply(c
,shared
.czero
); 
5434         if (zsetobj
->type 
!= REDIS_ZSET
) { 
5435             addReply(c
,shared
.wrongtypeerr
); 
5440         int llen 
= zs
->zsl
->length
; 
5443         /* convert negative indexes */ 
5444         if (start 
< 0) start 
= llen
+start
; 
5445         if (end 
< 0) end 
= llen
+end
; 
5446         if (start 
< 0) start 
= 0; 
5447         if (end 
< 0) end 
= 0; 
5449         /* indexes sanity checks */ 
5450         if (start 
> end 
|| start 
>= llen
) { 
5451             addReply(c
,shared
.czero
); 
5454         if (end 
>= llen
) end 
= llen
-1; 
5456         /* increment start and end because zsl*Rank functions 
5457          * use 1-based rank */ 
5458         deleted 
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
); 
5459         if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
); 
5460         server
.dirty 
+= deleted
; 
5461         addReplyLong(c
, deleted
); 
5470 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) { 
5471     zsetopsrc 
*d1 
= (void*) s1
, *d2 
= (void*) s2
; 
5472     unsigned long size1
, size2
; 
5473     size1 
= d1
->dict 
? dictSize(d1
->dict
) : 0; 
5474     size2 
= d2
->dict 
? dictSize(d2
->dict
) : 0; 
5475     return size1 
- size2
; 
5478 static void zunionInterGenericCommand(redisClient 
*c
, robj 
*dstkey
, int op
) { 
5486     /* expect zsetnum input keys to be given */ 
5487     zsetnum 
= atoi(c
->argv
[2]->ptr
); 
5489         addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNION/ZINTER\r\n")); 
5493     /* test if the expected number of keys would overflow */ 
5494     if (3+zsetnum 
> c
->argc
) { 
5495         addReply(c
,shared
.syntaxerr
); 
5499     /* read keys to be used for input */ 
5500     src 
= zmalloc(sizeof(zsetopsrc
) * zsetnum
); 
5501     for (i 
= 0, j 
= 3; i 
< zsetnum
; i
++, j
++) { 
5502         robj 
*zsetobj 
= lookupKeyWrite(c
->db
,c
->argv
[j
]); 
5506             if (zsetobj
->type 
!= REDIS_ZSET
) { 
5508                 addReply(c
,shared
.wrongtypeerr
); 
5511             src
[i
].dict 
= ((zset
*)zsetobj
->ptr
)->dict
; 
5514         /* default all weights to 1 */ 
5515         src
[i
].weight 
= 1.0; 
5518     /* parse optional extra arguments */ 
5520         int remaining 
= c
->argc
-j
; 
5523             if (!strcasecmp(c
->argv
[j
]->ptr
,"weights")) { 
5525                 if (remaining 
< zsetnum
) { 
5527                     addReplySds(c
,sdsnew("-ERR not enough weights for ZUNION/ZINTER\r\n")); 
5530                 for (i 
= 0; i 
< zsetnum
; i
++, j
++, remaining
--) { 
5531                     src
[i
].weight 
= strtod(c
->argv
[j
]->ptr
, NULL
); 
5535                 addReply(c
,shared
.syntaxerr
); 
5541     dstobj 
= createZsetObject(); 
5542     dstzset 
= dstobj
->ptr
; 
5544     if (op 
== REDIS_OP_INTER
) { 
5545         /* sort sets from the smallest to largest, this will improve our 
5546          * algorithm's performance */ 
5547         qsort(src
,zsetnum
,sizeof(zsetopsrc
), qsortCompareZsetopsrcByCardinality
); 
5549         /* skip going over all entries if the smallest zset is NULL or empty */ 
5550         if (src
[0].dict 
&& dictSize(src
[0].dict
) > 0) { 
5551             /* precondition: as src[0].dict is non-empty and the zsets are ordered 
5552              * from small to large, all src[i > 0].dict are non-empty too */ 
5553             di 
= dictGetIterator(src
[0].dict
); 
5554             while((de 
= dictNext(di
)) != NULL
) { 
5555                 double *score 
= zmalloc(sizeof(double)); 
5558                 for (j 
= 0; j 
< zsetnum
; j
++) { 
5559                     dictEntry 
*other 
= (j 
== 0) ? de 
: dictFind(src
[j
].dict
,dictGetEntryKey(de
)); 
5561                         *score 
= *score 
+ src
[j
].weight 
* (*(double*)dictGetEntryVal(other
)); 
5567                 /* skip entry when not present in every source dict */ 
5571                     robj 
*o 
= dictGetEntryKey(de
); 
5572                     dictAdd(dstzset
->dict
,o
,score
); 
5573                     incrRefCount(o
); /* added to dictionary */ 
5574                     zslInsert(dstzset
->zsl
,*score
,o
); 
5575                     incrRefCount(o
); /* added to skiplist */ 
5578             dictReleaseIterator(di
); 
5580     } else if (op 
== REDIS_OP_UNION
) { 
5581         for (i 
= 0; i 
< zsetnum
; i
++) { 
5582             if (!src
[i
].dict
) continue; 
5584             di 
= dictGetIterator(src
[i
].dict
); 
5585             while((de 
= dictNext(di
)) != NULL
) { 
5586                 /* skip key when already processed */ 
5587                 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue; 
5589                 double *score 
= zmalloc(sizeof(double)); 
5591                 for (j 
= 0; j 
< zsetnum
; j
++) { 
5592                     if (!src
[j
].dict
) continue; 
5594                     dictEntry 
*other 
= (i 
== j
) ? de 
: dictFind(src
[j
].dict
,dictGetEntryKey(de
)); 
5596                         *score 
= *score 
+ src
[j
].weight 
* (*(double*)dictGetEntryVal(other
)); 
5600                 robj 
*o 
= dictGetEntryKey(de
); 
5601                 dictAdd(dstzset
->dict
,o
,score
); 
5602                 incrRefCount(o
); /* added to dictionary */ 
5603                 zslInsert(dstzset
->zsl
,*score
,o
); 
5604                 incrRefCount(o
); /* added to skiplist */ 
5606             dictReleaseIterator(di
); 
5609         /* unknown operator */ 
5610         redisAssert(op 
== REDIS_OP_INTER 
|| op 
== REDIS_OP_UNION
); 
5613     deleteKey(c
->db
,dstkey
); 
5614     dictAdd(c
->db
->dict
,dstkey
,dstobj
); 
5615     incrRefCount(dstkey
); 
5617     addReplyLong(c
, dstzset
->zsl
->length
); 
5622 static void zunionCommand(redisClient 
*c
) { 
5623     zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
); 
5626 static void zinterCommand(redisClient 
*c
) { 
5627     zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
); 
5630 static void zrangeGenericCommand(redisClient 
*c
, int reverse
) { 
5632     int start 
= atoi(c
->argv
[2]->ptr
); 
5633     int end 
= atoi(c
->argv
[3]->ptr
); 
5636     if (c
->argc 
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) { 
5638     } else if (c
->argc 
>= 5) { 
5639         addReply(c
,shared
.syntaxerr
); 
5643     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5645         addReply(c
,shared
.nullmultibulk
); 
5647         if (o
->type 
!= REDIS_ZSET
) { 
5648             addReply(c
,shared
.wrongtypeerr
); 
5650             zset 
*zsetobj 
= o
->ptr
; 
5651             zskiplist 
*zsl 
= zsetobj
->zsl
; 
5654             int llen 
= zsl
->length
; 
5658             /* convert negative indexes */ 
5659             if (start 
< 0) start 
= llen
+start
; 
5660             if (end 
< 0) end 
= llen
+end
; 
5661             if (start 
< 0) start 
= 0; 
5662             if (end 
< 0) end 
= 0; 
5664             /* indexes sanity checks */ 
5665             if (start 
> end 
|| start 
>= llen
) { 
5666                 /* Out of range start or start > end result in empty list */ 
5667                 addReply(c
,shared
.emptymultibulk
); 
5670             if (end 
>= llen
) end 
= llen
-1; 
5671             rangelen 
= (end
-start
)+1; 
5673             /* check if starting point is trivial, before searching 
5674              * the element in log(N) time */ 
5676                 ln 
= start 
== 0 ? zsl
->tail 
: zslGetElementByRank(zsl
, llen
-start
); 
5678                 ln 
= start 
== 0 ? zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1); 
5681             /* Return the result in form of a multi-bulk reply */ 
5682             addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n", 
5683                 withscores 
? (rangelen
*2) : rangelen
)); 
5684             for (j 
= 0; j 
< rangelen
; j
++) { 
5686                 addReplyBulkLen(c
,ele
); 
5688                 addReply(c
,shared
.crlf
); 
5690                     addReplyDouble(c
,ln
->score
); 
5691                 ln 
= reverse 
? ln
->backward 
: ln
->forward
[0]; 
5697 static void zrangeCommand(redisClient 
*c
) { 
5698     zrangeGenericCommand(c
,0); 
5701 static void zrevrangeCommand(redisClient 
*c
) { 
5702     zrangeGenericCommand(c
,1); 
5705 /* This command implements both ZRANGEBYSCORE and ZCOUNT. 
5706  * If justcount is non-zero, just the count is returned. */ 
5707 static void genericZrangebyscoreCommand(redisClient 
*c
, int justcount
) { 
5710     int minex 
= 0, maxex 
= 0; /* are min or max exclusive? */ 
5711     int offset 
= 0, limit 
= -1; 
5715     /* Parse the min-max interval. If one of the values is prefixed 
5716      * by the "(" character, it's considered "open". For instance 
5717      * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max 
5718      * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */ 
5719     if (((char*)c
->argv
[2]->ptr
)[0] == '(') { 
5720         min 
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
); 
5723         min 
= strtod(c
->argv
[2]->ptr
,NULL
); 
5725     if (((char*)c
->argv
[3]->ptr
)[0] == '(') { 
5726         max 
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
); 
5729         max 
= strtod(c
->argv
[3]->ptr
,NULL
); 
5732     /* Parse "WITHSCORES": note that if the command was called with 
5733      * the name ZCOUNT then we are sure that c->argc == 4, so we'll never 
5734      * enter the following paths to parse WITHSCORES and LIMIT. */ 
5735     if (c
->argc 
== 5 || c
->argc 
== 8) { 
5736         if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0) 
5741     if (c
->argc 
!= (4 + withscores
) && c
->argc 
!= (7 + withscores
)) 
5745             sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n")); 
5750     if (c
->argc 
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) { 
5751         addReply(c
,shared
.syntaxerr
); 
5753     } else if (c
->argc 
== (7 + withscores
)) { 
5754         offset 
= atoi(c
->argv
[5]->ptr
); 
5755         limit 
= atoi(c
->argv
[6]->ptr
); 
5756         if (offset 
< 0) offset 
= 0; 
5759     /* Ok, lookup the key and get the range */ 
5760     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5762         addReply(c
,justcount 
? shared
.czero 
: shared
.nullmultibulk
); 
5764         if (o
->type 
!= REDIS_ZSET
) { 
5765             addReply(c
,shared
.wrongtypeerr
); 
5767             zset 
*zsetobj 
= o
->ptr
; 
5768             zskiplist 
*zsl 
= zsetobj
->zsl
; 
5770             robj 
*ele
, *lenobj 
= NULL
; 
5771             unsigned long rangelen 
= 0; 
5773             /* Get the first node with the score >= min, or with 
5774              * score > min if 'minex' is true. */ 
5775             ln 
= zslFirstWithScore(zsl
,min
); 
5776             while (minex 
&& ln 
&& ln
->score 
== min
) ln 
= ln
->forward
[0]; 
5779                 /* No element matching the speciifed interval */ 
5780                 addReply(c
,justcount 
? shared
.czero 
: shared
.emptymultibulk
); 
5784             /* We don't know in advance how many matching elements there 
5785              * are in the list, so we push this object that will represent 
5786              * the multi-bulk length in the output buffer, and will "fix" 
5789                 lenobj 
= createObject(REDIS_STRING
,NULL
); 
5791                 decrRefCount(lenobj
); 
5794             while(ln 
&& (maxex 
? (ln
->score 
< max
) : (ln
->score 
<= max
))) { 
5797                     ln 
= ln
->forward
[0]; 
5800                 if (limit 
== 0) break; 
5803                     addReplyBulkLen(c
,ele
); 
5805                     addReply(c
,shared
.crlf
); 
5807                         addReplyDouble(c
,ln
->score
); 
5809                 ln 
= ln
->forward
[0]; 
5811                 if (limit 
> 0) limit
--; 
5814                 addReplyLong(c
,(long)rangelen
); 
5816                 lenobj
->ptr 
= sdscatprintf(sdsempty(),"*%lu\r\n", 
5817                      withscores 
? (rangelen
*2) : rangelen
); 
5823 static void zrangebyscoreCommand(redisClient 
*c
) { 
5824     genericZrangebyscoreCommand(c
,0); 
5827 static void zcountCommand(redisClient 
*c
) { 
5828     genericZrangebyscoreCommand(c
,1); 
5831 static void zcardCommand(redisClient 
*c
) { 
5835     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5837         addReply(c
,shared
.czero
); 
5840         if (o
->type 
!= REDIS_ZSET
) { 
5841             addReply(c
,shared
.wrongtypeerr
); 
5844             addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
)); 
5849 static void zscoreCommand(redisClient 
*c
) { 
5853     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5855         addReply(c
,shared
.nullbulk
); 
5858         if (o
->type 
!= REDIS_ZSET
) { 
5859             addReply(c
,shared
.wrongtypeerr
); 
5864             de 
= dictFind(zs
->dict
,c
->argv
[2]); 
5866                 addReply(c
,shared
.nullbulk
); 
5868                 double *score 
= dictGetEntryVal(de
); 
5870                 addReplyDouble(c
,*score
); 
5876 static void zrankGenericCommand(redisClient 
*c
, int reverse
) { 
5878     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5880         addReply(c
,shared
.nullbulk
); 
5883     if (o
->type 
!= REDIS_ZSET
) { 
5884         addReply(c
,shared
.wrongtypeerr
); 
5887         zskiplist 
*zsl 
= zs
->zsl
; 
5891         de 
= dictFind(zs
->dict
,c
->argv
[2]); 
5893             addReply(c
,shared
.nullbulk
); 
5897         double *score 
= dictGetEntryVal(de
); 
5898         rank 
= zslGetRank(zsl
, *score
, c
->argv
[2]); 
5901                 addReplyLong(c
, zsl
->length 
- rank
); 
5903                 addReplyLong(c
, rank
-1); 
5906             addReply(c
,shared
.nullbulk
); 
5911 static void zrankCommand(redisClient 
*c
) { 
5912     zrankGenericCommand(c
, 0); 
5915 static void zrevrankCommand(redisClient 
*c
) { 
5916     zrankGenericCommand(c
, 1); 
5919 /* =================================== Hashes =============================== */ 
5920 static void hsetCommand(redisClient 
*c
) { 
5922     robj 
*o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
5925         o 
= createHashObject(); 
5926         dictAdd(c
->db
->dict
,c
->argv
[1],o
); 
5927         incrRefCount(c
->argv
[1]); 
5929         if (o
->type 
!= REDIS_HASH
) { 
5930             addReply(c
,shared
.wrongtypeerr
); 
5934     if (o
->encoding 
== REDIS_ENCODING_ZIPMAP
) { 
5935         unsigned char *zm 
= o
->ptr
; 
5936         robj 
*valobj 
= getDecodedObject(c
->argv
[3]); 
5938         zm 
= zipmapSet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
), 
5939             valobj
->ptr
,sdslen(valobj
->ptr
),&update
); 
5940         decrRefCount(valobj
); 
5943         if (dictAdd(o
->ptr
,c
->argv
[2],c
->argv
[3]) == DICT_OK
) { 
5944             incrRefCount(c
->argv
[2]); 
5948         incrRefCount(c
->argv
[3]); 
5951     addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",update 
== 0)); 
5954 static void hgetCommand(redisClient 
*c
) { 
5955     robj 
*o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
5958         addReply(c
,shared
.nullbulk
); 
5961         if (o
->type 
!= REDIS_HASH
) { 
5962             addReply(c
,shared
.wrongtypeerr
); 
5966         if (o
->encoding 
== REDIS_ENCODING_ZIPMAP
) { 
5967             unsigned char *zm 
= o
->ptr
; 
5971             if (zipmapGet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
), &val
,&vlen
)) { 
5972                 addReplySds(c
,sdscatprintf(sdsempty(),"$%u\r\n", vlen
)); 
5973                 addReplySds(c
,sdsnewlen(val
,vlen
)); 
5974                 addReply(c
,shared
.crlf
); 
5977                 addReply(c
,shared
.nullbulk
); 
5981             struct dictEntry 
*de
; 
5983             de 
= dictFind(o
->ptr
,c
->argv
[2]); 
5985                 addReply(c
,shared
.nullbulk
); 
5987                 robj 
*e 
= dictGetEntryVal(de
); 
5989                 addReplyBulkLen(c
,e
); 
5991                 addReply(c
,shared
.crlf
); 
5997 static void convertToRealHash(robj 
*o
) { 
5998     unsigned char *key
, *val
, *p
, *zm 
= o
->ptr
; 
5999     unsigned int klen
, vlen
; 
6000     dict 
*dict 
= dictCreate(&hashDictType
,NULL
); 
6002     assert(o
->type 
== REDIS_HASH 
&& o
->encoding 
!= REDIS_ENCODING_HT
); 
6003     p 
= zipmapRewind(zm
); 
6004     while((p 
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) { 
6005         robj 
*keyobj
, *valobj
; 
6007         keyobj 
= createStringObject((char*)key
,klen
); 
6008         valobj 
= createStringObject((char*)val
,vlen
); 
6009         tryObjectEncoding(keyobj
); 
6010         tryObjectEncoding(valobj
); 
6011         dictAdd(dict
,keyobj
,valobj
); 
6013     o
->encoding 
= REDIS_ENCODING_HT
; 
6018 /* ========================= Non type-specific commands  ==================== */ 
6020 static void flushdbCommand(redisClient 
*c
) { 
6021     server
.dirty 
+= dictSize(c
->db
->dict
); 
6022     dictEmpty(c
->db
->dict
); 
6023     dictEmpty(c
->db
->expires
); 
6024     addReply(c
,shared
.ok
); 
6027 static void flushallCommand(redisClient 
*c
) { 
6028     server
.dirty 
+= emptyDb(); 
6029     addReply(c
,shared
.ok
); 
6030     rdbSave(server
.dbfilename
); 
6034 static redisSortOperation 
*createSortOperation(int type
, robj 
*pattern
) { 
6035     redisSortOperation 
*so 
= zmalloc(sizeof(*so
)); 
6037     so
->pattern 
= pattern
; 
6041 /* Return the value associated to the key with a name obtained 
6042  * substituting the first occurence of '*' in 'pattern' with 'subst' */ 
6043 static robj 
*lookupKeyByPattern(redisDb 
*db
, robj 
*pattern
, robj 
*subst
) { 
6047     int prefixlen
, sublen
, postfixlen
; 
6048     /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */ 
6052         char buf
[REDIS_SORTKEY_MAX
+1]; 
6055     /* If the pattern is "#" return the substitution object itself in order 
6056      * to implement the "SORT ... GET #" feature. */ 
6057     spat 
= pattern
->ptr
; 
6058     if (spat
[0] == '#' && spat
[1] == '\0') { 
6062     /* The substitution object may be specially encoded. If so we create 
6063      * a decoded object on the fly. Otherwise getDecodedObject will just 
6064      * increment the ref count, that we'll decrement later. */ 
6065     subst 
= getDecodedObject(subst
); 
6068     if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
; 
6069     p 
= strchr(spat
,'*'); 
6071         decrRefCount(subst
); 
6076     sublen 
= sdslen(ssub
); 
6077     postfixlen 
= sdslen(spat
)-(prefixlen
+1); 
6078     memcpy(keyname
.buf
,spat
,prefixlen
); 
6079     memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
); 
6080     memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
); 
6081     keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0'; 
6082     keyname
.len 
= prefixlen
+sublen
+postfixlen
; 
6084     initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2)) 
6085     decrRefCount(subst
); 
6087     /* printf("lookup '%s' => %p\n", keyname.buf,de); */ 
6088     return lookupKeyRead(db
,&keyobj
); 
6091 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with 
6092  * the additional parameter is not standard but a BSD-specific we have to 
6093  * pass sorting parameters via the global 'server' structure */ 
6094 static int sortCompare(const void *s1
, const void *s2
) { 
6095     const redisSortObject 
*so1 
= s1
, *so2 
= s2
; 
6098     if (!server
.sort_alpha
) { 
6099         /* Numeric sorting. Here it's trivial as we precomputed scores */ 
6100         if (so1
->u
.score 
> so2
->u
.score
) { 
6102         } else if (so1
->u
.score 
< so2
->u
.score
) { 
6108         /* Alphanumeric sorting */ 
6109         if (server
.sort_bypattern
) { 
6110             if (!so1
->u
.cmpobj 
|| !so2
->u
.cmpobj
) { 
6111                 /* At least one compare object is NULL */ 
6112                 if (so1
->u
.cmpobj 
== so2
->u
.cmpobj
) 
6114                 else if (so1
->u
.cmpobj 
== NULL
) 
6119                 /* We have both the objects, use strcoll */ 
6120                 cmp 
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
); 
6123             /* Compare elements directly */ 
6126             dec1 
= getDecodedObject(so1
->obj
); 
6127             dec2 
= getDecodedObject(so2
->obj
); 
6128             cmp 
= strcoll(dec1
->ptr
,dec2
->ptr
); 
6133     return server
.sort_desc 
? -cmp 
: cmp
; 
6136 /* The SORT command is the most complex command in Redis. Warning: this code 
6137  * is optimized for speed and a bit less for readability */ 
6138 static void sortCommand(redisClient 
*c
) { 
6141     int desc 
= 0, alpha 
= 0; 
6142     int limit_start 
= 0, limit_count 
= -1, start
, end
; 
6143     int j
, dontsort 
= 0, vectorlen
; 
6144     int getop 
= 0; /* GET operation counter */ 
6145     robj 
*sortval
, *sortby 
= NULL
, *storekey 
= NULL
; 
6146     redisSortObject 
*vector
; /* Resulting vector to sort */ 
6148     /* Lookup the key to sort. It must be of the right types */ 
6149     sortval 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
6150     if (sortval 
== NULL
) { 
6151         addReply(c
,shared
.nullmultibulk
); 
6154     if (sortval
->type 
!= REDIS_SET 
&& sortval
->type 
!= REDIS_LIST 
&& 
6155         sortval
->type 
!= REDIS_ZSET
) 
6157         addReply(c
,shared
.wrongtypeerr
); 
6161     /* Create a list of operations to perform for every sorted element. 
6162      * Operations can be GET/DEL/INCR/DECR */ 
6163     operations 
= listCreate(); 
6164     listSetFreeMethod(operations
,zfree
); 
6167     /* Now we need to protect sortval incrementing its count, in the future 
6168      * SORT may have options able to overwrite/delete keys during the sorting 
6169      * and the sorted key itself may get destroied */ 
6170     incrRefCount(sortval
); 
6172     /* The SORT command has an SQL-alike syntax, parse it */ 
6173     while(j 
< c
->argc
) { 
6174         int leftargs 
= c
->argc
-j
-1; 
6175         if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) { 
6177         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) { 
6179         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) { 
6181         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs 
>= 2) { 
6182             limit_start 
= atoi(c
->argv
[j
+1]->ptr
); 
6183             limit_count 
= atoi(c
->argv
[j
+2]->ptr
); 
6185         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs 
>= 1) { 
6186             storekey 
= c
->argv
[j
+1]; 
6188         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs 
>= 1) { 
6189             sortby 
= c
->argv
[j
+1]; 
6190             /* If the BY pattern does not contain '*', i.e. it is constant, 
6191              * we don't need to sort nor to lookup the weight keys. */ 
6192             if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort 
= 1; 
6194         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs 
>= 1) { 
6195             listAddNodeTail(operations
,createSortOperation( 
6196                 REDIS_SORT_GET
,c
->argv
[j
+1])); 
6200             decrRefCount(sortval
); 
6201             listRelease(operations
); 
6202             addReply(c
,shared
.syntaxerr
); 
6208     /* Load the sorting vector with all the objects to sort */ 
6209     switch(sortval
->type
) { 
6210     case REDIS_LIST
: vectorlen 
= listLength((list
*)sortval
->ptr
); break; 
6211     case REDIS_SET
: vectorlen 
=  dictSize((dict
*)sortval
->ptr
); break; 
6212     case REDIS_ZSET
: vectorlen 
= dictSize(((zset
*)sortval
->ptr
)->dict
); break; 
6213     default: vectorlen 
= 0; redisAssert(0); /* Avoid GCC warning */ 
6215     vector 
= zmalloc(sizeof(redisSortObject
)*vectorlen
); 
6218     if (sortval
->type 
== REDIS_LIST
) { 
6219         list 
*list 
= sortval
->ptr
; 
6223         listRewind(list
,&li
); 
6224         while((ln 
= listNext(&li
))) { 
6225             robj 
*ele 
= ln
->value
; 
6226             vector
[j
].obj 
= ele
; 
6227             vector
[j
].u
.score 
= 0; 
6228             vector
[j
].u
.cmpobj 
= NULL
; 
6236         if (sortval
->type 
== REDIS_SET
) { 
6239             zset 
*zs 
= sortval
->ptr
; 
6243         di 
= dictGetIterator(set
); 
6244         while((setele 
= dictNext(di
)) != NULL
) { 
6245             vector
[j
].obj 
= dictGetEntryKey(setele
); 
6246             vector
[j
].u
.score 
= 0; 
6247             vector
[j
].u
.cmpobj 
= NULL
; 
6250         dictReleaseIterator(di
); 
6252     redisAssert(j 
== vectorlen
); 
6254     /* Now it's time to load the right scores in the sorting vector */ 
6255     if (dontsort 
== 0) { 
6256         for (j 
= 0; j 
< vectorlen
; j
++) { 
6260                 byval 
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
); 
6261                 if (!byval 
|| byval
->type 
!= REDIS_STRING
) continue; 
6263                     vector
[j
].u
.cmpobj 
= getDecodedObject(byval
); 
6265                     if (byval
->encoding 
== REDIS_ENCODING_RAW
) { 
6266                         vector
[j
].u
.score 
= strtod(byval
->ptr
,NULL
); 
6268                         /* Don't need to decode the object if it's 
6269                          * integer-encoded (the only encoding supported) so 
6270                          * far. We can just cast it */ 
6271                         if (byval
->encoding 
== REDIS_ENCODING_INT
) { 
6272                             vector
[j
].u
.score 
= (long)byval
->ptr
; 
6274                             redisAssert(1 != 1); 
6279                     if (vector
[j
].obj
->encoding 
== REDIS_ENCODING_RAW
) 
6280                         vector
[j
].u
.score 
= strtod(vector
[j
].obj
->ptr
,NULL
); 
6282                         if (vector
[j
].obj
->encoding 
== REDIS_ENCODING_INT
) 
6283                             vector
[j
].u
.score 
= (long) vector
[j
].obj
->ptr
; 
6285                             redisAssert(1 != 1); 
6292     /* We are ready to sort the vector... perform a bit of sanity check 
6293      * on the LIMIT option too. We'll use a partial version of quicksort. */ 
6294     start 
= (limit_start 
< 0) ? 0 : limit_start
; 
6295     end 
= (limit_count 
< 0) ? vectorlen
-1 : start
+limit_count
-1; 
6296     if (start 
>= vectorlen
) { 
6297         start 
= vectorlen
-1; 
6300     if (end 
>= vectorlen
) end 
= vectorlen
-1; 
6302     if (dontsort 
== 0) { 
6303         server
.sort_desc 
= desc
; 
6304         server
.sort_alpha 
= alpha
; 
6305         server
.sort_bypattern 
= sortby 
? 1 : 0; 
6306         if (sortby 
&& (start 
!= 0 || end 
!= vectorlen
-1)) 
6307             pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
); 
6309             qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
); 
6312     /* Send command output to the output buffer, performing the specified 
6313      * GET/DEL/INCR/DECR operations if any. */ 
6314     outputlen 
= getop 
? getop
*(end
-start
+1) : end
-start
+1; 
6315     if (storekey 
== NULL
) { 
6316         /* STORE option not specified, sent the sorting result to client */ 
6317         addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
)); 
6318         for (j 
= start
; j 
<= end
; j
++) { 
6323                 addReplyBulkLen(c
,vector
[j
].obj
); 
6324                 addReply(c
,vector
[j
].obj
); 
6325                 addReply(c
,shared
.crlf
); 
6327             listRewind(operations
,&li
); 
6328             while((ln 
= listNext(&li
))) { 
6329                 redisSortOperation 
*sop 
= ln
->value
; 
6330                 robj 
*val 
= lookupKeyByPattern(c
->db
,sop
->pattern
, 
6333                 if (sop
->type 
== REDIS_SORT_GET
) { 
6334                     if (!val 
|| val
->type 
!= REDIS_STRING
) { 
6335                         addReply(c
,shared
.nullbulk
); 
6337                         addReplyBulkLen(c
,val
); 
6339                         addReply(c
,shared
.crlf
); 
6342                     redisAssert(sop
->type 
== REDIS_SORT_GET
); /* always fails */ 
6347         robj 
*listObject 
= createListObject(); 
6348         list 
*listPtr 
= (list
*) listObject
->ptr
; 
6350         /* STORE option specified, set the sorting result as a List object */ 
6351         for (j 
= start
; j 
<= end
; j
++) { 
6356                 listAddNodeTail(listPtr
,vector
[j
].obj
); 
6357                 incrRefCount(vector
[j
].obj
); 
6359             listRewind(operations
,&li
); 
6360             while((ln 
= listNext(&li
))) { 
6361                 redisSortOperation 
*sop 
= ln
->value
; 
6362                 robj 
*val 
= lookupKeyByPattern(c
->db
,sop
->pattern
, 
6365                 if (sop
->type 
== REDIS_SORT_GET
) { 
6366                     if (!val 
|| val
->type 
!= REDIS_STRING
) { 
6367                         listAddNodeTail(listPtr
,createStringObject("",0)); 
6369                         listAddNodeTail(listPtr
,val
); 
6373                     redisAssert(sop
->type 
== REDIS_SORT_GET
); /* always fails */ 
6377         if (dictReplace(c
->db
->dict
,storekey
,listObject
)) { 
6378             incrRefCount(storekey
); 
6380         /* Note: we add 1 because the DB is dirty anyway since even if the 
6381          * SORT result is empty a new key is set and maybe the old content 
6383         server
.dirty 
+= 1+outputlen
; 
6384         addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
)); 
6388     decrRefCount(sortval
); 
6389     listRelease(operations
); 
6390     for (j 
= 0; j 
< vectorlen
; j
++) { 
6391         if (sortby 
&& alpha 
&& vector
[j
].u
.cmpobj
) 
6392             decrRefCount(vector
[j
].u
.cmpobj
); 
6397 /* Convert an amount of bytes into a human readable string in the form 
6398  * of 100B, 2G, 100M, 4K, and so forth. */ 
6399 static void bytesToHuman(char *s
, unsigned long long n
) { 
6404         sprintf(s
,"%lluB",n
); 
6406     } else if (n 
< (1024*1024)) { 
6407         d 
= (double)n
/(1024); 
6408         sprintf(s
,"%.2fK",d
); 
6409     } else if (n 
< (1024LL*1024*1024)) { 
6410         d 
= (double)n
/(1024*1024); 
6411         sprintf(s
,"%.2fM",d
); 
6412     } else if (n 
< (1024LL*1024*1024*1024)) { 
6413         d 
= (double)n
/(1024LL*1024*1024); 
6414         sprintf(s
,"%.2fG",d
); 
6418 /* Create the string returned by the INFO command. This is decoupled 
6419  * by the INFO command itself as we need to report the same information 
6420  * on memory corruption problems. */ 
6421 static sds 
genRedisInfoString(void) { 
6423     time_t uptime 
= time(NULL
)-server
.stat_starttime
; 
6427     bytesToHuman(hmem
,zmalloc_used_memory()); 
6428     info 
= sdscatprintf(sdsempty(), 
6429         "redis_version:%s\r\n" 
6431         "multiplexing_api:%s\r\n" 
6432         "process_id:%ld\r\n" 
6433         "uptime_in_seconds:%ld\r\n" 
6434         "uptime_in_days:%ld\r\n" 
6435         "connected_clients:%d\r\n" 
6436         "connected_slaves:%d\r\n" 
6437         "blocked_clients:%d\r\n" 
6438         "used_memory:%zu\r\n" 
6439         "used_memory_human:%s\r\n" 
6440         "changes_since_last_save:%lld\r\n" 
6441         "bgsave_in_progress:%d\r\n" 
6442         "last_save_time:%ld\r\n" 
6443         "bgrewriteaof_in_progress:%d\r\n" 
6444         "total_connections_received:%lld\r\n" 
6445         "total_commands_processed:%lld\r\n" 
6449         (sizeof(long) == 8) ? "64" : "32", 
6454         listLength(server
.clients
)-listLength(server
.slaves
), 
6455         listLength(server
.slaves
), 
6456         server
.blpop_blocked_clients
, 
6457         zmalloc_used_memory(), 
6460         server
.bgsavechildpid 
!= -1, 
6462         server
.bgrewritechildpid 
!= -1, 
6463         server
.stat_numconnections
, 
6464         server
.stat_numcommands
, 
6465         server
.vm_enabled 
!= 0, 
6466         server
.masterhost 
== NULL 
? "master" : "slave" 
6468     if (server
.masterhost
) { 
6469         info 
= sdscatprintf(info
, 
6470             "master_host:%s\r\n" 
6471             "master_port:%d\r\n" 
6472             "master_link_status:%s\r\n" 
6473             "master_last_io_seconds_ago:%d\r\n" 
6476             (server
.replstate 
== REDIS_REPL_CONNECTED
) ? 
6478             server
.master 
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1 
6481     if (server
.vm_enabled
) { 
6483         info 
= sdscatprintf(info
, 
6484             "vm_conf_max_memory:%llu\r\n" 
6485             "vm_conf_page_size:%llu\r\n" 
6486             "vm_conf_pages:%llu\r\n" 
6487             "vm_stats_used_pages:%llu\r\n" 
6488             "vm_stats_swapped_objects:%llu\r\n" 
6489             "vm_stats_swappin_count:%llu\r\n" 
6490             "vm_stats_swappout_count:%llu\r\n" 
6491             "vm_stats_io_newjobs_len:%lu\r\n" 
6492             "vm_stats_io_processing_len:%lu\r\n" 
6493             "vm_stats_io_processed_len:%lu\r\n" 
6494             "vm_stats_io_active_threads:%lu\r\n" 
6495             "vm_stats_blocked_clients:%lu\r\n" 
6496             ,(unsigned long long) server
.vm_max_memory
, 
6497             (unsigned long long) server
.vm_page_size
, 
6498             (unsigned long long) server
.vm_pages
, 
6499             (unsigned long long) server
.vm_stats_used_pages
, 
6500             (unsigned long long) server
.vm_stats_swapped_objects
, 
6501             (unsigned long long) server
.vm_stats_swapins
, 
6502             (unsigned long long) server
.vm_stats_swapouts
, 
6503             (unsigned long) listLength(server
.io_newjobs
), 
6504             (unsigned long) listLength(server
.io_processing
), 
6505             (unsigned long) listLength(server
.io_processed
), 
6506             (unsigned long) server
.io_active_threads
, 
6507             (unsigned long) server
.vm_blocked_clients
 
6511     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
6512         long long keys
, vkeys
; 
6514         keys 
= dictSize(server
.db
[j
].dict
); 
6515         vkeys 
= dictSize(server
.db
[j
].expires
); 
6516         if (keys 
|| vkeys
) { 
6517             info 
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n", 
6524 static void infoCommand(redisClient 
*c
) { 
6525     sds info 
= genRedisInfoString(); 
6526     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n", 
6527         (unsigned long)sdslen(info
))); 
6528     addReplySds(c
,info
); 
6529     addReply(c
,shared
.crlf
); 
6532 static void monitorCommand(redisClient 
*c
) { 
6533     /* ignore MONITOR if aleady slave or in monitor mode */ 
6534     if (c
->flags 
& REDIS_SLAVE
) return; 
6536     c
->flags 
|= (REDIS_SLAVE
|REDIS_MONITOR
); 
6538     listAddNodeTail(server
.monitors
,c
); 
6539     addReply(c
,shared
.ok
); 
6542 /* ================================= Expire ================================= */ 
6543 static int removeExpire(redisDb 
*db
, robj 
*key
) { 
6544     if (dictDelete(db
->expires
,key
) == DICT_OK
) { 
6551 static int setExpire(redisDb 
*db
, robj 
*key
, time_t when
) { 
6552     if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) { 
6560 /* Return the expire time of the specified key, or -1 if no expire 
6561  * is associated with this key (i.e. the key is non volatile) */ 
6562 static time_t getExpire(redisDb 
*db
, robj 
*key
) { 
6565     /* No expire? return ASAP */ 
6566     if (dictSize(db
->expires
) == 0 || 
6567        (de 
= dictFind(db
->expires
,key
)) == NULL
) return -1; 
6569     return (time_t) dictGetEntryVal(de
); 
6572 static int expireIfNeeded(redisDb 
*db
, robj 
*key
) { 
6576     /* No expire? return ASAP */ 
6577     if (dictSize(db
->expires
) == 0 || 
6578        (de 
= dictFind(db
->expires
,key
)) == NULL
) return 0; 
6580     /* Lookup the expire */ 
6581     when 
= (time_t) dictGetEntryVal(de
); 
6582     if (time(NULL
) <= when
) return 0; 
6584     /* Delete the key */ 
6585     dictDelete(db
->expires
,key
); 
6586     return dictDelete(db
->dict
,key
) == DICT_OK
; 
6589 static int deleteIfVolatile(redisDb 
*db
, robj 
*key
) { 
6592     /* No expire? return ASAP */ 
6593     if (dictSize(db
->expires
) == 0 || 
6594        (de 
= dictFind(db
->expires
,key
)) == NULL
) return 0; 
6596     /* Delete the key */ 
6598     dictDelete(db
->expires
,key
); 
6599     return dictDelete(db
->dict
,key
) == DICT_OK
; 
6602 static void expireGenericCommand(redisClient 
*c
, robj 
*key
, time_t seconds
) { 
6605     de 
= dictFind(c
->db
->dict
,key
); 
6607         addReply(c
,shared
.czero
); 
6611         if (deleteKey(c
->db
,key
)) server
.dirty
++; 
6612         addReply(c
, shared
.cone
); 
6615         time_t when 
= time(NULL
)+seconds
; 
6616         if (setExpire(c
->db
,key
,when
)) { 
6617             addReply(c
,shared
.cone
); 
6620             addReply(c
,shared
.czero
); 
6626 static void expireCommand(redisClient 
*c
) { 
6627     expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)); 
6630 static void expireatCommand(redisClient 
*c
) { 
6631     expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
)); 
6634 static void ttlCommand(redisClient 
*c
) { 
6638     expire 
= getExpire(c
->db
,c
->argv
[1]); 
6640         ttl 
= (int) (expire
-time(NULL
)); 
6641         if (ttl 
< 0) ttl 
= -1; 
6643     addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
)); 
6646 /* ================================ MULTI/EXEC ============================== */ 
6648 /* Client state initialization for MULTI/EXEC */ 
6649 static void initClientMultiState(redisClient 
*c
) { 
6650     c
->mstate
.commands 
= NULL
; 
6651     c
->mstate
.count 
= 0; 
6654 /* Release all the resources associated with MULTI/EXEC state */ 
6655 static void freeClientMultiState(redisClient 
*c
) { 
6658     for (j 
= 0; j 
< c
->mstate
.count
; j
++) { 
6660         multiCmd 
*mc 
= c
->mstate
.commands
+j
; 
6662         for (i 
= 0; i 
< mc
->argc
; i
++) 
6663             decrRefCount(mc
->argv
[i
]); 
6666     zfree(c
->mstate
.commands
); 
6669 /* Add a new command into the MULTI commands queue */ 
6670 static void queueMultiCommand(redisClient 
*c
, struct redisCommand 
*cmd
) { 
6674     c
->mstate
.commands 
= zrealloc(c
->mstate
.commands
, 
6675             sizeof(multiCmd
)*(c
->mstate
.count
+1)); 
6676     mc 
= c
->mstate
.commands
+c
->mstate
.count
; 
6679     mc
->argv 
= zmalloc(sizeof(robj
*)*c
->argc
); 
6680     memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
); 
6681     for (j 
= 0; j 
< c
->argc
; j
++) 
6682         incrRefCount(mc
->argv
[j
]); 
6686 static void multiCommand(redisClient 
*c
) { 
6687     c
->flags 
|= REDIS_MULTI
; 
6688     addReply(c
,shared
.ok
); 
6691 static void discardCommand(redisClient 
*c
) { 
6692     if (!(c
->flags 
& REDIS_MULTI
)) { 
6693         addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n")); 
6697     freeClientMultiState(c
); 
6698     initClientMultiState(c
); 
6699     c
->flags 
&= (~REDIS_MULTI
); 
6700     addReply(c
,shared
.ok
); 
6703 static void execCommand(redisClient 
*c
) { 
6708     if (!(c
->flags 
& REDIS_MULTI
)) { 
6709         addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n")); 
6713     orig_argv 
= c
->argv
; 
6714     orig_argc 
= c
->argc
; 
6715     addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
)); 
6716     for (j 
= 0; j 
< c
->mstate
.count
; j
++) { 
6717         c
->argc 
= c
->mstate
.commands
[j
].argc
; 
6718         c
->argv 
= c
->mstate
.commands
[j
].argv
; 
6719         call(c
,c
->mstate
.commands
[j
].cmd
); 
6721     c
->argv 
= orig_argv
; 
6722     c
->argc 
= orig_argc
; 
6723     freeClientMultiState(c
); 
6724     initClientMultiState(c
); 
6725     c
->flags 
&= (~REDIS_MULTI
); 
6728 /* =========================== Blocking Operations  ========================= */ 
6730 /* Currently Redis blocking operations support is limited to list POP ops, 
6731  * so the current implementation is not fully generic, but it is also not 
6732  * completely specific so it will not require a rewrite to support new 
6733  * kind of blocking operations in the future. 
6735  * Still it's important to note that list blocking operations can be already 
6736  * used as a notification mechanism in order to implement other blocking 
6737  * operations at application level, so there must be a very strong evidence 
6738  * of usefulness and generality before new blocking operations are implemented. 
6740  * This is how the current blocking POP works, we use BLPOP as example: 
6741  * - If the user calls BLPOP and the key exists and contains a non empty list 
6742  *   then LPOP is called instead. So BLPOP is semantically the same as LPOP 
6743  *   if there is not to block. 
6744  * - If instead BLPOP is called and the key does not exists or the list is 
6745  *   empty we need to block. In order to do so we remove the notification for 
6746  *   new data to read in the client socket (so that we'll not serve new 
6747  *   requests if the blocking request is not served). Also we put the client 
6748  *   in a dictionary (db->blockingkeys) mapping keys to a list of clients 
6749  *   blocking for this keys. 
6750  * - If a PUSH operation against a key with blocked clients waiting is 
6751  *   performed, we serve the first in the list: basically instead to push 
6752  *   the new element inside the list we return it to the (first / oldest) 
6753  *   blocking client, unblock the client, and remove it form the list. 
6755  * The above comment and the source code should be enough in order to understand 
6756  * the implementation and modify / fix it later. 
6759 /* Set a client in blocking mode for the specified key, with the specified 
6761 static void blockForKeys(redisClient 
*c
, robj 
**keys
, int numkeys
, time_t timeout
) { 
6766     c
->blockingkeys 
= zmalloc(sizeof(robj
*)*numkeys
); 
6767     c
->blockingkeysnum 
= numkeys
; 
6768     c
->blockingto 
= timeout
; 
6769     for (j 
= 0; j 
< numkeys
; j
++) { 
6770         /* Add the key in the client structure, to map clients -> keys */ 
6771         c
->blockingkeys
[j
] = keys
[j
]; 
6772         incrRefCount(keys
[j
]); 
6774         /* And in the other "side", to map keys -> clients */ 
6775         de 
= dictFind(c
->db
->blockingkeys
,keys
[j
]); 
6779             /* For every key we take a list of clients blocked for it */ 
6781             retval 
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
); 
6782             incrRefCount(keys
[j
]); 
6783             assert(retval 
== DICT_OK
); 
6785             l 
= dictGetEntryVal(de
); 
6787         listAddNodeTail(l
,c
); 
6789     /* Mark the client as a blocked client */ 
6790     c
->flags 
|= REDIS_BLOCKED
; 
6791     server
.blpop_blocked_clients
++; 
6794 /* Unblock a client that's waiting in a blocking operation such as BLPOP */ 
6795 static void unblockClientWaitingData(redisClient 
*c
) { 
6800     assert(c
->blockingkeys 
!= NULL
); 
6801     /* The client may wait for multiple keys, so unblock it for every key. */ 
6802     for (j 
= 0; j 
< c
->blockingkeysnum
; j
++) { 
6803         /* Remove this client from the list of clients waiting for this key. */ 
6804         de 
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]); 
6806         l 
= dictGetEntryVal(de
); 
6807         listDelNode(l
,listSearchKey(l
,c
)); 
6808         /* If the list is empty we need to remove it to avoid wasting memory */ 
6809         if (listLength(l
) == 0) 
6810             dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]); 
6811         decrRefCount(c
->blockingkeys
[j
]); 
6813     /* Cleanup the client structure */ 
6814     zfree(c
->blockingkeys
); 
6815     c
->blockingkeys 
= NULL
; 
6816     c
->flags 
&= (~REDIS_BLOCKED
); 
6817     server
.blpop_blocked_clients
--; 
6818     /* We want to process data if there is some command waiting 
6819      * in the input buffer. Note that this is safe even if 
6820      * unblockClientWaitingData() gets called from freeClient() because 
6821      * freeClient() will be smart enough to call this function 
6822      * *after* c->querybuf was set to NULL. */ 
6823     if (c
->querybuf 
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
); 
6826 /* This should be called from any function PUSHing into lists. 
6827  * 'c' is the "pushing client", 'key' is the key it is pushing data against, 
6828  * 'ele' is the element pushed. 
6830  * If the function returns 0 there was no client waiting for a list push 
6833  * If the function returns 1 there was a client waiting for a list push 
6834  * against this key, the element was passed to this client thus it's not 
6835  * needed to actually add it to the list and the caller should return asap. */ 
6836 static int handleClientsWaitingListPush(redisClient 
*c
, robj 
*key
, robj 
*ele
) { 
6837     struct dictEntry 
*de
; 
6838     redisClient 
*receiver
; 
6842     de 
= dictFind(c
->db
->blockingkeys
,key
); 
6843     if (de 
== NULL
) return 0; 
6844     l 
= dictGetEntryVal(de
); 
6847     receiver 
= ln
->value
; 
6849     addReplySds(receiver
,sdsnew("*2\r\n")); 
6850     addReplyBulkLen(receiver
,key
); 
6851     addReply(receiver
,key
); 
6852     addReply(receiver
,shared
.crlf
); 
6853     addReplyBulkLen(receiver
,ele
); 
6854     addReply(receiver
,ele
); 
6855     addReply(receiver
,shared
.crlf
); 
6856     unblockClientWaitingData(receiver
); 
6860 /* Blocking RPOP/LPOP */ 
6861 static void blockingPopGenericCommand(redisClient 
*c
, int where
) { 
6866     for (j 
= 1; j 
< c
->argc
-1; j
++) { 
6867         o 
= lookupKeyWrite(c
->db
,c
->argv
[j
]); 
6869             if (o
->type 
!= REDIS_LIST
) { 
6870                 addReply(c
,shared
.wrongtypeerr
); 
6873                 list 
*list 
= o
->ptr
; 
6874                 if (listLength(list
) != 0) { 
6875                     /* If the list contains elements fall back to the usual 
6876                      * non-blocking POP operation */ 
6877                     robj 
*argv
[2], **orig_argv
; 
6880                     /* We need to alter the command arguments before to call 
6881                      * popGenericCommand() as the command takes a single key. */ 
6882                     orig_argv 
= c
->argv
; 
6883                     orig_argc 
= c
->argc
; 
6884                     argv
[1] = c
->argv
[j
]; 
6888                     /* Also the return value is different, we need to output 
6889                      * the multi bulk reply header and the key name. The 
6890                      * "real" command will add the last element (the value) 
6891                      * for us. If this souds like an hack to you it's just 
6892                      * because it is... */ 
6893                     addReplySds(c
,sdsnew("*2\r\n")); 
6894                     addReplyBulkLen(c
,argv
[1]); 
6895                     addReply(c
,argv
[1]); 
6896                     addReply(c
,shared
.crlf
); 
6897                     popGenericCommand(c
,where
); 
6899                     /* Fix the client structure with the original stuff */ 
6900                     c
->argv 
= orig_argv
; 
6901                     c
->argc 
= orig_argc
; 
6907     /* If the list is empty or the key does not exists we must block */ 
6908     timeout 
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10); 
6909     if (timeout 
> 0) timeout 
+= time(NULL
); 
6910     blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
); 
6913 static void blpopCommand(redisClient 
*c
) { 
6914     blockingPopGenericCommand(c
,REDIS_HEAD
); 
6917 static void brpopCommand(redisClient 
*c
) { 
6918     blockingPopGenericCommand(c
,REDIS_TAIL
); 
6921 /* =============================== Replication  ============================= */ 
6923 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
6924     ssize_t nwritten
, ret 
= size
; 
6925     time_t start 
= time(NULL
); 
6929         if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) { 
6930             nwritten 
= write(fd
,ptr
,size
); 
6931             if (nwritten 
== -1) return -1; 
6935         if ((time(NULL
)-start
) > timeout
) { 
6943 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
6944     ssize_t nread
, totread 
= 0; 
6945     time_t start 
= time(NULL
); 
6949         if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) { 
6950             nread 
= read(fd
,ptr
,size
); 
6951             if (nread 
== -1) return -1; 
6956         if ((time(NULL
)-start
) > timeout
) { 
6964 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
6971         if (syncRead(fd
,&c
,1,timeout
) == -1) return -1; 
6974             if (nread 
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0'; 
6985 static void syncCommand(redisClient 
*c
) { 
6986     /* ignore SYNC if aleady slave or in monitor mode */ 
6987     if (c
->flags 
& REDIS_SLAVE
) return; 
6989     /* SYNC can't be issued when the server has pending data to send to 
6990      * the client about already issued commands. We need a fresh reply 
6991      * buffer registering the differences between the BGSAVE and the current 
6992      * dataset, so that we can copy to other slaves if needed. */ 
6993     if (listLength(c
->reply
) != 0) { 
6994         addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n")); 
6998     redisLog(REDIS_NOTICE
,"Slave ask for synchronization"); 
6999     /* Here we need to check if there is a background saving operation 
7000      * in progress, or if it is required to start one */ 
7001     if (server
.bgsavechildpid 
!= -1) { 
7002         /* Ok a background save is in progress. Let's check if it is a good 
7003          * one for replication, i.e. if there is another slave that is 
7004          * registering differences since the server forked to save */ 
7009         listRewind(server
.slaves
,&li
); 
7010         while((ln 
= listNext(&li
))) { 
7012             if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_END
) break; 
7015             /* Perfect, the server is already registering differences for 
7016              * another slave. Set the right state, and copy the buffer. */ 
7017             listRelease(c
->reply
); 
7018             c
->reply 
= listDup(slave
->reply
); 
7019             c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
7020             redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC"); 
7022             /* No way, we need to wait for the next BGSAVE in order to 
7023              * register differences */ 
7024             c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_START
; 
7025             redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC"); 
7028         /* Ok we don't have a BGSAVE in progress, let's start one */ 
7029         redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC"); 
7030         if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) { 
7031             redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE"); 
7032             addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n")); 
7035         c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
7038     c
->flags 
|= REDIS_SLAVE
; 
7040     listAddNodeTail(server
.slaves
,c
); 
7044 static void sendBulkToSlave(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
7045     redisClient 
*slave 
= privdata
; 
7047     REDIS_NOTUSED(mask
); 
7048     char buf
[REDIS_IOBUF_LEN
]; 
7049     ssize_t nwritten
, buflen
; 
7051     if (slave
->repldboff 
== 0) { 
7052         /* Write the bulk write count before to transfer the DB. In theory here 
7053          * we don't know how much room there is in the output buffer of the 
7054          * socket, but in pratice SO_SNDLOWAT (the minimum count for output 
7055          * operations) will never be smaller than the few bytes we need. */ 
7058         bulkcount 
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long) 
7060         if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
)) 
7068     lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
); 
7069     buflen 
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
); 
7071         redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s", 
7072             (buflen 
== 0) ? "premature EOF" : strerror(errno
)); 
7076     if ((nwritten 
= write(fd
,buf
,buflen
)) == -1) { 
7077         redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s", 
7082     slave
->repldboff 
+= nwritten
; 
7083     if (slave
->repldboff 
== slave
->repldbsize
) { 
7084         close(slave
->repldbfd
); 
7085         slave
->repldbfd 
= -1; 
7086         aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
); 
7087         slave
->replstate 
= REDIS_REPL_ONLINE
; 
7088         if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, 
7089             sendReplyToClient
, slave
) == AE_ERR
) { 
7093         addReplySds(slave
,sdsempty()); 
7094         redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded"); 
7098 /* This function is called at the end of every backgrond saving. 
7099  * The argument bgsaveerr is REDIS_OK if the background saving succeeded 
7100  * otherwise REDIS_ERR is passed to the function. 
7102  * The goal of this function is to handle slaves waiting for a successful 
7103  * background saving in order to perform non-blocking synchronization. */ 
7104 static void updateSlavesWaitingBgsave(int bgsaveerr
) { 
7106     int startbgsave 
= 0; 
7109     listRewind(server
.slaves
,&li
); 
7110     while((ln 
= listNext(&li
))) { 
7111         redisClient 
*slave 
= ln
->value
; 
7113         if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) { 
7115             slave
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
7116         } else if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_END
) { 
7117             struct redis_stat buf
; 
7119             if (bgsaveerr 
!= REDIS_OK
) { 
7121                 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error"); 
7124             if ((slave
->repldbfd 
= open(server
.dbfilename
,O_RDONLY
)) == -1 || 
7125                 redis_fstat(slave
->repldbfd
,&buf
) == -1) { 
7127                 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
)); 
7130             slave
->repldboff 
= 0; 
7131             slave
->repldbsize 
= buf
.st_size
; 
7132             slave
->replstate 
= REDIS_REPL_SEND_BULK
; 
7133             aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
); 
7134             if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) { 
7141         if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) { 
7144             listRewind(server
.slaves
,&li
); 
7145             redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed"); 
7146             while((ln 
= listNext(&li
))) { 
7147                 redisClient 
*slave 
= ln
->value
; 
7149                 if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) 
7156 static int syncWithMaster(void) { 
7157     char buf
[1024], tmpfile
[256], authcmd
[1024]; 
7159     int fd 
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
); 
7160     int dfd
, maxtries 
= 5; 
7163         redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s", 
7168     /* AUTH with the master if required. */ 
7169     if(server
.masterauth
) { 
7170         snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
); 
7171         if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) { 
7173             redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s", 
7177         /* Read the AUTH result.  */ 
7178         if (syncReadLine(fd
,buf
,1024,3600) == -1) { 
7180             redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s", 
7184         if (buf
[0] != '+') { 
7186             redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?"); 
7191     /* Issue the SYNC command */ 
7192     if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) { 
7194         redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s", 
7198     /* Read the bulk write count */ 
7199     if (syncReadLine(fd
,buf
,1024,3600) == -1) { 
7201         redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s", 
7205     if (buf
[0] != '$') { 
7207         redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?"); 
7210     dumpsize 
= strtol(buf
+1,NULL
,10); 
7211     redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
); 
7212     /* Read the bulk write data on a temp file */ 
7214         snprintf(tmpfile
,256, 
7215             "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid()); 
7216         dfd 
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644); 
7217         if (dfd 
!= -1) break; 
7221         redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
)); 
7225         int nread
, nwritten
; 
7227         nread 
= read(fd
,buf
,(dumpsize 
< 1024)?dumpsize
:1024); 
7229             redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s", 
7235         nwritten 
= write(dfd
,buf
,nread
); 
7236         if (nwritten 
== -1) { 
7237             redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
)); 
7245     if (rename(tmpfile
,server
.dbfilename
) == -1) { 
7246         redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
)); 
7252     if (rdbLoad(server
.dbfilename
) != REDIS_OK
) { 
7253         redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk"); 
7257     server
.master 
= createClient(fd
); 
7258     server
.master
->flags 
|= REDIS_MASTER
; 
7259     server
.master
->authenticated 
= 1; 
7260     server
.replstate 
= REDIS_REPL_CONNECTED
; 
7264 static void slaveofCommand(redisClient 
*c
) { 
7265     if (!strcasecmp(c
->argv
[1]->ptr
,"no") && 
7266         !strcasecmp(c
->argv
[2]->ptr
,"one")) { 
7267         if (server
.masterhost
) { 
7268             sdsfree(server
.masterhost
); 
7269             server
.masterhost 
= NULL
; 
7270             if (server
.master
) freeClient(server
.master
); 
7271             server
.replstate 
= REDIS_REPL_NONE
; 
7272             redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)"); 
7275         sdsfree(server
.masterhost
); 
7276         server
.masterhost 
= sdsdup(c
->argv
[1]->ptr
); 
7277         server
.masterport 
= atoi(c
->argv
[2]->ptr
); 
7278         if (server
.master
) freeClient(server
.master
); 
7279         server
.replstate 
= REDIS_REPL_CONNECT
; 
7280         redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)", 
7281             server
.masterhost
, server
.masterport
); 
7283     addReply(c
,shared
.ok
); 
7286 /* ============================ Maxmemory directive  ======================== */ 
7288 /* Try to free one object form the pre-allocated objects free list. 
7289  * This is useful under low mem conditions as by default we take 1 million 
7290  * free objects allocated. On success REDIS_OK is returned, otherwise 
7292 static int tryFreeOneObjectFromFreelist(void) { 
7295     if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
); 
7296     if (listLength(server
.objfreelist
)) { 
7297         listNode 
*head 
= listFirst(server
.objfreelist
); 
7298         o 
= listNodeValue(head
); 
7299         listDelNode(server
.objfreelist
,head
); 
7300         if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
7304         if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
); 
7309 /* This function gets called when 'maxmemory' is set on the config file to limit 
7310  * the max memory used by the server, and we are out of memory. 
7311  * This function will try to, in order: 
7313  * - Free objects from the free list 
7314  * - Try to remove keys with an EXPIRE set 
7316  * It is not possible to free enough memory to reach used-memory < maxmemory 
7317  * the server will start refusing commands that will enlarge even more the 
7320 static void freeMemoryIfNeeded(void) { 
7321     while (server
.maxmemory 
&& zmalloc_used_memory() > server
.maxmemory
) { 
7322         int j
, k
, freed 
= 0; 
7324         if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue; 
7325         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
7327             robj 
*minkey 
= NULL
; 
7328             struct dictEntry 
*de
; 
7330             if (dictSize(server
.db
[j
].expires
)) { 
7332                 /* From a sample of three keys drop the one nearest to 
7333                  * the natural expire */ 
7334                 for (k 
= 0; k 
< 3; k
++) { 
7337                     de 
= dictGetRandomKey(server
.db
[j
].expires
); 
7338                     t 
= (time_t) dictGetEntryVal(de
); 
7339                     if (minttl 
== -1 || t 
< minttl
) { 
7340                         minkey 
= dictGetEntryKey(de
); 
7344                 deleteKey(server
.db
+j
,minkey
); 
7347         if (!freed
) return; /* nothing to free... */ 
7351 /* ============================== Append Only file ========================== */ 
7353 static void feedAppendOnlyFile(struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
) { 
7354     sds buf 
= sdsempty(); 
7360     /* The DB this command was targetting is not the same as the last command 
7361      * we appendend. To issue a SELECT command is needed. */ 
7362     if (dictid 
!= server
.appendseldb
) { 
7365         snprintf(seldb
,sizeof(seldb
),"%d",dictid
); 
7366         buf 
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n", 
7367             (unsigned long)strlen(seldb
),seldb
); 
7368         server
.appendseldb 
= dictid
; 
7371     /* "Fix" the argv vector if the command is EXPIRE. We want to translate 
7372      * EXPIREs into EXPIREATs calls */ 
7373     if (cmd
->proc 
== expireCommand
) { 
7376         tmpargv
[0] = createStringObject("EXPIREAT",8); 
7377         tmpargv
[1] = argv
[1]; 
7378         incrRefCount(argv
[1]); 
7379         when 
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10); 
7380         tmpargv
[2] = createObject(REDIS_STRING
, 
7381             sdscatprintf(sdsempty(),"%ld",when
)); 
7385     /* Append the actual command */ 
7386     buf 
= sdscatprintf(buf
,"*%d\r\n",argc
); 
7387     for (j 
= 0; j 
< argc
; j
++) { 
7390         o 
= getDecodedObject(o
); 
7391         buf 
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
)); 
7392         buf 
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
)); 
7393         buf 
= sdscatlen(buf
,"\r\n",2); 
7397     /* Free the objects from the modified argv for EXPIREAT */ 
7398     if (cmd
->proc 
== expireCommand
) { 
7399         for (j 
= 0; j 
< 3; j
++) 
7400             decrRefCount(argv
[j
]); 
7403     /* We want to perform a single write. This should be guaranteed atomic 
7404      * at least if the filesystem we are writing is a real physical one. 
7405      * While this will save us against the server being killed I don't think 
7406      * there is much to do about the whole server stopping for power problems 
7408      nwritten 
= write(server
.appendfd
,buf
,sdslen(buf
)); 
7409      if (nwritten 
!= (signed)sdslen(buf
)) { 
7410         /* Ooops, we are in troubles. The best thing to do for now is 
7411          * to simply exit instead to give the illusion that everything is 
7412          * working as expected. */ 
7413          if (nwritten 
== -1) { 
7414             redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
)); 
7416             redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
)); 
7420     /* If a background append only file rewriting is in progress we want to 
7421      * accumulate the differences between the child DB and the current one 
7422      * in a buffer, so that when the child process will do its work we 
7423      * can append the differences to the new append only file. */ 
7424     if (server
.bgrewritechildpid 
!= -1) 
7425         server
.bgrewritebuf 
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
)); 
7429     if (server
.appendfsync 
== APPENDFSYNC_ALWAYS 
|| 
7430         (server
.appendfsync 
== APPENDFSYNC_EVERYSEC 
&& 
7431          now
-server
.lastfsync 
> 1)) 
7433         fsync(server
.appendfd
); /* Let's try to get this data on the disk */ 
7434         server
.lastfsync 
= now
; 
7438 /* In Redis commands are always executed in the context of a client, so in 
7439  * order to load the append only file we need to create a fake client. */ 
7440 static struct redisClient 
*createFakeClient(void) { 
7441     struct redisClient 
*c 
= zmalloc(sizeof(*c
)); 
7445     c
->querybuf 
= sdsempty(); 
7449     /* We set the fake client as a slave waiting for the synchronization 
7450      * so that Redis will not try to send replies to this client. */ 
7451     c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_START
; 
7452     c
->reply 
= listCreate(); 
7453     listSetFreeMethod(c
->reply
,decrRefCount
); 
7454     listSetDupMethod(c
->reply
,dupClientReplyValue
); 
7458 static void freeFakeClient(struct redisClient 
*c
) { 
7459     sdsfree(c
->querybuf
); 
7460     listRelease(c
->reply
); 
7464 /* Replay the append log file. On error REDIS_OK is returned. On non fatal 
7465  * error (the append only file is zero-length) REDIS_ERR is returned. On 
7466  * fatal error an error message is logged and the program exists. */ 
7467 int loadAppendOnlyFile(char *filename
) { 
7468     struct redisClient 
*fakeClient
; 
7469     FILE *fp 
= fopen(filename
,"r"); 
7470     struct redis_stat sb
; 
7471     unsigned long long loadedkeys 
= 0; 
7473     if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size 
== 0) 
7477         redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
)); 
7481     fakeClient 
= createFakeClient(); 
7488         struct redisCommand 
*cmd
; 
7490         if (fgets(buf
,sizeof(buf
),fp
) == NULL
) { 
7496         if (buf
[0] != '*') goto fmterr
; 
7498         argv 
= zmalloc(sizeof(robj
*)*argc
); 
7499         for (j 
= 0; j 
< argc
; j
++) { 
7500             if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
; 
7501             if (buf
[0] != '$') goto fmterr
; 
7502             len 
= strtol(buf
+1,NULL
,10); 
7503             argsds 
= sdsnewlen(NULL
,len
); 
7504             if (len 
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
; 
7505             argv
[j
] = createObject(REDIS_STRING
,argsds
); 
7506             if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */ 
7509         /* Command lookup */ 
7510         cmd 
= lookupCommand(argv
[0]->ptr
); 
7512             redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
); 
7515         /* Try object sharing and encoding */ 
7516         if (server
.shareobjects
) { 
7518             for(j 
= 1; j 
< argc
; j
++) 
7519                 argv
[j
] = tryObjectSharing(argv
[j
]); 
7521         if (cmd
->flags 
& REDIS_CMD_BULK
) 
7522             tryObjectEncoding(argv
[argc
-1]); 
7523         /* Run the command in the context of a fake client */ 
7524         fakeClient
->argc 
= argc
; 
7525         fakeClient
->argv 
= argv
; 
7526         cmd
->proc(fakeClient
); 
7527         /* Discard the reply objects list from the fake client */ 
7528         while(listLength(fakeClient
->reply
)) 
7529             listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
)); 
7530         /* Clean up, ready for the next command */ 
7531         for (j 
= 0; j 
< argc
; j
++) decrRefCount(argv
[j
]); 
7533         /* Handle swapping while loading big datasets when VM is on */ 
7535         if (server
.vm_enabled 
&& (loadedkeys 
% 5000) == 0) { 
7536             while (zmalloc_used_memory() > server
.vm_max_memory
) { 
7537                 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break; 
7542     freeFakeClient(fakeClient
); 
7547         redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file"); 
7549         redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
)); 
7553     redisLog(REDIS_WARNING
,"Bad file format reading the append only file"); 
7557 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */ 
7558 static int fwriteBulk(FILE *fp
, robj 
*obj
) { 
7562     /* Avoid the incr/decr ref count business if possible to help 
7563      * copy-on-write (we are often in a child process when this function 
7565      * Also makes sure that key objects don't get incrRefCount-ed when VM 
7567     if (obj
->encoding 
!= REDIS_ENCODING_RAW
) { 
7568         obj 
= getDecodedObject(obj
); 
7571     snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
)); 
7572     if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
; 
7573     if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0) 
7575     if (fwrite("\r\n",2,1,fp
) == 0) goto err
; 
7576     if (decrrc
) decrRefCount(obj
); 
7579     if (decrrc
) decrRefCount(obj
); 
7583 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */ 
7584 static int fwriteBulkDouble(FILE *fp
, double d
) { 
7585     char buf
[128], dbuf
[128]; 
7587     snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
); 
7588     snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2); 
7589     if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0; 
7590     if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0; 
7594 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */ 
7595 static int fwriteBulkLong(FILE *fp
, long l
) { 
7596     char buf
[128], lbuf
[128]; 
7598     snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
); 
7599     snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2); 
7600     if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0; 
7601     if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0; 
7605 /* Write a sequence of commands able to fully rebuild the dataset into 
7606  * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */ 
7607 static int rewriteAppendOnlyFile(char *filename
) { 
7608     dictIterator 
*di 
= NULL
; 
7613     time_t now 
= time(NULL
); 
7615     /* Note that we have to use a different temp name here compared to the 
7616      * one used by rewriteAppendOnlyFileBackground() function. */ 
7617     snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid()); 
7618     fp 
= fopen(tmpfile
,"w"); 
7620         redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
)); 
7623     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
7624         char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n"; 
7625         redisDb 
*db 
= server
.db
+j
; 
7627         if (dictSize(d
) == 0) continue; 
7628         di 
= dictGetIterator(d
); 
7634         /* SELECT the new DB */ 
7635         if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
; 
7636         if (fwriteBulkLong(fp
,j
) == 0) goto werr
; 
7638         /* Iterate this DB writing every entry */ 
7639         while((de 
= dictNext(di
)) != NULL
) { 
7644             key 
= dictGetEntryKey(de
); 
7645             /* If the value for this key is swapped, load a preview in memory. 
7646              * We use a "swapped" flag to remember if we need to free the 
7647              * value object instead to just increment the ref count anyway 
7648              * in order to avoid copy-on-write of pages if we are forked() */ 
7649             if (!server
.vm_enabled 
|| key
->storage 
== REDIS_VM_MEMORY 
|| 
7650                 key
->storage 
== REDIS_VM_SWAPPING
) { 
7651                 o 
= dictGetEntryVal(de
); 
7654                 o 
= vmPreviewObject(key
); 
7657             expiretime 
= getExpire(db
,key
); 
7659             /* Save the key and associated value */ 
7660             if (o
->type 
== REDIS_STRING
) { 
7661                 /* Emit a SET command */ 
7662                 char cmd
[]="*3\r\n$3\r\nSET\r\n"; 
7663                 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
; 
7665                 if (fwriteBulk(fp
,key
) == 0) goto werr
; 
7666                 if (fwriteBulk(fp
,o
) == 0) goto werr
; 
7667             } else if (o
->type 
== REDIS_LIST
) { 
7668                 /* Emit the RPUSHes needed to rebuild the list */ 
7669                 list 
*list 
= o
->ptr
; 
7673                 listRewind(list
,&li
); 
7674                 while((ln 
= listNext(&li
))) { 
7675                     char cmd
[]="*3\r\n$5\r\nRPUSH\r\n"; 
7676                     robj 
*eleobj 
= listNodeValue(ln
); 
7678                     if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
; 
7679                     if (fwriteBulk(fp
,key
) == 0) goto werr
; 
7680                     if (fwriteBulk(fp
,eleobj
) == 0) goto werr
; 
7682             } else if (o
->type 
== REDIS_SET
) { 
7683                 /* Emit the SADDs needed to rebuild the set */ 
7685                 dictIterator 
*di 
= dictGetIterator(set
); 
7688                 while((de 
= dictNext(di
)) != NULL
) { 
7689                     char cmd
[]="*3\r\n$4\r\nSADD\r\n"; 
7690                     robj 
*eleobj 
= dictGetEntryKey(de
); 
7692                     if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
; 
7693                     if (fwriteBulk(fp
,key
) == 0) goto werr
; 
7694                     if (fwriteBulk(fp
,eleobj
) == 0) goto werr
; 
7696                 dictReleaseIterator(di
); 
7697             } else if (o
->type 
== REDIS_ZSET
) { 
7698                 /* Emit the ZADDs needed to rebuild the sorted set */ 
7700                 dictIterator 
*di 
= dictGetIterator(zs
->dict
); 
7703                 while((de 
= dictNext(di
)) != NULL
) { 
7704                     char cmd
[]="*4\r\n$4\r\nZADD\r\n"; 
7705                     robj 
*eleobj 
= dictGetEntryKey(de
); 
7706                     double *score 
= dictGetEntryVal(de
); 
7708                     if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
; 
7709                     if (fwriteBulk(fp
,key
) == 0) goto werr
; 
7710                     if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
; 
7711                     if (fwriteBulk(fp
,eleobj
) == 0) goto werr
; 
7713                 dictReleaseIterator(di
); 
7715                 redisAssert(0 != 0); 
7717             /* Save the expire time */ 
7718             if (expiretime 
!= -1) { 
7719                 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n"; 
7720                 /* If this key is already expired skip it */ 
7721                 if (expiretime 
< now
) continue; 
7722                 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
; 
7723                 if (fwriteBulk(fp
,key
) == 0) goto werr
; 
7724                 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
; 
7726             if (swapped
) decrRefCount(o
); 
7728         dictReleaseIterator(di
); 
7731     /* Make sure data will not remain on the OS's output buffers */ 
7736     /* Use RENAME to make sure the DB file is changed atomically only 
7737      * if the generate DB file is ok. */ 
7738     if (rename(tmpfile
,filename
) == -1) { 
7739         redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
)); 
7743     redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed"); 
7749     redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
)); 
7750     if (di
) dictReleaseIterator(di
); 
7754 /* This is how rewriting of the append only file in background works: 
7756  * 1) The user calls BGREWRITEAOF 
7757  * 2) Redis calls this function, that forks(): 
7758  *    2a) the child rewrite the append only file in a temp file. 
7759  *    2b) the parent accumulates differences in server.bgrewritebuf. 
7760  * 3) When the child finished '2a' exists. 
7761  * 4) The parent will trap the exit code, if it's OK, will append the 
7762  *    data accumulated into server.bgrewritebuf into the temp file, and 
7763  *    finally will rename(2) the temp file in the actual file name. 
7764  *    The the new file is reopened as the new append only file. Profit! 
7766 static int rewriteAppendOnlyFileBackground(void) { 
7769     if (server
.bgrewritechildpid 
!= -1) return REDIS_ERR
; 
7770     if (server
.vm_enabled
) waitEmptyIOJobsQueue(); 
7771     if ((childpid 
= fork()) == 0) { 
7775         if (server
.vm_enabled
) vmReopenSwapFile(); 
7777         snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid()); 
7778         if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) { 
7785         if (childpid 
== -1) { 
7786             redisLog(REDIS_WARNING
, 
7787                 "Can't rewrite append only file in background: fork: %s", 
7791         redisLog(REDIS_NOTICE
, 
7792             "Background append only file rewriting started by pid %d",childpid
); 
7793         server
.bgrewritechildpid 
= childpid
; 
7794         /* We set appendseldb to -1 in order to force the next call to the 
7795          * feedAppendOnlyFile() to issue a SELECT command, so the differences 
7796          * accumulated by the parent into server.bgrewritebuf will start 
7797          * with a SELECT statement and it will be safe to merge. */ 
7798         server
.appendseldb 
= -1; 
7801     return REDIS_OK
; /* unreached */ 
7804 static void bgrewriteaofCommand(redisClient 
*c
) { 
7805     if (server
.bgrewritechildpid 
!= -1) { 
7806         addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n")); 
7809     if (rewriteAppendOnlyFileBackground() == REDIS_OK
) { 
7810         char *status 
= "+Background append only file rewriting started\r\n"; 
7811         addReplySds(c
,sdsnew(status
)); 
7813         addReply(c
,shared
.err
); 
7817 static void aofRemoveTempFile(pid_t childpid
) { 
7820     snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
); 
7824 /* Virtual Memory is composed mainly of two subsystems: 
7825  * - Blocking Virutal Memory 
7826  * - Threaded Virtual Memory I/O 
7827  * The two parts are not fully decoupled, but functions are split among two 
7828  * different sections of the source code (delimited by comments) in order to 
7829  * make more clear what functionality is about the blocking VM and what about 
7830  * the threaded (not blocking) VM. 
7834  * Redis VM is a blocking VM (one that blocks reading swapped values from 
7835  * disk into memory when a value swapped out is needed in memory) that is made 
7836  * unblocking by trying to examine the command argument vector in order to 
7837  * load in background values that will likely be needed in order to exec 
7838  * the command. The command is executed only once all the relevant keys 
7839  * are loaded into memory. 
7841  * This basically is almost as simple of a blocking VM, but almost as parallel 
7842  * as a fully non-blocking VM. 
7845 /* =================== Virtual Memory - Blocking Side  ====================== */ 
7847 /* substitute the first occurrence of '%p' with the process pid in the 
7848  * swap file name. */ 
7849 static void expandVmSwapFilename(void) { 
7850     char *p 
= strstr(server
.vm_swap_file
,"%p"); 
7856     new = sdscat(new,server
.vm_swap_file
); 
7857     new = sdscatprintf(new,"%ld",(long) getpid()); 
7858     new = sdscat(new,p
+2); 
7859     zfree(server
.vm_swap_file
); 
7860     server
.vm_swap_file 
= new; 
7863 static void vmInit(void) { 
7868     if (server
.vm_max_threads 
!= 0) 
7869         zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */ 
7871     expandVmSwapFilename(); 
7872     redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
); 
7873     if ((server
.vm_fp 
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) { 
7874         server
.vm_fp 
= fopen(server
.vm_swap_file
,"w+b"); 
7876     if (server
.vm_fp 
== NULL
) { 
7877         redisLog(REDIS_WARNING
, 
7878             "Impossible to open the swap file: %s. Exiting.", 
7882     server
.vm_fd 
= fileno(server
.vm_fp
); 
7883     server
.vm_next_page 
= 0; 
7884     server
.vm_near_pages 
= 0; 
7885     server
.vm_stats_used_pages 
= 0; 
7886     server
.vm_stats_swapped_objects 
= 0; 
7887     server
.vm_stats_swapouts 
= 0; 
7888     server
.vm_stats_swapins 
= 0; 
7889     totsize 
= server
.vm_pages
*server
.vm_page_size
; 
7890     redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
); 
7891     if (ftruncate(server
.vm_fd
,totsize
) == -1) { 
7892         redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.", 
7896         redisLog(REDIS_NOTICE
,"Swap file allocated with success"); 
7898     server
.vm_bitmap 
= zmalloc((server
.vm_pages
+7)/8); 
7899     redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages", 
7900         (long long) (server
.vm_pages
+7)/8, server
.vm_pages
); 
7901     memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8); 
7903     /* Initialize threaded I/O (used by Virtual Memory) */ 
7904     server
.io_newjobs 
= listCreate(); 
7905     server
.io_processing 
= listCreate(); 
7906     server
.io_processed 
= listCreate(); 
7907     server
.io_ready_clients 
= listCreate(); 
7908     pthread_mutex_init(&server
.io_mutex
,NULL
); 
7909     pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
); 
7910     pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
); 
7911     server
.io_active_threads 
= 0; 
7912     if (pipe(pipefds
) == -1) { 
7913         redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting." 
7917     server
.io_ready_pipe_read 
= pipefds
[0]; 
7918     server
.io_ready_pipe_write 
= pipefds
[1]; 
7919     redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
); 
7920     /* LZF requires a lot of stack */ 
7921     pthread_attr_init(&server
.io_threads_attr
); 
7922     pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
); 
7923     while (stacksize 
< REDIS_THREAD_STACK_SIZE
) stacksize 
*= 2; 
7924     pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
); 
7925     /* Listen for events in the threaded I/O pipe */ 
7926     if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
, 
7927         vmThreadedIOCompletedJob
, NULL
) == AE_ERR
) 
7928         oom("creating file event"); 
7931 /* Mark the page as used */ 
7932 static void vmMarkPageUsed(off_t page
) { 
7933     off_t byte 
= page
/8; 
7935     redisAssert(vmFreePage(page
) == 1); 
7936     server
.vm_bitmap
[byte
] |= 1<<bit
; 
7939 /* Mark N contiguous pages as used, with 'page' being the first. */ 
7940 static void vmMarkPagesUsed(off_t page
, off_t count
) { 
7943     for (j 
= 0; j 
< count
; j
++) 
7944         vmMarkPageUsed(page
+j
); 
7945     server
.vm_stats_used_pages 
+= count
; 
7946     redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n", 
7947         (long long)count
, (long long)page
); 
7950 /* Mark the page as free */ 
7951 static void vmMarkPageFree(off_t page
) { 
7952     off_t byte 
= page
/8; 
7954     redisAssert(vmFreePage(page
) == 0); 
7955     server
.vm_bitmap
[byte
] &= ~(1<<bit
); 
7958 /* Mark N contiguous pages as free, with 'page' being the first. */ 
7959 static void vmMarkPagesFree(off_t page
, off_t count
) { 
7962     for (j 
= 0; j 
< count
; j
++) 
7963         vmMarkPageFree(page
+j
); 
7964     server
.vm_stats_used_pages 
-= count
; 
7965     redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n", 
7966         (long long)count
, (long long)page
); 
7969 /* Test if the page is free */ 
7970 static int vmFreePage(off_t page
) { 
7971     off_t byte 
= page
/8; 
7973     return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0; 
7976 /* Find N contiguous free pages storing the first page of the cluster in *first. 
7977  * Returns REDIS_OK if it was able to find N contiguous pages, otherwise  
7978  * REDIS_ERR is returned. 
7980  * This function uses a simple algorithm: we try to allocate 
7981  * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start 
7982  * again from the start of the swap file searching for free spaces. 
7984  * If it looks pretty clear that there are no free pages near our offset 
7985  * we try to find less populated places doing a forward jump of 
7986  * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages 
7987  * without hurry, and then we jump again and so forth... 
7989  * This function can be improved using a free list to avoid to guess 
7990  * too much, since we could collect data about freed pages. 
7992  * note: I implemented this function just after watching an episode of 
7993  * Battlestar Galactica, where the hybrid was continuing to say "JUMP!" 
7995 static int vmFindContiguousPages(off_t 
*first
, off_t n
) { 
7996     off_t base
, offset 
= 0, since_jump 
= 0, numfree 
= 0; 
7998     if (server
.vm_near_pages 
== REDIS_VM_MAX_NEAR_PAGES
) { 
7999         server
.vm_near_pages 
= 0; 
8000         server
.vm_next_page 
= 0; 
8002     server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */ 
8003     base 
= server
.vm_next_page
; 
8005     while(offset 
< server
.vm_pages
) { 
8006         off_t 
this = base
+offset
; 
8008         /* If we overflow, restart from page zero */ 
8009         if (this >= server
.vm_pages
) { 
8010             this -= server
.vm_pages
; 
8012                 /* Just overflowed, what we found on tail is no longer 
8013                  * interesting, as it's no longer contiguous. */ 
8017         if (vmFreePage(this)) { 
8018             /* This is a free page */ 
8020             /* Already got N free pages? Return to the caller, with success */ 
8022                 *first 
= this-(n
-1); 
8023                 server
.vm_next_page 
= this+1; 
8024                 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
); 
8028             /* The current one is not a free page */ 
8032         /* Fast-forward if the current page is not free and we already 
8033          * searched enough near this place. */ 
8035         if (!numfree 
&& since_jump 
>= REDIS_VM_MAX_RANDOM_JUMP
/4) { 
8036             offset 
+= random() % REDIS_VM_MAX_RANDOM_JUMP
; 
8038             /* Note that even if we rewind after the jump, we are don't need 
8039              * to make sure numfree is set to zero as we only jump *if* it 
8040              * is set to zero. */ 
8042             /* Otherwise just check the next page */ 
8049 /* Write the specified object at the specified page of the swap file */ 
8050 static int vmWriteObjectOnSwap(robj 
*o
, off_t page
) { 
8051     if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
); 
8052     if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) { 
8053         if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
); 
8054         redisLog(REDIS_WARNING
, 
8055             "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s", 
8059     rdbSaveObject(server
.vm_fp
,o
); 
8060     fflush(server
.vm_fp
); 
8061     if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
); 
8065 /* Swap the 'val' object relative to 'key' into disk. Store all the information 
8066  * needed to later retrieve the object into the key object. 
8067  * If we can't find enough contiguous empty pages to swap the object on disk 
8068  * REDIS_ERR is returned. */ 
8069 static int vmSwapObjectBlocking(robj 
*key
, robj 
*val
) { 
8070     off_t pages 
= rdbSavedObjectPages(val
,NULL
); 
8073     assert(key
->storage 
== REDIS_VM_MEMORY
); 
8074     assert(key
->refcount 
== 1); 
8075     if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
; 
8076     if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
; 
8077     key
->vm
.page 
= page
; 
8078     key
->vm
.usedpages 
= pages
; 
8079     key
->storage 
= REDIS_VM_SWAPPED
; 
8080     key
->vtype 
= val
->type
; 
8081     decrRefCount(val
); /* Deallocate the object from memory. */ 
8082     vmMarkPagesUsed(page
,pages
); 
8083     redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)", 
8084         (unsigned char*) key
->ptr
, 
8085         (unsigned long long) page
, (unsigned long long) pages
); 
8086     server
.vm_stats_swapped_objects
++; 
8087     server
.vm_stats_swapouts
++; 
8091 static robj 
*vmReadObjectFromSwap(off_t page
, int type
) { 
8094     if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
); 
8095     if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) { 
8096         redisLog(REDIS_WARNING
, 
8097             "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s", 
8101     o 
= rdbLoadObject(type
,server
.vm_fp
); 
8103         redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
)); 
8106     if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
); 
8110 /* Load the value object relative to the 'key' object from swap to memory. 
8111  * The newly allocated object is returned. 
8113  * If preview is true the unserialized object is returned to the caller but 
8114  * no changes are made to the key object, nor the pages are marked as freed */ 
8115 static robj 
*vmGenericLoadObject(robj 
*key
, int preview
) { 
8118     redisAssert(key
->storage 
== REDIS_VM_SWAPPED 
|| key
->storage 
== REDIS_VM_LOADING
); 
8119     val 
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
); 
8121         key
->storage 
= REDIS_VM_MEMORY
; 
8122         key
->vm
.atime 
= server
.unixtime
; 
8123         vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
); 
8124         redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk", 
8125             (unsigned char*) key
->ptr
); 
8126         server
.vm_stats_swapped_objects
--; 
8128         redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk", 
8129             (unsigned char*) key
->ptr
); 
8131     server
.vm_stats_swapins
++; 
8135 /* Plain object loading, from swap to memory */ 
8136 static robj 
*vmLoadObject(robj 
*key
) { 
8137     /* If we are loading the object in background, stop it, we 
8138      * need to load this object synchronously ASAP. */ 
8139     if (key
->storage 
== REDIS_VM_LOADING
) 
8140         vmCancelThreadedIOJob(key
); 
8141     return vmGenericLoadObject(key
,0); 
8144 /* Just load the value on disk, without to modify the key. 
8145  * This is useful when we want to perform some operation on the value 
8146  * without to really bring it from swap to memory, like while saving the 
8147  * dataset or rewriting the append only log. */ 
8148 static robj 
*vmPreviewObject(robj 
*key
) { 
8149     return vmGenericLoadObject(key
,1); 
8152 /* How a good candidate is this object for swapping? 
8153  * The better candidate it is, the greater the returned value. 
8155  * Currently we try to perform a fast estimation of the object size in 
8156  * memory, and combine it with aging informations. 
8158  * Basically swappability = idle-time * log(estimated size) 
8160  * Bigger objects are preferred over smaller objects, but not 
8161  * proportionally, this is why we use the logarithm. This algorithm is 
8162  * just a first try and will probably be tuned later. */ 
8163 static double computeObjectSwappability(robj 
*o
) { 
8164     time_t age 
= server
.unixtime 
- o
->vm
.atime
; 
8168     struct dictEntry 
*de
; 
8171     if (age 
<= 0) return 0; 
8174         if (o
->encoding 
!= REDIS_ENCODING_RAW
) { 
8177             asize 
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2; 
8182         listNode 
*ln 
= listFirst(l
); 
8184         asize 
= sizeof(list
); 
8186             robj 
*ele 
= ln
->value
; 
8189             elesize 
= (ele
->encoding 
== REDIS_ENCODING_RAW
) ? 
8190                             (sizeof(*o
)+sdslen(ele
->ptr
)) : 
8192             asize 
+= (sizeof(listNode
)+elesize
)*listLength(l
); 
8197         z 
= (o
->type 
== REDIS_ZSET
); 
8198         d 
= z 
? ((zset
*)o
->ptr
)->dict 
: o
->ptr
; 
8200         asize 
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
)); 
8201         if (z
) asize 
+= sizeof(zset
)-sizeof(dict
); 
8206             de 
= dictGetRandomKey(d
); 
8207             ele 
= dictGetEntryKey(de
); 
8208             elesize 
= (ele
->encoding 
== REDIS_ENCODING_RAW
) ? 
8209                             (sizeof(*o
)+sdslen(ele
->ptr
)) : 
8211             asize 
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
); 
8212             if (z
) asize 
+= sizeof(zskiplistNode
)*dictSize(d
); 
8216     return (double)age
*log(1+asize
); 
8219 /* Try to swap an object that's a good candidate for swapping. 
8220  * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible 
8221  * to swap any object at all. 
8223  * If 'usethreaded' is true, Redis will try to swap the object in background 
8224  * using I/O threads. */ 
8225 static int vmSwapOneObject(int usethreads
) { 
8227     struct dictEntry 
*best 
= NULL
; 
8228     double best_swappability 
= 0; 
8229     redisDb 
*best_db 
= NULL
; 
8232     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
8233         redisDb 
*db 
= server
.db
+j
; 
8234         /* Why maxtries is set to 100? 
8235          * Because this way (usually) we'll find 1 object even if just 1% - 2% 
8236          * are swappable objects */ 
8239         if (dictSize(db
->dict
) == 0) continue; 
8240         for (i 
= 0; i 
< 5; i
++) { 
8242             double swappability
; 
8244             if (maxtries
) maxtries
--; 
8245             de 
= dictGetRandomKey(db
->dict
); 
8246             key 
= dictGetEntryKey(de
); 
8247             val 
= dictGetEntryVal(de
); 
8248             /* Only swap objects that are currently in memory. 
8250              * Also don't swap shared objects if threaded VM is on, as we 
8251              * try to ensure that the main thread does not touch the 
8252              * object while the I/O thread is using it, but we can't 
8253              * control other keys without adding additional mutex. */ 
8254             if (key
->storage 
!= REDIS_VM_MEMORY 
|| 
8255                 (server
.vm_max_threads 
!= 0 && val
->refcount 
!= 1)) { 
8256                 if (maxtries
) i
--; /* don't count this try */ 
8259             swappability 
= computeObjectSwappability(val
); 
8260             if (!best 
|| swappability 
> best_swappability
) { 
8262                 best_swappability 
= swappability
; 
8267     if (best 
== NULL
) return REDIS_ERR
; 
8268     key 
= dictGetEntryKey(best
); 
8269     val 
= dictGetEntryVal(best
); 
8271     redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f", 
8272         key
->ptr
, best_swappability
); 
8274     /* Unshare the key if needed */ 
8275     if (key
->refcount 
> 1) { 
8276         robj 
*newkey 
= dupStringObject(key
); 
8278         key 
= dictGetEntryKey(best
) = newkey
; 
8282         vmSwapObjectThreaded(key
,val
,best_db
); 
8285         if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) { 
8286             dictGetEntryVal(best
) = NULL
; 
8294 static int vmSwapOneObjectBlocking() { 
8295     return vmSwapOneObject(0); 
8298 static int vmSwapOneObjectThreaded() { 
8299     return vmSwapOneObject(1); 
8302 /* Return true if it's safe to swap out objects in a given moment. 
8303  * Basically we don't want to swap objects out while there is a BGSAVE 
8304  * or a BGAEOREWRITE running in backgroud. */ 
8305 static int vmCanSwapOut(void) { 
8306     return (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1); 
8309 /* Delete a key if swapped. Returns 1 if the key was found, was swapped 
8310  * and was deleted. Otherwise 0 is returned. */ 
8311 static int deleteIfSwapped(redisDb 
*db
, robj 
*key
) { 
8315     if ((de 
= dictFind(db
->dict
,key
)) == NULL
) return 0; 
8316     foundkey 
= dictGetEntryKey(de
); 
8317     if (foundkey
->storage 
== REDIS_VM_MEMORY
) return 0; 
8322 /* =================== Virtual Memory - Threaded I/O  ======================= */ 
8324 static void freeIOJob(iojob 
*j
) { 
8325     if ((j
->type 
== REDIS_IOJOB_PREPARE_SWAP 
|| 
8326         j
->type 
== REDIS_IOJOB_DO_SWAP 
|| 
8327         j
->type 
== REDIS_IOJOB_LOAD
) && j
->val 
!= NULL
) 
8328         decrRefCount(j
->val
); 
8329     decrRefCount(j
->key
); 
8333 /* Every time a thread finished a Job, it writes a byte into the write side 
8334  * of an unix pipe in order to "awake" the main thread, and this function 
8336 static void vmThreadedIOCompletedJob(aeEventLoop 
*el
, int fd
, void *privdata
, 
8340     int retval
, processed 
= 0, toprocess 
= -1, trytoswap 
= 1; 
8342     REDIS_NOTUSED(mask
); 
8343     REDIS_NOTUSED(privdata
); 
8345     /* For every byte we read in the read side of the pipe, there is one 
8346      * I/O job completed to process. */ 
8347     while((retval 
= read(fd
,buf
,1)) == 1) { 
8351         struct dictEntry 
*de
; 
8353         redisLog(REDIS_DEBUG
,"Processing I/O completed job"); 
8355         /* Get the processed element (the oldest one) */ 
8357         assert(listLength(server
.io_processed
) != 0); 
8358         if (toprocess 
== -1) { 
8359             toprocess 
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100; 
8360             if (toprocess 
<= 0) toprocess 
= 1; 
8362         ln 
= listFirst(server
.io_processed
); 
8364         listDelNode(server
.io_processed
,ln
); 
8366         /* If this job is marked as canceled, just ignore it */ 
8371         /* Post process it in the main thread, as there are things we 
8372          * can do just here to avoid race conditions and/or invasive locks */ 
8373         redisLog(REDIS_DEBUG
,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j
, j
->type
, (void*)j
->key
, (char*)j
->key
->ptr
, j
->key
->refcount
); 
8374         de 
= dictFind(j
->db
->dict
,j
->key
); 
8376         key 
= dictGetEntryKey(de
); 
8377         if (j
->type 
== REDIS_IOJOB_LOAD
) { 
8380             /* Key loaded, bring it at home */ 
8381             key
->storage 
= REDIS_VM_MEMORY
; 
8382             key
->vm
.atime 
= server
.unixtime
; 
8383             vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
); 
8384             redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)", 
8385                 (unsigned char*) key
->ptr
); 
8386             server
.vm_stats_swapped_objects
--; 
8387             server
.vm_stats_swapins
++; 
8388             dictGetEntryVal(de
) = j
->val
; 
8389             incrRefCount(j
->val
); 
8392             /* Handle clients waiting for this key to be loaded. */ 
8393             handleClientsBlockedOnSwappedKey(db
,key
); 
8394         } else if (j
->type 
== REDIS_IOJOB_PREPARE_SWAP
) { 
8395             /* Now we know the amount of pages required to swap this object. 
8396              * Let's find some space for it, and queue this task again 
8397              * rebranded as REDIS_IOJOB_DO_SWAP. */ 
8398             if (!vmCanSwapOut() || 
8399                 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
) 
8401                 /* Ooops... no space or we can't swap as there is 
8402                  * a fork()ed Redis trying to save stuff on disk. */ 
8404                 key
->storage 
= REDIS_VM_MEMORY
; /* undo operation */ 
8406                 /* Note that we need to mark this pages as used now, 
8407                  * if the job will be canceled, we'll mark them as freed 
8409                 vmMarkPagesUsed(j
->page
,j
->pages
); 
8410                 j
->type 
= REDIS_IOJOB_DO_SWAP
; 
8415         } else if (j
->type 
== REDIS_IOJOB_DO_SWAP
) { 
8418             /* Key swapped. We can finally free some memory. */ 
8419             if (key
->storage 
!= REDIS_VM_SWAPPING
) { 
8420                 printf("key->storage: %d\n",key
->storage
); 
8421                 printf("key->name: %s\n",(char*)key
->ptr
); 
8422                 printf("key->refcount: %d\n",key
->refcount
); 
8423                 printf("val: %p\n",(void*)j
->val
); 
8424                 printf("val->type: %d\n",j
->val
->type
); 
8425                 printf("val->ptr: %s\n",(char*)j
->val
->ptr
); 
8427             redisAssert(key
->storage 
== REDIS_VM_SWAPPING
); 
8428             val 
= dictGetEntryVal(de
); 
8429             key
->vm
.page 
= j
->page
; 
8430             key
->vm
.usedpages 
= j
->pages
; 
8431             key
->storage 
= REDIS_VM_SWAPPED
; 
8432             key
->vtype 
= j
->val
->type
; 
8433             decrRefCount(val
); /* Deallocate the object from memory. */ 
8434             dictGetEntryVal(de
) = NULL
; 
8435             redisLog(REDIS_DEBUG
, 
8436                 "VM: object %s swapped out at %lld (%lld pages) (threaded)", 
8437                 (unsigned char*) key
->ptr
, 
8438                 (unsigned long long) j
->page
, (unsigned long long) j
->pages
); 
8439             server
.vm_stats_swapped_objects
++; 
8440             server
.vm_stats_swapouts
++; 
8442             /* Put a few more swap requests in queue if we are still 
8444             if (trytoswap 
&& vmCanSwapOut() && 
8445                 zmalloc_used_memory() > server
.vm_max_memory
) 
8450                     more 
= listLength(server
.io_newjobs
) < 
8451                             (unsigned) server
.vm_max_threads
; 
8453                     /* Don't waste CPU time if swappable objects are rare. */ 
8454                     if (vmSwapOneObjectThreaded() == REDIS_ERR
) { 
8462         if (processed 
== toprocess
) return; 
8464     if (retval 
< 0 && errno 
!= EAGAIN
) { 
8465         redisLog(REDIS_WARNING
, 
8466             "WARNING: read(2) error in vmThreadedIOCompletedJob() %s", 
8471 static void lockThreadedIO(void) { 
8472     pthread_mutex_lock(&server
.io_mutex
); 
8475 static void unlockThreadedIO(void) { 
8476     pthread_mutex_unlock(&server
.io_mutex
); 
8479 /* Remove the specified object from the threaded I/O queue if still not 
8480  * processed, otherwise make sure to flag it as canceled. */ 
8481 static void vmCancelThreadedIOJob(robj 
*o
) { 
8483         server
.io_newjobs
,      /* 0 */ 
8484         server
.io_processing
,   /* 1 */ 
8485         server
.io_processed     
/* 2 */ 
8489     assert(o
->storage 
== REDIS_VM_LOADING 
|| o
->storage 
== REDIS_VM_SWAPPING
); 
8492     /* Search for a matching key in one of the queues */ 
8493     for (i 
= 0; i 
< 3; i
++) { 
8497         listRewind(lists
[i
],&li
); 
8498         while ((ln 
= listNext(&li
)) != NULL
) { 
8499             iojob 
*job 
= ln
->value
; 
8501             if (job
->canceled
) continue; /* Skip this, already canceled. */ 
8502             if (compareStringObjects(job
->key
,o
) == 0) { 
8503                 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n", 
8504                     (void*)job
, (char*)o
->ptr
, job
->type
, i
); 
8505                 /* Mark the pages as free since the swap didn't happened 
8506                  * or happened but is now discarded. */ 
8507                 if (i 
!= 1 && job
->type 
== REDIS_IOJOB_DO_SWAP
) 
8508                     vmMarkPagesFree(job
->page
,job
->pages
); 
8509                 /* Cancel the job. It depends on the list the job is 
8512                 case 0: /* io_newjobs */ 
8513                     /* If the job was yet not processed the best thing to do 
8514                      * is to remove it from the queue at all */ 
8516                     listDelNode(lists
[i
],ln
); 
8518                 case 1: /* io_processing */ 
8519                     /* Oh Shi- the thread is messing with the Job: 
8521                      * Probably it's accessing the object if this is a 
8522                      * PREPARE_SWAP or DO_SWAP job. 
8523                      * If it's a LOAD job it may be reading from disk and 
8524                      * if we don't wait for the job to terminate before to 
8525                      * cancel it, maybe in a few microseconds data can be 
8526                      * corrupted in this pages. So the short story is: 
8528                      * Better to wait for the job to move into the 
8529                      * next queue (processed)... */ 
8531                     /* We try again and again until the job is completed. */ 
8533                     /* But let's wait some time for the I/O thread 
8534                      * to finish with this job. After all this condition 
8535                      * should be very rare. */ 
8538                 case 2: /* io_processed */ 
8539                     /* The job was already processed, that's easy... 
8540                      * just mark it as canceled so that we'll ignore it 
8541                      * when processing completed jobs. */ 
8545                 /* Finally we have to adjust the storage type of the object 
8546                  * in order to "UNDO" the operaiton. */ 
8547                 if (o
->storage 
== REDIS_VM_LOADING
) 
8548                     o
->storage 
= REDIS_VM_SWAPPED
; 
8549                 else if (o
->storage 
== REDIS_VM_SWAPPING
) 
8550                     o
->storage 
= REDIS_VM_MEMORY
; 
8557     assert(1 != 1); /* We should never reach this */ 
8560 static void *IOThreadEntryPoint(void *arg
) { 
8565     pthread_detach(pthread_self()); 
8567         /* Get a new job to process */ 
8569         if (listLength(server
.io_newjobs
) == 0) { 
8570             /* No new jobs in queue, exit. */ 
8571             redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do", 
8572                 (long) pthread_self()); 
8573             server
.io_active_threads
--; 
8577         ln 
= listFirst(server
.io_newjobs
); 
8579         listDelNode(server
.io_newjobs
,ln
); 
8580         /* Add the job in the processing queue */ 
8581         j
->thread 
= pthread_self(); 
8582         listAddNodeTail(server
.io_processing
,j
); 
8583         ln 
= listLast(server
.io_processing
); /* We use ln later to remove it */ 
8585         redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'", 
8586             (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
); 
8588         /* Process the Job */ 
8589         if (j
->type 
== REDIS_IOJOB_LOAD
) { 
8590             j
->val 
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
); 
8591         } else if (j
->type 
== REDIS_IOJOB_PREPARE_SWAP
) { 
8592             FILE *fp 
= fopen("/dev/null","w+"); 
8593             j
->pages 
= rdbSavedObjectPages(j
->val
,fp
); 
8595         } else if (j
->type 
== REDIS_IOJOB_DO_SWAP
) { 
8596             if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
) 
8600         /* Done: insert the job into the processed queue */ 
8601         redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)", 
8602             (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
); 
8604         listDelNode(server
.io_processing
,ln
); 
8605         listAddNodeTail(server
.io_processed
,j
); 
8608         /* Signal the main thread there is new stuff to process */ 
8609         assert(write(server
.io_ready_pipe_write
,"x",1) == 1); 
8611     return NULL
; /* never reached */ 
8614 static void spawnIOThread(void) { 
8616     sigset_t mask
, omask
; 
8619     sigaddset(&mask
,SIGCHLD
); 
8620     sigaddset(&mask
,SIGHUP
); 
8621     sigaddset(&mask
,SIGPIPE
); 
8622     pthread_sigmask(SIG_SETMASK
, &mask
, &omask
); 
8623     pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
); 
8624     pthread_sigmask(SIG_SETMASK
, &omask
, NULL
); 
8625     server
.io_active_threads
++; 
8628 /* We need to wait for the last thread to exit before we are able to 
8629  * fork() in order to BGSAVE or BGREWRITEAOF. */ 
8630 static void waitEmptyIOJobsQueue(void) { 
8632         int io_processed_len
; 
8635         if (listLength(server
.io_newjobs
) == 0 && 
8636             listLength(server
.io_processing
) == 0 && 
8637             server
.io_active_threads 
== 0) 
8642         /* While waiting for empty jobs queue condition we post-process some 
8643          * finshed job, as I/O threads may be hanging trying to write against 
8644          * the io_ready_pipe_write FD but there are so much pending jobs that 
8646         io_processed_len 
= listLength(server
.io_processed
); 
8648         if (io_processed_len
) { 
8649             vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0); 
8650             usleep(1000); /* 1 millisecond */ 
8652             usleep(10000); /* 10 milliseconds */ 
8657 static void vmReopenSwapFile(void) { 
8658     /* Note: we don't close the old one as we are in the child process 
8659      * and don't want to mess at all with the original file object. */ 
8660     server
.vm_fp 
= fopen(server
.vm_swap_file
,"r+b"); 
8661     if (server
.vm_fp 
== NULL
) { 
8662         redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.", 
8663             server
.vm_swap_file
); 
8666     server
.vm_fd 
= fileno(server
.vm_fp
); 
8669 /* This function must be called while with threaded IO locked */ 
8670 static void queueIOJob(iojob 
*j
) { 
8671     redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n", 
8672         (void*)j
, j
->type
, (char*)j
->key
->ptr
); 
8673     listAddNodeTail(server
.io_newjobs
,j
); 
8674     if (server
.io_active_threads 
< server
.vm_max_threads
) 
8678 static int vmSwapObjectThreaded(robj 
*key
, robj 
*val
, redisDb 
*db
) { 
8681     assert(key
->storage 
== REDIS_VM_MEMORY
); 
8682     assert(key
->refcount 
== 1); 
8684     j 
= zmalloc(sizeof(*j
)); 
8685     j
->type 
= REDIS_IOJOB_PREPARE_SWAP
; 
8687     j
->key 
= dupStringObject(key
); 
8691     j
->thread 
= (pthread_t
) -1; 
8692     key
->storage 
= REDIS_VM_SWAPPING
; 
8700 /* ============ Virtual Memory - Blocking clients on missing keys =========== */ 
8702 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded. 
8703  * If there is not already a job loading the key, it is craeted. 
8704  * The key is added to the io_keys list in the client structure, and also 
8705  * in the hash table mapping swapped keys to waiting clients, that is, 
8706  * server.io_waited_keys. */ 
8707 static int waitForSwappedKey(redisClient 
*c
, robj 
*key
) { 
8708     struct dictEntry 
*de
; 
8712     /* If the key does not exist or is already in RAM we don't need to 
8713      * block the client at all. */ 
8714     de 
= dictFind(c
->db
->dict
,key
); 
8715     if (de 
== NULL
) return 0; 
8716     o 
= dictGetEntryKey(de
); 
8717     if (o
->storage 
== REDIS_VM_MEMORY
) { 
8719     } else if (o
->storage 
== REDIS_VM_SWAPPING
) { 
8720         /* We were swapping the key, undo it! */ 
8721         vmCancelThreadedIOJob(o
); 
8725     /* OK: the key is either swapped, or being loaded just now. */ 
8727     /* Add the key to the list of keys this client is waiting for. 
8728      * This maps clients to keys they are waiting for. */ 
8729     listAddNodeTail(c
->io_keys
,key
); 
8732     /* Add the client to the swapped keys => clients waiting map. */ 
8733     de 
= dictFind(c
->db
->io_keys
,key
); 
8737         /* For every key we take a list of clients blocked for it */ 
8739         retval 
= dictAdd(c
->db
->io_keys
,key
,l
); 
8741         assert(retval 
== DICT_OK
); 
8743         l 
= dictGetEntryVal(de
); 
8745     listAddNodeTail(l
,c
); 
8747     /* Are we already loading the key from disk? If not create a job */ 
8748     if (o
->storage 
== REDIS_VM_SWAPPED
) { 
8751         o
->storage 
= REDIS_VM_LOADING
; 
8752         j 
= zmalloc(sizeof(*j
)); 
8753         j
->type 
= REDIS_IOJOB_LOAD
; 
8755         j
->key 
= dupStringObject(key
); 
8756         j
->key
->vtype 
= o
->vtype
; 
8757         j
->page 
= o
->vm
.page
; 
8760         j
->thread 
= (pthread_t
) -1; 
8768 /* Is this client attempting to run a command against swapped keys? 
8769  * If so, block it ASAP, load the keys in background, then resume it. 
8771  * The important idea about this function is that it can fail! If keys will 
8772  * still be swapped when the client is resumed, this key lookups will 
8773  * just block loading keys from disk. In practical terms this should only 
8774  * happen with SORT BY command or if there is a bug in this function. 
8776  * Return 1 if the client is marked as blocked, 0 if the client can 
8777  * continue as the keys it is going to access appear to be in memory. */ 
8778 static int blockClientOnSwappedKeys(struct redisCommand 
*cmd
, redisClient 
*c
) { 
8781     if (cmd
->vm_firstkey 
== 0) return 0; 
8782     last 
= cmd
->vm_lastkey
; 
8783     if (last 
< 0) last 
= c
->argc
+last
; 
8784     for (j 
= cmd
->vm_firstkey
; j 
<= last
; j 
+= cmd
->vm_keystep
) 
8785         waitForSwappedKey(c
,c
->argv
[j
]); 
8786     /* If the client was blocked for at least one key, mark it as blocked. */ 
8787     if (listLength(c
->io_keys
)) { 
8788         c
->flags 
|= REDIS_IO_WAIT
; 
8789         aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
); 
8790         server
.vm_blocked_clients
++; 
8797 /* Remove the 'key' from the list of blocked keys for a given client. 
8799  * The function returns 1 when there are no longer blocking keys after 
8800  * the current one was removed (and the client can be unblocked). */ 
8801 static int dontWaitForSwappedKey(redisClient 
*c
, robj 
*key
) { 
8805     struct dictEntry 
*de
; 
8807     /* Remove the key from the list of keys this client is waiting for. */ 
8808     listRewind(c
->io_keys
,&li
); 
8809     while ((ln 
= listNext(&li
)) != NULL
) { 
8810         if (compareStringObjects(ln
->value
,key
) == 0) { 
8811             listDelNode(c
->io_keys
,ln
); 
8817     /* Remove the client form the key => waiting clients map. */ 
8818     de 
= dictFind(c
->db
->io_keys
,key
); 
8820     l 
= dictGetEntryVal(de
); 
8821     ln 
= listSearchKey(l
,c
); 
8824     if (listLength(l
) == 0) 
8825         dictDelete(c
->db
->io_keys
,key
); 
8827     return listLength(c
->io_keys
) == 0; 
8830 static void handleClientsBlockedOnSwappedKey(redisDb 
*db
, robj 
*key
) { 
8831     struct dictEntry 
*de
; 
8836     de 
= dictFind(db
->io_keys
,key
); 
8839     l 
= dictGetEntryVal(de
); 
8840     len 
= listLength(l
); 
8841     /* Note: we can't use something like while(listLength(l)) as the list 
8842      * can be freed by the calling function when we remove the last element. */ 
8845         redisClient 
*c 
= ln
->value
; 
8847         if (dontWaitForSwappedKey(c
,key
)) { 
8848             /* Put the client in the list of clients ready to go as we 
8849              * loaded all the keys about it. */ 
8850             listAddNodeTail(server
.io_ready_clients
,c
); 
8855 /* ================================= Debugging ============================== */ 
8857 static void debugCommand(redisClient 
*c
) { 
8858     if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) { 
8860     } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) { 
8861         if (rdbSave(server
.dbfilename
) != REDIS_OK
) { 
8862             addReply(c
,shared
.err
); 
8866         if (rdbLoad(server
.dbfilename
) != REDIS_OK
) { 
8867             addReply(c
,shared
.err
); 
8870         redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD"); 
8871         addReply(c
,shared
.ok
); 
8872     } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) { 
8874         if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) { 
8875             addReply(c
,shared
.err
); 
8878         redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF"); 
8879         addReply(c
,shared
.ok
); 
8880     } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc 
== 3) { 
8881         dictEntry 
*de 
= dictFind(c
->db
->dict
,c
->argv
[2]); 
8885             addReply(c
,shared
.nokeyerr
); 
8888         key 
= dictGetEntryKey(de
); 
8889         val 
= dictGetEntryVal(de
); 
8890         if (!server
.vm_enabled 
|| (key
->storage 
== REDIS_VM_MEMORY 
|| 
8891                                    key
->storage 
== REDIS_VM_SWAPPING
)) { 
8892             addReplySds(c
,sdscatprintf(sdsempty(), 
8893                 "+Key at:%p refcount:%d, value at:%p refcount:%d " 
8894                 "encoding:%d serializedlength:%lld\r\n", 
8895                 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
, 
8896                 val
->encoding
, (long long) rdbSavedObjectLen(val
,NULL
))); 
8898             addReplySds(c
,sdscatprintf(sdsempty(), 
8899                 "+Key at:%p refcount:%d, value swapped at: page %llu " 
8900                 "using %llu pages\r\n", 
8901                 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
, 
8902                 (unsigned long long) key
->vm
.usedpages
)); 
8904     } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc 
== 3) { 
8905         dictEntry 
*de 
= dictFind(c
->db
->dict
,c
->argv
[2]); 
8908         if (!server
.vm_enabled
) { 
8909             addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n")); 
8913             addReply(c
,shared
.nokeyerr
); 
8916         key 
= dictGetEntryKey(de
); 
8917         val 
= dictGetEntryVal(de
); 
8918         /* If the key is shared we want to create a copy */ 
8919         if (key
->refcount 
> 1) { 
8920             robj 
*newkey 
= dupStringObject(key
); 
8922             key 
= dictGetEntryKey(de
) = newkey
; 
8925         if (key
->storage 
!= REDIS_VM_MEMORY
) { 
8926             addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n")); 
8927         } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) { 
8928             dictGetEntryVal(de
) = NULL
; 
8929             addReply(c
,shared
.ok
); 
8931             addReply(c
,shared
.err
); 
8934         addReplySds(c
,sdsnew( 
8935             "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n")); 
8939 static void _redisAssert(char *estr
, char *file
, int line
) { 
8940     redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ==="); 
8941     redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
); 
8942 #ifdef HAVE_BACKTRACE 
8943     redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)"); 
8948 /* =================================== Main! ================================ */ 
8951 int linuxOvercommitMemoryValue(void) { 
8952     FILE *fp 
= fopen("/proc/sys/vm/overcommit_memory","r"); 
8956     if (fgets(buf
,64,fp
) == NULL
) { 
8965 void linuxOvercommitMemoryWarning(void) { 
8966     if (linuxOvercommitMemoryValue() == 0) { 
8967         redisLog(REDIS_WARNING
,"WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); 
8970 #endif /* __linux__ */ 
8972 static void daemonize(void) { 
8976     if (fork() != 0) exit(0); /* parent exits */ 
8977     setsid(); /* create a new session */ 
8979     /* Every output goes to /dev/null. If Redis is daemonized but 
8980      * the 'logfile' is set to 'stdout' in the configuration file 
8981      * it will not log at all. */ 
8982     if ((fd 
= open("/dev/null", O_RDWR
, 0)) != -1) { 
8983         dup2(fd
, STDIN_FILENO
); 
8984         dup2(fd
, STDOUT_FILENO
); 
8985         dup2(fd
, STDERR_FILENO
); 
8986         if (fd 
> STDERR_FILENO
) close(fd
); 
8988     /* Try to write the pid file */ 
8989     fp 
= fopen(server
.pidfile
,"w"); 
8991         fprintf(fp
,"%d\n",getpid()); 
8996 int main(int argc
, char **argv
) { 
9001         resetServerSaveParams(); 
9002         loadServerConfig(argv
[1]); 
9003     } else if (argc 
> 2) { 
9004         fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n"); 
9007         redisLog(REDIS_WARNING
,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'"); 
9009     if (server
.daemonize
) daemonize(); 
9011     redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
); 
9013     linuxOvercommitMemoryWarning(); 
9016     if (server
.appendonly
) { 
9017         if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
) 
9018             redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
); 
9020         if (rdbLoad(server
.dbfilename
) == REDIS_OK
) 
9021             redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
); 
9023     redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
); 
9024     aeSetBeforeSleepProc(server
.el
,beforeSleep
); 
9026     aeDeleteEventLoop(server
.el
); 
9030 /* ============================= Backtrace support ========================= */ 
9032 #ifdef HAVE_BACKTRACE 
9033 static char *findFuncName(void *pointer
, unsigned long *offset
); 
9035 static void *getMcontextEip(ucontext_t 
*uc
) { 
9036 #if defined(__FreeBSD__) 
9037     return (void*) uc
->uc_mcontext
.mc_eip
; 
9038 #elif defined(__dietlibc__) 
9039     return (void*) uc
->uc_mcontext
.eip
; 
9040 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) 
9042     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
9044     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
9046 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) 
9047   #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) 
9048     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
9050     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
9052 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__) 
9053     return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */ 
9054 #elif defined(__ia64__) /* Linux IA64 */ 
9055     return (void*) uc
->uc_mcontext
.sc_ip
; 
9061 static void segvHandler(int sig
, siginfo_t 
*info
, void *secret
) { 
9063     char **messages 
= NULL
; 
9064     int i
, trace_size 
= 0; 
9065     unsigned long offset
=0; 
9066     ucontext_t 
*uc 
= (ucontext_t
*) secret
; 
9068     REDIS_NOTUSED(info
); 
9070     redisLog(REDIS_WARNING
, 
9071         "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
); 
9072     infostring 
= genRedisInfoString(); 
9073     redisLog(REDIS_WARNING
, "%s",infostring
); 
9074     /* It's not safe to sdsfree() the returned string under memory 
9075      * corruption conditions. Let it leak as we are going to abort */ 
9077     trace_size 
= backtrace(trace
, 100); 
9078     /* overwrite sigaction with caller's address */ 
9079     if (getMcontextEip(uc
) != NULL
) { 
9080         trace
[1] = getMcontextEip(uc
); 
9082     messages 
= backtrace_symbols(trace
, trace_size
); 
9084     for (i
=1; i
<trace_size
; ++i
) { 
9085         char *fn 
= findFuncName(trace
[i
], &offset
), *p
; 
9087         p 
= strchr(messages
[i
],'+'); 
9088         if (!fn 
|| (p 
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) { 
9089             redisLog(REDIS_WARNING
,"%s", messages
[i
]); 
9091             redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
); 
9094     /* free(messages); Don't call free() with possibly corrupted memory. */ 
9098 static void setupSigSegvAction(void) { 
9099     struct sigaction act
; 
9101     sigemptyset (&act
.sa_mask
); 
9102     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction 
9103      * is used. Otherwise, sa_handler is used */ 
9104     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND 
| SA_SIGINFO
; 
9105     act
.sa_sigaction 
= segvHandler
; 
9106     sigaction (SIGSEGV
, &act
, NULL
); 
9107     sigaction (SIGBUS
, &act
, NULL
); 
9108     sigaction (SIGFPE
, &act
, NULL
); 
9109     sigaction (SIGILL
, &act
, NULL
); 
9110     sigaction (SIGBUS
, &act
, NULL
); 
9114 #include "staticsymbols.h" 
9115 /* This function try to convert a pointer into a function name. It's used in 
9116  * oreder to provide a backtrace under segmentation fault that's able to 
9117  * display functions declared as static (otherwise the backtrace is useless). */ 
9118 static char *findFuncName(void *pointer
, unsigned long *offset
){ 
9120     unsigned long off
, minoff 
= 0; 
9122     /* Try to match against the Symbol with the smallest offset */ 
9123     for (i
=0; symsTable
[i
].pointer
; i
++) { 
9124         unsigned long lp 
= (unsigned long) pointer
; 
9126         if (lp 
!= (unsigned long)-1 && lp 
>= symsTable
[i
].pointer
) { 
9127             off
=lp
-symsTable
[i
].pointer
; 
9128             if (ret 
< 0 || off 
< minoff
) { 
9134     if (ret 
== -1) return NULL
; 
9136     return symsTable
[ret
].name
; 
9138 #else /* HAVE_BACKTRACE */ 
9139 static void setupSigSegvAction(void) { 
9141 #endif /* HAVE_BACKTRACE */