这是从myjesky的一个帖子中截取出来的的内容
http://topic.csdn.net/t/20050420/13/3951787.html
内存复制占用很多时间的,为什么还要用mbuf这样一个结构?
简单的说,如果传指针,那么上层用户如果无意之中释放了某块内存,那么整个协议栈就可能会崩溃,而导致内核的崩溃(协议栈中保持着大量的mbuf链表。BSD和linux内核只信任内核本身。
mbuf在层与层之间,就是传递指针的,至于为什么不直接使用应用层buf,有几个原因:
1. 应用层buf不一定能够满足需要,比方说,我需要在前面加上IP头,可是前面没有空间了。
2. 发送过程是一直延伸到物理层的,也就是说,假如直接使用应用层buf,那么直到驱动的芯片发送完报文之前,系统必须锁定这块内存,你的应用层能接受这种等待么,要知道某些链路的速度是很慢的,而CPU快得多,所有比较合理的方法是,将数据复制到mbuf中,然后后面的发送过程使用mbuf,程序则可以快速 返回。
下面是手册中对mbuf的描述:
An mbuf is a basic unit of memorymanagement in the kernel IPC subsystem.
Network packets and socket buffers arestored in mbufs. A network packet
may span multiple mbufs arranged into a mbufchain (linked list), which
allows adding or trimming network headerswith little overhead.
While a developer should not bother with mbufinternals without serious
reason in order to avoid incompatibilitieswith future changes, it is
useful to understand the general structureof an mbuf.
An mbuf consists of a variable-sizedheader and a small internal buffer
for data.The total size of an mbuf, MSIZE, is a constant defined in
<sys/param.h>. The mbuf header includes:
m_next (struct mbuf *) A pointer to the next mbufin the mbuf
chain.
m_nextpkt (struct mbuf *) A pointer to the next mbufchain in the
queue
m_data (caddr_t) A pointer to data attached tothis mbuf.
m_len (int) The length of the data.
m_type (short) The type of the data.
m_flags (int) The mbuf flags.