本教程操作环境:linux7.3系统、dell g3电脑。
buffer和cache是什么1、 buffer(缓冲区)是系统两端处理速度平衡(从长时间尺度上看)时使用的。它的引入是为了减小短期内突发i/o的影响,起到流量整形的作用。
buffer是一个用于存储速度不同步的设备或优先级不同的设备之间传输数据的区域。通过缓冲区,可以使进程之间的相互等待变少,从而使从速度慢的设备读入数据时,速度快的设备的操作进程不发生间断。
比如:我们用x雷下载一部电影,不可能下载一点就写一点儿磁盘,这么干的话真的毁硬盘。反之先写到buffer缓冲区,攒多了再一次性写入磁盘,减少i/o,既有效率,又对硬盘友好。
2、 cache(缓存)则是两端处理速度不匹配时的一种折衷策略。因为cpu和memory之间的速度差异越来越大,所以人们充分利用数据的局部性特征,通过使用存储系统分级(memory hierarchy)的策略来减小这种差异带来的影响。
理解linux的cache和buffercache指的是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情况。
free命令的全解析
1. cache和buffer分析
从cat /proc/meminfo入手,先看看该接口的实现:
static int meminfo_proc_show(struct seq_file *m, void *v) { …… cached = global_page_state(nr_file_pages) - total_swapcache_pages() - i.bufferram; if (cached < 0) cached = 0; …… seq_printf(m, "memtotal: %8lu kb\n" "memfree: %8lu kb\n" "buffers: %8lu kb\n" "cached: %8lu kb\n" …… , k(i.totalram), k(i.freeram), k(i.bufferram), k(cached), …… ); …… }
其中,内核中以页框为单位,通过宏k转化成以kb为单位输出。这些值是通过si_meminfo来获取的:
void si_meminfo(struct sysinfo *val) { val->totalram = totalram_pages; val->sharedram = 0; val->freeram = global_page_state(nr_free_pages); val->bufferram = nr_blockdev_pages(); val->totalhigh = totalhigh_pages; val->freehigh = nr_free_highpages(); val->mem_unit = page_size; }
其中bufferram来自于nr_blockdev_pages(),该函数计算块设备使用的页框数,遍历所有块设备,将使用的页框数相加。而不包含普通文件使用的页框数。
long nr_blockdev_pages(void) { struct block_device *bdev; long ret = 0; spin_lock(&bdev_lock); list_for_each_entry(bdev, &all_bdevs, bd_list) { ret += bdev->bd_inode->i_mapping->nrpages; } spin_unlock(&bdev_lock); 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的文件操作,内存会发生什么变化:
[root nfs_dir] # ll -h file_50mb.bin -rw-rw-r-- 1 4104 4106 50.0m feb 24 2016 file_50mb.bin [root nfs_dir] # cat /proc/meminfo memtotal: 90532 kb memfree: 65696 kb buffers: 0 kb cached: 8148 kb …… [root@test nfs_dir] # cp file_50mb.bin / [root@test nfs_dir] # cat /proc/meminfo memtotal: 90532 kb memfree: 13012 kb buffers: 0 kb cached: 60488 kb
可以看到cp命令前后,memfree从65696 kb减少为13012 kb,cached从8148 kb增大为60488 kb,而buffers却不变。那么过一段时间,linux会自动释放掉所用的cache内存吗?一个小时后查看proc/meminfo显示cache仍然没有变化。
接着,我们看下使用dd命令对块设备写操作前后的内存变化:
[0225_19:10:44:10s][root@test nfs_dir] # cat /proc/meminfo [0225_19:10:44:10s]memtotal: 90532 kb [0225_19:10:44:10s]memfree: 58988 kb [0225_19:10:44:10s]buffers: 0 kb [0225_19:10:44:10s]cached: 4144 kb ...... ...... [0225_19:11:13:11s][root@test nfs_dir] # dd if=/dev/zero of=/dev/h_sda bs=10m count=2000 & [0225_19:11:17:11s][root@test nfs_dir] # cat /proc/meminfo [0225_19:11:17:11s]memtotal: 90532 kb [0225_19:11:17:11s]memfree: 11852 kb [0225_19:11:17:11s]buffers: 36224 kb [0225_19:11:17:11s]cached: 4148 kb ...... ...... [0225_19:11:21:11s][root@test nfs_dir] # cat /proc/meminfo [0225_19:11:21:11s]memtotal: 90532 kb [0225_19:11:21:11s]memfree: 11356 kb [0225_19:11:21:11s]buffers: 36732 kb [0225_19:11:21:11s]cached: 4148kb ...... ...... [0225_19:11:41:11s][root@test nfs_dir] # cat /proc/meminfo [0225_19:11:41:11s]memtotal: 90532 kb [0225_19:11:41:11s]memfree: 11864 kb [0225_19:11:41:11s]buffers: 36264 kb [0225_19:11:41:11s]cached: 4148 kb ….. ……
裸写块设备前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。
在程序中只要知道文件的句柄,就能用:
int posix_fadvise(int fd, off_t offset, off_t len, int advice);
posix_fadv_dontneed (该文件在接下来不会再被访问),但是曾有开发人员反馈怀疑该接口的有效性。那么该接口确实有效吗?首先,我们查看mm/fadvise.c内核代码来看posix_fadvise是如何实现的:
/* * posix_fadv_willneed could set pg_referenced, and posix_fadv_noreuse could * deactivate the pages and clear pg_referenced. */ syscall_define4(fadvise64_64, int, fd, loff_t, offset, loff_t, len, int, advice) { … … … … /* => 将指定范围内的数据从page cache中换出 */ case posix_fadv_dontneed: /* => 如果后备设备不忙的话,先调用__filemap_fdatawrite_range把脏页面刷掉 */ if (!bdi_write_congested(mapping->backing_dev_info)) /* => wb_sync_none: 不是同步等待页面刷新完成,只是提交了 */ /* => 而fsync和fdatasync是用wb_sync_all参数等到完成才返回的 */ __filemap_fdatawrite_range(mapping, offset, endbyte, wb_sync_none); /* first and last full page! */ start_index = (offset+(page_cache_size-1)) >> page_cache_shift; end_index = (endbyte >> page_cache_shift); /* => 接下来清除页面缓存 */ if (end_index >= start_index) { unsigned long count = invalidate_mapping_pages(mapping, start_index, end_index); /* * if fewer pages were invalidated than expected then * it is possible that some of the pages were on * a per-cpu pagevec for a remote cpu. drain all * pagevecs and try again. */ if (count < (end_index - start_index + 1)) { lru_add_drain_all(); invalidate_mapping_pages(mapping, start_index, end_index); } } break; … … … … }
我们可以看到如果后台系统不忙的话,会先调用__filemap_fdatawrite_range把脏页面刷掉,刷页面用的参数是是 wb_sync_none,也就是说不是同步等待页面刷新完成,提交完写脏页后立即返回了。
然后再调invalidate_mapping_pages清除页面,回收内存:
/* => 清除缓存页(除了脏页、上锁的、正在回写的或映射在页表中的)*/ unsigned long invalidate_mapping_pages(struct address_space *mapping, pgoff_t start, pgoff_t end) { struct pagevec pvec; pgoff_t index = start; unsigned long ret; unsigned long count = 0; int i; /* * note: this function may get called on a shmem/tmpfs mapping: * pagevec_lookup() might then return 0 prematurely (because it * got a gangful of swap entries); but it's hardly worth worrying * about - it can rarely have anything to free from such a mapping * (most pages are dirty), and already skips over any difficulties. */ pagevec_init(&pvec, 0); while (index <= end && pagevec_lookup(&pvec, mapping, index, min(end - index, (pgoff_t)pagevec_size - 1) + 1)) { mem_cgroup_uncharge_start(); for (i = 0; i < pagevec_count(&pvec); i++) { struct page *page = pvec.pages[i]; /* we rely upon deletion not changing page->index */ index = page->index; if (index > end) break; if (!trylock_page(page)) continue; warn_on(page->index != index); /* => 无效一个文件的缓存 */ ret = invalidate_inode_page(page); unlock_page(page); /* * invalidation is a hint that the page is no longer * of interest and try to speed up its reclaim. */ if (!ret) deactivate_page(page); count += ret; } pagevec_release(&pvec); mem_cgroup_uncharge_end(); cond_resched(); index++; } return count; } /* * safely invalidate one page from its pagecache mapping. * it only drops clean, unused pages. the page must be locked. * * returns 1 if the page is successfully invalidated, otherwise 0. */ /* => 无效一个文件的缓存 */ int invalidate_inode_page(struct page *page) { struct address_space *mapping = page_mapping(page); if (!mapping) return 0; /* => 若当前页是脏页或正在写回的页,直接返回 */ if (pagedirty(page) || pagewriteback(page)) return 0; /* => 若已经被映射到页表了,则直接返回 */ if (page_mapped(page)) return 0; /* => 如果满足了以上条件就调用invalidate_complete_page继续 */ return invalidate_complete_page(mapping, page); } 从上面的代码可以看到清除相关的页面要满足二个条件: 1. 不脏且没在回写; 2. 未被使用。如果满足了这二个条件就调用invalidate_complete_page继续: /* => 无效一个完整的页 */ static int invalidate_complete_page(struct address_space *mapping, struct page *page) { int ret; if (page->mapping != mapping) return 0; if (page_has_private(page) && !try_to_release_page(page, 0)) return 0; /* => 若满足以上更多条件,则从地址空间中解除该页 */ ret = remove_mapping(mapping, page); return ret; } /* * attempt to detach a locked page from its ->mapping. if it is dirty or if * someone else has a ref on the page, abort and return 0. if it was * successfully detached, return 1. assumes the caller has a single ref on * this page. */ /* => 从地址空间中解除该页 */ int remove_mapping(struct address_space *mapping, struct page *page) { if (__remove_mapping(mapping, page)) { /* * unfreezing the refcount with 1 rather than 2 effectively * drops the pagecache ref for us without requiring another * atomic operation. */ page_unfreeze_refs(page, 1); return 1; } return 0; } /* * same as remove_mapping, but if the page is removed from the mapping, it * gets returned with a refcount of 0. */ /* => 从地址空间中解除该页 */ static int __remove_mapping(struct address_space *mapping, struct page *page) { bug_on(!pagelocked(page)); bug_on(mapping != page_mapping(page)); spin_lock_irq(&mapping->tree_lock); /* * the non racy check for a busy page. * * must be careful with the order of the tests. when someone has * a ref to the page, it may be possible that they dirty it then * drop the reference. so if pagedirty is tested before page_count * here, then the following race may occur: * * get_user_pages(&page); * [user mapping goes away] * write_to(page); * !pagedirty(page) [good] * setpagedirty(page); * put_page(page); * !page_count(page) [good, discard it] * * [oops, our write_to data is lost] * * reversing the order of the tests ensures such a situation cannot * escape unnoticed. the smp_rmb is needed to ensure the page->flags * load is not satisfied before that of page->_count. * * note that if setpagedirty is always performed via set_page_dirty, * and thus under tree_lock, then this ordering is not required. */ if (!page_freeze_refs(page, 2)) goto cannot_free; /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */ if (unlikely(pagedirty(page))) { page_unfreeze_refs(page, 2); goto cannot_free; } if (pageswapcache(page)) { swp_entry_t swap = { .val = page_private(page) }; __delete_from_swap_cache(page); spin_unlock_irq(&mapping->tree_lock); swapcache_free(swap, page); } else { void (*freepage)(struct page *); freepage = mapping->a_ops->freepage; /* => 从页缓存中删除和释放该页 */ __delete_from_page_cache(page); spin_unlock_irq(&mapping->tree_lock); mem_cgroup_uncharge_cache_page(page); if (freepage != null) freepage(page); } return 1; cannot_free: spin_unlock_irq(&mapping->tree_lock); return 0; } /* * delete a page from the page cache and free it. caller has to make * sure the page is locked and that nobody else uses it - or that usage * is safe. the caller must hold the mapping's tree_lock. */ /* => 从页缓存中删除和释放该页 */ void __delete_from_page_cache(struct page *page) { struct address_space *mapping = page->mapping; trace_mm_filemap_delete_from_page_cache(page); /* * if we're uptodate, flush out into the cleancache, otherwise * invalidate any existing cleancache entries. we can't leave * stale data around in the cleancache once our page is gone */ if (pageuptodate(page) && pagemappedtodisk(page)) cleancache_put_page(page); else cleancache_invalidate_page(mapping, page); radix_tree_delete(&mapping->page_tree, page->index); /* => 解除与之绑定的地址空间结构 */ page->mapping = null; /* leave page->index set: truncation lookup relies upon it */ /* => 减少地址空间中的页计数 */ mapping->nrpages--; __dec_zone_page_state(page, nr_file_pages); if (pageswapbacked(page)) __dec_zone_page_state(page, nr_shmem); bug_on(page_mapped(page)); /* * some filesystems seem to re-dirty the page even after * the vm has canceled the dirty bit (eg ext3 journaling). * * fix it up by doing a final dirty accounting check after * having removed the page entirely. */ if (pagedirty(page) && mapping_cap_account_dirty(mapping)) { dec_zone_page_state(page, nr_file_dirty); dec_bdi_stat(mapping->backing_dev_info, bdi_reclaimable); } }
看到这里我们就明白了:为什么使用了posix_fadvise后相关的内存没有被释放出来:页面还脏是最关键的因素。
但是我们如何保证页面全部不脏呢?fdatasync或者fsync都是选择,或者linux下新系统调用sync_file_range都是可用的,这几个都是使用wb_sync_all模式强制要求回写完毕才返回的。所以应该这样做:
fdatasync(fd); 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原理及使用可以为我们后续后端设备所用。
快速安装指南:
$ git clone https://github.com/hoytech/vmtouch.git $ cd vmtouch $ make $ sudo make install
vmtouch用途:
查看一个文件(或者目录)哪些部分在内存中;把文件调入内存;把文件清除出内存,即释放page cache;把文件锁住在内存中而不被换出到磁盘上;……vmtouch实现:
其核心分别是两个系统调用,mincore和posix_fadvise。两者具体使用方法使用man帮助都有详细的说明。posix_fadvise已在上文提到,用法在此不作说明。简单说下mincore:
name mincore - determine whether pages are resident in memory synopsis #include <unistd.h> #include <sys/mman.h> int mincore(void *addr, size_t length, unsigned char *vec); feature test macro requirements for glibc (see feature_test_macros(7)): 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-mmax file size to touch-puse 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占用量
[root@test nfs_dir] # mkdir /mnt/usb && mount /dev/msc /mnt/usb/ [root@test usb] # vmtouch . files: 57 directories: 2 resident pages: 0/278786 0/1g 0% elapsed: 0.023126 seconds
例2、 当前test.bin文件的cache占用量?
[root@test usb] # vmtouch -v test.bin test.bin [ ] 0/25600 files: 1 directories: 0 resident pages: 0/25600 0/100m 0% elapsed: 0.001867 seconds
这时使用tail命令将部分文件读取到内存中:
[root@test usb] # busybox_v400 tail -n 10 test.bin > /dev/null
现在再来看一下:
[root@test usb] # vmtouch -v test.bin test.bin [ o] 240/25600 files: 1 directories: 0 resident pages: 240/25600 960k/100m 0.938% elapsed: 0.002019 seconds
可知目前文件test.bin的最后240个page驻留在内存中。
例3、 最后使用-t选项将剩下的test.bin文件全部读入内存:
[root@test usb] # vmtouch -vt test.bin test.bin [oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo] 25600/25600 files: 1 directories: 0 touched pages: 25600 (100m) elapsed: 39.049 seconds
例4、 再把test.bin占用的cachae全部释放:
[root@test usb] # vmtouch -ev test.bin evicting test.bin files: 1 directories: 0 evicted pages: 25600 (100m) elapsed: 0.01461 seconds
这时候再来看下是否真的被释放了:
[root@test usb] # vmtouch -v test.bin test.bin [ ] 0/25600 files: 1 directories: 0 resident pages: 0/25600 0/100m 0% elapsed: 0.001867 seconds
以上通过代码分析及实际操作总结了vmtouch工具的使用,建议app组后续集成或借鉴vmtouch工具并灵活应用到后端设备中,必能达到有效管理和控制page cache的目的。
4. 使用blkflsbuf清buffer
通过走读块设备驱动ioctl命令实现,发现该命令能有效的清除整个块设备所占用的buffer。
int blkdev_ioctl(struct block_device *bdev, fmode_t mode, unsigned cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct backing_dev_info *bdi; loff_t size; int ret, n; switch(cmd) { case blkflsbuf: if (!capable(cap_sys_admin)) return -eacces; ret = __blkdev_driver_ioctl(bdev, mode, cmd, arg); if (!is_unrecognized_ioctl(ret)) return ret; fsync_bdev(bdev); invalidate_bdev(bdev); return 0; case ……: ………… } /* invalidate clean unused buffers and pagecache. */ void invalidate_bdev(struct block_device *bdev) { struct address_space *mapping = bdev->bd_inode->i_mapping; if (mapping->nrpages == 0) return; invalidate_bh_lrus(); lru_add_drain_all(); /* make sure all lru add caches are flushed */ invalidate_mapping_pages(mapping, 0, -1); /* 99% of the time, we don't need to flush the cleancache on the bdev. * but, for the strange corners, lets be cautious */ cleancache_invalidate_inode(mapping); } export_symbol(invalidate_bdev);
光代码不够,现在让我们看下对/dev/h_sda这个块设备执行blkflsbuf的ioctl命令前后的实际内存变化:
[0225_19:10:25:10s][root@test nfs_dir] # cat /proc/meminfo [0225_19:10:25:10s]memtotal: 90532 kb [0225_19:10:25:10s]memfree: 12296 kb [0225_19:10:25:10s]buffers: 46076 kb [0225_19:10:25:10s]cached: 4136 kb ………… [0225_19:10:42:10s][root@test nfs_dir] # /mnt/nfs_dir/a.out [0225_19:10:42:10s]ioctl cmd blkflsbuf ok! [0225_19:10:44:10s][root@test nfs_dir] # cat /proc/meminfo [0225_19:10:44:10s]memtotal: 90532 kb [0225_19:10:44:10s]memfree: 58988 kb [0225_19:10:44:10s]buffers: 0 kb ………… [0225_19:10:44:10s]cached: 4144 kb
执行的效果如代码中看到的,buffers已被全部清除了,memfree一下增长了约46mb,可以知道原先的buffer已被回收并转化为可用的内存。整个过程cache几乎没有变化,仅增加的8k cache内存可以推断用于a.out本身及其他库文件的加载。
上述a.out的示例如下:
#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <sys/ioctl.h> #define blkflsbuf _io(0x12, 97) int main(int argc, char* argv[]) { int fd = -1; fd = open("/dev/h_sda", o_rdwr); if (fd < 0) { return -1; } if (ioctl(fd, blkflsbuf, 0)) { printf("ioctl cmd blkflsbuf failed, errno:%d\n", errno); } close(fd); printf("ioctl cmd blkflsbuf ok!\n"); 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进行操作。
首先来看下内核源码实现:
int drop_caches_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { int ret; ret = proc_dointvec_minmax(table, write, buffer, length, ppos); if (ret) return ret; if (write) { /* => echo 1 > /proc/sys/vm/drop_caches 清理页缓存 */ if (sysctl_drop_caches & 1) /* => 遍历所有的超级块,清理所有的缓存 */ iterate_supers(drop_pagecache_sb, null); if (sysctl_drop_caches & 2) drop_slab(); } return 0; } /** * iterate_supers - call function for all active superblocks * @f: function to call * @arg: argument to pass to it * * scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers(void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = null; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && (sb->s_flags & ms_born)) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } /* => 清理文件系统(包括bdev伪文件系统)的页缓存 */ static void drop_pagecache_sb(struct super_block *sb, void *unused) { struct inode *inode, *toput_inode = null; spin_lock(&inode_sb_list_lock); /* => 遍历所有的inode */ list_for_each_entry(inode, &sb->s_inodes, i_sb_list) { spin_lock(&inode->i_lock); /* * => 若当前状态为(i_freeing|i_will_free|i_new) 或 * => 若没有缓存页 * => 则跳过 */ if ((inode->i_state & (i_freeing|i_will_free|i_new)) || (inode->i_mapping->nrpages == 0)) { spin_unlock(&inode->i_lock); continue; } __iget(inode); spin_unlock(&inode->i_lock); spin_unlock(&inode_sb_list_lock); /* => 清除缓存页(除了脏页、上锁的、正在回写的或映射在页表中的)*/ invalidate_mapping_pages(inode->i_mapping, 0, -1); iput(toput_inode); toput_inode = inode; spin_lock(&inode_sb_list_lock); } spin_unlock(&inode_sb_list_lock); iput(toput_inode); }
综上,echo 1 > /proc/sys/vm/drop_caches会清除所有inode的缓存页,这里的inode包括vfs的inode、所有文件系统inode(也包括bdev伪文件系统块设备的inode的缓存页)。所以该命令执行后,就会将整个系统的page cache和buffer cache全部清除,当然前提是这些cache都是非脏的、没有正被使用的。
接下来看下实际效果:
[root@test usb] # cat /proc/meminfo memtotal: 90516 kb memfree: 12396 kb buffers: 96 kb cached: 60756 kb [root@test usb] # busybox_v400 sync [root@test usb] # busybox_v400 sync [root@test usb] # busybox_v400 sync [root@test usb] # echo 1 > /proc/sys/vm/drop_caches [root@test usb] # cat /proc/meminfo memtotal: 90516 kb memfree: 68820 kb buffers: 12 kb 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、内存管理、块设备驱动、页高速缓存、文件访问、页框回写),需要制定计划在后续工作中不断理解和消化。
相关推荐:《linux视频教程》
以上就是linux buffer是什么的详细内容。