1 /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ 2 #include "memcached.h" 3 #include <sys/stat.h> 4 #include <sys/socket.h> 5 #include <sys/signal.h> 6 #include <sys/resource.h> 7 #include <fcntl.h> 8 #include <netinet/in.h> 9 #include <errno.h> 10 #include <stdlib.h> 11 #include <stdio.h> 12 #include <string.h> 13 #include <time.h> 14 #include <assert.h> 15 16 /* Forward Declarations */ 17 static void item_link_q(item *it); 18 static void item_unlink_q(item *it); 19 20 /* 21 * We only reposition items in the LRU queue if they haven't been repositioned 22 * in this many seconds. That saves us from churning on frequently-accessed 23 * items. 24 */ 25 #define ITEM_UPDATE_INTERVAL 60 26 27 #define LARGEST_ID POWER_LARGEST 28 typedef struct { 29 unsigned int evicted; 30 unsigned int evicted_nonzero; 31 rel_time_t evicted_time; 32 unsigned int outofmemory; 33 unsigned int tailrepairs; 34 } itemstats_t; 35 36 static item *heads[LARGEST_ID]; 37 static item *tails[LARGEST_ID]; 38 static itemstats_t itemstats[LARGEST_ID]; 39 static unsigned int sizes[LARGEST_ID]; 40 41 void item_stats_reset(void) { 42 pthread_mutex_lock(&cache_lock); 43 memset(itemstats, 0, sizeof(itemstats)); 44 pthread_mutex_unlock(&cache_lock); 45 } 46 47 48 /* Get the next CAS id for a new item. */ 49 uint64_t get_cas_id(void) { 50 static uint64_t cas_id = 0; 51 return ++cas_id; 52 } 53 54 /* Enable this for reference-count debugging. */ 55 #if 0 56 # define DEBUG_REFCNT(it,op) \ 57 fprintf(stderr, "item %x refcnt(%c) %d %c%c%c\n", \ 58 it, op, it->refcount, \ 59 (it->it_flags & ITEM_LINKED) ? 'L' : ' ', \ 60 (it->it_flags & ITEM_SLABBED) ? 'S' : ' ') 61 #else 62 # define DEBUG_REFCNT(it,op) while(0) 63 #endif 64 65 /** 66 * Generates the variable-sized part of the header for an object. 67 * 68 * key - The key 69 * nkey - The length of the key 70 * flags - key flags 71 * nbytes - Number of bytes to hold value and addition CRLF terminator 72 * suffix - Buffer for the "VALUE" line suffix (flags, size). 73 * nsuffix - The length of the suffix is stored here. 74 * 75 * Returns the total size of the header. 76 */ 77 static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes, 78 char *suffix, uint8_t *nsuffix) { 79 /* suffix is defined at 40 chars elsewhere.. */ 80 *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2); 81 return sizeof(item) + nkey + *nsuffix + nbytes; 82 } 83 84 /*@null@*/ 85 item *do_item_alloc(char *key, const size_t nkey, const int flags, const rel_time_t exptime, const int nbytes) { 86 uint8_t nsuffix; 87 item *it = NULL; 88 char suffix[40]; 89 size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix); 90 if (settings.use_cas) { 91 ntotal += sizeof(uint64_t); 92 } 93 94 unsigned int id = slabs_clsid(ntotal); 95 if (id == 0) 96 return 0; 97 98 /* do a quick check if we have any expired items in the tail.. */ 99 int tries = 50; 100 item *search; 101 102 for (search = tails[id]; 103 tries > 0 && search != NULL; 104 tries--, search=search->prev) { 105 if (search->refcount == 0 && 106 (search->exptime != 0 && search->exptime < current_time)) { 107 it = search; 108 /* I don't want to actually free the object, just steal 109 * the item to avoid to grab the slab mutex twice ;-) 110 */ 111 it->refcount = 1; 112 do_item_unlink(it); 113 /* Initialize the item block: */ 114 it->slabs_clsid = 0; 115 it->refcount = 0; 116 break; 117 } 118 } 119 120 if (it == NULL && (it = slabs_alloc(ntotal, id)) == NULL) { 121 /* 122 ** Could not find an expired item at the tail, and memory allocation 123 ** failed. Try to evict some items! 124 */ 125 tries = 50; 126 127 /* If requested to not push old items out of cache when memory runs out, 128 * we're out of luck at this point... 129 */ 130 131 if (settings.evict_to_free == 0) { 132 itemstats[id].outofmemory++; 133 return NULL; 134 } 135 136 /* 137 * try to get one off the right LRU 138 * don't necessariuly unlink the tail because it may be locked: refcount>0 139 * search up from tail an item with refcount==0 and unlink it; give up after 50 140 * tries 141 */ 142 143 if (tails[id] == 0) { 144 itemstats[id].outofmemory++; 145 return NULL; 146 } 147 148 for (search = tails[id]; tries > 0 && search != NULL; tries--, search=search->prev) { 149 if (search->refcount == 0) { 150 if (search->exptime == 0 || search->exptime > current_time) { 151 itemstats[id].evicted++; 152 itemstats[id].evicted_time = current_time - search->time; 153 if (search->exptime != 0) 154 itemstats[id].evicted_nonzero++; 155 STATS_LOCK(); 156 stats.evictions++; 157 STATS_UNLOCK(); 158 } 159 do_item_unlink(search); 160 break; 161 } 162 } 163 it = slabs_alloc(ntotal, id); 164 if (it == 0) { 165 itemstats[id].outofmemory++; 166 /* Last ditch effort. There is a very rare bug which causes 167 * refcount leaks. We've fixed most of them, but it still happens, 168 * and it may happen in the future. 169 * We can reasonably assume no item can stay locked for more than 170 * three hours, so if we find one in the tail which is that old, 171 * free it anyway. 172 */ 173 tries = 50; 174 for (search = tails[id]; tries > 0 && search != NULL; tries--, search=search->prev) { 175 if (search->refcount != 0 && search->time + TAIL_REPAIR_TIME < current_time) { 176 itemstats[id].tailrepairs++; 177 search->refcount = 0; 178 do_item_unlink(search); 179 break; 180 } 181 } 182 it = slabs_alloc(ntotal, id); 183 if (it == 0) { 184 return NULL; 185 } 186 } 187 } 188 189 assert(it->slabs_clsid == 0); 190 191 it->slabs_clsid = id; 192 193 assert(it != heads[it->slabs_clsid]); 194 195 it->next = it->prev = it->h_next = 0; 196 it->refcount = 1; /* the caller will have a reference */ 197 DEBUG_REFCNT(it, '*'); 198 it->it_flags = settings.use_cas ? ITEM_CAS : 0; 199 it->nkey = nkey; 200 it->nbytes = nbytes; 201 memcpy(ITEM_key(it), key, nkey); 202 it->exptime = exptime; 203 memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix); 204 it->nsuffix = nsuffix; 205 return it; 206 } 207 208 void item_free(item *it) { 209 size_t ntotal = ITEM_ntotal(it); 210 unsigned int clsid; 211 assert((it->it_flags & ITEM_LINKED) == 0); 212 assert(it != heads[it->slabs_clsid]); 213 assert(it != tails[it->slabs_clsid]); 214 assert(it->refcount == 0); 215 216 /* so slab size changer can tell later if item is already free or not */ 217 clsid = it->slabs_clsid; 218 it->slabs_clsid = 0; 219 it->it_flags |= ITEM_SLABBED; 220 DEBUG_REFCNT(it, 'F'); 221 slabs_free(it, ntotal, clsid); 222 } 223 224 /** 225 * Returns true if an item will fit in the cache (its size does not exceed 226 * the maximum for a cache entry.) 227 */ 228 bool item_size_ok(const size_t nkey, const int flags, const int nbytes) { 229 char prefix[40]; 230 uint8_t nsuffix; 231 232 return slabs_clsid(item_make_header(nkey + 1, flags, nbytes, 233 prefix, &nsuffix)) != 0; 234 } 235 236 static void item_link_q(item *it) { /* item is the new head */ 237 item **head, **tail; 238 assert(it->slabs_clsid < LARGEST_ID); 239 assert((it->it_flags & ITEM_SLABBED) == 0); 240 241 head = &heads[it->slabs_clsid]; 242 tail = &tails[it->slabs_clsid]; 243 assert(it != *head); 244 assert((*head && *tail) || (*head == 0 && *tail == 0)); 245 it->prev = 0; 246 it->next = *head; 247 if (it->next) it->next->prev = it; 248 *head = it; 249 if (*tail == 0) *tail = it; 250 sizes[it->slabs_clsid]++; 251 return; 252 } 253 254 static void item_unlink_q(item *it) { 255 item **head, **tail; 256 assert(it->slabs_clsid < LARGEST_ID); 257 head = &heads[it->slabs_clsid]; 258 tail = &tails[it->slabs_clsid]; 259 260 if (*head == it) { 261 assert(it->prev == 0); 262 *head = it->next; 263 } 264 if (*tail == it) { 265 assert(it->next == 0); 266 *tail = it->prev; 267 } 268 assert(it->next != it); 269 assert(it->prev != it); 270 271 if (it->next) it->next->prev = it->prev; 272 if (it->prev) it->prev->next = it->next; 273 sizes[it->slabs_clsid]--; 274 return; 275 } 276 277 int do_item_link(item *it) { 278 MEMCACHED_ITEM_LINK(ITEM_key(it), it->nkey, it->nbytes); 279 assert((it->it_flags & (ITEM_LINKED|ITEM_SLABBED)) == 0); 280 assert(it->nbytes < (1024 * 1024)); /* 1MB max size */ 281 it->it_flags |= ITEM_LINKED; 282 it->time = current_time; 283 assoc_insert(it); 284 285 STATS_LOCK(); 286 stats.curr_bytes += ITEM_ntotal(it); 287 stats.curr_items += 1; 288 stats.total_items += 1; 289 STATS_UNLOCK(); 290 291 /* Allocate a new CAS ID on link. */ 292 ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); 293 294 item_link_q(it); 295 296 return 1; 297 } 298 299 void do_item_unlink(item *it) { 300 MEMCACHED_ITEM_UNLINK(ITEM_key(it), it->nkey, it->nbytes); 301 if ((it->it_flags & ITEM_LINKED) != 0) { 302 it->it_flags &= ~ITEM_LINKED; 303 STATS_LOCK(); 304 stats.curr_bytes -= ITEM_ntotal(it); 305 stats.curr_items -= 1; 306 STATS_UNLOCK(); 307 assoc_delete(ITEM_key(it), it->nkey); 308 item_unlink_q(it); 309 if (it->refcount == 0) item_free(it); 310 } 311 } 312 313 void do_item_remove(item *it) { 314 MEMCACHED_ITEM_REMOVE(ITEM_key(it), it->nkey, it->nbytes); 315 assert((it->it_flags & ITEM_SLABBED) == 0); 316 if (it->refcount != 0) { 317 it->refcount--; 318 DEBUG_REFCNT(it, '-'); 319 } 320 if (it->refcount == 0 && (it->it_flags & ITEM_LINKED) == 0) { 321 item_free(it); 322 } 323 } 324 325 void do_item_update(item *it) { 326 MEMCACHED_ITEM_UPDATE(ITEM_key(it), it->nkey, it->nbytes); 327 if (it->time < current_time - ITEM_UPDATE_INTERVAL) { 328 assert((it->it_flags & ITEM_SLABBED) == 0); 329 330 if ((it->it_flags & ITEM_LINKED) != 0) { 331 item_unlink_q(it); 332 it->time = current_time; 333 item_link_q(it); 334 } 335 } 336 } 337 338 int do_item_replace(item *it, item *new_it) { 339 MEMCACHED_ITEM_REPLACE(ITEM_key(it), it->nkey, it->nbytes, 340 ITEM_key(new_it), new_it->nkey, new_it->nbytes); 341 assert((it->it_flags & ITEM_SLABBED) == 0); 342 343 do_item_unlink(it); 344 return do_item_link(new_it); 345 } 346 347 /*@null@*/ 348 char *do_item_cachedump(const unsigned int slabs_clsid, const unsigned int limit, unsigned int *bytes) { 349 unsigned int memlimit = 2 * 1024 * 1024; /* 2MB max response size */ 350 char *buffer; 351 unsigned int bufcurr; 352 item *it; 353 unsigned int len; 354 unsigned int shown = 0; 355 char key_temp[KEY_MAX_LENGTH + 1]; 356 char temp[512]; 357 358 it = heads[slabs_clsid]; 359 360 buffer = malloc((size_t)memlimit); 361 if (buffer == 0) return NULL; 362 bufcurr = 0; 363 364 while (it != NULL && (limit == 0 || shown < limit)) { 365 assert(it->nkey <= KEY_MAX_LENGTH); 366 /* Copy the key since it may not be null-terminated in the struct */ 367 strncpy(key_temp, ITEM_key(it), it->nkey); 368 key_temp[it->nkey] = 0x00; /* terminate */ 369 len = snprintf(temp, sizeof(temp), "ITEM %s [%d b; %lu s]\r\n", 370 key_temp, it->nbytes - 2, 371 (unsigned long)it->exptime + process_started); 372 if (bufcurr + len + 6 > memlimit) /* 6 is END\r\n\0 */ 373 break; 374 memcpy(buffer + bufcurr, temp, len); 375 bufcurr += len; 376 shown++; 377 it = it->next; 378 } 379 380 memcpy(buffer + bufcurr, "END\r\n", 6); 381 bufcurr += 5; 382 383 *bytes = bufcurr; 384 return buffer; 385 } 386 387 void do_item_stats(ADD_STAT add_stats, void *c) { 388 int i; 389 for (i = 0; i < LARGEST_ID; i++) { 390 if (tails[i] != NULL) { 391 const char *fmt = "items:%d:%s"; 392 char key_str[STAT_KEY_LEN]; 393 char val_str[STAT_VAL_LEN]; 394 int klen = 0, vlen = 0; 395 396 APPEND_NUM_FMT_STAT(fmt, i, "number", "%u", sizes[i]); 397 APPEND_NUM_FMT_STAT(fmt, i, "age", "%u", tails[i]->time); 398 APPEND_NUM_FMT_STAT(fmt, i, "evicted", 399 "%u", itemstats[i].evicted); 400 APPEND_NUM_FMT_STAT(fmt, i, "evicted_nonzero", 401 "%u", itemstats[i].evicted_nonzero); 402 APPEND_NUM_FMT_STAT(fmt, i, "evicted_time", 403 "%u", itemstats[i].evicted_time); 404 APPEND_NUM_FMT_STAT(fmt, i, "outofmemory", 405 "%u", itemstats[i].outofmemory); 406 APPEND_NUM_FMT_STAT(fmt, i, "tailrepairs", 407 "%u", itemstats[i].tailrepairs);; 408 } 409 } 410 411 /* getting here means both ascii and binary terminators fit */ 412 add_stats(NULL, 0, NULL, 0, c); 413 } 414 415 /** dumps out a list of objects of each size, with granularity of 32 bytes */ 416 /*@null@*/ 417 void do_item_stats_sizes(ADD_STAT add_stats, void *c) { 418 419 /* max 1MB object, divided into 32 bytes size buckets */ 420 const int num_buckets = 32768; 421 unsigned int *histogram = calloc(num_buckets, sizeof(int)); 422 423 if (histogram != NULL) { 424 int i; 425 426 /* build the histogram */ 427 for (i = 0; i < LARGEST_ID; i++) { 428 item *iter = heads[i]; 429 while (iter) { 430 int ntotal = ITEM_ntotal(iter); 431 int bucket = ntotal / 32; 432 if ((ntotal % 32) != 0) bucket++; 433 if (bucket < num_buckets) histogram[bucket]++; 434 iter = iter->next; 435 } 436 } 437 438 /* write the buffer */ 439 for (i = 0; i < num_buckets; i++) { 440 if (histogram[i] != 0) { 441 char key[8]; 442 int klen = 0; 443 klen = snprintf(key, sizeof(key), "%d", i * 32); 444 assert(klen < sizeof(key)); 445 APPEND_STAT(key, "%u", histogram[i]); 446 } 447 } 448 free(histogram); 449 } 450 add_stats(NULL, 0, NULL, 0, c); 451 } 452 453 /** wrapper around assoc_find which does the lazy expiration logic */ 454 item *do_item_get(const char *key, const size_t nkey) { 455 item *it = assoc_find(key, nkey); 456 int was_found = 0; 457 458 if (settings.verbose > 2) { 459 if (it == NULL) { 460 fprintf(stderr, "> NOT FOUND %s", key); 461 } else { 462 fprintf(stderr, "> FOUND KEY %s", ITEM_key(it)); 463 was_found++; 464 } 465 } 466 467 if (it != NULL && settings.oldest_live != 0 && settings.oldest_live <= current_time && 468 it->time <= settings.oldest_live) { 469 do_item_unlink(it); /* MTSAFE - cache_lock held */ 470 it = NULL; 471 } 472 473 if (it == NULL && was_found) { 474 fprintf(stderr, " -nuked by flush"); 475 was_found--; 476 } 477 478 if (it != NULL && it->exptime != 0 && it->exptime <= current_time) { 479 do_item_unlink(it); /* MTSAFE - cache_lock held */ 480 it = NULL; 481 } 482 483 if (it == NULL && was_found) { 484 fprintf(stderr, " -nuked by expire"); 485 was_found--; 486 } 487 488 if (it != NULL) { 489 it->refcount++; 490 DEBUG_REFCNT(it, '+'); 491 } 492 493 if (settings.verbose > 2) 494 fprintf(stderr, "\n"); 495 496 return it; 497 } 498 499 /** returns an item whether or not it's expired. */ 500 item *do_item_get_nocheck(const char *key, const size_t nkey) { 501 item *it = assoc_find(key, nkey); 502 if (it) { 503 it->refcount++; 504 DEBUG_REFCNT(it, '+'); 505 } 506 return it; 507 } 508 509 /* expires items that are more recent than the oldest_live setting. */ 510 void do_item_flush_expired(void) { 511 int i; 512 item *iter, *next; 513 if (settings.oldest_live == 0) 514 return; 515 for (i = 0; i < LARGEST_ID; i++) { 516 /* The LRU is sorted in decreasing time order, and an item's timestamp 517 * is never newer than its last access time, so we only need to walk 518 * back until we hit an item older than the oldest_live time. 519 * The oldest_live checking will auto-expire the remaining items. 520 */ 521 for (iter = heads[i]; iter != NULL; iter = next) { 522 if (iter->time >= settings.oldest_live) { 523 next = iter->next; 524 if ((iter->it_flags & ITEM_SLABBED) == 0) { 525 do_item_unlink(iter); 526 } 527 } else { 528 /* We've hit the first old item. Continue to the next queue. */ 529 break; 530 } 531 } 532 } 533 } 534