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