2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_param.h"
38 #include "opt_mbuf_stress_test.h"
39 #include "opt_mbuf_profiling.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/limits.h>
46 #include <sys/malloc.h>
48 #include <sys/sysctl.h>
49 #include <sys/domain.h>
50 #include <sys/protosw.h>
54 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__init,
55 "struct mbuf *", "mbufinfo_t *",
56 "uint32_t", "uint32_t",
57 "uint16_t", "uint16_t",
58 "uint32_t", "uint32_t",
59 "uint32_t", "uint32_t");
61 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr,
62 "uint32_t", "uint32_t",
63 "uint16_t", "uint16_t",
64 "struct mbuf *", "mbufinfo_t *");
66 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
67 "uint32_t", "uint32_t",
68 "uint16_t", "uint16_t",
69 "struct mbuf *", "mbufinfo_t *");
71 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
72 "uint32_t", "uint32_t",
73 "uint16_t", "uint16_t",
74 "uint32_t", "uint32_t",
75 "struct mbuf *", "mbufinfo_t *");
77 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
78 "struct mbuf *", "mbufinfo_t *",
79 "uint32_t", "uint32_t",
80 "uint32_t", "uint32_t");
82 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
83 "struct mbuf *", "mbufinfo_t *",
84 "uint32_t", "uint32_t",
85 "uint32_t", "uint32_t",
88 SDT_PROBE_DEFINE(sdt, , , m__cljset);
90 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
91 "struct mbuf *", "mbufinfo_t *");
93 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
94 "struct mbuf *", "mbufinfo_t *");
96 #include <security/mac/mac_framework.h>
102 #ifdef MBUF_STRESS_TEST
107 int m_defragrandomfailures;
111 * sysctl(8) exported objects
113 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
114 &max_linkhdr, 0, "Size of largest link layer header");
115 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
116 &max_protohdr, 0, "Size of largest protocol layer header");
117 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
118 &max_hdr, 0, "Size of largest link plus protocol header");
119 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
120 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
121 #ifdef MBUF_STRESS_TEST
122 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
123 &m_defragpackets, 0, "");
124 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
125 &m_defragbytes, 0, "");
126 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
127 &m_defraguseless, 0, "");
128 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
129 &m_defragfailure, 0, "");
130 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
131 &m_defragrandomfailures, 0, "");
135 * Ensure the correct size of various mbuf parameters. It could be off due
136 * to compiler-induced padding and alignment artifacts.
138 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
139 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
142 * mbuf data storage should be 64-bit aligned regardless of architectural
143 * pointer size; check this is the case with and without a packet header.
145 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
146 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
149 * While the specific values here don't matter too much (i.e., +/- a few
150 * words), we do want to ensure that changes to these values are carefully
151 * reasoned about and properly documented. This is especially the case as
152 * network-protocol and device-driver modules encode these layouts, and must
153 * be recompiled if the structures change. Check these values at compile time
154 * against the ones documented in comments in mbuf.h.
156 * NB: Possibly they should be documented there via #define's and not just
159 #if defined(__LP64__)
160 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
161 CTASSERT(sizeof(struct pkthdr) == 56);
162 CTASSERT(sizeof(struct m_ext) == 48);
164 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
165 CTASSERT(sizeof(struct pkthdr) == 48);
166 CTASSERT(sizeof(struct m_ext) == 28);
170 * Assert that the queue(3) macros produce code of the same size as an old
171 * plain pointer does.
174 static struct mbuf __used m_assertbuf;
175 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
176 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
177 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
178 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
182 * Attach the cluster from *m to *n, set up m_ext in *n
183 * and bump the refcount of the cluster.
186 mb_dupcl(struct mbuf *n, struct mbuf *m)
188 volatile u_int *refcnt;
190 KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
191 KASSERT(!(n->m_flags & M_EXT), ("%s: M_EXT set on %p", __func__, n));
194 * Cache access optimization. For most kinds of external
195 * storage we don't need full copy of m_ext, since the
196 * holder of the 'ext_count' is responsible to carry the
197 * free routine and its arguments. Exclusion is EXT_EXTREF,
198 * where 'ext_cnt' doesn't point into mbuf at all.
200 if (m->m_ext.ext_type == EXT_EXTREF)
201 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
203 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
205 n->m_flags |= m->m_flags & M_RDONLY;
207 /* See if this is the mbuf that holds the embedded refcount. */
208 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
209 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
210 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
212 KASSERT(m->m_ext.ext_cnt != NULL,
213 ("%s: no refcounting pointer on %p", __func__, m));
214 refcnt = m->m_ext.ext_cnt;
220 atomic_add_int(refcnt, 1);
224 m_demote_pkthdr(struct mbuf *m)
229 m_tag_delete_chain(m, NULL);
230 m->m_flags &= ~M_PKTHDR;
231 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
235 * Clean up mbuf (chain) from any tags and packet headers.
236 * If "all" is set then the first mbuf in the chain will be
240 m_demote(struct mbuf *m0, int all, int flags)
244 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
245 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
247 if (m->m_flags & M_PKTHDR)
249 m->m_flags = m->m_flags & (M_EXT | M_RDONLY | M_NOFREE | flags);
254 * Sanity checks on mbuf (chain) for use in KASSERT() and general
256 * Returns 0 or panics when bad and 1 on all tests passed.
257 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
261 m_sanity(struct mbuf *m0, int sanitize)
268 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
270 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
273 for (m = m0; m != NULL; m = m->m_next) {
275 * Basic pointer checks. If any of these fails then some
276 * unrelated kernel memory before or after us is trashed.
277 * No way to recover from that.
281 if ((caddr_t)m->m_data < a)
282 M_SANITY_ACTION("m_data outside mbuf data range left");
283 if ((caddr_t)m->m_data > b)
284 M_SANITY_ACTION("m_data outside mbuf data range right");
285 if ((caddr_t)m->m_data + m->m_len > b)
286 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
288 /* m->m_nextpkt may only be set on first mbuf in chain. */
289 if (m != m0 && m->m_nextpkt != NULL) {
291 m_freem(m->m_nextpkt);
292 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
294 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
297 /* packet length (not mbuf length!) calculation */
298 if (m0->m_flags & M_PKTHDR)
301 /* m_tags may only be attached to first mbuf in chain. */
302 if (m != m0 && m->m_flags & M_PKTHDR &&
303 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
305 m_tag_delete_chain(m, NULL);
306 /* put in 0xDEADC0DE perhaps? */
308 M_SANITY_ACTION("m_tags on in-chain mbuf");
311 /* M_PKTHDR may only be set on first mbuf in chain */
312 if (m != m0 && m->m_flags & M_PKTHDR) {
314 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
315 m->m_flags &= ~M_PKTHDR;
316 /* put in 0xDEADCODE and leave hdr flag in */
318 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
322 if (pktlen && pktlen != m->m_pkthdr.len) {
326 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
330 #undef M_SANITY_ACTION
334 * Non-inlined part of m_init().
337 m_pkthdr_init(struct mbuf *m, int how)
342 m->m_data = m->m_pktdat;
343 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
345 /* If the label init fails, fail the alloc */
346 error = mac_mbuf_init(m, how);
355 * "Move" mbuf pkthdr from "from" to "to".
356 * "from" must have M_PKTHDR set, and "to" must be empty.
359 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
363 /* see below for why these are not enabled */
365 /* Note: with MAC, this may not be a good assertion. */
366 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
367 ("m_move_pkthdr: to has tags"));
371 * XXXMAC: It could be this should also occur for non-MAC?
373 if (to->m_flags & M_PKTHDR)
374 m_tag_delete_chain(to, NULL);
376 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
377 if ((to->m_flags & M_EXT) == 0)
378 to->m_data = to->m_pktdat;
379 to->m_pkthdr = from->m_pkthdr; /* especially tags */
380 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
381 from->m_flags &= ~M_PKTHDR;
385 * Duplicate "from"'s mbuf pkthdr in "to".
386 * "from" must have M_PKTHDR set, and "to" must be empty.
387 * In particular, this does a deep copy of the packet tags.
390 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
395 * The mbuf allocator only initializes the pkthdr
396 * when the mbuf is allocated with m_gethdr(). Many users
397 * (e.g. m_copy*, m_prepend) use m_get() and then
398 * smash the pkthdr as needed causing these
399 * assertions to trip. For now just disable them.
402 /* Note: with MAC, this may not be a good assertion. */
403 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
405 MBUF_CHECKSLEEP(how);
407 if (to->m_flags & M_PKTHDR)
408 m_tag_delete_chain(to, NULL);
410 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
411 if ((to->m_flags & M_EXT) == 0)
412 to->m_data = to->m_pktdat;
413 to->m_pkthdr = from->m_pkthdr;
414 SLIST_INIT(&to->m_pkthdr.tags);
415 return (m_tag_copy_chain(to, from, how));
419 * Lesser-used path for M_PREPEND:
420 * allocate new mbuf to prepend to chain,
424 m_prepend(struct mbuf *m, int len, int how)
428 if (m->m_flags & M_PKTHDR)
429 mn = m_gethdr(how, m->m_type);
431 mn = m_get(how, m->m_type);
436 if (m->m_flags & M_PKTHDR)
437 m_move_pkthdr(mn, m);
447 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
448 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
449 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
450 * Note that the copy is read-only, because clusters are not copied,
451 * only their reference counts are incremented.
454 m_copym(struct mbuf *m, int off0, int len, int wait)
456 struct mbuf *n, **np;
461 KASSERT(off >= 0, ("m_copym, negative off %d", off));
462 KASSERT(len >= 0, ("m_copym, negative len %d", len));
463 MBUF_CHECKSLEEP(wait);
464 if (off == 0 && m->m_flags & M_PKTHDR)
467 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
477 KASSERT(len == M_COPYALL,
478 ("m_copym, length > size of mbuf chain"));
482 n = m_gethdr(wait, m->m_type);
484 n = m_get(wait, m->m_type);
489 if (!m_dup_pkthdr(n, m, wait))
491 if (len == M_COPYALL)
492 n->m_pkthdr.len -= off0;
494 n->m_pkthdr.len = len;
497 n->m_len = min(len, m->m_len - off);
498 if (m->m_flags & M_EXT) {
499 n->m_data = m->m_data + off;
502 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
504 if (len != M_COPYALL)
518 * Copy an entire packet, including header (which must be present).
519 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
520 * Note that the copy is read-only, because clusters are not copied,
521 * only their reference counts are incremented.
522 * Preserve alignment of the first mbuf so if the creator has left
523 * some room at the beginning (e.g. for inserting protocol headers)
524 * the copies still have the room available.
527 m_copypacket(struct mbuf *m, int how)
529 struct mbuf *top, *n, *o;
531 MBUF_CHECKSLEEP(how);
532 n = m_get(how, m->m_type);
537 if (!m_dup_pkthdr(n, m, how))
540 if (m->m_flags & M_EXT) {
541 n->m_data = m->m_data;
544 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
545 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
550 o = m_get(how, m->m_type);
558 if (m->m_flags & M_EXT) {
559 n->m_data = m->m_data;
562 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
574 * Copy data from an mbuf chain starting "off" bytes from the beginning,
575 * continuing for "len" bytes, into the indicated buffer.
578 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
582 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
583 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
585 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
592 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
593 count = min(m->m_len - off, len);
594 bcopy(mtod(m, caddr_t) + off, cp, count);
603 * Copy a packet header mbuf chain into a completely new chain, including
604 * copying any mbuf clusters. Use this instead of m_copypacket() when
605 * you need a writable copy of an mbuf chain.
608 m_dup(const struct mbuf *m, int how)
610 struct mbuf **p, *top = NULL;
611 int remain, moff, nsize;
613 MBUF_CHECKSLEEP(how);
619 /* While there's more data, get a new mbuf, tack it on, and fill it */
620 remain = m->m_pkthdr.len;
623 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
626 /* Get the next new mbuf */
627 if (remain >= MINCLSIZE) {
628 n = m_getcl(how, m->m_type, 0);
631 n = m_get(how, m->m_type);
637 if (top == NULL) { /* First one, must be PKTHDR */
638 if (!m_dup_pkthdr(n, m, how)) {
642 if ((n->m_flags & M_EXT) == 0)
644 n->m_flags &= ~M_RDONLY;
648 /* Link it into the new chain */
652 /* Copy data from original mbuf(s) into new mbuf */
653 while (n->m_len < nsize && m != NULL) {
654 int chunk = min(nsize - n->m_len, m->m_len - moff);
656 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
660 if (moff == m->m_len) {
666 /* Check correct total mbuf length */
667 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
668 ("%s: bogus m_pkthdr.len", __func__));
678 * Concatenate mbuf chain n to m.
679 * Both chains must be of the same type (e.g. MT_DATA).
680 * Any m_pkthdr is not updated.
683 m_cat(struct mbuf *m, struct mbuf *n)
688 if (!M_WRITABLE(m) ||
689 M_TRAILINGSPACE(m) < n->m_len) {
690 /* just join the two chains */
694 /* splat the data from one into the other */
695 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
697 m->m_len += n->m_len;
703 * Concatenate two pkthdr mbuf chains.
706 m_catpkt(struct mbuf *m, struct mbuf *n)
712 m->m_pkthdr.len += n->m_pkthdr.len;
719 m_adj(struct mbuf *mp, int req_len)
725 if ((m = mp) == NULL)
731 while (m != NULL && len > 0) {
732 if (m->m_len <= len) {
742 if (mp->m_flags & M_PKTHDR)
743 mp->m_pkthdr.len -= (req_len - len);
746 * Trim from tail. Scan the mbuf chain,
747 * calculating its length and finding the last mbuf.
748 * If the adjustment only affects this mbuf, then just
749 * adjust and return. Otherwise, rescan and truncate
750 * after the remaining size.
756 if (m->m_next == (struct mbuf *)0)
760 if (m->m_len >= len) {
762 if (mp->m_flags & M_PKTHDR)
763 mp->m_pkthdr.len -= len;
770 * Correct length for chain is "count".
771 * Find the mbuf with last data, adjust its length,
772 * and toss data from remaining mbufs on chain.
775 if (m->m_flags & M_PKTHDR)
776 m->m_pkthdr.len = count;
777 for (; m; m = m->m_next) {
778 if (m->m_len >= count) {
780 if (m->m_next != NULL) {
792 * Rearange an mbuf chain so that len bytes are contiguous
793 * and in the data area of an mbuf (so that mtod will work
794 * for a structure of size len). Returns the resulting
795 * mbuf chain on success, frees it and returns null on failure.
796 * If there is room, it will add up to max_protohdr-len extra bytes to the
797 * contiguous region in an attempt to avoid being called next time.
800 m_pullup(struct mbuf *n, int len)
807 * If first mbuf has no cluster, and has room for len bytes
808 * without shifting current data, pullup into it,
809 * otherwise allocate a new mbuf to prepend to the chain.
811 if ((n->m_flags & M_EXT) == 0 &&
812 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
821 m = m_get(M_NOWAIT, n->m_type);
824 if (n->m_flags & M_PKTHDR)
827 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
829 count = min(min(max(len, max_protohdr), space), n->m_len);
830 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
840 } while (len > 0 && n);
853 * Like m_pullup(), except a new mbuf is always allocated, and we allow
854 * the amount of empty space before the data in the new mbuf to be specified
855 * (in the event that the caller expects to prepend later).
858 m_copyup(struct mbuf *n, int len, int dstoff)
863 if (len > (MHLEN - dstoff))
865 m = m_get(M_NOWAIT, n->m_type);
868 if (n->m_flags & M_PKTHDR)
871 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
873 count = min(min(max(len, max_protohdr), space), n->m_len);
874 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
884 } while (len > 0 && n);
897 * Partition an mbuf chain in two pieces, returning the tail --
898 * all but the first len0 bytes. In case of failure, it returns NULL and
899 * attempts to restore the chain to its original state.
901 * Note that the resulting mbufs might be read-only, because the new
902 * mbuf can end up sharing an mbuf cluster with the original mbuf if
903 * the "breaking point" happens to lie within a cluster mbuf. Use the
904 * M_WRITABLE() macro to check for this case.
907 m_split(struct mbuf *m0, int len0, int wait)
910 u_int len = len0, remain;
912 MBUF_CHECKSLEEP(wait);
913 for (m = m0; m && len > m->m_len; m = m->m_next)
917 remain = m->m_len - len;
918 if (m0->m_flags & M_PKTHDR && remain == 0) {
919 n = m_gethdr(wait, m0->m_type);
922 n->m_next = m->m_next;
924 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
925 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
926 m0->m_pkthdr.len = len0;
928 } else if (m0->m_flags & M_PKTHDR) {
929 n = m_gethdr(wait, m0->m_type);
932 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
933 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
934 m0->m_pkthdr.len = len0;
935 if (m->m_flags & M_EXT)
937 if (remain > MHLEN) {
938 /* m can't be the lead packet */
940 n->m_next = m_split(m, len, wait);
941 if (n->m_next == NULL) {
950 } else if (remain == 0) {
955 n = m_get(wait, m->m_type);
961 if (m->m_flags & M_EXT) {
962 n->m_data = m->m_data + len;
965 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
969 n->m_next = m->m_next;
974 * Routine to copy from device local memory into mbufs.
975 * Note that `off' argument is offset into first mbuf of target chain from
976 * which to begin copying the data to.
979 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
980 void (*copy)(char *from, caddr_t to, u_int len))
983 struct mbuf *top = NULL, **mp = ⊤
986 if (off < 0 || off > MHLEN)
990 if (top == NULL) { /* First one, must be PKTHDR */
991 if (totlen + off >= MINCLSIZE) {
992 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
995 m = m_gethdr(M_NOWAIT, MT_DATA);
998 /* Place initial small packet/header at end of mbuf */
999 if (m && totlen + off + max_linkhdr <= MHLEN) {
1000 m->m_data += max_linkhdr;
1006 m->m_pkthdr.rcvif = ifp;
1007 m->m_pkthdr.len = totlen;
1009 if (totlen + off >= MINCLSIZE) {
1010 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1013 m = m_get(M_NOWAIT, MT_DATA);
1026 m->m_len = len = min(totlen, len);
1028 copy(buf, mtod(m, caddr_t), (u_int)len);
1030 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1040 * Copy data from a buffer back into the indicated mbuf chain,
1041 * starting "off" bytes from the beginning, extending the mbuf
1042 * chain if necessary.
1045 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1048 struct mbuf *m = m0, *n;
1053 while (off > (mlen = m->m_len)) {
1056 if (m->m_next == NULL) {
1057 n = m_get(M_NOWAIT, m->m_type);
1060 bzero(mtod(n, caddr_t), MLEN);
1061 n->m_len = min(MLEN, len + off);
1067 if (m->m_next == NULL && (len > m->m_len - off)) {
1068 m->m_len += min(len - (m->m_len - off),
1069 M_TRAILINGSPACE(m));
1071 mlen = min (m->m_len - off, len);
1072 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1080 if (m->m_next == NULL) {
1081 n = m_get(M_NOWAIT, m->m_type);
1084 n->m_len = min(MLEN, len);
1089 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1090 m->m_pkthdr.len = totlen;
1094 * Append the specified data to the indicated mbuf chain,
1095 * Extend the mbuf chain if the new data does not fit in
1098 * Return 1 if able to complete the job; otherwise 0.
1101 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1104 int remainder, space;
1106 for (m = m0; m->m_next != NULL; m = m->m_next)
1109 space = M_TRAILINGSPACE(m);
1112 * Copy into available space.
1114 if (space > remainder)
1116 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1118 cp += space, remainder -= space;
1120 while (remainder > 0) {
1122 * Allocate a new mbuf; could check space
1123 * and allocate a cluster instead.
1125 n = m_get(M_NOWAIT, m->m_type);
1128 n->m_len = min(MLEN, remainder);
1129 bcopy(cp, mtod(n, caddr_t), n->m_len);
1130 cp += n->m_len, remainder -= n->m_len;
1134 if (m0->m_flags & M_PKTHDR)
1135 m0->m_pkthdr.len += len - remainder;
1136 return (remainder == 0);
1140 * Apply function f to the data in an mbuf chain starting "off" bytes from
1141 * the beginning, continuing for "len" bytes.
1144 m_apply(struct mbuf *m, int off, int len,
1145 int (*f)(void *, void *, u_int), void *arg)
1150 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1151 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1153 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1160 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1161 count = min(m->m_len - off, len);
1162 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1173 * Return a pointer to mbuf/offset of location in mbuf chain.
1176 m_getptr(struct mbuf *m, int loc, int *off)
1180 /* Normal end of search. */
1181 if (m->m_len > loc) {
1186 if (m->m_next == NULL) {
1188 /* Point at the end of valid data. */
1201 m_print(const struct mbuf *m, int maxlen)
1205 const struct mbuf *m2;
1208 printf("mbuf: %p\n", m);
1212 if (m->m_flags & M_PKTHDR)
1213 len = m->m_pkthdr.len;
1217 while (m2 != NULL && (len == -1 || len)) {
1219 if (maxlen != -1 && pdata > maxlen)
1221 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1222 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1223 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1224 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1226 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1232 printf("%d bytes unaccounted for.\n", len);
1237 m_fixhdr(struct mbuf *m0)
1241 len = m_length(m0, NULL);
1242 m0->m_pkthdr.len = len;
1247 m_length(struct mbuf *m0, struct mbuf **last)
1253 for (m = m0; m != NULL; m = m->m_next) {
1255 if (m->m_next == NULL)
1264 * Defragment a mbuf chain, returning the shortest possible
1265 * chain of mbufs and clusters. If allocation fails and
1266 * this cannot be completed, NULL will be returned, but
1267 * the passed in chain will be unchanged. Upon success,
1268 * the original chain will be freed, and the new chain
1271 * If a non-packet header is passed in, the original
1272 * mbuf (chain?) will be returned unharmed.
1275 m_defrag(struct mbuf *m0, int how)
1277 struct mbuf *m_new = NULL, *m_final = NULL;
1278 int progress = 0, length;
1280 MBUF_CHECKSLEEP(how);
1281 if (!(m0->m_flags & M_PKTHDR))
1284 m_fixhdr(m0); /* Needed sanity check */
1286 #ifdef MBUF_STRESS_TEST
1287 if (m_defragrandomfailures) {
1288 int temp = arc4random() & 0xff;
1294 if (m0->m_pkthdr.len > MHLEN)
1295 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1297 m_final = m_gethdr(how, MT_DATA);
1299 if (m_final == NULL)
1302 if (m_dup_pkthdr(m_final, m0, how) == 0)
1307 while (progress < m0->m_pkthdr.len) {
1308 length = m0->m_pkthdr.len - progress;
1309 if (length > MCLBYTES)
1312 if (m_new == NULL) {
1314 m_new = m_getcl(how, MT_DATA, 0);
1316 m_new = m_get(how, MT_DATA);
1321 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1323 m_new->m_len = length;
1324 if (m_new != m_final)
1325 m_cat(m_final, m_new);
1328 #ifdef MBUF_STRESS_TEST
1329 if (m0->m_next == NULL)
1334 #ifdef MBUF_STRESS_TEST
1336 m_defragbytes += m0->m_pkthdr.len;
1340 #ifdef MBUF_STRESS_TEST
1349 * Defragment an mbuf chain, returning at most maxfrags separate
1350 * mbufs+clusters. If this is not possible NULL is returned and
1351 * the original mbuf chain is left in its present (potentially
1352 * modified) state. We use two techniques: collapsing consecutive
1353 * mbufs and replacing consecutive mbufs by a cluster.
1355 * NB: this should really be named m_defrag but that name is taken
1358 m_collapse(struct mbuf *m0, int how, int maxfrags)
1360 struct mbuf *m, *n, *n2, **prev;
1364 * Calculate the current number of frags.
1367 for (m = m0; m != NULL; m = m->m_next)
1370 * First, try to collapse mbufs. Note that we always collapse
1371 * towards the front so we don't need to deal with moving the
1372 * pkthdr. This may be suboptimal if the first mbuf has much
1373 * less data than the following.
1381 if (M_WRITABLE(m) &&
1382 n->m_len < M_TRAILINGSPACE(m)) {
1383 bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1385 m->m_len += n->m_len;
1386 m->m_next = n->m_next;
1388 if (--curfrags <= maxfrags)
1393 KASSERT(maxfrags > 1,
1394 ("maxfrags %u, but normal collapse failed", maxfrags));
1396 * Collapse consecutive mbufs to a cluster.
1398 prev = &m0->m_next; /* NB: not the first mbuf */
1399 while ((n = *prev) != NULL) {
1400 if ((n2 = n->m_next) != NULL &&
1401 n->m_len + n2->m_len < MCLBYTES) {
1402 m = m_getcl(how, MT_DATA, 0);
1405 bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1406 bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1408 m->m_len = n->m_len + n2->m_len;
1409 m->m_next = n2->m_next;
1413 if (--curfrags <= maxfrags) /* +1 cl -2 mbufs */
1416 * Still not there, try the normal collapse
1417 * again before we allocate another cluster.
1424 * No place where we can collapse to a cluster; punt.
1425 * This can occur if, for example, you request 2 frags
1426 * but the packet requires that both be clusters (we
1427 * never reallocate the first mbuf to avoid moving the
1434 #ifdef MBUF_STRESS_TEST
1437 * Fragment an mbuf chain. There's no reason you'd ever want to do
1438 * this in normal usage, but it's great for stress testing various
1441 * If fragmentation is not possible, the original chain will be
1444 * Possible length values:
1445 * 0 no fragmentation will occur
1446 * > 0 each fragment will be of the specified length
1447 * -1 each fragment will be the same random value in length
1448 * -2 each fragment's length will be entirely random
1449 * (Random values range from 1 to 256)
1452 m_fragment(struct mbuf *m0, int how, int length)
1454 struct mbuf *m_first, *m_last;
1455 int divisor = 255, progress = 0, fraglen;
1457 if (!(m0->m_flags & M_PKTHDR))
1460 if (length == 0 || length < -2)
1462 if (length > MCLBYTES)
1464 if (length < 0 && divisor > MCLBYTES)
1467 length = 1 + (arc4random() % divisor);
1471 m_fixhdr(m0); /* Needed sanity check */
1473 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1474 if (m_first == NULL)
1477 if (m_dup_pkthdr(m_first, m0, how) == 0)
1482 while (progress < m0->m_pkthdr.len) {
1484 fraglen = 1 + (arc4random() % divisor);
1485 if (fraglen > m0->m_pkthdr.len - progress)
1486 fraglen = m0->m_pkthdr.len - progress;
1488 if (progress != 0) {
1489 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1493 m_last->m_next = m_new;
1497 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1498 progress += fraglen;
1499 m_last->m_len = fraglen;
1507 /* Return the original chain on failure */
1514 * Copy the contents of uio into a properly sized mbuf chain.
1517 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1519 struct mbuf *m, *mb;
1525 * len can be zero or an arbitrary large value bound by
1526 * the total data supplied by the uio.
1529 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1531 total = uio->uio_resid;
1534 * The smallest unit returned by m_getm2() is a single mbuf
1535 * with pkthdr. We can't align past it.
1541 * Give us the full allocation or nothing.
1542 * If len is zero return the smallest empty mbuf.
1544 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1549 /* Fill all mbufs with uio data and update header information. */
1550 for (mb = m; mb != NULL; mb = mb->m_next) {
1551 length = min(M_TRAILINGSPACE(mb), total - progress);
1553 error = uiomove(mtod(mb, void *), length, uio);
1561 if (flags & M_PKTHDR)
1562 m->m_pkthdr.len += length;
1564 KASSERT(progress == total, ("%s: progress != total", __func__));
1570 * Copy an mbuf chain into a uio limited by len if set.
1573 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
1575 int error, length, total;
1579 total = min(uio->uio_resid, len);
1581 total = uio->uio_resid;
1583 /* Fill the uio with data from the mbufs. */
1584 for (; m != NULL; m = m->m_next) {
1585 length = min(m->m_len, total - progress);
1587 error = uiomove(mtod(m, void *), length, uio);
1598 * Create a writable copy of the mbuf chain. While doing this
1599 * we compact the chain with a goal of producing a chain with
1600 * at most two mbufs. The second mbuf in this chain is likely
1601 * to be a cluster. The primary purpose of this work is to create
1602 * a writable packet for encryption, compression, etc. The
1603 * secondary goal is to linearize the data so the data can be
1604 * passed to crypto hardware in the most efficient manner possible.
1607 m_unshare(struct mbuf *m0, int how)
1609 struct mbuf *m, *mprev;
1610 struct mbuf *n, *mfirst, *mlast;
1614 for (m = m0; m != NULL; m = mprev->m_next) {
1616 * Regular mbufs are ignored unless there's a cluster
1617 * in front of it that we can use to coalesce. We do
1618 * the latter mainly so later clusters can be coalesced
1619 * also w/o having to handle them specially (i.e. convert
1620 * mbuf+cluster -> cluster). This optimization is heavily
1621 * influenced by the assumption that we're running over
1622 * Ethernet where MCLBYTES is large enough that the max
1623 * packet size will permit lots of coalescing into a
1624 * single cluster. This in turn permits efficient
1625 * crypto operations, especially when using hardware.
1627 if ((m->m_flags & M_EXT) == 0) {
1628 if (mprev && (mprev->m_flags & M_EXT) &&
1629 m->m_len <= M_TRAILINGSPACE(mprev)) {
1630 /* XXX: this ignores mbuf types */
1631 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1632 mtod(m, caddr_t), m->m_len);
1633 mprev->m_len += m->m_len;
1634 mprev->m_next = m->m_next; /* unlink from chain */
1635 m_free(m); /* reclaim mbuf */
1642 * Writable mbufs are left alone (for now).
1644 if (M_WRITABLE(m)) {
1650 * Not writable, replace with a copy or coalesce with
1651 * the previous mbuf if possible (since we have to copy
1652 * it anyway, we try to reduce the number of mbufs and
1653 * clusters so that future work is easier).
1655 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1656 /* NB: we only coalesce into a cluster or larger */
1657 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1658 m->m_len <= M_TRAILINGSPACE(mprev)) {
1659 /* XXX: this ignores mbuf types */
1660 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1661 mtod(m, caddr_t), m->m_len);
1662 mprev->m_len += m->m_len;
1663 mprev->m_next = m->m_next; /* unlink from chain */
1664 m_free(m); /* reclaim mbuf */
1669 * Allocate new space to hold the copy and copy the data.
1670 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1671 * splitting them into clusters. We could just malloc a
1672 * buffer and make it external but too many device drivers
1673 * don't know how to break up the non-contiguous memory when
1676 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
1681 if (m->m_flags & M_PKTHDR) {
1682 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
1684 m_move_pkthdr(n, m);
1691 int cc = min(len, MCLBYTES);
1692 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1698 newipsecstat.ips_clcopied++;
1706 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
1713 n->m_next = m->m_next;
1715 m0 = mfirst; /* new head of chain */
1717 mprev->m_next = mfirst; /* replace old mbuf */
1718 m_free(m); /* release old mbuf */
1724 #ifdef MBUF_PROFILING
1726 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
1727 struct mbufprofile {
1728 uintmax_t wasted[MP_BUCKETS];
1729 uintmax_t used[MP_BUCKETS];
1730 uintmax_t segments[MP_BUCKETS];
1733 #define MP_MAXDIGITS 21 /* strlen("16,000,000,000,000,000,000") == 21 */
1734 #define MP_NUMLINES 6
1735 #define MP_NUMSPERLINE 16
1736 #define MP_EXTRABYTES 64 /* > strlen("used:\nwasted:\nsegments:\n") */
1737 /* work out max space needed and add a bit of spare space too */
1738 #define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
1739 #define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
1741 char mbprofbuf[MP_BUFSIZE];
1744 m_profile(struct mbuf *m)
1753 if (m->m_flags & M_EXT) {
1754 wasted += MHLEN - sizeof(m->m_ext) +
1755 m->m_ext.ext_size - m->m_len;
1757 if (m->m_flags & M_PKTHDR)
1758 wasted += MHLEN - m->m_len;
1760 wasted += MLEN - m->m_len;
1764 /* be paranoid.. it helps */
1765 if (segments > MP_BUCKETS - 1)
1766 segments = MP_BUCKETS - 1;
1769 if (wasted > 100000)
1771 /* store in the appropriate bucket */
1772 /* don't bother locking. if it's slightly off, so what? */
1773 mbprof.segments[segments]++;
1774 mbprof.used[fls(used)]++;
1775 mbprof.wasted[fls(wasted)]++;
1779 mbprof_textify(void)
1785 p = &mbprof.wasted[0];
1787 offset = snprintf(c, MP_MAXLINE + 10,
1789 "%ju %ju %ju %ju %ju %ju %ju %ju "
1790 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1791 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1792 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1794 p = &mbprof.wasted[16];
1796 offset = snprintf(c, MP_MAXLINE,
1797 "%ju %ju %ju %ju %ju %ju %ju %ju "
1798 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1799 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1800 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1802 p = &mbprof.used[0];
1804 offset = snprintf(c, MP_MAXLINE + 10,
1806 "%ju %ju %ju %ju %ju %ju %ju %ju "
1807 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1808 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1809 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1811 p = &mbprof.used[16];
1813 offset = snprintf(c, MP_MAXLINE,
1814 "%ju %ju %ju %ju %ju %ju %ju %ju "
1815 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1816 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1817 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1819 p = &mbprof.segments[0];
1821 offset = snprintf(c, MP_MAXLINE + 10,
1823 "%ju %ju %ju %ju %ju %ju %ju %ju "
1824 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1825 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1826 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1828 p = &mbprof.segments[16];
1830 offset = snprintf(c, MP_MAXLINE,
1831 "%ju %ju %ju %ju %ju %ju %ju %ju "
1832 "%ju %ju %ju %ju %ju %ju %ju %jju",
1833 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1834 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1839 mbprof_handler(SYSCTL_HANDLER_ARGS)
1844 error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
1849 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
1854 error = sysctl_handle_int(oidp, &clear, 0, req);
1855 if (error || !req->newptr)
1859 bzero(&mbprof, sizeof(mbprof));
1866 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile, CTLTYPE_STRING|CTLFLAG_RD,
1867 NULL, 0, mbprof_handler, "A", "mbuf profiling statistics");
1869 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr, CTLTYPE_INT|CTLFLAG_RW,
1870 NULL, 0, mbprof_clr_handler, "I", "clear mbuf profiling statistics");