手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Memcached内存管理

items

[日期:2012-09-15] 来源:Linux社区  作者:caiyun [字体:大 中 小]

memcached.h中item的声明

  1. /** 
  2.  * Structure for storing items within memcached. 
  3.  */  
  4. typedef struct _stritem {  
  5.     struct _stritem *next;  
  6.     struct _stritem *prev;  
  7.     struct _stritem *h_next;    /* hash chain next */  
  8.     rel_time_t      time;       /* least recent access */  
  9.     rel_time_t      exptime;    /* expire time */  
  10.     int             nbytes;     /* size of data */  
  11.     unsigned short  refcount;  
  12.     uint8_t         nsuffix;    /* length of flags-and-length string */  
  13.     uint8_t         it_flags;   /* ITEM_* above */  
  14.     uint8_t         slabs_clsid;/* which slab class we're in */  
  15.     uint8_t         nkey;       /* key length, w/terminating null and padding */  
  16.     /* this odd type prevents type-punning issues when we do 
  17.      * the little shuffle to save space when not using CAS. */  
  18. union {  
  19.         uint64_t cas;  
  20.         char end;  
  21.     } data[];  
  22.   
  23. } item;  

next,pre是双向链表使用的,用于slots,heads和tails,h_next则用于hash表

time 是最近访问时间,time=current_time, 新的item都会放在对应id双向链表的开头,而do_item_alloc会从链表尾开始搜链表,变相的实现了LRU

exptime 过期时间

nbytes 实际数据的字节数

refcount 引用次数

nsuffix 后缀的长度,以下代码赋值

  1. *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);  
即通过snprintf返回的值

it_flags

slab_clsid 所属的slabclass的id

nkey 键长

  1. union {  
  2.     uint64_t cas;  
  3.     char end;  
  4. } data[];  
变长数组,真正存放key-value的地方

具体的内容为 cas + key + suffix + data

cas 是一个编号,不一定会使用

key是键

suffix是后缀,由前面的snprintf赋值

data就是我们的数据了

一组调用的宏,位于memcached.h

  1. #define ITEM_get_cas(i) (((i)->it_flags & ITEM_CAS) ? \   
  2.         (i)->data->cas : (uint64_t)0)  
  3.   
  4. #define ITEM_set_cas(i,v) { \   
  5.     if ((i)->it_flags & ITEM_CAS) { \  
  6.         (i)->data->cas = v; \  
  7.     } \  
  8. }  
  9.   
  10. #define ITEM_key(item) (((char*)&((item)->data)) \   
  11.          + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))  
  12.   
  13. #define ITEM_suffix(item) ((char*) &((item)->data) + (item)->nkey + 1 \   
  14.          + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))  
  15.   
  16. #define ITEM_data(item) ((char*) &((item)->data) + (item)->nkey + 1 \   
  17.          + (item)->nsuffix \  
  18.          + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))  
  19.   
  20. #define ITEM_ntotal(item) (sizeof(struct _stritem) + (item)->nkey + 1 \   
  21.          + (item)->nsuffix + (item)->nbytes \  
  22.          + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))  
用于获取具体item的cas,key,suffix和data的起始地址。

从宏ITEM_ntotal可以看出一个item 的实际长度为 sizeof(item) + nkey + 1 + nsuffix + nbytes  ( + sizoef(uint64_t), 如果使用了cas)

上面的数据结构就是item的大概,下面就看看item是如何获取内存和释放内存

item.c中的重要全局变量

  1. static item *heads[LARGEST_ID];  
  2. static item *tails[LARGEST_ID];  
为对应的slabclass中从slots获取而来空间(以item方式组织的双向链表),分别指向链表的头尾,LRU。

do_item_alloc函数

  1. /** 
  2.  * Generates the variable-sized part of the header for an object. 
  3.  * 
  4.  * key     - The key 
  5.  * nkey    - The length of the key 
  6.  * flags   - key flags 
  7.  * nbytes  - Number of bytes to hold value and addition CRLF terminator 
  8.  * suffix  - Buffer for the "VALUE" line suffix (flags, size). 
  9.  * nsuffix - The length of the suffix is stored here. 
  10.  * 
  11.  * Returns the total size of the header. 
  12.  */  
  13. static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes,  
  14.                      char *suffix, uint8_t *nsuffix) {  
  15.     /* suffix is defined at 40 chars elsewhere.. */  
  16.     *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);  
  17.     return sizeof(item) + nkey + *nsuffix + nbytes;  
  18. }  
给suffix赋值,并返回item总的长度(除去cas的)。总长度用于决定该item属于哪个slabclass
  1. /*@null@*/  
  2. item *do_item_alloc(char *key, const size_t nkey, const int flags, const rel_time_t exptime, const int nbytes) {  
  3.     uint8_t nsuffix;  
  4.     item *it = NULL;  
  5.     char suffix[40];  
  6.     size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);  
  7.     if (settings.use_cas) {  
  8.         ntotal += sizeof(uint64_t);  
  9.     }  
  10.   
  11.     unsigned int id = slabs_clsid(ntotal);  
  12.     if (id == 0)  
  13.         return 0;  
  14.   
  15.     mutex_lock(&cache_lock);  
  16.     /* do a quick check if we have any expired items in the tail.. */  
  17.   
  18.    item *search;  
  19.     rel_time_t oldest_live = settings.oldest_live;  
  20.     //从尾部开始搜索,因为尾部的time总是最早的,所以就是一种LRU实现   
  21.     search = tails[id];  
  22.     if (search != NULL && (refcount_incr(&search->refcount) == 2)) {  
  23.         if ((search->exptime != 0 && search->exptime < current_time)  
  24.             || (search->time <= oldest_live && oldest_live <= current_time)) {  // dead by flush   //如果尾部的item已经超时,那么就替换掉   
  25.             STATS_LOCK();  
  26.             stats.reclaimed++;  
  27.             STATS_UNLOCK();  
  28.             itemstats[id].reclaimed++;  
  29.             if ((search->it_flags & ITEM_FETCHED) == 0) {  
  30.                 STATS_LOCK();  
  31.                 stats.expired_unfetched++;  
  32.                 STATS_UNLOCK();  
  33.                 itemstats[id].expired_unfetched++;  
  34.             }  
  35.               
  36.             //替换掉已经超时的item   
  37.             it = search;  
  38.             slabs_adjust_mem_requested(it->slabs_clsid, ITEM_ntotal(it), ntotal);   //虽然属于同一个slabclass,但是长度仍可能不一样,需要修改一下   
  39.             do_item_unlink_nolock(it, hash(ITEM_key(it), it->nkey, 0));                     //将超时的item从双向链表和hash表中除去   
  40.             /* Initialize the item block: */  
  41.             it->slabs_clsid = 0;                                                                                           //slab_clsid设为0   
  42.         } else if ((it = slabs_alloc(ntotal, id)) == NULL) {//没有超时,则从slabclass中的slots获取空间,还是失败的话   
  43.             if (settings.evict_to_free == 0) {                       //evict_to_free = 0 的话则直接返回null,否则强行将最后一个item替换掉   
  44.                 itemstats[id].outofmemory++;  
  45.                 mutex_unlock(&cache_lock);  
  46.                 return NULL;  
  47.             }  
  48.             itemstats[id].evicted++;  
  49.             itemstats[id].evicted_time = current_time - search->time;  
  50.             if (search->exptime != 0)  
  51.                 itemstats[id].evicted_nonzero++;  
  52.             if ((search->it_flags & ITEM_FETCHED) == 0) {  
  53.                 STATS_LOCK();  
  54.                 stats.evicted_unfetched++;  
  55.                 STATS_UNLOCK();  
  56.                 itemstats[id].evicted_unfetched++;  
  57.             }  
  58.             STATS_LOCK();  
  59.             stats.evictions++;  
  60.             STATS_UNLOCK();  
  61.             it = search;  
  62.             slabs_adjust_mem_requested(it->slabs_clsid, ITEM_ntotal(it), ntotal);  
  63.             do_item_unlink_nolock(it, hash(ITEM_key(it), it->nkey, 0));  
  64.             /* Initialize the item block: */  
  65.             it->slabs_clsid = 0;  
  66.   
  67.             /* If we've just evicted an item, and the automover is set to 
  68.              * angry bird mode, attempt to rip memory into this slab class. 
  69.              * TODO: Move valid object detection into a function, and on a 
  70.              * "successful" memory pull, look behind and see if the next alloc 
  71.              * would be an eviction. Then kick off the slab mover before the 
  72.              * eviction happens. 
  73.              */  
  74.             if (settings.slab_automove == 2)  
  75.                 slabs_reassign(-1, id);  
  76.         } else {  
  77.             refcount_decr(&search->refcount);  
  78.         }  
  79.     } else {  
  80.         /* If the LRU is empty or locked, attempt to allocate memory */  
  81.         it = slabs_alloc(ntotal, id);  
  82.         if (search != NULL)  
  83.             refcount_decr(&search->refcount);  
  84.     }  
  85.   
  86.     if (it == NULL) {  
  87.         itemstats[id].outofmemory++;  
  88.         /* Last ditch effort. There was a very rare bug which caused 
  89.          * refcount leaks. We leave this just in case they ever happen again. 
  90.          * We can reasonably assume no item can stay locked for more than 
  91.          * three hours, so if we find one in the tail which is that old, 
  92.          * free it anyway. 
  93.          */  
  94.         if (search != NULL &&  
  95.             search->refcount != 2 &&  
  96.             search->time + TAIL_REPAIR_TIME < current_time) {  
  97.             itemstats[id].tailrepairs++;  
  98.             search->refcount = 1;  
  99.             do_item_unlink_nolock(search, hash(ITEM_key(search), search->nkey, 0));  
  100.         }  
  101.         mutex_unlock(&cache_lock);  
  102.         return NULL;  
  103.     }  
  104.   
  105.     assert(it->slabs_clsid == 0);  
  106.     assert(it != heads[id]);  
  107.   
  108.     /* Item initialization can happen outside of the lock; the item's already 
  109.      * been removed from the slab LRU. 
  110.      */  
  111.   
  112.   
  113.     //初始化一些item属性,可以看出这里只是申请了data所需要的空间,而未给data真正的赋值,并且将其连入到LRU和hash表的操作也不在这   
  114.     it->refcount = 1;     /* the caller will have a reference */  
  115.     mutex_unlock(&cache_lock);  
  116.     it->next = it->prev = it->h_next = 0;  
  117.     it->slabs_clsid = id;  
  118.   
  119.     DEBUG_REFCNT(it, '*');  
  120.     it->it_flags = settings.use_cas ? ITEM_CAS : 0;  
  121.     it->nkey = nkey;  
  122.     it->nbytes = nbytes;  
  123.     memcpy(ITEM_key(it), key, nkey);  
  124.     it->exptime = exptime;  
  125.     memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix);  
  126.     it->nsuffix = nsuffix;  
  127.     return it;  
  128. }  
上面代码如果要替换掉最后的item时会将其从LRU和hash表中除掉
  1. void do_item_unlink(item *it, const uint32_t hv) {  
  2.     MEMCACHED_ITEM_UNLINK(ITEM_key(it), it->nkey, it->nbytes);  
  3.     mutex_lock(&cache_lock);  
  4.     if ((it->it_flags & ITEM_LINKED) != 0) {  
  5.         it->it_flags &= ~ITEM_LINKED;  
  6.         STATS_LOCK();  
  7.         stats.curr_bytes -= ITEM_ntotal(it);  
  8.         stats.curr_items -= 1;  
  9.         STATS_UNLOCK();  
  10.         assoc_delete(ITEM_key(it), it->nkey, hv);              //从hash表中删除,在assoc.c中再解释   
  11.         item_unlink_q(it);                                                     //从LRU中删除    
  12.         do_item_remove(it);                                                //返回item的空间    
  13.     }  
  14.     mutex_unlock(&cache_lock);  
  15. }  
item_unlink_q函数
  1. static void item_unlink_q(item *it) {  
  2.     item **head, **tail;  
  3.     assert(it->slabs_clsid < LARGEST_ID);  
  4.     head = &heads[it->slabs_clsid];  
  5.     tail = &tails[it->slabs_clsid];  
  6.   
  7.     if (*head == it) {  
  8.         assert(it->prev == 0);  
  9.         *head = it->next;  
  10.     }  
  11.     if (*tail == it) {  
  12.         assert(it->next == 0);  
  13.         *tail = it->prev;  
  14.     }  
  15.     assert(it->next != it);  
  16.     assert(it->prev != it);  
  17.   
  18.     if (it->next) it->next->prev = it->prev;  
  19.     if (it->prev) it->prev->next = it->next;  
  20.     sizes[it->slabs_clsid]--;  
  21.     return;  
  22. }  
还是很好懂的,就是普通的双向链表操作。

do_item_remove函数

  1. void do_item_remove(item *it) {  
  2.     MEMCACHED_ITEM_REMOVE(ITEM_key(it), it->nkey, it->nbytes);  
  3.     assert((it->it_flags & ITEM_SLABBED) == 0);  
  4.   
  5.     if (refcount_decr(&it->refcount) == 0) {  
  6.         item_free(it);  
  7.     }  
  8. }  
如果refcount为0则调用item_free返还item占用的空间
  1. void item_free(item *it) {  
  2.     size_t ntotal = ITEM_ntotal(it);  
  3.     unsigned int clsid;  
  4.     assert((it->it_flags & ITEM_LINKED) == 0);  
  5.     assert(it != heads[it->slabs_clsid]);  
  6.     assert(it != tails[it->slabs_clsid]);  
  7.     assert(it->refcount == 0);  
  8.   
  9.     /* so slab size changer can tell later if item is already free or not */  
  10.     clsid = it->slabs_clsid;  
  11.     it->slabs_clsid = 0;  
  12.     DEBUG_REFCNT(it, 'F');  
  13.     slabs_free(it, ntotal, clsid);  
  14. }  
实际就是调用slabs_free将item占用的内存放回到slabclass的slots中。

还有几个重要的函数

do_item_link 就是将item放入对用的LRU和hash表中

int do_item_link(item *it, const uint32_t hv) {
    MEMCACHED_ITEM_LINK(ITEM_key(it), it->nkey, it->nbytes);
    assert((it->it_flags & (ITEM_LINKED|ITEM_SLABBED)) == 0);
    mutex_lock(&cache_lock);
    it->it_flags |= ITEM_LINKED;
    it->time = current_time;

    STATS_LOCK();
    stats.curr_bytes += ITEM_ntotal(it);
    stats.curr_items += 1;
    stats.total_items += 1;
    STATS_UNLOCK();

    /* Allocate a new CAS ID on link. */
    ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
    assoc_insert(it, hv);
    item_link_q(it);
    refcount_incr(&it->refcount);
    mutex_unlock(&cache_lock);

    return 1;
}


item_link_q函数,就是将item加入到LRU中

static void item_link_q(item *it) { /* item is the new head */
    item **head, **tail;
    assert(it->slabs_clsid < LARGEST_ID);
    assert((it->it_flags & ITEM_SLABBED) == 0);

    head = &heads[it->slabs_clsid];
    tail = &tails[it->slabs_clsid];
    assert(it != *head);
    assert((*head && *tail) || (*head == 0 && *tail == 0));
    it->prev = 0;
    it->next = *head;
    if (it->next) it->next->prev = it;
    *head = it;
    if (*tail == 0) *tail = it;
    sizes[it->slabs_clsid]++;
    return;
}

do_item_update函数,就是改变其最后访问时间,反映到链表上就是将其移到链表头

  1. void do_item_update(item *it) {  
  2.     MEMCACHED_ITEM_UPDATE(ITEM_key(it), it->nkey, it->nbytes);  
  3.     if (it->time < current_time - ITEM_UPDATE_INTERVAL) {  
  4.         assert((it->it_flags & ITEM_SLABBED) == 0);  
  5.   
  6.         mutex_lock(&cache_lock);  
  7.         if ((it->it_flags & ITEM_LINKED) != 0) {  
  8.             item_unlink_q(it);  
  9.             it->time = current_time;  
  10.             item_link_q(it);  
  11.         }  
  12.         mutex_unlock(&cache_lock);  
  13.     }  
  14. }  
do_item_touch函数,改变exptime
  1. item *do_item_touch(const char *key, size_t nkey, uint32_t exptime,  
  2.                     const uint32_t hv) {  
  3.     item *it = do_item_get(key, nkey, hv);  
  4.     if (it != NULL) {  
  5.         it->exptime = exptime;  
  6.     }  
  7.     return it;  
  8. }  

do_item_get函数:通过hash表(key)来找到所要的所要的item ,其实就是调用assoc_find函数,将在后面再讲

  1. /** wrapper around assoc_find which does the lazy expiration logic */  
  2. item *do_item_get(const char *key, const size_t nkey, const uint32_t hv) {  
  3.     mutex_lock(&cache_lock);  
  4.     item *it = assoc_find(key, nkey, hv);  
  5.     if (it != NULL) {  
  6.         refcount_incr(&it->refcount);  
  7.         /* Optimization for slab reassignment. prevents popular items from 
  8.          * jamming in busy wait. Can only do this here to satisfy lock order 
  9.          * of item_lock, cache_lock, slabs_lock. */  
  10.         if (slab_rebalance_signal &&  
  11.             ((void *)it >= slab_rebal.slab_start && (void *)it < slab_rebal.slab_end)) {  
  12.             do_item_unlink_nolock(it, hv);  
  13.             do_item_remove(it);  
  14.             it = NULL;  
  15.         }  
  16.     }  
  17.     mutex_unlock(&cache_lock);  
  18.     int was_found = 0;  
  19.   
  20.     if (settings.verbose > 2) {  
  21.         if (it == NULL) {  
  22.             fprintf(stderr, "> NOT FOUND %s", key);  
  23.         } else {  
  24.             fprintf(stderr, "> FOUND KEY %s", ITEM_key(it));  
  25.             was_found++;  
  26.         }  
  27.     }  
  28.   
  29.     if (it != NULL) {  
  30.         if (settings.oldest_live != 0 && settings.oldest_live <= current_time &&  
  31.             it->time <= settings.oldest_live) {  
  32.             do_item_unlink(it, hv);  
  33.             do_item_remove(it);  
  34.             it = NULL;  
  35.             if (was_found) {  
  36.                 fprintf(stderr, " -nuked by flush");  
  37.             }  
  38.         } else if (it->exptime != 0 && it->exptime <= current_time) {  
  39.             do_item_unlink(it, hv);  
  40.             do_item_remove(it);  
  41.             it = NULL;  
  42.             if (was_found) {  
  43.                 fprintf(stderr, " -nuked by expire");  
  44.             }  
  45.         } else {  
  46.             it->it_flags |= ITEM_FETCHED;  
  47.             DEBUG_REFCNT(it, '+');  
  48.         }  
  49.     }  
  50.   
  51.     if (settings.verbose > 2)  
  52.         fprintf(stderr, "\n");  
  53.   
  54.     return it;  
  55. }  
大概就这样了吧。

一张图

linux
【内容导航】
第1页:slabs 第2页:items
第3页:assoc
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款