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$");
35 #include "opt_param.h"
36 #include "opt_mbuf_stress_test.h"
37 #include "opt_mbuf_profiling.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 * Ensure the correct size of various mbuf parameters. It could be off due
91 * to compiler-induced padding and alignment artifacts.
93 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
94 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
97 * mbuf data storage should be 64-bit aligned regardless of architectural
98 * pointer size; check this is the case with and without a packet header.
100 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
101 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
104 * While the specific values here don't matter too much (i.e., +/- a few
105 * words), we do want to ensure that changes to these values are carefully
106 * reasoned about and properly documented. This is especially the case as
107 * network-protocol and device-driver modules encode these layouts, and must
108 * be recompiled if the structures change. Check these values at compile time
109 * against the ones documented in comments in mbuf.h.
111 * NB: Possibly they should be documented there via #define's and not just
114 #if defined(__LP64__)
115 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
116 CTASSERT(sizeof(struct pkthdr) == 56);
117 CTASSERT(sizeof(struct m_ext) == 48);
119 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
120 CTASSERT(sizeof(struct pkthdr) == 48);
121 CTASSERT(sizeof(struct m_ext) == 28);
125 * Assert that the queue(3) macros produce code of the same size as an old
126 * plain pointer does.
129 static struct mbuf m_assertbuf;
130 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
131 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
132 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
133 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
137 * Attach the cluster from *m to *n, set up m_ext in *n
138 * and bump the refcount of the cluster.
141 mb_dupcl(struct mbuf *n, struct mbuf *m)
143 volatile u_int *refcnt;
145 KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
146 KASSERT(!(n->m_flags & M_EXT), ("%s: M_EXT set on %p", __func__, n));
150 n->m_flags |= m->m_flags & M_RDONLY;
152 /* See if this is the mbuf that holds the embedded refcount. */
153 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
154 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
155 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
157 KASSERT(m->m_ext.ext_cnt != NULL,
158 ("%s: no refcounting pointer on %p", __func__, m));
159 refcnt = m->m_ext.ext_cnt;
165 atomic_add_int(refcnt, 1);
169 m_demote_pkthdr(struct mbuf *m)
174 m_tag_delete_chain(m, NULL);
175 m->m_flags &= ~M_PKTHDR;
176 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
180 * Clean up mbuf (chain) from any tags and packet headers.
181 * If "all" is set then the first mbuf in the chain will be
185 m_demote(struct mbuf *m0, int all, int flags)
189 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
190 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
192 if (m->m_flags & M_PKTHDR)
194 m->m_flags = m->m_flags & (M_EXT | M_RDONLY | M_NOFREE | flags);
199 * Sanity checks on mbuf (chain) for use in KASSERT() and general
201 * Returns 0 or panics when bad and 1 on all tests passed.
202 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
206 m_sanity(struct mbuf *m0, int sanitize)
213 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
215 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
218 for (m = m0; m != NULL; m = m->m_next) {
220 * Basic pointer checks. If any of these fails then some
221 * unrelated kernel memory before or after us is trashed.
222 * No way to recover from that.
226 if ((caddr_t)m->m_data < a)
227 M_SANITY_ACTION("m_data outside mbuf data range left");
228 if ((caddr_t)m->m_data > b)
229 M_SANITY_ACTION("m_data outside mbuf data range right");
230 if ((caddr_t)m->m_data + m->m_len > b)
231 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
233 /* m->m_nextpkt may only be set on first mbuf in chain. */
234 if (m != m0 && m->m_nextpkt != NULL) {
236 m_freem(m->m_nextpkt);
237 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
239 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
242 /* packet length (not mbuf length!) calculation */
243 if (m0->m_flags & M_PKTHDR)
246 /* m_tags may only be attached to first mbuf in chain. */
247 if (m != m0 && m->m_flags & M_PKTHDR &&
248 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
250 m_tag_delete_chain(m, NULL);
251 /* put in 0xDEADC0DE perhaps? */
253 M_SANITY_ACTION("m_tags on in-chain mbuf");
256 /* M_PKTHDR may only be set on first mbuf in chain */
257 if (m != m0 && m->m_flags & M_PKTHDR) {
259 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
260 m->m_flags &= ~M_PKTHDR;
261 /* put in 0xDEADCODE and leave hdr flag in */
263 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
267 if (pktlen && pktlen != m->m_pkthdr.len) {
271 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
275 #undef M_SANITY_ACTION
279 * Non-inlined part of m_init().
282 m_pkthdr_init(struct mbuf *m, int how)
287 m->m_data = m->m_pktdat;
288 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
290 /* If the label init fails, fail the alloc */
291 error = mac_mbuf_init(m, how);
300 * "Move" mbuf pkthdr from "from" to "to".
301 * "from" must have M_PKTHDR set, and "to" must be empty.
304 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
308 /* see below for why these are not enabled */
310 /* Note: with MAC, this may not be a good assertion. */
311 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
312 ("m_move_pkthdr: to has tags"));
316 * XXXMAC: It could be this should also occur for non-MAC?
318 if (to->m_flags & M_PKTHDR)
319 m_tag_delete_chain(to, NULL);
321 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
322 if ((to->m_flags & M_EXT) == 0)
323 to->m_data = to->m_pktdat;
324 to->m_pkthdr = from->m_pkthdr; /* especially tags */
325 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
326 from->m_flags &= ~M_PKTHDR;
330 * Duplicate "from"'s mbuf pkthdr in "to".
331 * "from" must have M_PKTHDR set, and "to" must be empty.
332 * In particular, this does a deep copy of the packet tags.
335 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
340 * The mbuf allocator only initializes the pkthdr
341 * when the mbuf is allocated with m_gethdr(). Many users
342 * (e.g. m_copy*, m_prepend) use m_get() and then
343 * smash the pkthdr as needed causing these
344 * assertions to trip. For now just disable them.
347 /* Note: with MAC, this may not be a good assertion. */
348 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
350 MBUF_CHECKSLEEP(how);
352 if (to->m_flags & M_PKTHDR)
353 m_tag_delete_chain(to, NULL);
355 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
356 if ((to->m_flags & M_EXT) == 0)
357 to->m_data = to->m_pktdat;
358 to->m_pkthdr = from->m_pkthdr;
359 SLIST_INIT(&to->m_pkthdr.tags);
360 return (m_tag_copy_chain(to, from, how));
364 * Lesser-used path for M_PREPEND:
365 * allocate new mbuf to prepend to chain,
369 m_prepend(struct mbuf *m, int len, int how)
373 if (m->m_flags & M_PKTHDR)
374 mn = m_gethdr(how, m->m_type);
376 mn = m_get(how, m->m_type);
381 if (m->m_flags & M_PKTHDR)
382 m_move_pkthdr(mn, m);
392 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
393 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
394 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
395 * Note that the copy is read-only, because clusters are not copied,
396 * only their reference counts are incremented.
399 m_copym(struct mbuf *m, int off0, int len, int wait)
401 struct mbuf *n, **np;
406 KASSERT(off >= 0, ("m_copym, negative off %d", off));
407 KASSERT(len >= 0, ("m_copym, negative len %d", len));
408 MBUF_CHECKSLEEP(wait);
409 if (off == 0 && m->m_flags & M_PKTHDR)
412 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
422 KASSERT(len == M_COPYALL,
423 ("m_copym, length > size of mbuf chain"));
427 n = m_gethdr(wait, m->m_type);
429 n = m_get(wait, m->m_type);
434 if (!m_dup_pkthdr(n, m, wait))
436 if (len == M_COPYALL)
437 n->m_pkthdr.len -= off0;
439 n->m_pkthdr.len = len;
442 n->m_len = min(len, m->m_len - off);
443 if (m->m_flags & M_EXT) {
444 n->m_data = m->m_data + off;
447 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
449 if (len != M_COPYALL)
463 * Copy an entire packet, including header (which must be present).
464 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
465 * Note that the copy is read-only, because clusters are not copied,
466 * only their reference counts are incremented.
467 * Preserve alignment of the first mbuf so if the creator has left
468 * some room at the beginning (e.g. for inserting protocol headers)
469 * the copies still have the room available.
472 m_copypacket(struct mbuf *m, int how)
474 struct mbuf *top, *n, *o;
476 MBUF_CHECKSLEEP(how);
477 n = m_get(how, m->m_type);
482 if (!m_dup_pkthdr(n, m, how))
485 if (m->m_flags & M_EXT) {
486 n->m_data = m->m_data;
489 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
490 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
495 o = m_get(how, m->m_type);
503 if (m->m_flags & M_EXT) {
504 n->m_data = m->m_data;
507 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
519 * Copy data from an mbuf chain starting "off" bytes from the beginning,
520 * continuing for "len" bytes, into the indicated buffer.
523 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
527 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
528 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
530 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
537 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
538 count = min(m->m_len - off, len);
539 bcopy(mtod(m, caddr_t) + off, cp, count);
548 * Copy a packet header mbuf chain into a completely new chain, including
549 * copying any mbuf clusters. Use this instead of m_copypacket() when
550 * you need a writable copy of an mbuf chain.
553 m_dup(const struct mbuf *m, int how)
555 struct mbuf **p, *top = NULL;
556 int remain, moff, nsize;
558 MBUF_CHECKSLEEP(how);
564 /* While there's more data, get a new mbuf, tack it on, and fill it */
565 remain = m->m_pkthdr.len;
568 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
571 /* Get the next new mbuf */
572 if (remain >= MINCLSIZE) {
573 n = m_getcl(how, m->m_type, 0);
576 n = m_get(how, m->m_type);
582 if (top == NULL) { /* First one, must be PKTHDR */
583 if (!m_dup_pkthdr(n, m, how)) {
587 if ((n->m_flags & M_EXT) == 0)
589 n->m_flags &= ~M_RDONLY;
593 /* Link it into the new chain */
597 /* Copy data from original mbuf(s) into new mbuf */
598 while (n->m_len < nsize && m != NULL) {
599 int chunk = min(nsize - n->m_len, m->m_len - moff);
601 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
605 if (moff == m->m_len) {
611 /* Check correct total mbuf length */
612 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
613 ("%s: bogus m_pkthdr.len", __func__));
623 * Concatenate mbuf chain n to m.
624 * Both chains must be of the same type (e.g. MT_DATA).
625 * Any m_pkthdr is not updated.
628 m_cat(struct mbuf *m, struct mbuf *n)
633 if (!M_WRITABLE(m) ||
634 M_TRAILINGSPACE(m) < n->m_len) {
635 /* just join the two chains */
639 /* splat the data from one into the other */
640 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
642 m->m_len += n->m_len;
648 * Concatenate two pkthdr mbuf chains.
651 m_catpkt(struct mbuf *m, struct mbuf *n)
657 m->m_pkthdr.len += n->m_pkthdr.len;
664 m_adj(struct mbuf *mp, int req_len)
670 if ((m = mp) == NULL)
676 while (m != NULL && len > 0) {
677 if (m->m_len <= len) {
687 if (mp->m_flags & M_PKTHDR)
688 mp->m_pkthdr.len -= (req_len - len);
691 * Trim from tail. Scan the mbuf chain,
692 * calculating its length and finding the last mbuf.
693 * If the adjustment only affects this mbuf, then just
694 * adjust and return. Otherwise, rescan and truncate
695 * after the remaining size.
701 if (m->m_next == (struct mbuf *)0)
705 if (m->m_len >= len) {
707 if (mp->m_flags & M_PKTHDR)
708 mp->m_pkthdr.len -= len;
715 * Correct length for chain is "count".
716 * Find the mbuf with last data, adjust its length,
717 * and toss data from remaining mbufs on chain.
720 if (m->m_flags & M_PKTHDR)
721 m->m_pkthdr.len = count;
722 for (; m; m = m->m_next) {
723 if (m->m_len >= count) {
725 if (m->m_next != NULL) {
737 * Rearange an mbuf chain so that len bytes are contiguous
738 * and in the data area of an mbuf (so that mtod will work
739 * for a structure of size len). Returns the resulting
740 * mbuf chain on success, frees it and returns null on failure.
741 * If there is room, it will add up to max_protohdr-len extra bytes to the
742 * contiguous region in an attempt to avoid being called next time.
745 m_pullup(struct mbuf *n, int len)
752 * If first mbuf has no cluster, and has room for len bytes
753 * without shifting current data, pullup into it,
754 * otherwise allocate a new mbuf to prepend to the chain.
756 if ((n->m_flags & M_EXT) == 0 &&
757 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
766 m = m_get(M_NOWAIT, n->m_type);
769 if (n->m_flags & M_PKTHDR)
772 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
774 count = min(min(max(len, max_protohdr), space), n->m_len);
775 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
785 } while (len > 0 && n);
798 * Like m_pullup(), except a new mbuf is always allocated, and we allow
799 * the amount of empty space before the data in the new mbuf to be specified
800 * (in the event that the caller expects to prepend later).
803 m_copyup(struct mbuf *n, int len, int dstoff)
808 if (len > (MHLEN - dstoff))
810 m = m_get(M_NOWAIT, n->m_type);
813 if (n->m_flags & M_PKTHDR)
816 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
818 count = min(min(max(len, max_protohdr), space), n->m_len);
819 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
829 } while (len > 0 && n);
842 * Partition an mbuf chain in two pieces, returning the tail --
843 * all but the first len0 bytes. In case of failure, it returns NULL and
844 * attempts to restore the chain to its original state.
846 * Note that the resulting mbufs might be read-only, because the new
847 * mbuf can end up sharing an mbuf cluster with the original mbuf if
848 * the "breaking point" happens to lie within a cluster mbuf. Use the
849 * M_WRITABLE() macro to check for this case.
852 m_split(struct mbuf *m0, int len0, int wait)
855 u_int len = len0, remain;
857 MBUF_CHECKSLEEP(wait);
858 for (m = m0; m && len > m->m_len; m = m->m_next)
862 remain = m->m_len - len;
863 if (m0->m_flags & M_PKTHDR && remain == 0) {
864 n = m_gethdr(wait, m0->m_type);
867 n->m_next = m->m_next;
869 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
870 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
871 m0->m_pkthdr.len = len0;
873 } else if (m0->m_flags & M_PKTHDR) {
874 n = m_gethdr(wait, m0->m_type);
877 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
878 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
879 m0->m_pkthdr.len = len0;
880 if (m->m_flags & M_EXT)
882 if (remain > MHLEN) {
883 /* m can't be the lead packet */
885 n->m_next = m_split(m, len, wait);
886 if (n->m_next == NULL) {
895 } else if (remain == 0) {
900 n = m_get(wait, m->m_type);
906 if (m->m_flags & M_EXT) {
907 n->m_data = m->m_data + len;
910 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
914 n->m_next = m->m_next;
919 * Routine to copy from device local memory into mbufs.
920 * Note that `off' argument is offset into first mbuf of target chain from
921 * which to begin copying the data to.
924 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
925 void (*copy)(char *from, caddr_t to, u_int len))
928 struct mbuf *top = NULL, **mp = ⊤
931 if (off < 0 || off > MHLEN)
935 if (top == NULL) { /* First one, must be PKTHDR */
936 if (totlen + off >= MINCLSIZE) {
937 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
940 m = m_gethdr(M_NOWAIT, MT_DATA);
943 /* Place initial small packet/header at end of mbuf */
944 if (m && totlen + off + max_linkhdr <= MLEN) {
945 m->m_data += max_linkhdr;
951 m->m_pkthdr.rcvif = ifp;
952 m->m_pkthdr.len = totlen;
954 if (totlen + off >= MINCLSIZE) {
955 m = m_getcl(M_NOWAIT, MT_DATA, 0);
958 m = m_get(M_NOWAIT, MT_DATA);
971 m->m_len = len = min(totlen, len);
973 copy(buf, mtod(m, caddr_t), (u_int)len);
975 bcopy(buf, mtod(m, caddr_t), (u_int)len);
985 * Copy data from a buffer back into the indicated mbuf chain,
986 * starting "off" bytes from the beginning, extending the mbuf
987 * chain if necessary.
990 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
993 struct mbuf *m = m0, *n;
998 while (off > (mlen = m->m_len)) {
1001 if (m->m_next == NULL) {
1002 n = m_get(M_NOWAIT, m->m_type);
1005 bzero(mtod(n, caddr_t), MLEN);
1006 n->m_len = min(MLEN, len + off);
1012 if (m->m_next == NULL && (len > m->m_len - off)) {
1013 m->m_len += min(len - (m->m_len - off),
1014 M_TRAILINGSPACE(m));
1016 mlen = min (m->m_len - off, len);
1017 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1025 if (m->m_next == NULL) {
1026 n = m_get(M_NOWAIT, m->m_type);
1029 n->m_len = min(MLEN, len);
1034 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1035 m->m_pkthdr.len = totlen;
1039 * Append the specified data to the indicated mbuf chain,
1040 * Extend the mbuf chain if the new data does not fit in
1043 * Return 1 if able to complete the job; otherwise 0.
1046 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1049 int remainder, space;
1051 for (m = m0; m->m_next != NULL; m = m->m_next)
1054 space = M_TRAILINGSPACE(m);
1057 * Copy into available space.
1059 if (space > remainder)
1061 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1063 cp += space, remainder -= space;
1065 while (remainder > 0) {
1067 * Allocate a new mbuf; could check space
1068 * and allocate a cluster instead.
1070 n = m_get(M_NOWAIT, m->m_type);
1073 n->m_len = min(MLEN, remainder);
1074 bcopy(cp, mtod(n, caddr_t), n->m_len);
1075 cp += n->m_len, remainder -= n->m_len;
1079 if (m0->m_flags & M_PKTHDR)
1080 m0->m_pkthdr.len += len - remainder;
1081 return (remainder == 0);
1085 * Apply function f to the data in an mbuf chain starting "off" bytes from
1086 * the beginning, continuing for "len" bytes.
1089 m_apply(struct mbuf *m, int off, int len,
1090 int (*f)(void *, void *, u_int), void *arg)
1095 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1096 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1098 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1105 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1106 count = min(m->m_len - off, len);
1107 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1118 * Return a pointer to mbuf/offset of location in mbuf chain.
1121 m_getptr(struct mbuf *m, int loc, int *off)
1125 /* Normal end of search. */
1126 if (m->m_len > loc) {
1131 if (m->m_next == NULL) {
1133 /* Point at the end of valid data. */
1146 m_print(const struct mbuf *m, int maxlen)
1150 const struct mbuf *m2;
1153 printf("mbuf: %p\n", m);
1157 if (m->m_flags & M_PKTHDR)
1158 len = m->m_pkthdr.len;
1162 while (m2 != NULL && (len == -1 || len)) {
1164 if (maxlen != -1 && pdata > maxlen)
1166 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1167 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1168 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1169 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1171 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1177 printf("%d bytes unaccounted for.\n", len);
1182 m_fixhdr(struct mbuf *m0)
1186 len = m_length(m0, NULL);
1187 m0->m_pkthdr.len = len;
1192 m_length(struct mbuf *m0, struct mbuf **last)
1198 for (m = m0; m != NULL; m = m->m_next) {
1200 if (m->m_next == NULL)
1209 * Defragment a mbuf chain, returning the shortest possible
1210 * chain of mbufs and clusters. If allocation fails and
1211 * this cannot be completed, NULL will be returned, but
1212 * the passed in chain will be unchanged. Upon success,
1213 * the original chain will be freed, and the new chain
1216 * If a non-packet header is passed in, the original
1217 * mbuf (chain?) will be returned unharmed.
1220 m_defrag(struct mbuf *m0, int how)
1222 struct mbuf *m_new = NULL, *m_final = NULL;
1223 int progress = 0, length;
1225 MBUF_CHECKSLEEP(how);
1226 if (!(m0->m_flags & M_PKTHDR))
1229 m_fixhdr(m0); /* Needed sanity check */
1231 #ifdef MBUF_STRESS_TEST
1232 if (m_defragrandomfailures) {
1233 int temp = arc4random() & 0xff;
1239 if (m0->m_pkthdr.len > MHLEN)
1240 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1242 m_final = m_gethdr(how, MT_DATA);
1244 if (m_final == NULL)
1247 if (m_dup_pkthdr(m_final, m0, how) == 0)
1252 while (progress < m0->m_pkthdr.len) {
1253 length = m0->m_pkthdr.len - progress;
1254 if (length > MCLBYTES)
1257 if (m_new == NULL) {
1259 m_new = m_getcl(how, MT_DATA, 0);
1261 m_new = m_get(how, MT_DATA);
1266 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1268 m_new->m_len = length;
1269 if (m_new != m_final)
1270 m_cat(m_final, m_new);
1273 #ifdef MBUF_STRESS_TEST
1274 if (m0->m_next == NULL)
1279 #ifdef MBUF_STRESS_TEST
1281 m_defragbytes += m0->m_pkthdr.len;
1285 #ifdef MBUF_STRESS_TEST
1294 * Defragment an mbuf chain, returning at most maxfrags separate
1295 * mbufs+clusters. If this is not possible NULL is returned and
1296 * the original mbuf chain is left in it's present (potentially
1297 * modified) state. We use two techniques: collapsing consecutive
1298 * mbufs and replacing consecutive mbufs by a cluster.
1300 * NB: this should really be named m_defrag but that name is taken
1303 m_collapse(struct mbuf *m0, int how, int maxfrags)
1305 struct mbuf *m, *n, *n2, **prev;
1309 * Calculate the current number of frags.
1312 for (m = m0; m != NULL; m = m->m_next)
1315 * First, try to collapse mbufs. Note that we always collapse
1316 * towards the front so we don't need to deal with moving the
1317 * pkthdr. This may be suboptimal if the first mbuf has much
1318 * less data than the following.
1326 if (M_WRITABLE(m) &&
1327 n->m_len < M_TRAILINGSPACE(m)) {
1328 bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1330 m->m_len += n->m_len;
1331 m->m_next = n->m_next;
1333 if (--curfrags <= maxfrags)
1338 KASSERT(maxfrags > 1,
1339 ("maxfrags %u, but normal collapse failed", maxfrags));
1341 * Collapse consecutive mbufs to a cluster.
1343 prev = &m0->m_next; /* NB: not the first mbuf */
1344 while ((n = *prev) != NULL) {
1345 if ((n2 = n->m_next) != NULL &&
1346 n->m_len + n2->m_len < MCLBYTES) {
1347 m = m_getcl(how, MT_DATA, 0);
1350 bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1351 bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1353 m->m_len = n->m_len + n2->m_len;
1354 m->m_next = n2->m_next;
1358 if (--curfrags <= maxfrags) /* +1 cl -2 mbufs */
1361 * Still not there, try the normal collapse
1362 * again before we allocate another cluster.
1369 * No place where we can collapse to a cluster; punt.
1370 * This can occur if, for example, you request 2 frags
1371 * but the packet requires that both be clusters (we
1372 * never reallocate the first mbuf to avoid moving the
1379 #ifdef MBUF_STRESS_TEST
1382 * Fragment an mbuf chain. There's no reason you'd ever want to do
1383 * this in normal usage, but it's great for stress testing various
1386 * If fragmentation is not possible, the original chain will be
1389 * Possible length values:
1390 * 0 no fragmentation will occur
1391 * > 0 each fragment will be of the specified length
1392 * -1 each fragment will be the same random value in length
1393 * -2 each fragment's length will be entirely random
1394 * (Random values range from 1 to 256)
1397 m_fragment(struct mbuf *m0, int how, int length)
1399 struct mbuf *m_new = NULL, *m_final = NULL;
1402 if (!(m0->m_flags & M_PKTHDR))
1405 if ((length == 0) || (length < -2))
1408 m_fixhdr(m0); /* Needed sanity check */
1410 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1412 if (m_final == NULL)
1415 if (m_dup_pkthdr(m_final, m0, how) == 0)
1421 length = 1 + (arc4random() & 255);
1423 while (progress < m0->m_pkthdr.len) {
1429 fraglen = 1 + (arc4random() & 255);
1430 if (fraglen > m0->m_pkthdr.len - progress)
1431 fraglen = m0->m_pkthdr.len - progress;
1433 if (fraglen > MCLBYTES)
1436 if (m_new == NULL) {
1437 m_new = m_getcl(how, MT_DATA, 0);
1442 m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1443 progress += fraglen;
1444 m_new->m_len = fraglen;
1445 if (m_new != m_final)
1446 m_cat(m_final, m_new);
1455 /* Return the original chain on failure */
1462 * Copy the contents of uio into a properly sized mbuf chain.
1465 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1467 struct mbuf *m, *mb;
1473 * len can be zero or an arbitrary large value bound by
1474 * the total data supplied by the uio.
1477 total = min(uio->uio_resid, len);
1479 total = uio->uio_resid;
1482 * The smallest unit returned by m_getm2() is a single mbuf
1483 * with pkthdr. We can't align past it.
1489 * Give us the full allocation or nothing.
1490 * If len is zero return the smallest empty mbuf.
1492 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1497 /* Fill all mbufs with uio data and update header information. */
1498 for (mb = m; mb != NULL; mb = mb->m_next) {
1499 length = min(M_TRAILINGSPACE(mb), total - progress);
1501 error = uiomove(mtod(mb, void *), length, uio);
1509 if (flags & M_PKTHDR)
1510 m->m_pkthdr.len += length;
1512 KASSERT(progress == total, ("%s: progress != total", __func__));
1518 * Copy an mbuf chain into a uio limited by len if set.
1521 m_mbuftouio(struct uio *uio, struct mbuf *m, int len)
1523 int error, length, total;
1527 total = min(uio->uio_resid, len);
1529 total = uio->uio_resid;
1531 /* Fill the uio with data from the mbufs. */
1532 for (; m != NULL; m = m->m_next) {
1533 length = min(m->m_len, total - progress);
1535 error = uiomove(mtod(m, void *), length, uio);
1546 * Create a writable copy of the mbuf chain. While doing this
1547 * we compact the chain with a goal of producing a chain with
1548 * at most two mbufs. The second mbuf in this chain is likely
1549 * to be a cluster. The primary purpose of this work is to create
1550 * a writable packet for encryption, compression, etc. The
1551 * secondary goal is to linearize the data so the data can be
1552 * passed to crypto hardware in the most efficient manner possible.
1555 m_unshare(struct mbuf *m0, int how)
1557 struct mbuf *m, *mprev;
1558 struct mbuf *n, *mfirst, *mlast;
1562 for (m = m0; m != NULL; m = mprev->m_next) {
1564 * Regular mbufs are ignored unless there's a cluster
1565 * in front of it that we can use to coalesce. We do
1566 * the latter mainly so later clusters can be coalesced
1567 * also w/o having to handle them specially (i.e. convert
1568 * mbuf+cluster -> cluster). This optimization is heavily
1569 * influenced by the assumption that we're running over
1570 * Ethernet where MCLBYTES is large enough that the max
1571 * packet size will permit lots of coalescing into a
1572 * single cluster. This in turn permits efficient
1573 * crypto operations, especially when using hardware.
1575 if ((m->m_flags & M_EXT) == 0) {
1576 if (mprev && (mprev->m_flags & M_EXT) &&
1577 m->m_len <= M_TRAILINGSPACE(mprev)) {
1578 /* XXX: this ignores mbuf types */
1579 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1580 mtod(m, caddr_t), m->m_len);
1581 mprev->m_len += m->m_len;
1582 mprev->m_next = m->m_next; /* unlink from chain */
1583 m_free(m); /* reclaim mbuf */
1585 newipsecstat.ips_mbcoalesced++;
1593 * Writable mbufs are left alone (for now).
1595 if (M_WRITABLE(m)) {
1601 * Not writable, replace with a copy or coalesce with
1602 * the previous mbuf if possible (since we have to copy
1603 * it anyway, we try to reduce the number of mbufs and
1604 * clusters so that future work is easier).
1606 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1607 /* NB: we only coalesce into a cluster or larger */
1608 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1609 m->m_len <= M_TRAILINGSPACE(mprev)) {
1610 /* XXX: this ignores mbuf types */
1611 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1612 mtod(m, caddr_t), m->m_len);
1613 mprev->m_len += m->m_len;
1614 mprev->m_next = m->m_next; /* unlink from chain */
1615 m_free(m); /* reclaim mbuf */
1617 newipsecstat.ips_clcoalesced++;
1623 * Allocate new space to hold the copy and copy the data.
1624 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1625 * splitting them into clusters. We could just malloc a
1626 * buffer and make it external but too many device drivers
1627 * don't know how to break up the non-contiguous memory when
1630 n = m_getcl(how, m->m_type, m->m_flags);
1635 if (m->m_flags & M_PKTHDR) {
1636 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
1638 m_move_pkthdr(n, m);
1645 int cc = min(len, MCLBYTES);
1646 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1652 newipsecstat.ips_clcopied++;
1660 n = m_getcl(how, m->m_type, m->m_flags);
1667 n->m_next = m->m_next;
1669 m0 = mfirst; /* new head of chain */
1671 mprev->m_next = mfirst; /* replace old mbuf */
1672 m_free(m); /* release old mbuf */
1678 #ifdef MBUF_PROFILING
1680 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
1681 struct mbufprofile {
1682 uintmax_t wasted[MP_BUCKETS];
1683 uintmax_t used[MP_BUCKETS];
1684 uintmax_t segments[MP_BUCKETS];
1687 #define MP_MAXDIGITS 21 /* strlen("16,000,000,000,000,000,000") == 21 */
1688 #define MP_NUMLINES 6
1689 #define MP_NUMSPERLINE 16
1690 #define MP_EXTRABYTES 64 /* > strlen("used:\nwasted:\nsegments:\n") */
1691 /* work out max space needed and add a bit of spare space too */
1692 #define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
1693 #define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
1695 char mbprofbuf[MP_BUFSIZE];
1698 m_profile(struct mbuf *m)
1707 if (m->m_flags & M_EXT) {
1708 wasted += MHLEN - sizeof(m->m_ext) +
1709 m->m_ext.ext_size - m->m_len;
1711 if (m->m_flags & M_PKTHDR)
1712 wasted += MHLEN - m->m_len;
1714 wasted += MLEN - m->m_len;
1718 /* be paranoid.. it helps */
1719 if (segments > MP_BUCKETS - 1)
1720 segments = MP_BUCKETS - 1;
1723 if (wasted > 100000)
1725 /* store in the appropriate bucket */
1726 /* don't bother locking. if it's slightly off, so what? */
1727 mbprof.segments[segments]++;
1728 mbprof.used[fls(used)]++;
1729 mbprof.wasted[fls(wasted)]++;
1733 mbprof_textify(void)
1739 p = &mbprof.wasted[0];
1741 offset = snprintf(c, MP_MAXLINE + 10,
1743 "%ju %ju %ju %ju %ju %ju %ju %ju "
1744 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1745 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1746 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1748 p = &mbprof.wasted[16];
1750 offset = snprintf(c, MP_MAXLINE,
1751 "%ju %ju %ju %ju %ju %ju %ju %ju "
1752 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1753 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1754 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1756 p = &mbprof.used[0];
1758 offset = snprintf(c, MP_MAXLINE + 10,
1760 "%ju %ju %ju %ju %ju %ju %ju %ju "
1761 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1762 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1763 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1765 p = &mbprof.used[16];
1767 offset = snprintf(c, MP_MAXLINE,
1768 "%ju %ju %ju %ju %ju %ju %ju %ju "
1769 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1770 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1771 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1773 p = &mbprof.segments[0];
1775 offset = snprintf(c, MP_MAXLINE + 10,
1777 "%ju %ju %ju %ju %ju %ju %ju %ju "
1778 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1779 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1780 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1782 p = &mbprof.segments[16];
1784 offset = snprintf(c, MP_MAXLINE,
1785 "%ju %ju %ju %ju %ju %ju %ju %ju "
1786 "%ju %ju %ju %ju %ju %ju %ju %jju",
1787 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1788 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1793 mbprof_handler(SYSCTL_HANDLER_ARGS)
1798 error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
1803 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
1808 error = sysctl_handle_int(oidp, &clear, 0, req);
1809 if (error || !req->newptr)
1813 bzero(&mbprof, sizeof(mbprof));
1820 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile, CTLTYPE_STRING|CTLFLAG_RD,
1821 NULL, 0, mbprof_handler, "A", "mbuf profiling statistics");
1823 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr, CTLTYPE_INT|CTLFLAG_RW,
1824 NULL, 0, mbprof_clr_handler, "I", "clear mbuf profiling statistics");