2 * Copyright (c) 1982, 1986, 1988, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
36 #include "opt_param.h"
37 #include "opt_mbuf_stress_test.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/limits.h>
44 #include <sys/malloc.h>
46 #include <sys/sysctl.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
51 #include <security/mac/mac_framework.h>
57 #ifdef MBUF_STRESS_TEST
62 int m_defragrandomfailures;
66 * sysctl(8) exported objects
68 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
69 &max_linkhdr, 0, "Size of largest link layer header");
70 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
71 &max_protohdr, 0, "Size of largest protocol layer header");
72 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
73 &max_hdr, 0, "Size of largest link plus protocol header");
74 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
75 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
76 #ifdef MBUF_STRESS_TEST
77 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
78 &m_defragpackets, 0, "");
79 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
80 &m_defragbytes, 0, "");
81 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
82 &m_defraguseless, 0, "");
83 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
84 &m_defragfailure, 0, "");
85 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
86 &m_defragrandomfailures, 0, "");
90 * Allocate a given length worth of mbufs and/or clusters (whatever fits
91 * best) and return a pointer to the top of the allocated chain. If an
92 * existing mbuf chain is provided, then we will append the new chain
93 * to the existing one but still return the top of the newly allocated
97 m_getm2(struct mbuf *m, int len, int how, short type, int flags)
99 struct mbuf *mb, *nm = NULL, *mtail = NULL;
101 KASSERT(len >= 0, ("%s: len is < 0", __func__));
103 /* Validate flags. */
104 flags &= (M_PKTHDR | M_EOR);
106 /* Packet header mbuf must be first in chain. */
107 if ((flags & M_PKTHDR) && m != NULL)
110 /* Loop and append maximum sized mbufs to the chain tail. */
113 mb = m_getjcl(how, type, (flags & M_PKTHDR),
115 else if (len >= MINCLSIZE)
116 mb = m_getcl(how, type, (flags & M_PKTHDR));
117 else if (flags & M_PKTHDR)
118 mb = m_gethdr(how, type);
120 mb = m_get(how, type);
122 /* Fail the whole operation if one mbuf can't be allocated. */
130 len -= (mb->m_flags & M_EXT) ? mb->m_ext.ext_size :
131 ((mb->m_flags & M_PKTHDR) ? MHLEN : MLEN);
137 flags &= ~M_PKTHDR; /* Only valid on the first mbuf. */
140 mtail->m_flags |= M_EOR; /* Only valid on the last mbuf. */
142 /* If mbuf was supplied, append new chain to the end of it. */
144 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
147 mtail->m_flags &= ~M_EOR;
155 * Free an entire chain of mbufs and associated external buffers, if
159 m_freem(struct mbuf *mb)
167 * Configure a provided mbuf to refer to the provided external storage
168 * buffer and setup a reference count for said buffer. If the setting
169 * up of the reference count fails, the M_EXT bit will not be set. If
170 * successfull, the M_EXT bit is set in the mbuf's flags.
173 * mb The existing mbuf to which to attach the provided buffer.
174 * buf The address of the provided external storage buffer.
175 * size The size of the provided buffer.
176 * freef A pointer to a routine that is responsible for freeing the
177 * provided external storage buffer.
178 * args A pointer to an argument structure (of any type) to be passed
179 * to the provided freef routine (may be NULL).
180 * flags Any other flags to be passed to the provided mbuf.
181 * type The type that the external storage buffer should be
188 m_extadd(struct mbuf *mb, caddr_t buf, u_int size,
189 void (*freef)(void *, void *), void *args, int flags, int type)
191 KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
193 if (type != EXT_EXTREF)
194 mb->m_ext.ref_cnt = (u_int *)uma_zalloc(zone_ext_refcnt, M_NOWAIT);
195 if (mb->m_ext.ref_cnt != NULL) {
196 *(mb->m_ext.ref_cnt) = 1;
197 mb->m_flags |= (M_EXT | flags);
198 mb->m_ext.ext_buf = buf;
199 mb->m_data = mb->m_ext.ext_buf;
200 mb->m_ext.ext_size = size;
201 mb->m_ext.ext_free = freef;
202 mb->m_ext.ext_args = args;
203 mb->m_ext.ext_type = type;
208 * Non-directly-exported function to clean up after mbufs with M_EXT
209 * storage attached to them if the reference count hits 1.
212 mb_free_ext(struct mbuf *m)
214 KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
215 KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
217 /* Free attached storage if this mbuf is the only reference to it. */
218 if (*(m->m_ext.ref_cnt) == 1 ||
219 atomic_fetchadd_int(m->m_ext.ref_cnt, -1) == 1) {
220 switch (m->m_ext.ext_type) {
221 case EXT_PACKET: /* The packet zone is special. */
222 if (*(m->m_ext.ref_cnt) == 0)
223 *(m->m_ext.ref_cnt) = 1;
224 uma_zfree(zone_pack, m);
225 return; /* Job done. */
227 uma_zfree(zone_clust, m->m_ext.ext_buf);
230 uma_zfree(zone_jumbop, m->m_ext.ext_buf);
233 uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
236 uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
242 *(m->m_ext.ref_cnt) = 0;
243 uma_zfree(zone_ext_refcnt, __DEVOLATILE(u_int *,
247 KASSERT(m->m_ext.ext_free != NULL,
248 ("%s: ext_free not set", __func__));
249 (*(m->m_ext.ext_free))(m->m_ext.ext_buf,
253 KASSERT(m->m_ext.ext_type == 0,
254 ("%s: unknown ext_type", __func__));
258 * Free this mbuf back to the mbuf zone with all m_ext
259 * information purged.
261 m->m_ext.ext_buf = NULL;
262 m->m_ext.ext_free = NULL;
263 m->m_ext.ext_args = NULL;
264 m->m_ext.ref_cnt = NULL;
265 m->m_ext.ext_size = 0;
266 m->m_ext.ext_type = 0;
267 m->m_flags &= ~M_EXT;
268 uma_zfree(zone_mbuf, m);
272 * Attach the the cluster from *m to *n, set up m_ext in *n
273 * and bump the refcount of the cluster.
276 mb_dupcl(struct mbuf *n, struct mbuf *m)
278 KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
279 KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
280 KASSERT((n->m_flags & M_EXT) == 0, ("%s: M_EXT set", __func__));
282 if (*(m->m_ext.ref_cnt) == 1)
283 *(m->m_ext.ref_cnt) += 1;
285 atomic_add_int(m->m_ext.ref_cnt, 1);
286 n->m_ext.ext_buf = m->m_ext.ext_buf;
287 n->m_ext.ext_free = m->m_ext.ext_free;
288 n->m_ext.ext_args = m->m_ext.ext_args;
289 n->m_ext.ext_size = m->m_ext.ext_size;
290 n->m_ext.ref_cnt = m->m_ext.ref_cnt;
291 n->m_ext.ext_type = m->m_ext.ext_type;
296 * Clean up mbuf (chain) from any tags and packet headers.
297 * If "all" is set then the first mbuf in the chain will be
301 m_demote(struct mbuf *m0, int all)
305 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
306 if (m->m_flags & M_PKTHDR) {
307 m_tag_delete_chain(m, NULL);
308 m->m_flags &= ~M_PKTHDR;
309 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
311 if (m->m_type == MT_HEADER)
313 if (m != m0 && m->m_nextpkt != NULL)
315 m->m_flags = m->m_flags & (M_EXT|M_EOR|M_RDONLY|M_FREELIST);
320 * Sanity checks on mbuf (chain) for use in KASSERT() and general
322 * Returns 0 or panics when bad and 1 on all tests passed.
323 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
327 m_sanity(struct mbuf *m0, int sanitize)
333 #define M_SANITY_ACTION(s) return (0)
334 /* #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m) */
336 for (m = m0; m != NULL; m = m->m_next) {
338 * Basic pointer checks. If any of these fails then some
339 * unrelated kernel memory before or after us is trashed.
340 * No way to recover from that.
342 a = ((m->m_flags & M_EXT) ? m->m_ext.ext_buf :
343 ((m->m_flags & M_PKTHDR) ? (caddr_t)(&m->m_pktdat) :
344 (caddr_t)(&m->m_dat)) );
345 b = (caddr_t)(a + (m->m_flags & M_EXT ? m->m_ext.ext_size :
346 ((m->m_flags & M_PKTHDR) ? MHLEN : MLEN)));
347 if ((caddr_t)m->m_data < a)
348 M_SANITY_ACTION("m_data outside mbuf data range left");
349 if ((caddr_t)m->m_data > b)
350 M_SANITY_ACTION("m_data outside mbuf data range right");
351 if ((caddr_t)m->m_data + m->m_len > b)
352 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
353 if ((m->m_flags & M_PKTHDR) && m->m_pkthdr.header) {
354 if ((caddr_t)m->m_pkthdr.header < a ||
355 (caddr_t)m->m_pkthdr.header > b)
356 M_SANITY_ACTION("m_pkthdr.header outside mbuf data range");
359 /* m->m_nextpkt may only be set on first mbuf in chain. */
360 if (m != m0 && m->m_nextpkt != NULL) {
362 m_freem(m->m_nextpkt);
363 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
365 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
368 /* correct type correlations. */
369 if (m->m_type == MT_HEADER && !(m->m_flags & M_PKTHDR)) {
373 M_SANITY_ACTION("MT_HEADER set but not M_PKTHDR");
376 /* packet length (not mbuf length!) calculation */
377 if (m0->m_flags & M_PKTHDR)
380 /* m_tags may only be attached to first mbuf in chain. */
381 if (m != m0 && m->m_flags & M_PKTHDR &&
382 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
384 m_tag_delete_chain(m, NULL);
385 /* put in 0xDEADC0DE perhaps? */
387 M_SANITY_ACTION("m_tags on in-chain mbuf");
390 /* M_PKTHDR may only be set on first mbuf in chain */
391 if (m != m0 && m->m_flags & M_PKTHDR) {
393 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
394 m->m_flags &= ~M_PKTHDR;
395 /* put in 0xDEADCODE and leave hdr flag in */
397 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
401 if (pktlen && pktlen != m->m_pkthdr.len) {
405 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
409 #undef M_SANITY_ACTION
414 * "Move" mbuf pkthdr from "from" to "to".
415 * "from" must have M_PKTHDR set, and "to" must be empty.
418 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
422 /* see below for why these are not enabled */
424 /* Note: with MAC, this may not be a good assertion. */
425 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
426 ("m_move_pkthdr: to has tags"));
430 * XXXMAC: It could be this should also occur for non-MAC?
432 if (to->m_flags & M_PKTHDR)
433 m_tag_delete_chain(to, NULL);
435 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
436 if ((to->m_flags & M_EXT) == 0)
437 to->m_data = to->m_pktdat;
438 to->m_pkthdr = from->m_pkthdr; /* especially tags */
439 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
440 from->m_flags &= ~M_PKTHDR;
444 * Duplicate "from"'s mbuf pkthdr in "to".
445 * "from" must have M_PKTHDR set, and "to" must be empty.
446 * In particular, this does a deep copy of the packet tags.
449 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
454 * The mbuf allocator only initializes the pkthdr
455 * when the mbuf is allocated with MGETHDR. Many users
456 * (e.g. m_copy*, m_prepend) use MGET and then
457 * smash the pkthdr as needed causing these
458 * assertions to trip. For now just disable them.
461 /* Note: with MAC, this may not be a good assertion. */
462 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
464 MBUF_CHECKSLEEP(how);
466 if (to->m_flags & M_PKTHDR)
467 m_tag_delete_chain(to, NULL);
469 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
470 if ((to->m_flags & M_EXT) == 0)
471 to->m_data = to->m_pktdat;
472 to->m_pkthdr = from->m_pkthdr;
473 SLIST_INIT(&to->m_pkthdr.tags);
474 return (m_tag_copy_chain(to, from, MBTOM(how)));
478 * Lesser-used path for M_PREPEND:
479 * allocate new mbuf to prepend to chain,
483 m_prepend(struct mbuf *m, int len, int how)
487 if (m->m_flags & M_PKTHDR)
488 MGETHDR(mn, how, m->m_type);
490 MGET(mn, how, m->m_type);
495 if (m->m_flags & M_PKTHDR)
496 M_MOVE_PKTHDR(mn, m);
499 if(m->m_flags & M_PKTHDR) {
511 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
512 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
513 * The wait parameter is a choice of M_TRYWAIT/M_DONTWAIT from caller.
514 * Note that the copy is read-only, because clusters are not copied,
515 * only their reference counts are incremented.
518 m_copym(struct mbuf *m, int off0, int len, int wait)
520 struct mbuf *n, **np;
525 KASSERT(off >= 0, ("m_copym, negative off %d", off));
526 KASSERT(len >= 0, ("m_copym, negative len %d", len));
527 MBUF_CHECKSLEEP(wait);
528 if (off == 0 && m->m_flags & M_PKTHDR)
531 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
541 KASSERT(len == M_COPYALL,
542 ("m_copym, length > size of mbuf chain"));
546 MGETHDR(n, wait, m->m_type);
548 MGET(n, wait, m->m_type);
553 if (!m_dup_pkthdr(n, m, wait))
555 if (len == M_COPYALL)
556 n->m_pkthdr.len -= off0;
558 n->m_pkthdr.len = len;
561 n->m_len = min(len, m->m_len - off);
562 if (m->m_flags & M_EXT) {
563 n->m_data = m->m_data + off;
566 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
568 if (len != M_COPYALL)
575 mbstat.m_mcfail++; /* XXX: No consistency. */
580 mbstat.m_mcfail++; /* XXX: No consistency. */
585 * Returns mbuf chain with new head for the prepending case.
586 * Copies from mbuf (chain) n from off for len to mbuf (chain) m
587 * either prepending or appending the data.
588 * The resulting mbuf (chain) m is fully writeable.
589 * m is destination (is made writeable)
590 * n is source, off is offset in source, len is len from offset
591 * dir, 0 append, 1 prepend
592 * how, wait or nowait
596 m_bcopyxxx(void *s, void *t, u_int len)
598 bcopy(s, t, (size_t)len);
603 m_copymdata(struct mbuf *m, struct mbuf *n, int off, int len,
606 struct mbuf *mm, *x, *z, *prev = NULL;
611 KASSERT(m != NULL && n != NULL, ("m_copymdata, no target or source"));
612 KASSERT(off >= 0, ("m_copymdata, negative off %d", off));
613 KASSERT(len >= 0, ("m_copymdata, negative len %d", len));
614 KASSERT(prep == 0 || prep == 1, ("m_copymdata, unknown direction %d", prep));
623 for (z = n; z != NULL; z = z->m_next)
625 if (len == M_COPYALL)
627 if (off + len > nlen || len < 1)
630 if (!M_WRITABLE(mm)) {
631 /* XXX: Use proper m_xxx function instead. */
632 x = m_getcl(how, MT_DATA, mm->m_flags);
635 bcopy(mm->m_ext.ext_buf, x->m_ext.ext_buf, x->m_ext.ext_size);
636 p = x->m_ext.ext_buf + (mm->m_data - mm->m_ext.ext_buf);
646 * Append/prepend the data. Allocating mbufs as necessary.
648 /* Shortcut if enough free space in first/last mbuf. */
649 if (!prep && M_TRAILINGSPACE(mm) >= len) {
650 m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t) +
653 mm->m_pkthdr.len += len;
656 if (prep && M_LEADINGSPACE(mm) >= len) {
657 mm->m_data = mtod(mm, caddr_t) - len;
658 m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t));
660 mm->m_pkthdr.len += len;
664 /* Expand first/last mbuf to cluster if possible. */
665 if (!prep && !(mm->m_flags & M_EXT) && len > M_TRAILINGSPACE(mm)) {
666 bcopy(mm->m_data, &buf, mm->m_len);
668 if (!(mm->m_flags & M_EXT))
670 bcopy(&buf, mm->m_ext.ext_buf, mm->m_len);
671 mm->m_data = mm->m_ext.ext_buf;
672 mm->m_pkthdr.header = NULL;
674 if (prep && !(mm->m_flags & M_EXT) && len > M_LEADINGSPACE(mm)) {
675 bcopy(mm->m_data, &buf, mm->m_len);
677 if (!(mm->m_flags & M_EXT))
679 bcopy(&buf, (caddr_t *)mm->m_ext.ext_buf +
680 mm->m_ext.ext_size - mm->m_len, mm->m_len);
681 mm->m_data = (caddr_t)mm->m_ext.ext_buf +
682 mm->m_ext.ext_size - mm->m_len;
683 mm->m_pkthdr.header = NULL;
686 /* Append/prepend as many mbuf (clusters) as necessary to fit len. */
687 if (!prep && len > M_TRAILINGSPACE(mm)) {
688 if (!m_getm(mm, len - M_TRAILINGSPACE(mm), how, MT_DATA))
691 if (prep && len > M_LEADINGSPACE(mm)) {
692 if (!(z = m_getm(NULL, len - M_LEADINGSPACE(mm), how, MT_DATA)))
695 for (x = z; x != NULL; x = x->m_next) {
696 i += x->m_flags & M_EXT ? x->m_ext.ext_size :
697 (x->m_flags & M_PKTHDR ? MHLEN : MLEN);
701 z->m_data += i - len;
702 m_move_pkthdr(mm, z);
707 /* Seek to start position in source mbuf. Optimization for long chains. */
715 /* Copy data into target mbuf. */
718 KASSERT(z != NULL, ("m_copymdata, falling off target edge"));
719 i = M_TRAILINGSPACE(z);
720 m_apply(n, off, i, m_bcopyxxx, mtod(z, caddr_t) + z->m_len);
722 /* fixup pkthdr.len if necessary */
723 if ((prep ? mm : m)->m_flags & M_PKTHDR)
724 (prep ? mm : m)->m_pkthdr.len += i;
729 return (prep ? mm : m);
733 * Copy an entire packet, including header (which must be present).
734 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
735 * Note that the copy is read-only, because clusters are not copied,
736 * only their reference counts are incremented.
737 * Preserve alignment of the first mbuf so if the creator has left
738 * some room at the beginning (e.g. for inserting protocol headers)
739 * the copies still have the room available.
742 m_copypacket(struct mbuf *m, int how)
744 struct mbuf *top, *n, *o;
746 MBUF_CHECKSLEEP(how);
747 MGET(n, how, m->m_type);
752 if (!m_dup_pkthdr(n, m, how))
755 if (m->m_flags & M_EXT) {
756 n->m_data = m->m_data;
759 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
760 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
765 MGET(o, how, m->m_type);
773 if (m->m_flags & M_EXT) {
774 n->m_data = m->m_data;
777 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
785 mbstat.m_mcfail++; /* XXX: No consistency. */
790 * Copy data from an mbuf chain starting "off" bytes from the beginning,
791 * continuing for "len" bytes, into the indicated buffer.
794 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
798 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
799 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
801 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
808 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
809 count = min(m->m_len - off, len);
810 bcopy(mtod(m, caddr_t) + off, cp, count);
819 * Copy a packet header mbuf chain into a completely new chain, including
820 * copying any mbuf clusters. Use this instead of m_copypacket() when
821 * you need a writable copy of an mbuf chain.
824 m_dup(struct mbuf *m, int how)
826 struct mbuf **p, *top = NULL;
827 int remain, moff, nsize;
829 MBUF_CHECKSLEEP(how);
835 /* While there's more data, get a new mbuf, tack it on, and fill it */
836 remain = m->m_pkthdr.len;
839 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
842 /* Get the next new mbuf */
843 if (remain >= MINCLSIZE) {
844 n = m_getcl(how, m->m_type, 0);
847 n = m_get(how, m->m_type);
853 if (top == NULL) { /* First one, must be PKTHDR */
854 if (!m_dup_pkthdr(n, m, how)) {
858 if ((n->m_flags & M_EXT) == 0)
863 /* Link it into the new chain */
867 /* Copy data from original mbuf(s) into new mbuf */
868 while (n->m_len < nsize && m != NULL) {
869 int chunk = min(nsize - n->m_len, m->m_len - moff);
871 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
875 if (moff == m->m_len) {
881 /* Check correct total mbuf length */
882 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
883 ("%s: bogus m_pkthdr.len", __func__));
889 mbstat.m_mcfail++; /* XXX: No consistency. */
894 * Concatenate mbuf chain n to m.
895 * Both chains must be of the same type (e.g. MT_DATA).
896 * Any m_pkthdr is not updated.
899 m_cat(struct mbuf *m, struct mbuf *n)
904 if (m->m_flags & M_EXT ||
905 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
906 /* just join the two chains */
910 /* splat the data from one into the other */
911 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
913 m->m_len += n->m_len;
919 m_adj(struct mbuf *mp, int req_len)
925 if ((m = mp) == NULL)
931 while (m != NULL && len > 0) {
932 if (m->m_len <= len) {
943 if (mp->m_flags & M_PKTHDR)
944 m->m_pkthdr.len -= (req_len - len);
947 * Trim from tail. Scan the mbuf chain,
948 * calculating its length and finding the last mbuf.
949 * If the adjustment only affects this mbuf, then just
950 * adjust and return. Otherwise, rescan and truncate
951 * after the remaining size.
957 if (m->m_next == (struct mbuf *)0)
961 if (m->m_len >= len) {
963 if (mp->m_flags & M_PKTHDR)
964 mp->m_pkthdr.len -= len;
971 * Correct length for chain is "count".
972 * Find the mbuf with last data, adjust its length,
973 * and toss data from remaining mbufs on chain.
976 if (m->m_flags & M_PKTHDR)
977 m->m_pkthdr.len = count;
978 for (; m; m = m->m_next) {
979 if (m->m_len >= count) {
981 if (m->m_next != NULL) {
993 * Rearange an mbuf chain so that len bytes are contiguous
994 * and in the data area of an mbuf (so that mtod and dtom
995 * will work for a structure of size len). Returns the resulting
996 * mbuf chain on success, frees it and returns null on failure.
997 * If there is room, it will add up to max_protohdr-len extra bytes to the
998 * contiguous region in an attempt to avoid being called next time.
1001 m_pullup(struct mbuf *n, int len)
1008 * If first mbuf has no cluster, and has room for len bytes
1009 * without shifting current data, pullup into it,
1010 * otherwise allocate a new mbuf to prepend to the chain.
1012 if ((n->m_flags & M_EXT) == 0 &&
1013 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1014 if (n->m_len >= len)
1022 MGET(m, M_DONTWAIT, n->m_type);
1026 if (n->m_flags & M_PKTHDR)
1027 M_MOVE_PKTHDR(m, n);
1029 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1031 count = min(min(max(len, max_protohdr), space), n->m_len);
1032 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1042 } while (len > 0 && n);
1051 mbstat.m_mpfail++; /* XXX: No consistency. */
1056 * Like m_pullup(), except a new mbuf is always allocated, and we allow
1057 * the amount of empty space before the data in the new mbuf to be specified
1058 * (in the event that the caller expects to prepend later).
1063 m_copyup(struct mbuf *n, int len, int dstoff)
1068 if (len > (MHLEN - dstoff))
1070 MGET(m, M_DONTWAIT, n->m_type);
1074 if (n->m_flags & M_PKTHDR)
1075 M_MOVE_PKTHDR(m, n);
1076 m->m_data += dstoff;
1077 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1079 count = min(min(max(len, max_protohdr), space), n->m_len);
1080 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1090 } while (len > 0 && n);
1104 * Partition an mbuf chain in two pieces, returning the tail --
1105 * all but the first len0 bytes. In case of failure, it returns NULL and
1106 * attempts to restore the chain to its original state.
1108 * Note that the resulting mbufs might be read-only, because the new
1109 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1110 * the "breaking point" happens to lie within a cluster mbuf. Use the
1111 * M_WRITABLE() macro to check for this case.
1114 m_split(struct mbuf *m0, int len0, int wait)
1117 u_int len = len0, remain;
1119 MBUF_CHECKSLEEP(wait);
1120 for (m = m0; m && len > m->m_len; m = m->m_next)
1124 remain = m->m_len - len;
1125 if (m0->m_flags & M_PKTHDR) {
1126 MGETHDR(n, wait, m0->m_type);
1129 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1130 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1131 m0->m_pkthdr.len = len0;
1132 if (m->m_flags & M_EXT)
1134 if (remain > MHLEN) {
1135 /* m can't be the lead packet */
1137 n->m_next = m_split(m, len, wait);
1138 if (n->m_next == NULL) {
1146 MH_ALIGN(n, remain);
1147 } else if (remain == 0) {
1152 MGET(n, wait, m->m_type);
1158 if (m->m_flags & M_EXT) {
1159 n->m_data = m->m_data + len;
1162 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1166 n->m_next = m->m_next;
1171 * Routine to copy from device local memory into mbufs.
1172 * Note that `off' argument is offset into first mbuf of target chain from
1173 * which to begin copying the data to.
1176 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1177 void (*copy)(char *from, caddr_t to, u_int len))
1180 struct mbuf *top = NULL, **mp = ⊤
1183 if (off < 0 || off > MHLEN)
1186 while (totlen > 0) {
1187 if (top == NULL) { /* First one, must be PKTHDR */
1188 if (totlen + off >= MINCLSIZE) {
1189 m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1192 m = m_gethdr(M_DONTWAIT, MT_DATA);
1195 /* Place initial small packet/header at end of mbuf */
1196 if (m && totlen + off + max_linkhdr <= MLEN) {
1197 m->m_data += max_linkhdr;
1203 m->m_pkthdr.rcvif = ifp;
1204 m->m_pkthdr.len = totlen;
1206 if (totlen + off >= MINCLSIZE) {
1207 m = m_getcl(M_DONTWAIT, MT_DATA, 0);
1210 m = m_get(M_DONTWAIT, MT_DATA);
1223 m->m_len = len = min(totlen, len);
1225 copy(buf, mtod(m, caddr_t), (u_int)len);
1227 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1237 * Copy data from a buffer back into the indicated mbuf chain,
1238 * starting "off" bytes from the beginning, extending the mbuf
1239 * chain if necessary.
1242 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1245 struct mbuf *m = m0, *n;
1250 while (off > (mlen = m->m_len)) {
1253 if (m->m_next == NULL) {
1254 n = m_get(M_DONTWAIT, m->m_type);
1257 bzero(mtod(n, caddr_t), MLEN);
1258 n->m_len = min(MLEN, len + off);
1264 mlen = min (m->m_len - off, len);
1265 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1273 if (m->m_next == NULL) {
1274 n = m_get(M_DONTWAIT, m->m_type);
1277 n->m_len = min(MLEN, len);
1282 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1283 m->m_pkthdr.len = totlen;
1287 * Append the specified data to the indicated mbuf chain,
1288 * Extend the mbuf chain if the new data does not fit in
1291 * Return 1 if able to complete the job; otherwise 0.
1294 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1297 int remainder, space;
1299 for (m = m0; m->m_next != NULL; m = m->m_next)
1302 space = M_TRAILINGSPACE(m);
1305 * Copy into available space.
1307 if (space > remainder)
1309 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1311 cp += space, remainder -= space;
1313 while (remainder > 0) {
1315 * Allocate a new mbuf; could check space
1316 * and allocate a cluster instead.
1318 n = m_get(M_DONTWAIT, m->m_type);
1321 n->m_len = min(MLEN, remainder);
1322 bcopy(cp, mtod(n, caddr_t), n->m_len);
1323 cp += n->m_len, remainder -= n->m_len;
1327 if (m0->m_flags & M_PKTHDR)
1328 m0->m_pkthdr.len += len - remainder;
1329 return (remainder == 0);
1333 * Apply function f to the data in an mbuf chain starting "off" bytes from
1334 * the beginning, continuing for "len" bytes.
1337 m_apply(struct mbuf *m, int off, int len,
1338 int (*f)(void *, void *, u_int), void *arg)
1343 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1344 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1346 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1353 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1354 count = min(m->m_len - off, len);
1355 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1366 * Return a pointer to mbuf/offset of location in mbuf chain.
1369 m_getptr(struct mbuf *m, int loc, int *off)
1373 /* Normal end of search. */
1374 if (m->m_len > loc) {
1379 if (m->m_next == NULL) {
1381 /* Point at the end of valid data. */
1394 m_print(const struct mbuf *m, int maxlen)
1398 const struct mbuf *m2;
1400 if (m->m_flags & M_PKTHDR)
1401 len = m->m_pkthdr.len;
1405 while (m2 != NULL && (len == -1 || len)) {
1407 if (maxlen != -1 && pdata > maxlen)
1409 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1410 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1411 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1412 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1414 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1420 printf("%d bytes unaccounted for.\n", len);
1425 m_fixhdr(struct mbuf *m0)
1429 len = m_length(m0, NULL);
1430 m0->m_pkthdr.len = len;
1435 m_length(struct mbuf *m0, struct mbuf **last)
1441 for (m = m0; m != NULL; m = m->m_next) {
1443 if (m->m_next == NULL)
1452 * Defragment a mbuf chain, returning the shortest possible
1453 * chain of mbufs and clusters. If allocation fails and
1454 * this cannot be completed, NULL will be returned, but
1455 * the passed in chain will be unchanged. Upon success,
1456 * the original chain will be freed, and the new chain
1459 * If a non-packet header is passed in, the original
1460 * mbuf (chain?) will be returned unharmed.
1463 m_defrag(struct mbuf *m0, int how)
1465 struct mbuf *m_new = NULL, *m_final = NULL;
1466 int progress = 0, length;
1468 MBUF_CHECKSLEEP(how);
1469 if (!(m0->m_flags & M_PKTHDR))
1472 m_fixhdr(m0); /* Needed sanity check */
1474 #ifdef MBUF_STRESS_TEST
1475 if (m_defragrandomfailures) {
1476 int temp = arc4random() & 0xff;
1482 if (m0->m_pkthdr.len > MHLEN)
1483 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1485 m_final = m_gethdr(how, MT_DATA);
1487 if (m_final == NULL)
1490 if (m_dup_pkthdr(m_final, m0, how) == 0)
1495 while (progress < m0->m_pkthdr.len) {
1496 length = m0->m_pkthdr.len - progress;
1497 if (length > MCLBYTES)
1500 if (m_new == NULL) {
1502 m_new = m_getcl(how, MT_DATA, 0);
1504 m_new = m_get(how, MT_DATA);
1509 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1511 m_new->m_len = length;
1512 if (m_new != m_final)
1513 m_cat(m_final, m_new);
1516 #ifdef MBUF_STRESS_TEST
1517 if (m0->m_next == NULL)
1522 #ifdef MBUF_STRESS_TEST
1524 m_defragbytes += m0->m_pkthdr.len;
1528 #ifdef MBUF_STRESS_TEST
1536 #ifdef MBUF_STRESS_TEST
1539 * Fragment an mbuf chain. There's no reason you'd ever want to do
1540 * this in normal usage, but it's great for stress testing various
1543 * If fragmentation is not possible, the original chain will be
1546 * Possible length values:
1547 * 0 no fragmentation will occur
1548 * > 0 each fragment will be of the specified length
1549 * -1 each fragment will be the same random value in length
1550 * -2 each fragment's length will be entirely random
1551 * (Random values range from 1 to 256)
1554 m_fragment(struct mbuf *m0, int how, int length)
1556 struct mbuf *m_new = NULL, *m_final = NULL;
1559 if (!(m0->m_flags & M_PKTHDR))
1562 if ((length == 0) || (length < -2))
1565 m_fixhdr(m0); /* Needed sanity check */
1567 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1569 if (m_final == NULL)
1572 if (m_dup_pkthdr(m_final, m0, how) == 0)
1578 length = 1 + (arc4random() & 255);
1580 while (progress < m0->m_pkthdr.len) {
1586 fraglen = 1 + (arc4random() & 255);
1587 if (fraglen > m0->m_pkthdr.len - progress)
1588 fraglen = m0->m_pkthdr.len - progress;
1590 if (fraglen > MCLBYTES)
1593 if (m_new == NULL) {
1594 m_new = m_getcl(how, MT_DATA, 0);
1599 m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1600 progress += fraglen;
1601 m_new->m_len = fraglen;
1602 if (m_new != m_final)
1603 m_cat(m_final, m_new);
1612 /* Return the original chain on failure */
1619 * Copy the contents of uio into a properly sized mbuf chain.
1622 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1624 struct mbuf *m, *mb;
1625 int error, length, total;
1629 * len can be zero or an arbitrary large value bound by
1630 * the total data supplied by the uio.
1633 total = min(uio->uio_resid, len);
1635 total = uio->uio_resid;
1638 * The smallest unit returned by m_getm2() is a single mbuf
1639 * with pkthdr. We can't align past it. Align align itself.
1642 align &= ~(sizeof(long) - 1);
1646 /* Give us all or nothing. */
1647 m = m_getm2(NULL, total + align, how, MT_DATA, flags);
1652 /* Fill all mbufs with uio data and update header information. */
1653 for (mb = m; mb != NULL; mb = mb->m_next) {
1654 length = min(M_TRAILINGSPACE(mb), total - progress);
1656 error = uiomove(mtod(mb, void *), length, uio);
1664 if (flags & M_PKTHDR)
1665 m->m_pkthdr.len += length;
1667 KASSERT(progress == total, ("%s: progress != total", __func__));
1673 * Set the m_data pointer of a newly-allocated mbuf
1674 * to place an object of the specified size at the
1675 * end of the mbuf, longword aligned.
1678 m_align(struct mbuf *m, int len)
1682 if (m->m_flags & M_EXT)
1683 adjust = m->m_ext.ext_size - len;
1684 else if (m->m_flags & M_PKTHDR)
1685 adjust = MHLEN - len;
1687 adjust = MLEN - len;
1688 m->m_data += adjust &~ (sizeof(long)-1);
1692 * Create a writable copy of the mbuf chain. While doing this
1693 * we compact the chain with a goal of producing a chain with
1694 * at most two mbufs. The second mbuf in this chain is likely
1695 * to be a cluster. The primary purpose of this work is to create
1696 * a writable packet for encryption, compression, etc. The
1697 * secondary goal is to linearize the data so the data can be
1698 * passed to crypto hardware in the most efficient manner possible.
1701 m_unshare(struct mbuf *m0, int how)
1703 struct mbuf *m, *mprev;
1704 struct mbuf *n, *mfirst, *mlast;
1708 for (m = m0; m != NULL; m = mprev->m_next) {
1710 * Regular mbufs are ignored unless there's a cluster
1711 * in front of it that we can use to coalesce. We do
1712 * the latter mainly so later clusters can be coalesced
1713 * also w/o having to handle them specially (i.e. convert
1714 * mbuf+cluster -> cluster). This optimization is heavily
1715 * influenced by the assumption that we're running over
1716 * Ethernet where MCLBYTES is large enough that the max
1717 * packet size will permit lots of coalescing into a
1718 * single cluster. This in turn permits efficient
1719 * crypto operations, especially when using hardware.
1721 if ((m->m_flags & M_EXT) == 0) {
1722 if (mprev && (mprev->m_flags & M_EXT) &&
1723 m->m_len <= M_TRAILINGSPACE(mprev)) {
1724 /* XXX: this ignores mbuf types */
1725 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1726 mtod(m, caddr_t), m->m_len);
1727 mprev->m_len += m->m_len;
1728 mprev->m_next = m->m_next; /* unlink from chain */
1729 m_free(m); /* reclaim mbuf */
1731 newipsecstat.ips_mbcoalesced++;
1739 * Writable mbufs are left alone (for now).
1741 if (M_WRITABLE(m)) {
1747 * Not writable, replace with a copy or coalesce with
1748 * the previous mbuf if possible (since we have to copy
1749 * it anyway, we try to reduce the number of mbufs and
1750 * clusters so that future work is easier).
1752 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1753 /* NB: we only coalesce into a cluster or larger */
1754 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1755 m->m_len <= M_TRAILINGSPACE(mprev)) {
1756 /* XXX: this ignores mbuf types */
1757 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1758 mtod(m, caddr_t), m->m_len);
1759 mprev->m_len += m->m_len;
1760 mprev->m_next = m->m_next; /* unlink from chain */
1761 m_free(m); /* reclaim mbuf */
1763 newipsecstat.ips_clcoalesced++;
1769 * Allocate new space to hold the copy...
1771 /* XXX why can M_PKTHDR be set past the first mbuf? */
1772 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
1774 * NB: if a packet header is present we must
1775 * allocate the mbuf separately from any cluster
1776 * because M_MOVE_PKTHDR will smash the data
1777 * pointer and drop the M_EXT marker.
1779 MGETHDR(n, how, m->m_type);
1784 M_MOVE_PKTHDR(n, m);
1786 if ((n->m_flags & M_EXT) == 0) {
1792 n = m_getcl(how, m->m_type, m->m_flags);
1799 * ... and copy the data. We deal with jumbo mbufs
1800 * (i.e. m_len > MCLBYTES) by splitting them into
1801 * clusters. We could just malloc a buffer and make
1802 * it external but too many device drivers don't know
1803 * how to break up the non-contiguous memory when
1811 int cc = min(len, MCLBYTES);
1812 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1818 newipsecstat.ips_clcopied++;
1826 n = m_getcl(how, m->m_type, m->m_flags);
1833 n->m_next = m->m_next;
1835 m0 = mfirst; /* new head of chain */
1837 mprev->m_next = mfirst; /* replace old mbuf */
1838 m_free(m); /* release old mbuf */