root/trunk/server/items.c @ 737

Revision 737, 13.2 kB (checked in by dormando, 21 months ago)

Useless check. 'id' will never be higher than POWER_LARGEST.
Which is defined as 200 in slabs.c, but LARGEST_ID is defined as 255 in items.c? Weird.

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