有效分配内核中的内存 [英] Efficiently Allocate Memory in Kernel

查看:80
本文介绍了有效分配内核中的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个内核模块,在该模块中我将获得接近8 mbps的TCP/IP数据包.我必须将这些数据包存储500ms.稍后,这些数据包应按顺序转发.这些应该为30名成员完成.什么是最好的实施方法?我是否应该将kmalloc一次使用一次(kmalloc(64000000, GFP_ATOMIC)?因为每次执行kmallockfree都会花费时间,从而导致性能问题.另外,如果我一口气在内核中分配内存,Linux内核会允许我这样做吗?

I want to write a kernel module where I am getting TCP/IP packets near 8 mbps. I have to store these packet for 500ms duration. Later these packets should be forwarded sequentially. And these should be done for 30 members. What should be best approach to implement? Should I use kmalloc for once (kmalloc(64000000, GFP_ATOMIC)? Because each time if I do kmalloc and kfree it will take time, leading to a performance issue. Also if I allocate memory in kernel in one shot will the linux kernel will allow me to do that?

推荐答案

我曾经写过一个内核模块,用于处理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)无法返回内存,则无需考虑策略.实际上,在重负载下,这种情况实际上经常会发生.
  • It is fast (no mallocing/freeing at runtime)
  • You don't have to think of a strategy if 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.

这篇关于有效分配内核中的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆