Linux内核中内存cache的实现

本文档的Copyleft归yfydz所有,使用GPL发布,可以自由拷贝,转载,转载时请保持文档的完整性,
严禁用于任何商业用途。
msn: yfydz_no1@hotmail.com
来源:http://yfydz.cublog.cn
Java代码   收藏代码
  1. 1. 前言  
  2.   
  3. kmem_cache是Linux内核提供的快速内存缓冲接口,这些内存块要求是大小相同的,因为分配出的内  
  4. 存在接口释放时并不真正释放,而是作为缓存保留,下一次请求分配时就可以直接使用,省去了各种  
  5. 内存块初始化或释放的操作,因此分配速度很快,通常用于大数量的内存块分配的情况,如inode节  
  6. 点,skbuff头, netfilter的连接等,其实kmalloc也是从kmem_cache中分配的,可通  
  7. 过/proc/slabinfo文件直接读取cache分配情况。  
  8. 以下Linux内核代码版本为2.6.19.2, 程序主要出自mm/slab.c文件, 2.42.6基本原理差不多,但具  
  9. 体实现中有了不少变化。  
  10.   
  11. 2. slab和page  
  12.   
  13. 在介绍kmem_cache之前需要先介绍page和slab这两个定义。众所周知,page是内核中内存基本管理单  
  14. 位,每个page的内存大小是固定的,对X86机器来说,是4K;slab则是kmem_cache的具体的内存空间  
  15. 形式,根据cache的对象的大小,每个slab可以有1个page到最多32(128/4)个page;如果cache对象比  
  16. 一个page的空间小,这个slab中会容纳多个对象以尽可能地利用空间。  
  17. struct slab {  
  18. // 链表  
  19.  struct list_head list;  
  20. // 未用空间的偏移  
  21.  unsigned long colouroff;  
  22. // 具体的内存缓冲区地址  
  23.  void *s_mem;  /* including colour offset */  
  24. // 每个slab中的正在使用的对象数量  
  25.  unsigned int inuse; /* num of objs active in slab */  
  26. // 空闲对象  
  27.  kmem_bufctl_t free;  
  28.  unsigned short nodeid;  
  29. };  
  30.    
  31. 3. 数据结构  
  32.   
  33. kmem_cache数据结构并没有定义在.h的头文件中,在头文件中只是该结构的一个类型定义,因为其他  
  34. 地方使用kmem_cache时完全不需要知道其内部结构,各接口函数完全封装结构中的信息,这是用C实  
  35. 现OO编程的常用方式。  
  36.   
  37. /* include/linux/slab.h */  
  38. // 这里只是一个类型定义  
  39. typedef struct kmem_cache kmem_cache_t;  
  40.   
  41. /* mm/slab.c */  
  42. // 在C文件中进行完整的定义  
  43.   
  44. /* 
  45.  * struct array_cache 
  46.  * 
  47.  * Purpose: 
  48.  * - LIFO ordering, to hand out cache-warm objects from _alloc 
  49.  * - reduce the number of linked list operations 
  50.  * - reduce spinlock operations 
  51.  * 
  52.  * The limit is stored in the per-cpu structure to reduce the data cache 
  53.  * footprint. 
  54.  * 
  55.  */  
  56. // 这是每个CPU对应的cache数据  
  57. struct array_cache {  
  58.  unsigned int avail;  
  59.  unsigned int limit;  
  60.  unsigned int batchcount;  
  61.  unsigned int touched;  
  62.  spinlock_t lock;  
  63.  void *entry[0]; /* 
  64.     * Must have this definition in here for the proper 
  65.     * alignment of array_cache. Also simplifies accessing 
  66.     * the entries. 
  67.     * [0] is for gcc 2.95. It should really be []. 
  68.     */  
  69. };  
  70.   
  71. /* 
  72.  * The slab lists for all objects. 
  73.  */  
  74. // 这是cache管理的slab的链表  
  75. struct kmem_list3 {  
  76. // 该链表中slab中既有正在使用的对象,也有空闲对象  
  77.  struct list_head slabs_partial; /* partial list first, better asm code */  
  78. // 该链表中slab的对象都在使用中  
  79.  struct list_head slabs_full;  
  80. // 该链表中slab的对象都是空闲的  
  81.  struct list_head slabs_free;  
  82. // 空闲的对象数  
  83.  unsigned long free_objects;  
  84. // 空闲的限值,超过就该释放掉一些了  
  85.  unsigned int free_limit;  
  86.  unsigned int colour_next; /* Per-node cache coloring */  
  87.  spinlock_t list_lock;  
  88.  struct array_cache *shared; /* shared per node */  
  89.  struct array_cache **alien; /* on other nodes */  
  90.  unsigned long next_reap; /* updated without locking */  
  91.  int free_touched;  /* updated without locking */  
  92. };  
  93.   
  94. struct kmem_cache {  
  95. /* 1) per-cpu data, touched during every alloc/free */  
  96. // 每个CPU对应的cache数组  
  97.  struct array_cache *array[NR_CPUS];  
  98. /* 2) Cache tunables. Protected by cache_chain_mutex */  
  99. // 没有空闲对象时为处理器一次批量分配的对象数量  
  100.  unsigned int batchcount;  
  101. // 在将缓冲池中一半空闲对象释放到全局缓冲池前缓冲池中允许的空闲对象的数量  
  102.  unsigned int limit;  
  103.  unsigned int shared;  
  104. //  
  105.  unsigned int buffer_size;  
  106. /* 3) touched by every alloc & free from the backend */  
  107. // MAX_NUMNODES个cache节点链表,MAX_NUMNODES是编译内核时定义的  
  108.  struct kmem_list3 *nodelists[MAX_NUMNODES];  
  109.  unsigned int flags;  /* constant flags */  
  110. // 每个slab中的对象数  
  111.  unsigned int num;  /* # of objs per slab */  
  112. /* 4) cache_grow/shrink */  
  113.  /* order of pgs per slab (2^n) */  
  114. // 表明在内存页中的slab块的大小, 如果对象大小小于4K,该值为1  
  115. // 超过4K,该值为slab大小相对4K的倍数, 如对于32K, 该值为8  
  116.  unsigned int gfporder;  
  117.  /* force GFP flags, e.g. GFP_DMA */  
  118.  gfp_t gfpflags;  
  119.  size_t colour;   /* cache colouring range */  
  120.  unsigned int colour_off; /* colour offset */  
  121.  struct kmem_cache *slabp_cache;  
  122.  unsigned int slab_size;  
  123.  unsigned int dflags;  /* dynamic flags */  
  124.  /* constructor func */  
  125. // cache构造函数  
  126.  void (*ctor) (void *, struct kmem_cache *, unsigned long);  
  127.  /* de-constructor func */  
  128. // cache析构函数  
  129.  void (*dtor) (void *, struct kmem_cache *, unsigned long);  
  130. /* 5) cache creation/removal */  
  131. // cache的名称  
  132.  const char *name;  
  133. // cache链表中的下一项  
  134.  struct list_head next;  
  135. /* 6) statistics */  
  136. #if STATS  
  137.  unsigned long num_active;  
  138.  unsigned long num_allocations;  
  139.  unsigned long high_mark;  
  140.  unsigned long grown;  
  141.  unsigned long reaped;  
  142.  unsigned long errors;  
  143.  unsigned long max_freeable;  
  144.  unsigned long node_allocs;  
  145.  unsigned long node_frees;  
  146.  unsigned long node_overflow;  
  147.  atomic_t allochit;  
  148.  atomic_t allocmiss;  
  149.  atomic_t freehit;  
  150.  atomic_t freemiss;  
  151. #endif  
  152. #if DEBUG  
  153.  /* 
  154.   * If debugging is enabled, then the allocator can add additional 
  155.   * fields and/or padding to every object. buffer_size contains the total 
  156.   * object size including these internal fields, the following two 
  157.   * variables contain the offset to the user object and its size. 
  158.   */  
  159.  int obj_offset;  
  160.  int obj_size;  
  161. #endif  
  162. };  
  163.   
  164. 内核cache的管理链表本身也是一个cache, 因此定义了一个静态的cache结构作为这个cache链表的链  
  165. 表头:  
  166. /* internal cache of cache description objs */  
  167. static struct kmem_cache cache_cache = {  
  168.  .batchcount = 1,  
  169.  .limit = BOOT_CPUCACHE_ENTRIES,  
  170.  .shared = 1,  
  171.  .buffer_size = sizeof(struct kmem_cache),  
  172.  .name = "kmem_cache",  
  173. #if DEBUG  
  174.  .obj_size = sizeof(struct kmem_cache),  
  175. #endif  
  176. };  
  177. /proc/slabinfo就是这个cache链表的基本信息.  
  178.   
  179. 关于cache, slab, page的关系可大致表示如下:  
  180.   
  181.     cache <-------------------> cache <--------------------->cache  
  182.                                   |  
  183.                                   V  
  184.                               kmem_list3  
  185.                                   |  
  186.                +--------------------------------------+  
  187.                |                  |                   |  
  188.                V                  V                   V  
  189.            slab_full         slab_partial         slab_free  
  190.                |                  |                   |  
  191.                V                  V                   V  
  192.              slab               slab                 slab  
  193.                |                  |                   |  
  194.                V                  V                   V  
  195.              page               page                 page  
  196.                |                  |                   |  
  197.        +-------------+     +--------------+     +-------------+  
  198.        |             |     |              |     |             |  
  199.        V             V     V              V     V             V  
  200.     object  ...  object   object  ...  object object  ...  object  
  201.    
  202. 4. 操作函数  
  203.   
  204. 4.1 基本用法  
  205.   
  206. 为使用kmem_cache, 先要用kmem_cache_create函数创建cache, 如:  
  207. static kmem_cache_t *ip_conntrack_cachep __read_mostly;  
  208.  ip_conntrack_cachep = kmem_cache_create("ip_conntrack",  
  209.                                          sizeof(struct ip_conntrack), 0,  
  210.                                          0, NULL, NULL);  
  211. 分配对象空间时使用kmem_cache_alloc函数, 如:  
  212.  conntrack = kmem_cache_alloc(ip_conntrack_cachep, GFP_ATOMIC);  
  213.   
  214. 释放对象时kmem_cache_free函数, 如:  
  215.  kmem_cache_free(ip_conntrack_cachep, conntrack);  
  216.   
  217. 模块结束,销毁cache时使用kmem_cache_destroy函数, 如:  
  218.  kmem_cache_destroy(ip_conntrack_cachep);  
  219.    
  220. 4.2 创建cache: kmem_cache_create  
  221.   
  222. 该函数创建kmem_cache结构,要提供该cache的名称,每个单元块的大小参数, 其他参数则可以为0或  
  223. NULL。  
  224. 这个函数重点就是根据所需要的内存块大小确定合适的、对齐的slab块大小  
  225. /* mm/slab.c */  
  226. // name是该cache的名称  
  227. // size是cahce中对象的大小, 一般情况下其他参数都可为0或NULL  
  228. // align: 指定size要按align对齐  
  229. struct kmem_cache *  
  230. kmem_cache_create (const char *name, size_t size, size_t align,  
  231.  unsigned long flags,  
  232.  void (*ctor)(void*, struct kmem_cache *, unsigned long),  
  233.  void (*dtor)(void*, struct kmem_cache *, unsigned long))  
  234. {  
  235.  size_t left_over, slab_size, ralign;  
  236.  struct kmem_cache *cachep = NULL, *pc;  
  237.  /* 
  238.   * Sanity checks... these are all serious usage bugs. 
  239.   */  
  240. // cache名不能为空,不能在中断中分配,每个单元块不能太大,也不能太小  
  241. // 如果定义了析构函数不能没有构造函数  
  242.  if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||  
  243.      (size > (1 << MAX_OBJ_ORDER) * PAGE_SIZE) || (dtor && !ctor)) {  
  244.   printk(KERN_ERR "%s: Early error in slab %s\n", __FUNCTION__,  
  245.     name);  
  246.   BUG();  
  247.  }  
  248.  /* 
  249.   * Prevent CPUs from coming and going. 
  250.   * lock_cpu_hotplug() nests outside cache_chain_mutex 
  251.   */  
  252.  lock_cpu_hotplug();  
  253. // 锁住cache链表  
  254.  mutex_lock(&cache_chain_mutex);  
  255. // 循环cache链表,此为全局链表  
  256.  list_for_each_entry(pc, &cache_chain, next) {  
  257.   mm_segment_t old_fs = get_fs();  
  258.   char tmp;  
  259.   int res;  
  260.   /* 
  261.    * This happens when the module gets unloaded and doesn't 
  262.    * destroy its slab cache and no-one else reuses the vmalloc 
  263.    * area of the module.  Print a warning. 
  264.    */  
  265. // 检查一下cache是否有效,可能会由于模块的释放却没清除掉  
  266.   set_fs(KERNEL_DS);  
  267.   res = __get_user(tmp, pc->name);  
  268.   set_fs(old_fs);  
  269.   if (res) {  
  270.    printk("SLAB: cache with size %d has lost its name\n",  
  271.           pc->buffer_size);  
  272.    continue;  
  273.   }  
  274. // 相同名称的cache已经有了,出错返回  
  275.   if (!strcmp(pc->name, name)) {  
  276.    printk("kmem_cache_create: duplicate cache %s\n", name);  
  277.    dump_stack();  
  278.    goto oops;  
  279.   }  
  280.  }  
  281. // 可以忽略DEBUG中的代码  
  282. #if DEBUG  
  283.  WARN_ON(strchr(name, ' ')); /* It confuses parsers */  
  284.  if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {  
  285.   /* No constructor, but inital state check requested */  
  286.   printk(KERN_ERR "%s: No con, but init state check "  
  287.          "requested - %s\n", __FUNCTION__, name);  
  288.   flags &= ~SLAB_DEBUG_INITIAL;  
  289.  }  
  290. #if FORCED_DEBUG  
  291.  /* 
  292.   * Enable redzoning and last user accounting, except for caches with 
  293.   * large objects, if the increased size would increase the object size 
  294.   * above the next power of two: caches with object sizes just above a 
  295.   * power of two have a significant amount of internal fragmentation. 
  296.   */  
  297.  if (size < 4096 || fls(size - 1) == fls(size-1 + 3 * BYTES_PER_WORD))  
  298.   flags |= SLAB_RED_ZONE | SLAB_STORE_USER;  
  299.  if (!(flags & SLAB_DESTROY_BY_RCU))  
  300.   flags |= SLAB_POISON;  
  301. #endif  
  302.  if (flags & SLAB_DESTROY_BY_RCU)  
  303.   BUG_ON(flags & SLAB_POISON);  
  304. #endif  
  305.  if (flags & SLAB_DESTROY_BY_RCU)  
  306.   BUG_ON(dtor);  
  307.  /* 
  308.   * Always checks flags, a caller might be expecting debug support which 
  309.   * isn't available. 
  310.   */  
  311.  BUG_ON(flags & ~CREATE_MASK);  
  312.  /* 
  313.   * Check that size is in terms of words.  This is needed to avoid 
  314.   * unaligned accesses for some archs when redzoning is used, and makes 
  315.   * sure any on-slab bufctl's are also correctly aligned. 
  316.   */  
  317. // 将对象长度先按BYTES_PER_WORD扩展对齐, 32位机为4字节对齐  
  318.  if (size & (BYTES_PER_WORD - 1)) {  
  319.   size += (BYTES_PER_WORD - 1);  
  320.   size &= ~(BYTES_PER_WORD - 1);  
  321.  }  
  322.  /* calculate the final buffer alignment: */  
  323. // 以下根据函数标志计算实际对齐值  
  324.  /* 1) arch recommendation: can be overridden for debug */  
  325.  if (flags & SLAB_HWCACHE_ALIGN) {  
  326. // 要根据硬件CACHE进行字节对齐,对齐都是2的指数倍  
  327.   /* 
  328.    * Default alignment: as specified by the arch code.  Except if 
  329.    * an object is really small, then squeeze multiple objects into 
  330.    * one cacheline. 
  331.    */  
  332.   ralign = cache_line_size();  
  333.   while (size <= ralign / 2)  
  334.    ralign /= 2;  
  335.  } else {  
  336.   ralign = BYTES_PER_WORD;  
  337.  }  
  338.  /* 
  339.   * Redzoning and user store require word alignment. Note this will be 
  340.   * overridden by architecture or caller mandated alignment if either 
  341.   * is greater than BYTES_PER_WORD. 
  342.   */  
  343.  if (flags & SLAB_RED_ZONE || flags & SLAB_STORE_USER)  
  344.   ralign = BYTES_PER_WORD;  
  345.  /* 2) arch mandated alignment: disables debug if necessary */  
  346.  if (ralign < ARCH_SLAB_MINALIGN) {  
  347.   ralign = ARCH_SLAB_MINALIGN;  
  348.   if (ralign > BYTES_PER_WORD)  
  349.    flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);  
  350.  }  
  351.  /* 3) caller mandated alignment: disables debug if necessary */  
  352.  if (ralign < align) {  
  353. // 如果根据系统情况计算出的对齐值小于要求的对齐值,用参数里的对齐值  
  354.   ralign = align;  
  355.   if (ralign > BYTES_PER_WORD)  
  356.    flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);  
  357.  }  
  358.  /* 
  359.   * 4) Store it. 
  360.   */  
  361. // 真正的对齐值  
  362.  align = ralign;  
  363.  /* Get cache's description obj. */  
  364. // 分配cache本身的内存空间,并清零,SLAB_KERNEL标志表明该操作可能会休眠  
  365.  cachep = kmem_cache_zalloc(&cache_cache, SLAB_KERNEL);  
  366.  if (!cachep)  
  367.   goto oops;  
  368. #if DEBUG  
  369.  cachep->obj_size = size;  
  370.  /* 
  371.   * Both debugging options require word-alignment which is calculated 
  372.   * into align above. 
  373.   */  
  374.  if (flags & SLAB_RED_ZONE) {  
  375.   /* add space for red zone words */  
  376.   cachep->obj_offset += BYTES_PER_WORD;  
  377.   size += 2 * BYTES_PER_WORD;  
  378.  }  
  379.  if (flags & SLAB_STORE_USER) {  
  380.   /* user store requires one word storage behind the end of 
  381.    * the real object. 
  382.    */  
  383.   size += BYTES_PER_WORD;  
  384.  }  
  385. #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)  
  386.  if (size >= malloc_sizes[INDEX_L3 + 1].cs_size  
  387.      && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {  
  388.   cachep->obj_offset += PAGE_SIZE - size;  
  389.   size = PAGE_SIZE;  
  390.  }  
  391. #endif  
  392. #endif  
  393.  /* 
  394.   * Determine if the slab management is 'on' or 'off' slab. 
  395.   * (bootstrapping cannot cope with offslab caches so don't do 
  396.   * it too early on.) 
  397.   */  
  398.  if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init)  
  399. // 如果对象大小比较大,设置CFLGS_OFF_SLAB标志  
  400. // (PAGE_SIZE >> 3)在X86下是512  
  401.   /* 
  402.    * Size is large, assume best to place the slab management obj 
  403.    * off-slab (should allow better packing of objs). 
  404.    */  
  405.   flags |= CFLGS_OFF_SLAB;  
  406. // 根据算出的对齐长度重新对齐内存单元长度  
  407.  size = ALIGN(size, align);  
  408. // 计算要分配size大小相对slab大小的阶数,返回每个slab的剩余空间数  
  409.  left_over = calculate_slab_order(cachep, size, align, flags);  
  410.  if (!cachep->num) {  
  411. // cachep->num为每个slab中的对象数  
  412. // 为0表示找不到合适的内存slab块大小  
  413.   printk("kmem_cache_create: couldn't create cache %s.\n", name);  
  414.   kmem_cache_free(&cache_cache, cachep);  
  415.   cachep = NULL;  
  416.   goto oops;  
  417.  }  
  418. // 对齐slab结构本身大小, 大小包括slab头(struct slab), 以及cachep->num个对象  
  419. // 的控制量的大小, kmem_bufctl_t其实是一个无符合整数  
  420. // typedef unsigned int kmem_bufctl_t  
  421.  slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)  
  422.      + sizeof(struct slab), align);  
  423.  /* 
  424.   * If the slab has been placed off-slab, and we have enough space then 
  425.   * move it on-slab. This is at the expense of any extra colouring. 
  426.   */  
  427. // 有OFF_SLAB标志而且slab剩余空间比slab本身还大  
  428.  if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {  
  429. // 将slab参数移到剩余空间中  
  430.   flags &= ~CFLGS_OFF_SLAB;  
  431.   left_over -= slab_size;  
  432.  }  
  433.  if (flags & CFLGS_OFF_SLAB) {  
  434.   /* really off slab. No need for manual alignment */  
  435.   slab_size =  
  436.       cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);  
  437.  }  
  438. // 填写cache块的基本信息  
  439. // colour_off是根据硬件L1 CACHE元素大小来定  
  440. // 是  
  441.  cachep->colour_off = cache_line_size();  
  442.  /* Offset must be a multiple of the alignment. */  
  443.  if (cachep->colour_off < align)  
  444.   cachep->colour_off = align;  
  445. // colour是指在剩余空间中能用的colour_off偏移值的数量  
  446. // 表明能放几个整的L1 CACHE元素  
  447.  cachep->colour = left_over / cachep->colour_off;  
  448. // slab控制部分大小  
  449.  cachep->slab_size = slab_size;  
  450.  cachep->flags = flags;  
  451.  cachep->gfpflags = 0;  
  452.  if (flags & SLAB_CACHE_DMA)  
  453.   cachep->gfpflags |= GFP_DMA;  
  454. // 实际内存缓冲区大小  
  455.  cachep->buffer_size = size;  
  456.  if (flags & CFLGS_OFF_SLAB) {  
  457.   cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);  
  458.   /* 
  459.    * This is a possibility for one of the malloc_sizes caches. 
  460.    * But since we go off slab only for object size greater than 
  461.    * PAGE_SIZE/8, and malloc_sizes gets created in ascending order, 
  462.    * this should not happen at all. 
  463.    * But leave a BUG_ON for some lucky dude. 
  464.    */  
  465.   BUG_ON(!cachep->slabp_cache);  
  466.  }  
  467.  cachep->ctor = ctor;  
  468.  cachep->dtor = dtor;  
  469.  cachep->name = name;  
  470. // 建立每个CPU各自的cache数据  
  471.  if (setup_cpu_cache(cachep)) {  
  472.   __kmem_cache_destroy(cachep);  
  473.   cachep = NULL;  
  474.   goto oops;  
  475.  }  
  476.  /* cache setup completed, link it into the list */  
  477. // 将新建的cache块挂接到cache链表  
  478.  list_add(&cachep->next, &cache_chain);  
  479. oops:  
  480.  if (!cachep && (flags & SLAB_PANIC))  
  481.   panic("kmem_cache_create(): failed to create slab `%s'\n",  
  482.         name);  
  483.  mutex_unlock(&cache_chain_mutex);  
  484.  unlock_cpu_hotplug();  
  485.  return cachep;  
  486. }  
  487. // 该函数可在内核模块中访问  
  488. EXPORT_SYMBOL(kmem_cache_create);  
  489.    
  490.   
  491. 4.3 分配单元kmem_cache_(z)alloc()  
  492.   
  493. 有kmem_cache_alloc()和kmem_cache_zalloc()两个函数,后者只是增加将分配出的单元空间清零的  
  494. 操作。这两个函数返回分配好的cache单元空间  
  495. /* mm/slab.c */  
  496. /** 
  497.  * kmem_cache_alloc - Allocate an object 
  498.  * @cachep: The cache to allocate from. 
  499.  * @flags: See kmalloc(). 
  500.  * 
  501.  * Allocate an object from this cache.  The flags are only relevant 
  502.  * if the cache has no available objects. 
  503.  */  
  504. void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)  
  505. {  
  506.  return __cache_alloc(cachep, flags, __builtin_return_address(0));  
  507. }  
  508. EXPORT_SYMBOL(kmem_cache_alloc);  
  509. /** 
  510.  * kmem_cache_zalloc - Allocate an object. The memory is set to zero. 
  511.  * @cache: The cache to allocate from. 
  512.  * @flags: See kmalloc(). 
  513.  * 
  514.  * Allocate an object from this cache and set the allocated memory to zero. 
  515.  * The flags are only relevant if the cache has no available objects. 
  516.  */  
  517. void *kmem_cache_zalloc(struct kmem_cache *cache, gfp_t flags)  
  518. {  
  519.  void *ret = __cache_alloc(cache, flags, __builtin_return_address(0));  
  520.  if (ret)  
  521.   memset(ret, 0, obj_size(cache));  
  522.  return ret;  
  523. }  
  524. EXPORT_SYMBOL(kmem_cache_zalloc);  
  525. 这两个函数核心都是调用__cahce_alloc函数来分配cache:  
  526. // 两个下划线的cache_alloc  
  527. // 在内核配置了CONFIG_NUMA时NUMA_BUILD为1,否则为0  
  528. static __always_inline void *__cache_alloc(struct kmem_cache *cachep,  
  529.       gfp_t flags, void *caller)  
  530. {  
  531.  unsigned long save_flags;  
  532.  void *objp = NULL;  
  533.  cache_alloc_debugcheck_before(cachep, flags);  
  534.  local_irq_save(save_flags);  
  535.  if (unlikely(NUMA_BUILD &&  
  536.    current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY)))  
  537. // 进入此处的可能性比较小  
  538.   objp = alternate_node_alloc(cachep, flags);  
  539.  if (!objp)  
  540. // 主要是进入该函数分配,这个是4下划线的cache_cache  
  541.   objp = ____cache_alloc(cachep, flags);  
  542.  /* 
  543.   * We may just have run out of memory on the local node. 
  544.   * __cache_alloc_node() knows how to locate memory on other nodes 
  545.   */  
  546.   if (NUMA_BUILD && !objp)  
  547.    objp = __cache_alloc_node(cachep, flags, numa_node_id());  
  548.  local_irq_restore(save_flags);  
  549. // 实际为objp=objp, 没啥操作  
  550.  objp = cache_alloc_debugcheck_after(cachep, flags, objp,  
  551.          caller);  
  552.  prefetchw(objp);  
  553.  return objp;  
  554. }  
  555.   
  556. // 重点还是这个四个下划线的cache_alloc  
  557. static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)  
  558. {  
  559.  void *objp;  
  560.  struct array_cache *ac;  
  561.  check_irq_off();  
  562. // 每个cpu对应的cache数组  
  563.  ac = cpu_cache_get(cachep);  
  564.  if (likely(ac->avail)) {  
  565. // 当前cache单元空间中有元素,不用重新分配,将缓冲的cache返回  
  566.   STATS_INC_ALLOCHIT(cachep);  
  567.   ac->touched = 1;  
  568.   objp = ac->entry[--ac->avail];  
  569.  } else {  
  570. // 否则新分配cache单元  
  571.   STATS_INC_ALLOCMISS(cachep);  
  572.   objp = cache_alloc_refill(cachep, flags);  
  573.  }  
  574.  return objp;  
  575. }  
  576.   
  577. // 分配cache单元  
  578. static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)  
  579. {  
  580.  int batchcount;  
  581.  struct kmem_list3 *l3;  
  582.  struct array_cache *ac;  
  583.  int node;  
  584. // cpu到node值的转换  
  585.  node = numa_node_id();  
  586.  check_irq_off();  
  587. // 每个cpu对应的cache数组  
  588.  ac = cpu_cache_get(cachep);  
  589. retry:  
  590. // 一次批量分配的数量, 分配是批量进行, 这样不用每次请求都分配操作一次  
  591.  batchcount = ac->batchcount;  
  592.  if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {  
  593.   /* 
  594.    * If there was little recent activity on this cache, then 
  595.    * perform only a partial refill.  Otherwise we could generate 
  596.    * refill bouncing. 
  597.    */  
  598.   batchcount = BATCHREFILL_LIMIT;  
  599.  }  
  600. // 和CPU对应的具体list3链表  
  601.  l3 = cachep->nodelists[node];  
  602.  BUG_ON(ac->avail > 0 || !l3);  
  603.  spin_lock(&l3->list_lock);  
  604.  /* See if we can refill from the shared array */  
  605. // 可从共享的数组中获取空间  
  606.  if (l3->shared && transfer_objects(ac, l3->shared, batchcount))  
  607.   goto alloc_done;  
  608. // 批量循环  
  609.  while (batchcount > 0) {  
  610.   struct list_head *entry;  
  611.   struct slab *slabp;  
  612.   /* Get slab alloc is to come from. */  
  613. // 从部分使用的slab链表中获取链表元素  
  614.   entry = l3->slabs_partial.next;  
  615.   if (entry == &l3->slabs_partial) {  
  616. // 已经到链表头,说明该部分使用的slab链表已经都用完了  
  617. // 得从空闲slab链表中找空间了  
  618.    l3->free_touched = 1;  
  619.    entry = l3->slabs_free.next;  
  620.    if (entry == &l3->slabs_free)  
  621. // 空闲slab链表也用完了, 整个cache该增加了  
  622.     goto must_grow;  
  623.   }  
  624. // 获取可用的slab指针  
  625.   slabp = list_entry(entry, struct slab, list);  
  626.   check_slabp(cachep, slabp);  
  627.   check_spinlock_acquired(cachep);  
  628. // 从该slab块中批量提取可用的对象数  
  629.   while (slabp->inuse < cachep->num && batchcount--) {  
  630.    STATS_INC_ALLOCED(cachep);  
  631.    STATS_INC_ACTIVE(cachep);  
  632.    STATS_SET_HIGH(cachep);  
  633. // avail记录了实际分配出的对象数  
  634.    ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,  
  635.            node);  
  636.   }  
  637.   check_slabp(cachep, slabp);  
  638.   /* move slabp to correct slabp list: */  
  639. // 把该slab先从所在链表断开  
  640.   list_del(&slabp->list);  
  641. // 根据是否slab中的对象已经用完,将slab挂到全部使用链表或部分使用链表  
  642.   if (slabp->free == BUFCTL_END)  
  643.    list_add(&slabp->list, &l3->slabs_full);  
  644.   else  
  645.    list_add(&slabp->list, &l3->slabs_partial);  
  646.  }  
  647. must_grow:  
  648. // 已经分配了一些对象出去, 减少空闲对象数  
  649.  l3->free_objects -= ac->avail;  
  650. alloc_done:  
  651.  spin_unlock(&l3->list_lock);  
  652.  if (unlikely(!ac->avail)) {  
  653. // avail为0, 表示没有可分配的对象了, cache必须增大了  
  654.   int x;  
  655. // 增加cache中内存,增加slab数  
  656.   x = cache_grow(cachep, flags, node);  
  657.   /* cache_grow can reenable interrupts, then ac could change. */  
  658.   ac = cpu_cache_get(cachep);  
  659.   if (!x && ac->avail == 0/* no objects in sight? abort */  
  660.    return NULL;  
  661.   if (!ac->avail)  /* objects refilled by interrupt? */  
  662.    goto retry;  
  663.  }  
  664.  ac->touched = 1;  
  665. // 返回对象指针  
  666.  return ac->entry[--ac->avail];  
  667. }  
  668.    
  669. 4.4 释放cache单元kmem_cache_free  
  670.   
  671. 其实不是真正完全释放, 只是将对象空间添回cache的空闲slab链表中而已  
  672. /** 
  673.  * kmem_cache_free - Deallocate an object 
  674.  * @cachep: The cache the allocation was from. 
  675.  * @objp: The previously allocated object. 
  676.  * 
  677.  * Free an object which was previously allocated from this 
  678.  * cache. 
  679.  */  
  680. // 其实只是__cache_free()的包裹函数  
  681. void kmem_cache_free(struct kmem_cache *cachep, void *objp)  
  682. {  
  683.  unsigned long flags;  
  684.  BUG_ON(virt_to_cache(objp) != cachep);  
  685.  local_irq_save(flags);  
  686.  __cache_free(cachep, objp);  
  687.  local_irq_restore(flags);  
  688. }  
  689. EXPORT_SYMBOL(kmem_cache_free);  
  690.   
  691. /* 
  692.  * Release an obj back to its cache. If the obj has a constructed state, it must 
  693.  * be in this state _before_ it is released.  Called with disabled ints. 
  694.  */  
  695. static inline void __cache_free(struct kmem_cache *cachep, void *objp)  
  696. {  
  697.  struct array_cache *ac = cpu_cache_get(cachep);  
  698.  check_irq_off();  
  699.  objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));  
  700.  if (cache_free_alien(cachep, objp))  
  701.   return;  
  702.  if (likely(ac->avail < ac->limit)) {  
  703. // 空闲值小于限值  
  704.   STATS_INC_FREEHIT(cachep);  
  705. // 只是简单将要释放的cache单元添加到空闲单元数组中  
  706. // avail增加表示可用对象增加  
  707.   ac->entry[ac->avail++] = objp;  
  708.   return;  
  709.  } else {  
  710. // 空闲数大于等于限值  
  711.   STATS_INC_FREEMISS(cachep);  
  712. // 释放一些节点  
  713.   cache_flusharray(cachep, ac);  
  714. // 再将要释放的cache单元添加到空闲单元数组中  
  715. // avail增加表示可用对象增加  
  716.   ac->entry[ac->avail++] = objp;  
  717.  }  
  718. }  
  719.    
  720. 4.5 摧毁cache结构  
  721.   
  722. 这个一般是在模块退出函数中进行清理工作时调用的,如果已经编到内核了, 那这个函数基本不会被  
  723. 调用:  
  724. /** 
  725.  * kmem_cache_destroy - delete a cache 
  726.  * @cachep: the cache to destroy 
  727.  * 
  728.  * Remove a struct kmem_cache object from the slab cache. 
  729.  * 
  730.  * It is expected this function will be called by a module when it is 
  731.  * unloaded.  This will remove the cache completely, and avoid a duplicate 
  732.  * cache being allocated each time a module is loaded and unloaded, if the 
  733.  * module doesn't have persistent in-kernel storage across loads and unloads. 
  734.  * 
  735.  * The cache must be empty before calling this function. 
  736.  * 
  737.  * The caller must guarantee that noone will allocate memory from the cache 
  738.  * during the kmem_cache_destroy(). 
  739.  */  
  740. void kmem_cache_destroy(struct kmem_cache *cachep)  
  741. {  
  742.  BUG_ON(!cachep || in_interrupt());  
  743.  /* Don't let CPUs to come and go */  
  744.  lock_cpu_hotplug();  
  745.  /* Find the cache in the chain of caches. */  
  746.  mutex_lock(&cache_chain_mutex);  
  747.  /* 
  748.   * the chain is never empty, cache_cache is never destroyed 
  749.   */  
  750. // cache的第一个元素cache_cache是静态量,该链表永远不会空  
  751. // 从cache链表中删除cache  
  752.  list_del(&cachep->next);  
  753.  mutex_unlock(&cache_chain_mutex);  
  754. // 尽可能释放cache中的slab单元块  
  755.  if (__cache_shrink(cachep)) {  
  756.   slab_error(cachep, "Can't free all objects");  
  757.   mutex_lock(&cache_chain_mutex);  
  758.   list_add(&cachep->next, &cache_chain);  
  759.   mutex_unlock(&cache_chain_mutex);  
  760.   unlock_cpu_hotplug();  
  761.   return;  
  762.  }  
  763.  if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))  
  764.   synchronize_rcu();  
  765. // 释放cache  
  766.  __kmem_cache_destroy(cachep);  
  767.  unlock_cpu_hotplug();  
  768. }  
  769. EXPORT_SYMBOL(kmem_cache_destroy);  
  770.   
  771. // 真正的摧毁cache函数  
  772. static void __kmem_cache_destroy(struct kmem_cache *cachep)  
  773. {  
  774.  int i;  
  775.  struct kmem_list3 *l3;  
  776. // 释放cache中所有CPU的数组  
  777.  for_each_online_cpu(i)  
  778.      kfree(cachep->array[i]);  
  779.  /* NUMA: free the list3 structures */  
  780. // 释放list3中的所有内存  
  781.  for_each_online_node(i) {  
  782.   l3 = cachep->nodelists[i];  
  783.   if (l3) {  
  784.    kfree(l3->shared);  
  785.    free_alien_cache(l3->alien);  
  786.    kfree(l3);  
  787.   }  
  788.  }  
  789. // 释放cache本身  
  790.  kmem_cache_free(&cache_cache, cachep);  
  791. }  
  792.   
  793. 4.6 缩减cache  
  794.   
  795. 该函数尽可能地释放cache中的slab块, 当cache空闲空间太多时会释放掉一些内存供其他内核部分使  
  796. 用.  
  797.   
  798. /** 
  799.  * kmem_cache_shrink - Shrink a cache. 
  800.  * @cachep: The cache to shrink. 
  801.  * 
  802.  * Releases as many slabs as possible for a cache. 
  803.  * To help debugging, a zero exit status indicates all slabs were released. 
  804.  */  
  805. // 只是一个包裹函数  
  806. int kmem_cache_shrink(struct kmem_cache *cachep)  
  807. {  
  808.  BUG_ON(!cachep || in_interrupt());  
  809.  return __cache_shrink(cachep);  
  810. }  
  811. EXPORT_SYMBOL(kmem_cache_shrink);  
  812.    
  813. static int __cache_shrink(struct kmem_cache *cachep)  
  814. {  
  815.  int ret = 0, i = 0;  
  816.  struct kmem_list3 *l3;  
  817. // 释放cache中每个CPU对应的空间  
  818.  drain_cpu_caches(cachep);  
  819.  check_irq_on();  
  820.  for_each_online_node(i) {  
  821. // 释放每个节点的list3  
  822.   l3 = cachep->nodelists[i];  
  823.   if (!l3)  
  824.    continue;  
  825. // 将slab从slab_free中释放  
  826.   drain_freelist(cachep, l3, l3->free_objects);  
  827.   ret += !list_empty(&l3->slabs_full) ||  
  828.    !list_empty(&l3->slabs_partial);  
  829.  }  
  830.  return (ret ? 1 : 0);  
  831. }  
  832.   
  833. static void drain_cpu_caches(struct kmem_cache *cachep)  
  834. {  
  835.  struct kmem_list3 *l3;  
  836.  int node;  
  837.  on_each_cpu(do_drain, cachep, 11);  
  838.  check_irq_on();  
  839.  for_each_online_node(node) {  
  840.   l3 = cachep->nodelists[node];  
  841.   if (l3 && l3->alien)  
  842. // 释放cache的list3的alien部分  
  843.    drain_alien_cache(cachep, l3->alien);  
  844.  }  
  845.  for_each_online_node(node) {  
  846.   l3 = cachep->nodelists[node];  
  847.   if (l3)  
  848. // 释放list3的数组空间  
  849.    drain_array(cachep, l3, l3->shared, 1, node);  
  850.  }  
  851. }  
  852. /* 
  853.  * Remove slabs from the list of free slabs. 
  854.  * Specify the number of slabs to drain in tofree. 
  855.  * 
  856.  * Returns the actual number of slabs released. 
  857.  */  
  858. static int drain_freelist(struct kmem_cache *cache,  
  859.    struct kmem_list3 *l3, int tofree)  
  860. {  
  861.  struct list_head *p;  
  862.  int nr_freed;  
  863.  struct slab *slabp;  
  864.  nr_freed = 0;  
  865. // 从slabs_free链表释放  
  866.  while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {  
  867.   spin_lock_irq(&l3->list_lock);  
  868.   p = l3->slabs_free.prev;  
  869.   if (p == &l3->slabs_free) {  
  870.    spin_unlock_irq(&l3->list_lock);  
  871.    goto out;  
  872.   }  
  873. // 获取slab  
  874.   slabp = list_entry(p, struct slab, list);  
  875. #if DEBUG  
  876.   BUG_ON(slabp->inuse);  
  877. #endif  
  878. // 将slab从链表中删除  
  879.   list_del(&slabp->list);  
  880.   /* 
  881.    * Safe to drop the lock. The slab is no longer linked 
  882.    * to the cache. 
  883.    */  
  884. // 空闲对象数减少一个slab中的对象数  
  885.   l3->free_objects -= cache->num;  
  886.   spin_unlock_irq(&l3->list_lock);  
  887. // 释放slab  
  888.   slab_destroy(cache, slabp);  
  889.   nr_freed++;  
  890.  }  
  891. out:  
  892.  return nr_freed;  
  893. }  
  894.    
  895. 4.7  kmalloc和kfree  
  896. kmalloc也是通过cache来实现的, 只不过每此kmalloc的大小不同, 因此是从不同的cache中分配:  
  897. /* include/linux/slab.h */  
  898. // 注意kmalloc是在头文件中定义的  
  899. static inline void *kmalloc(size_t size, gfp_t flags)  
  900. {  
  901.  if (__builtin_constant_p(size)) {  
  902. // 以下是找一个对象大小刚好大于等于size的cache  
  903.   int i = 0;  
  904. #define CACHE(x) \  
  905.   if (size <= x) \  
  906.    goto found; \  
  907.   else \  
  908.    i++;  
  909. #include "kmalloc_sizes.h"  
  910. #undef CACHE  
  911.   {  
  912.    extern void __you_cannot_kmalloc_that_much(void);  
  913.    __you_cannot_kmalloc_that_much();  
  914.   }  
  915. found:  
  916. // 实际还是通过kmem_cache_alloc来分配内存空间, 因此也是cache  
  917.   return kmem_cache_alloc((flags & GFP_DMA) ?  
  918.    malloc_sizes[i].cs_dmacachep :  
  919.    malloc_sizes[i].cs_cachep, flags);  
  920.  }  
  921. // 通过该函数最后也是由__cache_alloc()函数来分配空间  
  922.  return __kmalloc(size, flags);  
  923. }  
  924.   
  925. // 这是kmalloc_sizes.h文件内容, 实际就是定义CACHE中可用的对象大小  
  926. // 普通情况下最大是128K, 也就是kmalloc能分配的最大内存量  
  927. #if (PAGE_SIZE == 4096)  
  928.  CACHE(32)  
  929. #endif  
  930.  CACHE(64)  
  931. #if L1_CACHE_BYTES < 64  
  932.  CACHE(96)  
  933. #endif  
  934.  CACHE(128)  
  935. #if L1_CACHE_BYTES < 128  
  936.  CACHE(192)  
  937. #endif  
  938.  CACHE(256)  
  939.  CACHE(512)  
  940.  CACHE(1024)  
  941.  CACHE(2048)  
  942.  CACHE(4096)  
  943.  CACHE(8192)  
  944.  CACHE(16384)  
  945.  CACHE(32768)  
  946.  CACHE(65536)  
  947.  CACHE(131072)  
  948. #if (NR_CPUS > 512) || (MAX_NUMNODES > 256) || !defined(CONFIG_MMU)  
  949.  CACHE(262144)  
  950. #endif  
  951. #ifndef CONFIG_MMU  
  952.  CACHE(524288)  
  953.  CACHE(1048576)  
  954. #ifdef CONFIG_LARGE_ALLOCS  
  955.  CACHE(2097152)  
  956.  CACHE(4194304)  
  957.  CACHE(8388608)  
  958.  CACHE(16777216)  
  959.  CACHE(33554432)  
  960. #endif /* CONFIG_LARGE_ALLOCS */  
  961. #endif /* CONFIG_MMU 
  962. /* mm/slab.c */  
  963. // kfree实际也是调用__cache_free来释放空间  
  964. void kfree(const void *objp)  
  965. {  
  966.  struct kmem_cache *c;  
  967.  unsigned long flags;  
  968.  if (unlikely(!objp))  
  969.   return;  
  970.  local_irq_save(flags);  
  971.  kfree_debugcheck(objp);  
  972.  c = virt_to_cache(objp);  
  973.  debug_check_no_locks_freed(objp, obj_size(c));  
  974.  __cache_free(c, (void *)objp);  
  975.  local_irq_restore(flags);  
  976. }  
  977. EXPORT_SYMBOL(kfree);  
  978.    
  979. 5. 结论  
  980.   
  981. cache的使用使得在频繁增加删除对象的处理效率得到提高, 这也就是为什么普通情况下  
  982. 从/proc/meminfo中看Linux的空闲内存不多的原因,因为很多内存都是cache的,没有真正释放。 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值