开发者

available memory in kernel

开发者 https://www.devze.com 2023-03-14 02:49 出处:网络
Is there a kern开发者_运维百科el function which returns amount of kernel memory available(Not vmalloc related).First, let me say that if you\'re going to make any policy decisions (should I proceed wi

Is there a kern开发者_运维百科el function which returns amount of kernel memory available(Not vmalloc related).


First, let me say that if you're going to make any policy decisions (should I proceed with this operation?) based on this information, STOP. As WGW pointed out, there are unavoidable races here; memory can be used up between when you check and when you use it. Just test for errors on your memory allocations and have an appropriate failure path. Moreover, if you request memory when there isn't enough free memory, often the kernel can obtain more free memory by cleaning up various cache memory, swapping to disk, freeing slabs, etc. And kernel memory fragmentation can fail large (multiple page) allocations when not made through vmalloc even with plenty of memory free.

That said, there are APIs for querying kernel memory availability. You should note that the kernel has multiple memory pools, so even if one of these API says you have no free RAM, it could be that it's available in the memory pool you are interested in.

First, we have si_meminfo. This is the call that provides availability data for /proc/meminfo, among other things, and reports on the current state of the buddy page allocator. Note that cached and buffer ram can be converted to free ram very quickly.

global_page_state(NR_SLAB_RECLAIMABLE) can also be used to get counts of how much slab memory can be quickly reclaimed. If you request an allocation, this memory can and will be freed on demand.

The SLUB allocator (used for kalloc() and the like, among others) also provides statistics for its internal memory pools that can also reflect free memory within each memory pool. This may not be available with the same API depending on which allocator is selected in your configuration - please do not use this data except for debugging. The relevant code (implementing /proc/slabinfo) can be found in mm/slub.c


What kind of use is the available memory for you? Worst case you run in a race condition with checking available memory:

  1. You get the available memory. It`s enough.
  2. Multitasking, a.k.a. the scheduler of the kernel, stops your process and continues with another one which allocates a bunch of the available memory.
  3. The scheduler continues with your process.
  4. Your allocations fails though step 1 showed enough available memory.
0

精彩评论

暂无评论...
验证码 换一张
取 消