更新时间:2022-05-28 23:57:44
我曾经写过一个内核模块,用于处理10Gbs链路上的数据包.我使用vmalloc
分配了大约1GB的连续(虚拟)内存,将静态大小的哈希表放入其中以执行连接跟踪(
I once wrote a kernel module processing packets on a 10Gbs link. I used vmalloc
to allocate about 1GByte of continuous (virtual) memory to put a static size hash table into it to perform connection tracking (code).
如果您知道需要多少内存,建议您对其进行预分配.这有两个优点
If you know how much memory you need, I recommend to pre-allocate it. This has two advantages
kmalloc(_, GFP_ATOMIC)
无法返回内存,则无需考虑策略.实际上,在重负载下,这种情况实际上经常会发生.kmalloc(_, GFP_ATOMIC)
can not return you memory. This can actually happen quite often under heavy load.缺点
因此,要编写特殊用途的内核模块,请预先分配尽可能多的内存;)
So, for writing a special-purpose kernel module, please pre-allocate as much memory as you can get ;)
如果您为许多新手用户使用的商品硬件编写内核模块,***按需分配内存(并且浪费更少的内存).
If you write a kernel module for commodity hardware used by many novice users, it would be nice to allocate memory on demand (and waste less memory).
您在哪里分配内存? GFP_ATOMIC
只能返回非常少量的内存,并且仅在内存分配无法休眠时才应使用.您可以在安全进入睡眠状态时使用GFP_KERNEL
,例如,不在中断上下文中.有关更多信息,请参见此问题.在模块初始化期间使用vmalloc
来预分配所有内存是安全的.
Where do you allocate memory? GFP_ATOMIC
can only return a very small amount of memory and should only be used if your memory allocation cannot sleep. You can use GFP_KERNEL
when it is safe to sleep, e.g., not in interrupt context. See this question for more. It is safe to use vmalloc
during module initialization to pre-allocate all you memory.