Linux的Cache和Buffer理解

系统 Linux
首先说明,本文讨论的cache指的是Linux中的page cache,buffer指的是buffer cache,也即cat /proc/meminfo中显示的cache和buffer。

首先说明,本文讨论的cache指的是Linux中的page cache,buffer指的是buffer cache,也即cat /proc/meminfo中显示的cache和buffer。

我们知道,Linux下频繁存取文件或单个大文件时物理内存会很快被用光,当程序结束后内存不会被正常释放而是一直作为cahce占着内存。因此系统经常会因为这点导致OOM产生,尤其在等大压力场景下概率较高,此时,第一时间查看cache和buffer内存是非常高的。此类问题目前尚未有一个很好的解决方案,以往遇到大多会做规避处理,因此本案尝试给出一个分析和解决的思路。

解决该问题的关键是理解什么是cache和buffer,什么时候消耗在哪里以及如何控制cache和buffer,所以本问主要围绕这几点展开。整个讨论过程尽量先从内核源码分析入手,然后提炼APP相关接口并进行实际操作验证,最后总结给出应用程序的编程建议。

可以通过free或者cat /proc/meminfo查看到系统的buffer和cache情况。

Linux的Cache和Buffer理解

free命令的全解析

1. Cache和Buffer分析

从cat /proc/meminfo入手,先看看该接口的实现:

  1. static int meminfo_proc_show(struct seq_file *m, void *v)  
  2.  
  3. ……  
  4. cached = global_page_state(NR_FILE_PAGES) -  
  5.  total_swapcache_pages() - i.bufferram;  
  6. if (cached < 0 
  7.  cached = 0 
  8. ……  
  9.  seq_printf(m,  
  10.  "MemTotal: %8lu kB\n"  
  11.  "MemFree: %8lu kB\n"  
  12.  "Buffers: %8lu kB\n"  
  13.  "Cached: %8lu kB\n"  
  14.  ……  
  15.  ,  
  16.  K(i.totalram),  
  17.  K(i.freeram),  
  18.  K(i.bufferram),  
  19.  K(cached),  
  20.  ……  
  21.  );  
  22. ……  

其中,内核中以页框为单位,通过宏K转化成以KB为单位输出。这些值是通过si_meminfo来获取的:

  1. void si_meminfo(struct sysinfo *val) 
  2.  val->totalram = totalram_pages
  3.  val->sharedram = 0
  4.  val->freeram = global_page_state(NR_FREE_PAGES); 
  5.  val->bufferram = nr_blockdev_pages(); 
  6.  val->totalhigh = totalhigh_pages
  7.  val->freehigh = nr_free_highpages(); 
  8.  val->mem_unit = PAGE_SIZE

其中bufferram来自于nr_blockdev_pages(),该函数计算块设备使用的页框数,遍历所有块设备,将使用的页框数相加。而不包含普通文件使用的页框数。

  1. long nr_blockdev_pages(void)  
  2.  
  3.  struct block_device *bdev;  
  4.  long ret = 0 
  5.  spin_lock(&bdev_lock);  
  6.  list_for_each_entry(bdev, &all_bdevs, bd_list) {  
  7.  ret += bdev->bd_inode->i_mapping->nrpages;  
  8.  }  
  9.  spin_unlock(&bdev_lock);  
  10.  return ret;  

从以上得出meminfo中cache和buffer的来源:

  • Buffer就是块设备占用的页框数量;
  • Cache的大小为内核总的page cache减去swap cache和块设备占用的页框数量,实际上cache即为普通文件的占用的page cache。

通过内核代码分析(这里略过复杂的内核代码分析),虽然两者在实现上差别不是很大,都是通过address_space对象进行管理的,但是page cache是对文件数据的缓存而buffer cache是对块设备数据的缓存。对于每个块设备都会分配一个def_blk_ops的文件操作方法,这是设备的操作方法,在每个块设备的inode(bdev伪文件系统的inode)下面会存在一个radix tree,这个radix tree下面将会放置缓存数据的page页。这个page的数量将会在cat /proc/meminfobuffer一栏中显示。也就是在没有文件系统的情况下,采用dd等工具直接对块设备进行操作的数据会缓存到buffer cache中。如果块设备做了文件系统,那么文件系统中的文件都有一个inode,这个inode会分配ext3_ops之类的操作方法,这些方法是文件系统的方法,在这个inode下面同样存在一个radix tree,这里也会缓存文件的page页,缓存页的数量在cat /proc/meminfo的cache一栏进行统计。此时对文件操作,那么数据大多会缓存到page cache,不多的是文件系统文件的元数据会缓存到buffer cache。

这里,我们使用cp命令拷贝一个50MB的文件操作,内存会发生什么变化:

  1. [root nfs_dir] # ll -h file_50MB.bin 
  2. -rw-rw-r-- 1 4104 4106 50.0M Feb 24 2016 file_50MB.bin 
  3. [root nfs_dir] # cat /proc/meminfo 
  4. MemTotal: 90532 kB 
  5. MemFree: 65696 kB 
  6. Buffers: 0 kB 
  7. Cached: 8148 kB 
  8. …… 
  9. [root@test nfs_dir] # cp file_50MB.bin / 
  10. [root@test nfs_dir] # cat /proc/meminfo 
  11. MemTotal: 90532 kB 
  12. MemFree: 13012 kB 
  13. Buffers: 0 kB 
  14. Cached: 60488 kB 

可以看到cp命令前后,MemFree从65696 kB减少为13012 kB,Cached从8148 kB增大为60488 kB,而Buffers却不变。那么过一段时间,Linux会自动释放掉所用的cache内存吗?一个小时后查看proc/meminfo显示cache仍然没有变化。

接着,我们看下使用dd命令对块设备写操作前后的内存变化:

  1. [0225_19:10:44:10s][root@test nfs_dir] # cat /proc/meminfo 
  2. [0225_19:10:44:10s]MemTotal: 90532 kB  
  3. [0225_19:10:44:10s]MemFree: 58988 kB  
  4. [0225_19:10:44:10s]Buffers: 0 kB  
  5. [0225_19:10:44:10s]Cached: 4144 kB  
  6. ...... ......  
  7. [0225_19:11:13:11s][root@test nfs_dir] # dd if=/dev/zero of=/dev/h_sda bs=10M count=2000 &  
  8. [0225_19:11:17:11s][root@test nfs_dir] # cat /proc/meminfo  
  9. [0225_19:11:17:11s]MemTotal: 90532 kB  
  10. [0225_19:11:17:11s]MemFree: 11852 kB  
  11. [0225_19:11:17:11s]Buffers: 36224 kB  
  12. [0225_19:11:17:11s]Cached: 4148 kB  
  13. ...... ......  
  14. [0225_19:11:21:11s][root@test nfs_dir] # cat /proc/meminfo  
  15. [0225_19:11:21:11s]MemTotal: 90532 kB  
  16. [0225_19:11:21:11s]MemFree: 11356 kB  
  17. [0225_19:11:21:11s]Buffers: 36732 kB  
  18. [0225_19:11:21:11s]Cached: 4148kB  
  19. ...... ......  
  20. [0225_19:11:41:11s][root@test nfs_dir] # cat /proc/meminfo  
  21. [0225_19:11:41:11s]MemTotal: 90532 kB  
  22. [0225_19:11:41:11s]MemFree: 11864 kB  
  23. [0225_19:11:41:11s]Buffers: 36264 kB  
  24. [0225_19:11:41:11s]Cached: 4148 kB  
  25. ….. …… 

裸写块设备前Buffs为0,裸写硬盘过程中每隔一段时间查看内存信息发现Buffers一直在增加,空闲内存越来越少,而Cached数量一直保持不变。

总结:

通过代码分析及实际操作,我们理解了buffer cache和page cache都会占用内存,但也看到了两者的差别。page cache针对文件的cache,buffer是针对块设备数据的cache。Linux在可用内存充裕的情况下,不会主动释放page cache和buffer cache。

2. 使用posix_fadvise控制Cache

在Linux中文件的读写一般是通过buffer io方式,以便充分利用到page cache。

Buffer IO的特点是读的时候,先检查页缓存里面是否有需要的数据,如果没有就从设备读取,返回给用户的同时,加到缓存一份;写的时候,直接写到缓存去,再由后台的进程定期刷到磁盘去。这样的机制看起来非常的好,实际也能提高文件读写的效率。

但是当系统的IO比较密集时,就会出问题。当系统写的很多,超过了内存的某个上限时,后台的回写线程就会出来回收页面,但是一旦回收的速度小于写入的速度,就会触发OOM。最关键的是整个过程由内核参与,用户不好控制。

那么到底如何才能有效的控制cache呢?

目前主要由两种方法来规避风险:

  • 走direct io;
  • 走buffer io,但是定期清除无用page cache;

这里当然讨论的是第二种方式,即在buffer io方式下如何有效控制page cache。

在程序中只要知道文件的句柄,就能用:

  1. int posix_fadvise(int fd, off_t offset, off_t len, int advice); 

POSIX_FADV_DONTNEED (该文件在接下来不会再被访问),但是曾有开发人员反馈怀疑该接口的有效性。那么该接口确实有效吗?首先,我们查看mm/fadvise.c内核代码来看posix_fadvise是如何实现的:

  1. /*  
  2.  * POSIX_FADV_WILLNEED could set PG_Referenced, and POSIX_FADV_NOREUSE could  
  3.  * deactivate the pages and clear PG_Referenced.  
  4.  */  
  5. SYSCALL_DEFINE4(fadvise64_64, int, fd, loff_t, offset, loff_t, len, int, advice)  
  6.  
  7.  … … … …  
  8.  /* => 将指定范围内的数据从page cache中换出 */  
  9.  case POSIX_FADV_DONTNEED:  
  10.  /* => 如果后备设备不忙的话,先调用__filemap_fdatawrite_range把脏页面刷掉 */  
  11.  if (!bdi_write_congested(mapping->backing_dev_info))  
  12.  /* => WB_SYNC_NONE: 不是同步等待页面刷新完成,只是提交了 */  
  13.  /* => 而fsync和fdatasync是用WB_SYNC_ALL参数等到完成才返回的 */  
  14.  __filemap_fdatawrite_range(mapping, offset, endbyte,  
  15.  WB_SYNC_NONE);  
  16.   
  17.  
  18.  /* First and last FULL page! */  
  19.  start_index = (offset+(PAGE_CACHE_SIZE-1)) >> PAGE_CACHE_SHIFT;  
  20.  end_index = (endbyte >> PAGE_CACHE_SHIFT);  
  21.   
  22.  
  23.  /* => 接下来清除页面缓存 */ 
  24.  if (end_index >= start_index) {  
  25.  unsigned long count = invalidate_mapping_pages(mapping,  
  26.  start_index, end_index); 
  27.   
  28.  
  29.  /*  
  30.  * If fewer pages were invalidated than expected then  
  31.  * it is possible that some of the pages were on 
  32.  * a per-cpu pagevec for a remote CPU. Drain all  
  33.  * pagevecs and try again.  
  34.  */  
  35.  if (count < (end_index - start_index + 1)) {  
  36.  lru_add_drain_all();  
  37.  invalidate_mapping_pages(mapping, start_index,  
  38.  end_index);  
  39.  }  
  40.  }  
  41.  break;  
  42. … … … …  

我们可以看到如果后台系统不忙的话,会先调用__filemap_fdatawrite_range把脏页面刷掉,刷页面用的参数是是 WB_SYNC_NONE,也就是说不是同步等待页面刷新完成,提交完写脏页后立即返回了。

然后再调invalidate_mapping_pages清除页面,回收内存:

  1. /* => 清除缓存页(除了脏页、上锁的、正在回写的或映射在页表中的)*/  
  2. unsigned long invalidate_mapping_pages(struct address_space *mapping,  
  3.  pgoff_t start, pgoff_t end)  
  4.  
  5.  struct pagevec pvec;  
  6.  pgoff_t index = start 
  7.  unsigned long ret;  
  8.  unsigned long count = 0 
  9.  int i;  
  10.   
  11.  
  12.  /*  
  13.  * Note: this function may get called on a shmem/tmpfs mapping:  
  14.  * pagevec_lookup() might then return 0 prematurely (because it  
  15.  * got a gangful of swap entries); but it's hardly worth worrying  
  16.  * about - it can rarely have anything to free from such a mapping  
  17.  * (most pages are dirty), and already skips over any difficulties.  
  18.  */  
  19.   
  20.  
  21.  pagevec_init(&pvec, 0);  
  22.  while (index <= end && pagevec_lookup(&pvec, mapping, index,  
  23.  min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1)) {  
  24.  mem_cgroup_uncharge_start();  
  25.  for (i = 0; i < pagevec_count(&pvec); i++) {  
  26.  struct page *page = pvec.pages[i];  
  27.   
  28.  
  29.  /* We rely upon deletion not changing page->index */  
  30.  index = page->index;  
  31.  if (index > end)  
  32.  break;  
  33.   
  34.  
  35.  if (!trylock_page(page))  
  36.  continue;  
  37.  WARN_ON(page->index != index);  
  38.  /* => 无效一个文件的缓存 */  
  39.  ret = invalidate_inode_page(page);  
  40.  unlock_page(page);  
  41.  /*  
  42.  * Invalidation is a hint that the page is no longer  
  43.  * of interest and try to speed up its reclaim.  
  44.  */  
  45.  if (!ret)  
  46.  deactivate_page(page);  
  47.  count += ret;  
  48.  }  
  49.  pagevec_release(&pvec);  
  50.  mem_cgroup_uncharge_end();  
  51.  cond_resched();  
  52.  index++;  
  53.  }  
  54.  return count;  
  55.    
  56.  
  57. /*  
  58.  * Safely invalidate one page from its pagecache mapping.  
  59.  * It only drops clean, unused pages. The page must be locked.  
  60.  *  
  61.  * Returns 1 if the page is successfully invalidated, otherwise 0.  
  62.  */  
  63. /* => 无效一个文件的缓存 */  
  64. int invalidate_inode_page(struct page *page)  
  65.  
  66.  struct address_space *mapping = page_mapping(page);  
  67.  if (!mapping)  
  68.  return 0;  
  69.  /* => 若当前页是脏页或正在写回的页,直接返回 */  
  70.  if (PageDirty(page) || PageWriteback(page))  
  71.  return 0;  
  72.  /* => 若已经被映射到页表了,则直接返回 */  
  73.  if (page_mapped(page))  
  74.  return 0;  
  75.  /* => 如果满足了以上条件就调用invalidate_complete_page继续 */  
  76.  return invalidate_complete_page(mapping, page);  
  77.  
  78. 从上面的代码可以看到清除相关的页面要满足二个条件: 1. 不脏且没在回写; 2. 未被使用。如果满足了这二个条件就调用invalidate_complete_page继续:  
  79. /* => 无效一个完整的页 */  
  80. static int  
  81. invalidate_complete_page(struct address_space *mapping, struct page *page)  
  82.  
  83.  int ret;  
  84.   
  85.  
  86.  if (page->mapping != mapping)  
  87.  return 0;  
  88.   
  89.  
  90.  if (page_has_private(page) && !try_to_release_page(page, 0))  
  91.  return 0;  
  92.   
  93.  
  94.  /* => 若满足以上更多条件,则从地址空间中解除该页 */  
  95.  ret = remove_mapping(mapping, page); 
  96.    
  97.  
  98.  return ret;  
  99.  
  100.   
  101.  
  102. /*  
  103.  * Attempt to detach a locked page from its ->mapping. If it is dirty or if  
  104.  * someone else has a ref on the page, abort and return 0. If it was  
  105.  * successfully detached, return 1. Assumes the caller has a single ref on  
  106.  * this page.  
  107.  */  
  108. /* => 从地址空间中解除该页 */  
  109. int remove_mapping(struct address_space *mapping, struct page *page) 
  110.  
  111.  if (__remove_mapping(mapping, page)) {  
  112.  /*  
  113.  * Unfreezing the refcount with 1 rather than 2 effectively  
  114.  * drops the pagecache ref for us without requiring another  
  115.  * atomic operation.  
  116.  */  
  117.  page_unfreeze_refs(page, 1);  
  118.  return 1;  
  119.  }  
  120.  return 0;  
  121.    
  122.  
  123. /*  
  124.  * Same as remove_mapping, but if the page is removed from the mapping, it  
  125.  * gets returned with a refcount of 0.  
  126.  */  
  127. /* => 从地址空间中解除该页 */  
  128. static int __remove_mapping(struct address_space *mapping, struct page *page)  
  129.  
  130.  BUG_ON(!PageLocked(page));  
  131.  BUG_ON(mapping != page_mapping(page));  
  132.   
  133.  
  134.  spin_lock_irq(&mapping->tree_lock);  
  135.  /*  
  136.  * The non racy check for a busy page.  
  137.  *  
  138.  * Must be careful with the order of the tests. When someone has  
  139.  * a ref to the page, it may be possible that they dirty it then  
  140.  * drop the reference. So if PageDirty is tested before page_count 
  141.  * here, then the following race may occur: 
  142.  *  
  143.  * get_user_pages(&page);  
  144.  * [user mapping goes away]  
  145.  * write_to(page);  
  146.  * !PageDirty(page) [good]  
  147.  * SetPageDirty(page); 
  148.  * put_page(page); 
  149.  * !page_count(page) [good, discard it]  
  150.  *  
  151.  * [oops, our write_to data is lost]  
  152.  *  
  153.  * Reversing the order of the tests ensures such a situation cannot  
  154.  * escape unnoticed. The smp_rmb is needed to ensure the page->flags  
  155.  * load is not satisfied before that of page->_count.  
  156.  *  
  157.  * Note that if SetPageDirty is always performed via set_page_dirty,  
  158.  * and thus under tree_lock, then this ordering is not required. 
  159.  */  
  160.  if (!page_freeze_refs(page, 2))  
  161.  goto cannot_free;  
  162.  /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */  
  163.  if (unlikely(PageDirty(page))) {  
  164.  page_unfreeze_refs(page, 2);  
  165.  goto cannot_free; 
  166.  } 
  167.   
  168.  if (PageSwapCache(page)) {  
  169.  swp_entry_t swap = { .val = page_private(page) }; 
  170.  __delete_from_swap_cache(page);  
  171.  spin_unlock_irq(&mapping->tree_lock);  
  172.  swapcache_free(swap, page);  
  173.  } else {  
  174.  void (*freepage)(struct page *);  
  175.   
  176.  
  177.  freepage = mapping->a_ops->freepage;  
  178.   
  179.   /* => 从页缓存中删除和释放该页 */ 
  180.   __delete_from_page_cache(page); 
  181.   spin_unlock_irq(&mapping->tree_lock); 
  182.   mem_cgroup_uncharge_cache_page(page); 
  183.    
  184.   if (freepage != NULL) 
  185.   freepage(page);  
  186.  }  
  187.   
  188.   return 1;  
  189.   
  190.  
  191. cannot_free:  
  192.  spin_unlock_irq(&mapping->tree_lock);  
  193.  return 0;  
  194.  
  195.   
  196.  /* 
  197.  * Delete a page from the page cache and free it. Caller has to make  
  198.  * sure the page is locked and that nobody else uses it - or that usage  
  199.  * is safe. The caller must hold the mapping's tree_lock.  
  200.  */  
  201. /* => 从页缓存中删除和释放该页 */  
  202. void __delete_from_page_cache(struct page *page)  
  203.  
  204.  struct address_space *mapping = page->mapping;  
  205.    
  206.  trace_mm_filemap_delete_from_page_cache(page);  
  207.  /*  
  208.  * if we're uptodate, flush out into the cleancache, otherwise  
  209.  * invalidate any existing cleancache entries. We can't leave  
  210.  * stale data around in the cleancache once our page is gone  
  211.  */  
  212.  if (PageUptodate(page) && PageMappedToDisk(page))  
  213.  cleancache_put_page(page);  
  214.  else  
  215.  cleancache_invalidate_page(mapping, page);  
  216.   
  217.  
  218.  radix_tree_delete(&mapping->page_tree, page->index);  
  219.  /* => 解除与之绑定的地址空间结构 */  
  220.  page->mapping = NULL 
  221.  /* Leave page->index set: truncation lookup relies upon it */  
  222.  /* => 减少地址空间中的页计数 */ 
  223.  mapping->nrpages--; 
  224.  __dec_zone_page_state(page, NR_FILE_PAGES);  
  225.  if (PageSwapBacked(page))  
  226.  __dec_zone_page_state(page, NR_SHMEM);  
  227.  BUG_ON(page_mapped(page)); 
  228.    
  229.  
  230.  /*  
  231.  * Some filesystems seem to re-dirty the page even after  
  232.  * the VM has canceled the dirty bit (eg ext3 journaling).  
  233.  *  
  234.  * Fix it up by doing a final dirty accounting check after  
  235.  * having removed the page entirely.  
  236.  */  
  237.  if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {  
  238.  dec_zone_page_state(page, NR_FILE_DIRTY);  
  239.  dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE); 
  240.  } 

看到这里我们就明白了:为什么使用了posix_fadvise后相关的内存没有被释放出来:页面还脏是最关键的因素。

但是我们如何保证页面全部不脏呢?fdatasync或者fsync都是选择,或者Linux下新系统调用sync_file_range都是可用的,这几个都是使用WB_SYNC_ALL模式强制要求回写完毕才返回的。所以应该这样做:

  1. fdatasync(fd); 
  2. posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); 

总结:

使用posix_fadvise可以有效的清除page cache,作用范围为文件级。下面给出应用程序编程建议:

  • 用于测试I/O的效率时,可以用posix_fadvise来消除cache的影响;
  • 当确认访问的文件在接下来一段时间不再被访问时,很有必要调用posix_fadvise来避免占用不必要的可用内存空间。
  • 若当前系统内存十分紧张时,且在读写一个很大的文件时,为避免OOM风险,可以分段边读写边清cache,但也直接导致性能的下降,毕竟空间和时间是一对矛盾体。

3. 使用vmtouch控制Cache

vmtouch是一个可移植的文件系统cahce诊断和控制工具。近来该工具被广泛使用,最典型的例子是:移动应用Instagram(照片墙)后台服务端使用了vmtouch管理控制page cache。了解vmtouch原理及使用可以为我们后续后端设备所用。

快速安装指南:

  1. $ git clone https://github.com/hoytech/vmtouch.git 
  2. $ cd vmtouch 
  3. $ make 
  4. $ sudo make install 

vmtouch用途:

  • 查看一个文件(或者目录)哪些部分在内存中;
  • 把文件调入内存;
  • 把文件清除出内存,即释放page cache;
  • 把文件锁住在内存中而不被换出到磁盘上;
  • ……

vmtouch实现:

其核心分别是两个系统调用,mincore和posix_fadvise。两者具体使用方法使用man帮助都有详细的说明。posix_fadvise已在上文提到,用法在此不作说明。简单说下mincore:

  1. NAME 
  2.  mincore - determine whether pages are resident in memory 
  3.  
  4.   
  5. SYNOPSIS 
  6.  #include <unistd.h> 
  7.  #include <sys/mman.h> 
  8.   
  9.  
  10.  int mincore(void *addr, size_t length, unsigned char *vec); 
  11.  
  12.   
  13.  Feature Test Macro Requirements for glibc (see feature_test_macros(7)): 
  14.  
  15.   
  16.  mincore(): _BSD_SOURCE || _SVID_SOURCE 

mincore需要调用者传入文件的地址(通常由mmap()返回),它会把文件在内存中的情况写在vec中。

vmtouch工具用法:

Usage:vmtouch [OPTIONS] ... FILES OR DIRECTORIES ...

Options:

  • -t touch pages into memory
  • -e evict pages from memory
  • -l lock pages in physical memory with mlock(2)
  • -L lock pages in physical memory with mlockall(2)
  • -d daemon mode
  • -m max file size to touch
  • -p use the specified portion instead of the entire file
  • -f follow symbolic links
  • -h also count hardlinked copies
  • -w wait until all pages are locked (only useful together with -d)
  • -v verbose
  • -q quiet

用法举例:

例1、 获取当前/mnt/usb目录下cache占用量

  1. [root@test nfs_dir] # mkdir /mnt/usb && mount /dev/msc /mnt/usb/  
  2. [root@test usb] # vmtouch .  
  3.  Files: 57  
  4.  Directories: 2  
  5.  Resident Pages: 0/278786 0/1G 0%  
  6.  Elapsed: 0.023126 seconds 

例2、 当前test.bin文件的cache占用量?

  1. [root@test usb] # vmtouch -v test.bin  
  2. test.bin  
  3. [ ] 0/25600  
  4.   
  5.  
  6.  Files: 1  
  7.  Directories: 0  
  8.  Resident Pages: 0/25600 0/100M 0%  
  9.  Elapsed: 0.001867 seconds 

这时使用tail命令将部分文件读取到内存中:

  1. [root@test usb] # busybox_v400 tail -n 10 test.bin > /dev/null 

现在再来看一下:

  1. [root@test usb] # vmtouch -v test.bin  
  2. test.bin  
  3. [ o] 240/25600  
  4.   
  5.  
  6.  Files: 1  
  7.  Directories: 0  
  8.  Resident Pages: 240/25600 960K/100M 0.938%  
  9.  Elapsed: 0.002019 seconds 

可知目前文件test.bin的最后240个page驻留在内存中。

例3、 最后使用-t选项将剩下的test.bin文件全部读入内存:

  1. [root@test usb] # vmtouch -vt test.bin  
  2. test.bin  
  3. [OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO] 25600/25600  
  4.   
  5.  
  6.  Files: 1  
  7.  Directories: 0  
  8.  Touched Pages: 25600 (100M) 
  9.  Elapsed: 39.049 seconds 

例4、 再把test.bin占用的cachae全部释放:

  1. [root@test usb] # vmtouch -ev test.bin  
  2. Evicting test.bin  
  3.   
  4.  
  5.  Files: 1  
  6.  Directories: 0  
  7.  Evicted Pages: 25600 (100M)  
  8.  Elapsed: 0.01461 seconds 

这时候再来看下是否真的被释放了:

  1. [root@test usb] # vmtouch -v test.bin  
  2. test.bin  
  3. [ ] 0/25600  
  4.   
  5.  
  6.  Files: 1  
  7.  Directories: 0  
  8.  Resident Pages: 0/25600 0/100M 0%  
  9.  Elapsed: 0.001867 seconds 

以上通过代码分析及实际操作总结了vmtouch工具的使用,建议APP组后续集成或借鉴vmtouch工具并灵活应用到后端设备中,必能达到有效管理和控制page cache的目的。

4. 使用BLKFLSBUF清Buffer

通过走读块设备驱动IOCTL命令实现,发现该命令能有效的清除整个块设备所占用的buffer。

  1. int blkdev_ioctl(struct block_device *bdev, fmode_t mode, unsigned cmd,  
  2.  unsigned long arg)  
  3.  
  4.  struct gendisk *disk = bdev->bd_disk;  
  5.  struct backing_dev_info *bdi;  
  6.  loff_t size;  
  7.  int ret, n;  
  8.   
  9.  
  10.  switch(cmd) {  
  11.  case BLKFLSBUF:  
  12.  if (!capable(CAP_SYS_ADMIN))  
  13.  return -EACCES;  
  14.   
  15.  
  16.  ret = __blkdev_driver_ioctl(bdev, mode, cmd, arg);  
  17.  if (!is_unrecognized_ioctl(ret))  
  18.  return ret;  
  19.   
  20.  
  21.  fsync_bdev(bdev);  
  22.  invalidate_bdev(bdev); 
  23.  return 0;  
  24. case ……:  
  25. …………  
  26.  
  27.   
  28.  
  29. /* Invalidate clean unused buffers and pagecache. */  
  30. void invalidate_bdev(struct block_device *bdev)  
  31.  
  32.  struct address_space *mapping = bdev->bd_inode->i_mapping;  
  33.   
  34.  
  35.  if (mapping->nrpages == 0)  
  36.  return;  
  37.   
  38.  
  39.  invalidate_bh_lrus();  
  40.  lru_add_drain_all(); /* make sure all lru add caches are flushed */  
  41.  invalidate_mapping_pages(mapping, 0, -1);  
  42.  /* 99% of the time, we don't need to flush the cleancache on the bdev.  
  43.  * But, for the strange corners, lets be cautious  
  44.  */  
  45.  cleancache_invalidate_inode(mapping);  
  46.  
  47. EXPORT_SYMBOL(invalidate_bdev); 

光代码不够,现在让我们看下对/dev/h_sda这个块设备执行BLKFLSBUF的IOCTL命令前后的实际内存变化:

  1. [0225_19:10:25:10s][root@test nfs_dir] # cat /proc/meminfo  
  2. [0225_19:10:25:10s]MemTotal: 90532 kB  
  3. [0225_19:10:25:10s]MemFree: 12296 kB  
  4. [0225_19:10:25:10s]Buffers: 46076 kB  
  5. [0225_19:10:25:10s]Cached: 4136 kB  
  6. …………  
  7. [0225_19:10:42:10s][root@test nfs_dir] # /mnt/nfs_dir/a.out  
  8. [0225_19:10:42:10s]ioctl cmd BLKFLSBUF ok!  
  9. [0225_19:10:44:10s][root@test nfs_dir] # cat /proc/meminfo  
  10. [0225_19:10:44:10s]MemTotal: 90532 kB  
  11. [0225_19:10:44:10s]MemFree: 58988 kB  
  12. [0225_19:10:44:10s]Buffers: 0 kB  
  13. …………  
  14. [0225_19:10:44:10s]Cached: 4144 kB 

执行的效果如代码中看到的,Buffers已被全部清除了,MemFree一下增长了约46MB,可以知道原先的Buffer已被回收并转化为可用的内存。整个过程Cache几乎没有变化,仅增加的8K cache内存可以推断用于a.out本身及其他库文件的加载。

上述a.out的示例如下:

  1. #include <stdio.h>  
  2. #include <fcntl.h>  
  3. #include <errno.h> 
  4. #include <sys/ioctl.h> 
  5. #define BLKFLSBUF _IO(0x12, 97) 
  6. int main(int argc, char* argv[])  
  7.  
  8.  int fd = -1;  
  9.  fd = open("/dev/h_sda", O_RDWR); 
  10.  if (fd < 0
  11.  { 
  12.  return -1; 
  13.  }  
  14.  if (ioctl(fd, BLKFLSBUF, 0))  
  15.  {  
  16.  printf("ioctl cmd BLKFLSBUF failed, errno:%d\n", errno);  
  17.  } 
  18.  close(fd); 
  19. printf("ioctl cmd BLKFLSBUF ok!\n"); 
  20.  return 0;  

综上,使用块设备命令BLKFLSBUF能有效的清除块设备上的所有buffer,且清除后的buffer能立即被释放变为可用内存。

利用这一点,联系后端业务场景,给出应用程序编程建议:

  • 每次关闭一个块设备文件描述符前,必须要调用BLKFLSBUF命令,确保buffer中的脏数据及时刷入块设备,避免意外断电导致数据丢失,同时也起到及时释放回收buffer的目的。
  • 当操作一个较大的块设备时,必要时可以调用BLKFLSBUF命令。怎样算较大的块设备?一般理解为当前Linux系统可用的物理内存小于操作的块设备大小。

5. 使用drop_caches控制Cache和Buffer

/proc是一个虚拟文件系统,我们可以通过对它的读写操作作为与kernel实体间进行通信的一种手段.也就是说可以通过修改/proc中的文件来对当前kernel的行为做出调整。关于Cache和Buffer的控制,我们可以通过echo 1 > /proc/sys/vm/drop_caches进行操作。

首先来看下内核源码实现:

  1. int drop_caches_sysctl_handler(ctl_table *table, int write,  
  2.  void __user *buffer, size_t *length, loff_t *ppos)  
  3.  
  4.  int ret;  
  5.   
  6.  
  7.  ret = proc_dointvec_minmax(table, write, buffer, length, ppos);  
  8.  if (ret)  
  9.  return ret;  
  10.  if (write) {  
  11.  /* => echo 1 > /proc/sys/vm/drop_caches 清理页缓存 */  
  12.  if (sysctl_drop_caches & 1)  
  13.  /* => 遍历所有的超级块,清理所有的缓存 */  
  14.  iterate_supers(drop_pagecache_sb, NULL);  
  15.  if (sysctl_drop_caches & 2)  
  16.  drop_slab();  
  17.  }  
  18.  return 0;  
  19.  
  20.   
  21.  
  22. /**  
  23.  * iterate_supers - call function for all active superblocks  
  24.  * @f: function to call  
  25.  * @arg: argument to pass to it  
  26.  *  
  27.  * Scans the superblock list and calls given function, passing it  
  28.  * locked superblock and given argument.  
  29.  */  
  30. void iterate_supers(void (*f)(struct super_block *, void *), void *arg)  
  31.  
  32.  struct super_block *sb, *p = NULL 
  33.   
  34.  
  35.  spin_lock(&sb_lock);  
  36.  list_for_each_entry(sb, &super_blocks, s_list) {  
  37.  if (hlist_unhashed(&sb->s_instances))  
  38.  continue;  
  39.  sb->s_count++;  
  40.  spin_unlock(&sb_lock);  
  41.   
  42.  
  43.  down_read(&sb->s_umount); 
  44.  if (sb->s_root && (sb->s_flags & MS_BORN))  
  45.  f(sb, arg);  
  46.  up_read(&sb->s_umount); 
  47.   
  48.  
  49.  spin_lock(&sb_lock);  
  50.  if (p) 
  51.  __put_super(p);  
  52.  p = sb 
  53.  }  
  54.  if (p)  
  55.  __put_super(p);  
  56.  spin_unlock(&sb_lock); 
  57.   
  58.  
  59. /* => 清理文件系统(包括bdev伪文件系统)的页缓存 */  
  60. static void drop_pagecache_sb(struct super_block *sb, void *unused)  
  61.  
  62.  struct inode *inode, *toput_inode = NULL 
  63.   
  64.  
  65.  spin_lock(&inode_sb_list_lock);  
  66.  /* => 遍历所有的inode */  
  67.  list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {  
  68.  spin_lock(&inode->i_lock);  
  69.  /* 
  70.  * => 若当前状态为(I_FREEING|I_WILL_FREE|I_NEW) 或  
  71.  * => 若没有缓存页  
  72.  * => 则跳过  
  73.  */  
  74.  if ((inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) ||  
  75.  (inode->i_mapping->nrpages == 0)) { 
  76.  spin_unlock(&inode->i_lock);  
  77.  continue;  
  78.  }  
  79.  __iget(inode);  
  80.  spin_unlock(&inode->i_lock);  
  81.  spin_unlock(&inode_sb_list_lock);  
  82.  /* => 清除缓存页(除了脏页、上锁的、正在回写的或映射在页表中的)*/  
  83.  invalidate_mapping_pages(inode->i_mapping, 0, -1);  
  84.  iput(toput_inode);  
  85.  toput_inode = inode;  
  86.  spin_lock(&inode_sb_list_lock);  
  87.  } 
  88.  spin_unlock(&inode_sb_list_lock);  
  89.  iput(toput_inode);  

综上,echo 1 > /proc/sys/vm/drop_caches会清除所有inode的缓存页,这里的inode包括VFS的inode、所有文件系统inode(也包括bdev伪文件系统块设备的inode的缓存页)。所以该命令执行后,就会将整个系统的page cache和buffer cache全部清除,当然前提是这些cache都是非脏的、没有正被使用的。

接下来看下实际效果:

  1. [root@test usb] # cat /proc/meminfo 
  2. MemTotal: 90516 kB 
  3. MemFree: 12396 kB 
  4. Buffers: 96 kB 
  5. Cached: 60756 kB 
  6. [root@test usb] # busybox_v400 sync 
  7. [root@test usb] # busybox_v400 sync 
  8. [root@test usb] # busybox_v400 sync 
  9. [root@test usb] # echo 1 > /proc/sys/vm/drop_caches 
  10. [root@test usb] # cat /proc/meminfo 
  11. MemTotal: 90516 kB 
  12. MemFree: 68820 kB 
  13. Buffers: 12 kB 
  14. Cached: 4464 kB 

可以看到Buffers和Cached都降了下来,在drop_caches前建议执行sync命令,以确保数据的完整性。sync 命令会将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延迟的块 I/O 和读写映射文件等。

上面的设置虽然简单但是比较粗暴,使cache的作用基本无法发挥,尤其在系统压力比较大时进行drop cache处理容易产生问题。因为drop_cache是全局在清内存,清的过程会加页面锁,导致有些进程等页面锁时超时,导致问题发生。因此,需要根据系统的状况进行适当的调节寻找最佳的方案。

6. 经验总结

以上分别讨论了Cache和Buffer分别从哪里来?什么时候消耗在哪里?如何分别控制Cache和Buffer这三个问题。最后还介绍了vmtouch工具的使用。

要深入理解Linux的Cache和Buffer牵涉大量内核核心机制(VFS、内存管理、块设备驱动、页高速缓存、文件访问、页框回写),需要制定计划在后续工作中不断理解和消化。

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2017-08-22 14:26:39

Linuxbuffercache

2018-08-03 09:07:40

Linux内存buffercache

2020-08-13 11:35:52

Linuxswapbuffer

2020-06-22 08:30:42

Linux内存手动释放

2021-03-30 10:50:18

Linux内存命令

2015-06-16 10:41:57

Linux清除内存Buffer

2020-12-23 13:14:00

LinuxLinux内存Swap

2021-08-31 10:32:11

LinuxPage Cache命令

2022-05-13 09:02:34

LinuxBufferCache

2011-07-18 18:01:34

buffer cach

2021-10-16 05:00:32

.js Buffer模块

2020-08-10 18:03:54

Cache存储器CPU

2021-08-26 13:57:56

Node.jsEncodingBuffer

2017-06-26 10:22:22

Linux平均负载性能监控

2009-12-08 12:10:30

2019-12-26 08:45:46

Linux虚拟内存

2019-06-21 10:52:28

软连接硬链接Linux

2021-06-07 09:41:48

NodeBuffer 网络协议

2019-04-12 14:26:17

Linux命令文件

2017-06-05 11:03:07

Linuxshutdown命令
点赞
收藏

51CTO技术栈公众号