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 #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>
50 #include <sys/vmmeter.h>
54 #include <vm/vm_pageout.h>
55 #include <vm/vm_page.h>
57 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__init,
58 "struct mbuf *", "mbufinfo_t *",
59 "uint32_t", "uint32_t",
60 "uint16_t", "uint16_t",
61 "uint32_t", "uint32_t",
62 "uint32_t", "uint32_t");
64 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr_raw,
65 "uint32_t", "uint32_t",
66 "uint16_t", "uint16_t",
67 "struct mbuf *", "mbufinfo_t *");
69 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr,
70 "uint32_t", "uint32_t",
71 "uint16_t", "uint16_t",
72 "struct mbuf *", "mbufinfo_t *");
74 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get_raw,
75 "uint32_t", "uint32_t",
76 "uint16_t", "uint16_t",
77 "struct mbuf *", "mbufinfo_t *");
79 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
80 "uint32_t", "uint32_t",
81 "uint16_t", "uint16_t",
82 "struct mbuf *", "mbufinfo_t *");
84 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
85 "uint32_t", "uint32_t",
86 "uint16_t", "uint16_t",
87 "uint32_t", "uint32_t",
88 "struct mbuf *", "mbufinfo_t *");
90 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__getjcl,
91 "uint32_t", "uint32_t",
92 "uint16_t", "uint16_t",
93 "uint32_t", "uint32_t",
94 "uint32_t", "uint32_t",
95 "struct mbuf *", "mbufinfo_t *");
97 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
98 "struct mbuf *", "mbufinfo_t *",
99 "uint32_t", "uint32_t",
100 "uint32_t", "uint32_t");
102 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
103 "struct mbuf *", "mbufinfo_t *",
104 "uint32_t", "uint32_t",
105 "uint32_t", "uint32_t",
108 SDT_PROBE_DEFINE(sdt, , , m__cljset);
110 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
111 "struct mbuf *", "mbufinfo_t *");
113 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
114 "struct mbuf *", "mbufinfo_t *");
116 #include <security/mac/mac_framework.h>
119 * Provide minimum possible defaults for link and protocol header space,
120 * assuming IPv4 over Ethernet. Enabling IPv6, IEEE802.11 or some other
121 * protocol may grow these values.
123 u_int max_linkhdr = 16;
124 u_int max_protohdr = 40;
125 u_int max_hdr = 16 + 40;
126 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
127 &max_linkhdr, 16, "Size of largest link layer header");
128 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
129 &max_protohdr, 40, "Size of largest protocol layer header");
130 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
131 &max_hdr, 16 + 40, "Size of largest link plus protocol header");
137 max_hdr = max_linkhdr + max_protohdr;
138 MPASS(max_hdr <= MHLEN);
142 max_linkhdr_grow(u_int new)
145 if (new > max_linkhdr) {
152 max_protohdr_grow(u_int new)
155 if (new > max_protohdr) {
161 #ifdef MBUF_STRESS_TEST
166 int m_defragrandomfailures;
168 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
169 &m_defragpackets, 0, "");
170 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
171 &m_defragbytes, 0, "");
172 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
173 &m_defraguseless, 0, "");
174 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
175 &m_defragfailure, 0, "");
176 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
177 &m_defragrandomfailures, 0, "");
181 * Ensure the correct size of various mbuf parameters. It could be off due
182 * to compiler-induced padding and alignment artifacts.
184 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
185 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
188 * mbuf data storage should be 64-bit aligned regardless of architectural
189 * pointer size; check this is the case with and without a packet header.
191 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
192 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
195 * While the specific values here don't matter too much (i.e., +/- a few
196 * words), we do want to ensure that changes to these values are carefully
197 * reasoned about and properly documented. This is especially the case as
198 * network-protocol and device-driver modules encode these layouts, and must
199 * be recompiled if the structures change. Check these values at compile time
200 * against the ones documented in comments in mbuf.h.
202 * NB: Possibly they should be documented there via #define's and not just
205 #if defined(__LP64__)
206 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
207 CTASSERT(sizeof(struct pkthdr) == 64);
208 CTASSERT(sizeof(struct m_ext) == 160);
210 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
211 CTASSERT(sizeof(struct pkthdr) == 56);
212 #if defined(__powerpc__) && defined(BOOKE)
213 /* PowerPC booke has 64-bit physical pointers. */
214 CTASSERT(sizeof(struct m_ext) == 176);
216 CTASSERT(sizeof(struct m_ext) == 172);
221 * Assert that the queue(3) macros produce code of the same size as an old
222 * plain pointer does.
225 static struct mbuf __used m_assertbuf;
226 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
227 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
228 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
229 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
233 * Attach the cluster from *m to *n, set up m_ext in *n
234 * and bump the refcount of the cluster.
237 mb_dupcl(struct mbuf *n, struct mbuf *m)
239 volatile u_int *refcnt;
241 KASSERT(m->m_flags & (M_EXT|M_EXTPG),
242 ("%s: M_EXT|M_EXTPG not set on %p", __func__, m));
243 KASSERT(!(n->m_flags & (M_EXT|M_EXTPG)),
244 ("%s: M_EXT|M_EXTPG set on %p", __func__, n));
247 * Cache access optimization.
249 * o Regular M_EXT storage doesn't need full copy of m_ext, since
250 * the holder of the 'ext_count' is responsible to carry the free
251 * routine and its arguments.
252 * o M_EXTPG data is split between main part of mbuf and m_ext, the
253 * main part is copied in full, the m_ext part is similar to M_EXT.
254 * o EXT_EXTREF, where 'ext_cnt' doesn't point into mbuf at all, is
255 * special - it needs full copy of m_ext into each mbuf, since any
256 * copy could end up as the last to free.
258 if (m->m_flags & M_EXTPG) {
259 bcopy(&m->m_epg_startcopy, &n->m_epg_startcopy,
260 __rangeof(struct mbuf, m_epg_startcopy, m_epg_endcopy));
261 bcopy(&m->m_ext, &n->m_ext, m_epg_ext_copylen);
262 } else if (m->m_ext.ext_type == EXT_EXTREF)
263 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
265 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
267 n->m_flags |= m->m_flags & (M_RDONLY | M_EXT | M_EXTPG);
269 /* See if this is the mbuf that holds the embedded refcount. */
270 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
271 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
272 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
274 KASSERT(m->m_ext.ext_cnt != NULL,
275 ("%s: no refcounting pointer on %p", __func__, m));
276 refcnt = m->m_ext.ext_cnt;
282 atomic_add_int(refcnt, 1);
286 m_demote_pkthdr(struct mbuf *m)
290 M_ASSERT_NO_SND_TAG(m);
292 m_tag_delete_chain(m, NULL);
293 m->m_flags &= ~M_PKTHDR;
294 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
298 * Clean up mbuf (chain) from any tags and packet headers.
299 * If "all" is set then the first mbuf in the chain will be
303 m_demote(struct mbuf *m0, int all, int flags)
307 flags |= M_DEMOTEFLAGS;
309 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
310 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
312 if (m->m_flags & M_PKTHDR)
319 * Sanity checks on mbuf (chain) for use in KASSERT() and general
321 * Returns 0 or panics when bad and 1 on all tests passed.
322 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
326 m_sanity(struct mbuf *m0, int sanitize)
333 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
335 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
338 for (m = m0; m != NULL; m = m->m_next) {
340 * Basic pointer checks. If any of these fails then some
341 * unrelated kernel memory before or after us is trashed.
342 * No way to recover from that.
346 if ((caddr_t)m->m_data < a)
347 M_SANITY_ACTION("m_data outside mbuf data range left");
348 if ((caddr_t)m->m_data > b)
349 M_SANITY_ACTION("m_data outside mbuf data range right");
350 if ((caddr_t)m->m_data + m->m_len > b)
351 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
353 /* m->m_nextpkt may only be set on first mbuf in chain. */
354 if (m != m0 && m->m_nextpkt != NULL) {
356 m_freem(m->m_nextpkt);
357 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
359 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
362 /* packet length (not mbuf length!) calculation */
363 if (m0->m_flags & M_PKTHDR)
366 /* m_tags may only be attached to first mbuf in chain. */
367 if (m != m0 && m->m_flags & M_PKTHDR &&
368 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
370 m_tag_delete_chain(m, NULL);
371 /* put in 0xDEADC0DE perhaps? */
373 M_SANITY_ACTION("m_tags on in-chain mbuf");
376 /* M_PKTHDR may only be set on first mbuf in chain */
377 if (m != m0 && m->m_flags & M_PKTHDR) {
379 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
380 m->m_flags &= ~M_PKTHDR;
381 /* put in 0xDEADCODE and leave hdr flag in */
383 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
387 if (pktlen && pktlen != m->m_pkthdr.len) {
391 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
395 #undef M_SANITY_ACTION
399 * Non-inlined part of m_init().
402 m_pkthdr_init(struct mbuf *m, int how)
407 m->m_data = m->m_pktdat;
408 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
410 m->m_pkthdr.numa_domain = M_NODOM;
413 /* If the label init fails, fail the alloc */
414 error = mac_mbuf_init(m, how);
423 * "Move" mbuf pkthdr from "from" to "to".
424 * "from" must have M_PKTHDR set, and "to" must be empty.
427 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
431 /* see below for why these are not enabled */
433 /* Note: with MAC, this may not be a good assertion. */
434 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
435 ("m_move_pkthdr: to has tags"));
439 * XXXMAC: It could be this should also occur for non-MAC?
441 if (to->m_flags & M_PKTHDR)
442 m_tag_delete_chain(to, NULL);
444 to->m_flags = (from->m_flags & M_COPYFLAGS) |
445 (to->m_flags & (M_EXT | M_EXTPG));
446 if ((to->m_flags & M_EXT) == 0)
447 to->m_data = to->m_pktdat;
448 to->m_pkthdr = from->m_pkthdr; /* especially tags */
449 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
450 from->m_flags &= ~M_PKTHDR;
451 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG) {
452 from->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
453 from->m_pkthdr.snd_tag = NULL;
458 * Duplicate "from"'s mbuf pkthdr in "to".
459 * "from" must have M_PKTHDR set, and "to" must be empty.
460 * In particular, this does a deep copy of the packet tags.
463 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
468 * The mbuf allocator only initializes the pkthdr
469 * when the mbuf is allocated with m_gethdr(). Many users
470 * (e.g. m_copy*, m_prepend) use m_get() and then
471 * smash the pkthdr as needed causing these
472 * assertions to trip. For now just disable them.
475 /* Note: with MAC, this may not be a good assertion. */
476 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
478 MBUF_CHECKSLEEP(how);
480 if (to->m_flags & M_PKTHDR)
481 m_tag_delete_chain(to, NULL);
483 to->m_flags = (from->m_flags & M_COPYFLAGS) |
484 (to->m_flags & (M_EXT | M_EXTPG));
485 if ((to->m_flags & M_EXT) == 0)
486 to->m_data = to->m_pktdat;
487 to->m_pkthdr = from->m_pkthdr;
488 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG)
489 m_snd_tag_ref(from->m_pkthdr.snd_tag);
490 SLIST_INIT(&to->m_pkthdr.tags);
491 return (m_tag_copy_chain(to, from, how));
495 * Lesser-used path for M_PREPEND:
496 * allocate new mbuf to prepend to chain,
500 m_prepend(struct mbuf *m, int len, int how)
504 if (m->m_flags & M_PKTHDR)
505 mn = m_gethdr(how, m->m_type);
507 mn = m_get(how, m->m_type);
512 if (m->m_flags & M_PKTHDR)
513 m_move_pkthdr(mn, m);
523 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
524 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
525 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
526 * Note that the copy is read-only, because clusters are not copied,
527 * only their reference counts are incremented.
530 m_copym(struct mbuf *m, int off0, int len, int wait)
532 struct mbuf *n, **np;
537 KASSERT(off >= 0, ("m_copym, negative off %d", off));
538 KASSERT(len >= 0, ("m_copym, negative len %d", len));
539 MBUF_CHECKSLEEP(wait);
540 if (off == 0 && m->m_flags & M_PKTHDR)
543 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
553 KASSERT(len == M_COPYALL,
554 ("m_copym, length > size of mbuf chain"));
558 n = m_gethdr(wait, m->m_type);
560 n = m_get(wait, m->m_type);
565 if (!m_dup_pkthdr(n, m, wait))
567 if (len == M_COPYALL)
568 n->m_pkthdr.len -= off0;
570 n->m_pkthdr.len = len;
573 n->m_len = min(len, m->m_len - off);
574 if (m->m_flags & (M_EXT|M_EXTPG)) {
575 n->m_data = m->m_data + off;
578 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
580 if (len != M_COPYALL)
594 * Copy an entire packet, including header (which must be present).
595 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
596 * Note that the copy is read-only, because clusters are not copied,
597 * only their reference counts are incremented.
598 * Preserve alignment of the first mbuf so if the creator has left
599 * some room at the beginning (e.g. for inserting protocol headers)
600 * the copies still have the room available.
603 m_copypacket(struct mbuf *m, int how)
605 struct mbuf *top, *n, *o;
607 MBUF_CHECKSLEEP(how);
608 n = m_get(how, m->m_type);
613 if (!m_dup_pkthdr(n, m, how))
616 if (m->m_flags & (M_EXT|M_EXTPG)) {
617 n->m_data = m->m_data;
620 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
621 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
626 o = m_get(how, m->m_type);
634 if (m->m_flags & (M_EXT|M_EXTPG)) {
635 n->m_data = m->m_data;
638 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
650 m_copyfromunmapped(const struct mbuf *m, int off, int len, caddr_t cp)
654 int error __diagused;
656 KASSERT(off >= 0, ("m_copyfromunmapped: negative off %d", off));
657 KASSERT(len >= 0, ("m_copyfromunmapped: negative len %d", len));
658 KASSERT(off < m->m_len,
659 ("m_copyfromunmapped: len exceeds mbuf length"));
664 uio.uio_segflg = UIO_SYSSPACE;
667 uio.uio_rw = UIO_READ;
668 error = m_unmapped_uiomove(m, off, &uio, len);
669 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
674 * Copy data from an mbuf chain starting "off" bytes from the beginning,
675 * continuing for "len" bytes, into the indicated buffer.
678 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
682 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
683 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
685 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
692 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
693 count = min(m->m_len - off, len);
694 if ((m->m_flags & M_EXTPG) != 0)
695 m_copyfromunmapped(m, off, count, cp);
697 bcopy(mtod(m, caddr_t) + off, cp, count);
706 * Copy a packet header mbuf chain into a completely new chain, including
707 * copying any mbuf clusters. Use this instead of m_copypacket() when
708 * you need a writable copy of an mbuf chain.
711 m_dup(const struct mbuf *m, int how)
713 struct mbuf **p, *top = NULL;
714 int remain, moff, nsize;
716 MBUF_CHECKSLEEP(how);
722 /* While there's more data, get a new mbuf, tack it on, and fill it */
723 remain = m->m_pkthdr.len;
726 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
729 /* Get the next new mbuf */
730 if (remain >= MINCLSIZE) {
731 n = m_getcl(how, m->m_type, 0);
734 n = m_get(how, m->m_type);
740 if (top == NULL) { /* First one, must be PKTHDR */
741 if (!m_dup_pkthdr(n, m, how)) {
745 if ((n->m_flags & M_EXT) == 0)
747 n->m_flags &= ~M_RDONLY;
751 /* Link it into the new chain */
755 /* Copy data from original mbuf(s) into new mbuf */
756 while (n->m_len < nsize && m != NULL) {
757 int chunk = min(nsize - n->m_len, m->m_len - moff);
759 m_copydata(m, moff, chunk, n->m_data + n->m_len);
763 if (moff == m->m_len) {
769 /* Check correct total mbuf length */
770 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
771 ("%s: bogus m_pkthdr.len", __func__));
781 * Concatenate mbuf chain n to m.
782 * Both chains must be of the same type (e.g. MT_DATA).
783 * Any m_pkthdr is not updated.
786 m_cat(struct mbuf *m, struct mbuf *n)
791 if (!M_WRITABLE(m) ||
792 (n->m_flags & M_EXTPG) != 0 ||
793 M_TRAILINGSPACE(m) < n->m_len) {
794 /* just join the two chains */
798 /* splat the data from one into the other */
799 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
801 m->m_len += n->m_len;
807 * Concatenate two pkthdr mbuf chains.
810 m_catpkt(struct mbuf *m, struct mbuf *n)
816 m->m_pkthdr.len += n->m_pkthdr.len;
823 m_adj(struct mbuf *mp, int req_len)
829 if ((m = mp) == NULL)
835 while (m != NULL && len > 0) {
836 if (m->m_len <= len) {
846 if (mp->m_flags & M_PKTHDR)
847 mp->m_pkthdr.len -= (req_len - len);
850 * Trim from tail. Scan the mbuf chain,
851 * calculating its length and finding the last mbuf.
852 * If the adjustment only affects this mbuf, then just
853 * adjust and return. Otherwise, rescan and truncate
854 * after the remaining size.
860 if (m->m_next == (struct mbuf *)0)
864 if (m->m_len >= len) {
866 if (mp->m_flags & M_PKTHDR)
867 mp->m_pkthdr.len -= len;
874 * Correct length for chain is "count".
875 * Find the mbuf with last data, adjust its length,
876 * and toss data from remaining mbufs on chain.
879 if (m->m_flags & M_PKTHDR)
880 m->m_pkthdr.len = count;
881 for (; m; m = m->m_next) {
882 if (m->m_len >= count) {
884 if (m->m_next != NULL) {
896 m_adj_decap(struct mbuf *mp, int len)
901 if ((mp->m_flags & M_PKTHDR) != 0) {
903 * If flowid was calculated by card from the inner
904 * headers, move flowid to the decapsulated mbuf
905 * chain, otherwise clear. This depends on the
906 * internals of m_adj, which keeps pkthdr as is, in
907 * particular not changing rsstype and flowid.
909 rsstype = mp->m_pkthdr.rsstype;
910 if ((rsstype & M_HASHTYPE_INNER) != 0) {
911 M_HASHTYPE_SET(mp, rsstype & ~M_HASHTYPE_INNER);
913 M_HASHTYPE_CLEAR(mp);
919 * Rearange an mbuf chain so that len bytes are contiguous
920 * and in the data area of an mbuf (so that mtod will work
921 * for a structure of size len). Returns the resulting
922 * mbuf chain on success, frees it and returns null on failure.
923 * If there is room, it will add up to max_protohdr-len extra bytes to the
924 * contiguous region in an attempt to avoid being called next time.
927 m_pullup(struct mbuf *n, int len)
933 KASSERT((n->m_flags & M_EXTPG) == 0,
934 ("%s: unmapped mbuf %p", __func__, n));
937 * If first mbuf has no cluster, and has room for len bytes
938 * without shifting current data, pullup into it,
939 * otherwise allocate a new mbuf to prepend to the chain.
941 if ((n->m_flags & M_EXT) == 0 &&
942 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
951 m = m_get(M_NOWAIT, n->m_type);
954 if (n->m_flags & M_PKTHDR)
957 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
959 count = min(min(max(len, max_protohdr), space), n->m_len);
960 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
970 } while (len > 0 && n);
983 * Like m_pullup(), except a new mbuf is always allocated, and we allow
984 * the amount of empty space before the data in the new mbuf to be specified
985 * (in the event that the caller expects to prepend later).
988 m_copyup(struct mbuf *n, int len, int dstoff)
993 if (len > (MHLEN - dstoff))
995 m = m_get(M_NOWAIT, n->m_type);
998 if (n->m_flags & M_PKTHDR)
1000 m->m_data += dstoff;
1001 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1003 count = min(min(max(len, max_protohdr), space), n->m_len);
1004 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1014 } while (len > 0 && n);
1027 * Partition an mbuf chain in two pieces, returning the tail --
1028 * all but the first len0 bytes. In case of failure, it returns NULL and
1029 * attempts to restore the chain to its original state.
1031 * Note that the resulting mbufs might be read-only, because the new
1032 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1033 * the "breaking point" happens to lie within a cluster mbuf. Use the
1034 * M_WRITABLE() macro to check for this case.
1037 m_split(struct mbuf *m0, int len0, int wait)
1040 u_int len = len0, remain;
1042 MBUF_CHECKSLEEP(wait);
1043 for (m = m0; m && len > m->m_len; m = m->m_next)
1047 remain = m->m_len - len;
1048 if (m0->m_flags & M_PKTHDR && remain == 0) {
1049 n = m_gethdr(wait, m0->m_type);
1052 n->m_next = m->m_next;
1054 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1055 n->m_pkthdr.snd_tag =
1056 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1057 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1059 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1060 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1061 m0->m_pkthdr.len = len0;
1063 } else if (m0->m_flags & M_PKTHDR) {
1064 n = m_gethdr(wait, m0->m_type);
1067 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1068 n->m_pkthdr.snd_tag =
1069 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1070 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1072 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1073 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1074 m0->m_pkthdr.len = len0;
1075 if (m->m_flags & (M_EXT|M_EXTPG))
1077 if (remain > MHLEN) {
1078 /* m can't be the lead packet */
1080 n->m_next = m_split(m, len, wait);
1081 if (n->m_next == NULL) {
1090 } else if (remain == 0) {
1095 n = m_get(wait, m->m_type);
1101 if (m->m_flags & (M_EXT|M_EXTPG)) {
1102 n->m_data = m->m_data + len;
1105 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1109 n->m_next = m->m_next;
1114 * Routine to copy from device local memory into mbufs.
1115 * Note that `off' argument is offset into first mbuf of target chain from
1116 * which to begin copying the data to.
1119 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1120 void (*copy)(char *from, caddr_t to, u_int len))
1123 struct mbuf *top = NULL, **mp = ⊤
1126 if (off < 0 || off > MHLEN)
1129 while (totlen > 0) {
1130 if (top == NULL) { /* First one, must be PKTHDR */
1131 if (totlen + off >= MINCLSIZE) {
1132 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1135 m = m_gethdr(M_NOWAIT, MT_DATA);
1138 /* Place initial small packet/header at end of mbuf */
1139 if (m && totlen + off + max_linkhdr <= MHLEN) {
1140 m->m_data += max_linkhdr;
1146 m->m_pkthdr.rcvif = ifp;
1147 m->m_pkthdr.len = totlen;
1149 if (totlen + off >= MINCLSIZE) {
1150 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1153 m = m_get(M_NOWAIT, MT_DATA);
1166 m->m_len = len = min(totlen, len);
1168 copy(buf, mtod(m, caddr_t), (u_int)len);
1170 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1180 m_copytounmapped(const struct mbuf *m, int off, int len, c_caddr_t cp)
1184 int error __diagused;
1186 KASSERT(off >= 0, ("m_copytounmapped: negative off %d", off));
1187 KASSERT(len >= 0, ("m_copytounmapped: negative len %d", len));
1188 KASSERT(off < m->m_len, ("m_copytounmapped: len exceeds mbuf length"));
1189 iov.iov_base = __DECONST(caddr_t, cp);
1191 uio.uio_resid = len;
1193 uio.uio_segflg = UIO_SYSSPACE;
1196 uio.uio_rw = UIO_WRITE;
1197 error = m_unmapped_uiomove(m, off, &uio, len);
1198 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
1203 * Copy data from a buffer back into the indicated mbuf chain,
1204 * starting "off" bytes from the beginning, extending the mbuf
1205 * chain if necessary.
1208 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1211 struct mbuf *m = m0, *n;
1216 while (off > (mlen = m->m_len)) {
1219 if (m->m_next == NULL) {
1220 n = m_get(M_NOWAIT, m->m_type);
1223 bzero(mtod(n, caddr_t), MLEN);
1224 n->m_len = min(MLEN, len + off);
1230 if (m->m_next == NULL && (len > m->m_len - off)) {
1231 m->m_len += min(len - (m->m_len - off),
1232 M_TRAILINGSPACE(m));
1234 mlen = min (m->m_len - off, len);
1235 if ((m->m_flags & M_EXTPG) != 0)
1236 m_copytounmapped(m, off, mlen, cp);
1238 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1246 if (m->m_next == NULL) {
1247 n = m_get(M_NOWAIT, m->m_type);
1250 n->m_len = min(MLEN, len);
1255 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1256 m->m_pkthdr.len = totlen;
1260 * Append the specified data to the indicated mbuf chain,
1261 * Extend the mbuf chain if the new data does not fit in
1264 * Return 1 if able to complete the job; otherwise 0.
1267 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1270 int remainder, space;
1272 for (m = m0; m->m_next != NULL; m = m->m_next)
1275 space = M_TRAILINGSPACE(m);
1278 * Copy into available space.
1280 if (space > remainder)
1282 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1284 cp += space, remainder -= space;
1286 while (remainder > 0) {
1288 * Allocate a new mbuf; could check space
1289 * and allocate a cluster instead.
1291 n = m_get(M_NOWAIT, m->m_type);
1294 n->m_len = min(MLEN, remainder);
1295 bcopy(cp, mtod(n, caddr_t), n->m_len);
1296 cp += n->m_len, remainder -= n->m_len;
1300 if (m0->m_flags & M_PKTHDR)
1301 m0->m_pkthdr.len += len - remainder;
1302 return (remainder == 0);
1306 m_apply_extpg_one(struct mbuf *m, int off, int len,
1307 int (*f)(void *, void *, u_int), void *arg)
1310 u_int i, count, pgoff, pglen;
1313 KASSERT(PMAP_HAS_DMAP,
1314 ("m_apply_extpg_one does not support unmapped mbufs"));
1315 off += mtod(m, vm_offset_t);
1316 if (off < m->m_epg_hdrlen) {
1317 count = min(m->m_epg_hdrlen - off, len);
1318 rval = f(arg, m->m_epg_hdr + off, count);
1324 off -= m->m_epg_hdrlen;
1325 pgoff = m->m_epg_1st_off;
1326 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
1327 pglen = m_epg_pagelen(m, i, pgoff);
1329 count = min(pglen - off, len);
1330 p = (void *)PHYS_TO_DMAP(m->m_epg_pa[i] + pgoff + off);
1331 rval = f(arg, p, count);
1341 KASSERT(off < m->m_epg_trllen,
1342 ("m_apply_extpg_one: offset beyond trailer"));
1343 KASSERT(len <= m->m_epg_trllen - off,
1344 ("m_apply_extpg_one: length beyond trailer"));
1345 return (f(arg, m->m_epg_trail + off, len));
1350 /* Apply function f to the data in a single mbuf. */
1352 m_apply_one(struct mbuf *m, int off, int len,
1353 int (*f)(void *, void *, u_int), void *arg)
1355 if ((m->m_flags & M_EXTPG) != 0)
1356 return (m_apply_extpg_one(m, off, len, f, arg));
1358 return (f(arg, mtod(m, caddr_t) + off, len));
1362 * Apply function f to the data in an mbuf chain starting "off" bytes from
1363 * the beginning, continuing for "len" bytes.
1366 m_apply(struct mbuf *m, int off, int len,
1367 int (*f)(void *, void *, u_int), void *arg)
1372 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1373 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1375 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1382 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1383 count = min(m->m_len - off, len);
1384 rval = m_apply_one(m, off, count, f, arg);
1395 * Return a pointer to mbuf/offset of location in mbuf chain.
1398 m_getptr(struct mbuf *m, int loc, int *off)
1402 /* Normal end of search. */
1403 if (m->m_len > loc) {
1408 if (m->m_next == NULL) {
1410 /* Point at the end of valid data. */
1423 m_print(const struct mbuf *m, int maxlen)
1427 const struct mbuf *m2;
1430 printf("mbuf: %p\n", m);
1434 if (m->m_flags & M_PKTHDR)
1435 len = m->m_pkthdr.len;
1439 while (m2 != NULL && (len == -1 || len)) {
1441 if (maxlen != -1 && pdata > maxlen)
1443 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1444 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1445 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1446 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1448 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1454 printf("%d bytes unaccounted for.\n", len);
1459 m_fixhdr(struct mbuf *m0)
1463 len = m_length(m0, NULL);
1464 m0->m_pkthdr.len = len;
1469 m_length(struct mbuf *m0, struct mbuf **last)
1475 for (m = m0; m != NULL; m = m->m_next) {
1477 if (m->m_next == NULL)
1486 * Defragment a mbuf chain, returning the shortest possible
1487 * chain of mbufs and clusters. If allocation fails and
1488 * this cannot be completed, NULL will be returned, but
1489 * the passed in chain will be unchanged. Upon success,
1490 * the original chain will be freed, and the new chain
1493 * If a non-packet header is passed in, the original
1494 * mbuf (chain?) will be returned unharmed.
1497 m_defrag(struct mbuf *m0, int how)
1499 struct mbuf *m_new = NULL, *m_final = NULL;
1500 int progress = 0, length;
1502 MBUF_CHECKSLEEP(how);
1503 if (!(m0->m_flags & M_PKTHDR))
1506 m_fixhdr(m0); /* Needed sanity check */
1508 #ifdef MBUF_STRESS_TEST
1509 if (m_defragrandomfailures) {
1510 int temp = arc4random() & 0xff;
1516 if (m0->m_pkthdr.len > MHLEN)
1517 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1519 m_final = m_gethdr(how, MT_DATA);
1521 if (m_final == NULL)
1524 if (m_dup_pkthdr(m_final, m0, how) == 0)
1529 while (progress < m0->m_pkthdr.len) {
1530 length = m0->m_pkthdr.len - progress;
1531 if (length > MCLBYTES)
1534 if (m_new == NULL) {
1536 m_new = m_getcl(how, MT_DATA, 0);
1538 m_new = m_get(how, MT_DATA);
1543 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1545 m_new->m_len = length;
1546 if (m_new != m_final)
1547 m_cat(m_final, m_new);
1550 #ifdef MBUF_STRESS_TEST
1551 if (m0->m_next == NULL)
1556 #ifdef MBUF_STRESS_TEST
1558 m_defragbytes += m0->m_pkthdr.len;
1562 #ifdef MBUF_STRESS_TEST
1571 * Return the number of fragments an mbuf will use. This is usually
1572 * used as a proxy for the number of scatter/gather elements needed by
1573 * a DMA engine to access an mbuf. In general mapped mbufs are
1574 * assumed to be backed by physically contiguous buffers that only
1575 * need a single fragment. Unmapped mbufs, on the other hand, can
1576 * span disjoint physical pages.
1579 frags_per_mbuf(struct mbuf *m)
1583 if ((m->m_flags & M_EXTPG) == 0)
1587 * The header and trailer are counted as a single fragment
1588 * each when present.
1590 * XXX: This overestimates the number of fragments by assuming
1591 * all the backing physical pages are disjoint.
1594 if (m->m_epg_hdrlen != 0)
1596 frags += m->m_epg_npgs;
1597 if (m->m_epg_trllen != 0)
1604 * Defragment an mbuf chain, returning at most maxfrags separate
1605 * mbufs+clusters. If this is not possible NULL is returned and
1606 * the original mbuf chain is left in its present (potentially
1607 * modified) state. We use two techniques: collapsing consecutive
1608 * mbufs and replacing consecutive mbufs by a cluster.
1610 * NB: this should really be named m_defrag but that name is taken
1613 m_collapse(struct mbuf *m0, int how, int maxfrags)
1615 struct mbuf *m, *n, *n2, **prev;
1619 * Calculate the current number of frags.
1622 for (m = m0; m != NULL; m = m->m_next)
1623 curfrags += frags_per_mbuf(m);
1625 * First, try to collapse mbufs. Note that we always collapse
1626 * towards the front so we don't need to deal with moving the
1627 * pkthdr. This may be suboptimal if the first mbuf has much
1628 * less data than the following.
1636 if (M_WRITABLE(m) &&
1637 n->m_len < M_TRAILINGSPACE(m)) {
1638 m_copydata(n, 0, n->m_len,
1639 mtod(m, char *) + m->m_len);
1640 m->m_len += n->m_len;
1641 m->m_next = n->m_next;
1642 curfrags -= frags_per_mbuf(n);
1644 if (curfrags <= maxfrags)
1649 KASSERT(maxfrags > 1,
1650 ("maxfrags %u, but normal collapse failed", maxfrags));
1652 * Collapse consecutive mbufs to a cluster.
1654 prev = &m0->m_next; /* NB: not the first mbuf */
1655 while ((n = *prev) != NULL) {
1656 if ((n2 = n->m_next) != NULL &&
1657 n->m_len + n2->m_len < MCLBYTES) {
1658 m = m_getcl(how, MT_DATA, 0);
1661 m_copydata(n, 0, n->m_len, mtod(m, char *));
1662 m_copydata(n2, 0, n2->m_len,
1663 mtod(m, char *) + n->m_len);
1664 m->m_len = n->m_len + n2->m_len;
1665 m->m_next = n2->m_next;
1667 curfrags += 1; /* For the new cluster */
1668 curfrags -= frags_per_mbuf(n);
1669 curfrags -= frags_per_mbuf(n2);
1672 if (curfrags <= maxfrags)
1675 * Still not there, try the normal collapse
1676 * again before we allocate another cluster.
1683 * No place where we can collapse to a cluster; punt.
1684 * This can occur if, for example, you request 2 frags
1685 * but the packet requires that both be clusters (we
1686 * never reallocate the first mbuf to avoid moving the
1693 #ifdef MBUF_STRESS_TEST
1696 * Fragment an mbuf chain. There's no reason you'd ever want to do
1697 * this in normal usage, but it's great for stress testing various
1700 * If fragmentation is not possible, the original chain will be
1703 * Possible length values:
1704 * 0 no fragmentation will occur
1705 * > 0 each fragment will be of the specified length
1706 * -1 each fragment will be the same random value in length
1707 * -2 each fragment's length will be entirely random
1708 * (Random values range from 1 to 256)
1711 m_fragment(struct mbuf *m0, int how, int length)
1713 struct mbuf *m_first, *m_last;
1714 int divisor = 255, progress = 0, fraglen;
1716 if (!(m0->m_flags & M_PKTHDR))
1719 if (length == 0 || length < -2)
1721 if (length > MCLBYTES)
1723 if (length < 0 && divisor > MCLBYTES)
1726 length = 1 + (arc4random() % divisor);
1730 m_fixhdr(m0); /* Needed sanity check */
1732 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1733 if (m_first == NULL)
1736 if (m_dup_pkthdr(m_first, m0, how) == 0)
1741 while (progress < m0->m_pkthdr.len) {
1743 fraglen = 1 + (arc4random() % divisor);
1744 if (fraglen > m0->m_pkthdr.len - progress)
1745 fraglen = m0->m_pkthdr.len - progress;
1747 if (progress != 0) {
1748 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1752 m_last->m_next = m_new;
1756 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1757 progress += fraglen;
1758 m_last->m_len = fraglen;
1766 /* Return the original chain on failure */
1773 * Free pages from mbuf_ext_pgs, assuming they were allocated via
1774 * vm_page_alloc() and aren't associated with any object. Complement
1775 * to allocator from m_uiotombuf_nomap().
1778 mb_free_mext_pgs(struct mbuf *m)
1783 for (int i = 0; i < m->m_epg_npgs; i++) {
1784 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1785 vm_page_unwire_noq(pg);
1790 static struct mbuf *
1791 m_uiotombuf_nomap(struct uio *uio, int how, int len, int maxseg, int flags)
1793 struct mbuf *m, *mb, *prev;
1794 vm_page_t pg_array[MBUF_PEXT_MAX_PGS];
1795 int error, length, i, needed;
1797 int pflags = malloc2vm_flags(how) | VM_ALLOC_NODUMP | VM_ALLOC_WIRED;
1799 MPASS((flags & M_PKTHDR) == 0);
1800 MPASS((how & M_ZERO) == 0);
1803 * len can be zero or an arbitrary large value bound by
1804 * the total data supplied by the uio.
1807 total = MIN(uio->uio_resid, len);
1809 total = uio->uio_resid;
1812 maxseg = MBUF_PEXT_MAX_PGS * PAGE_SIZE;
1815 * If total is zero, return an empty mbuf. This can occur
1816 * for TLS 1.0 connections which send empty fragments as
1817 * a countermeasure against the known-IV weakness in CBC
1820 if (__predict_false(total == 0)) {
1821 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1824 mb->m_epg_flags = EPG_FLAG_ANON;
1829 * Allocate the pages
1833 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1841 mb->m_epg_flags = EPG_FLAG_ANON;
1842 needed = length = MIN(maxseg, total);
1843 for (i = 0; needed > 0; i++, needed -= PAGE_SIZE) {
1845 pg_array[i] = vm_page_alloc_noobj(pflags);
1846 if (pg_array[i] == NULL) {
1847 if (how & M_NOWAIT) {
1854 mb->m_epg_pa[i] = VM_PAGE_TO_PHYS(pg_array[i]);
1857 mb->m_epg_last_len = length - PAGE_SIZE * (mb->m_epg_npgs - 1);
1858 MBUF_EXT_PGS_ASSERT_SANITY(mb);
1860 error = uiomove_fromphys(pg_array, 0, length, uio);
1864 mb->m_ext.ext_size += PAGE_SIZE * mb->m_epg_npgs;
1865 if (flags & M_PKTHDR)
1866 m->m_pkthdr.len += length;
1876 * Copy the contents of uio into a properly sized mbuf chain.
1879 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1881 struct mbuf *m, *mb;
1886 if (flags & M_EXTPG)
1887 return (m_uiotombuf_nomap(uio, how, len, align, flags));
1890 * len can be zero or an arbitrary large value bound by
1891 * the total data supplied by the uio.
1894 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1896 total = uio->uio_resid;
1899 * The smallest unit returned by m_getm2() is a single mbuf
1900 * with pkthdr. We can't align past it.
1906 * Give us the full allocation or nothing.
1907 * If len is zero return the smallest empty mbuf.
1909 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1914 /* Fill all mbufs with uio data and update header information. */
1915 for (mb = m; mb != NULL; mb = mb->m_next) {
1916 length = min(M_TRAILINGSPACE(mb), total - progress);
1918 error = uiomove(mtod(mb, void *), length, uio);
1926 if (flags & M_PKTHDR) {
1927 m->m_pkthdr.len += length;
1928 m->m_pkthdr.memlen += MSIZE;
1929 if (mb->m_flags & M_EXT)
1930 m->m_pkthdr.memlen += mb->m_ext.ext_size;
1933 KASSERT(progress == total, ("%s: progress != total", __func__));
1939 * Copy data to/from an unmapped mbuf into a uio limited by len if set.
1942 m_unmapped_uiomove(const struct mbuf *m, int m_off, struct uio *uio, int len)
1945 int error, i, off, pglen, pgoff, seglen, segoff;
1950 /* Skip over any data removed from the front. */
1951 off = mtod(m, vm_offset_t);
1954 if (m->m_epg_hdrlen != 0) {
1955 if (off >= m->m_epg_hdrlen) {
1956 off -= m->m_epg_hdrlen;
1958 seglen = m->m_epg_hdrlen - off;
1960 seglen = min(seglen, len);
1963 error = uiomove(__DECONST(void *,
1964 &m->m_epg_hdr[segoff]), seglen, uio);
1967 pgoff = m->m_epg_1st_off;
1968 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
1969 pglen = m_epg_pagelen(m, i, pgoff);
1975 seglen = pglen - off;
1976 segoff = pgoff + off;
1978 seglen = min(seglen, len);
1980 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1981 error = uiomove_fromphys(&pg, segoff, seglen, uio);
1984 if (len != 0 && error == 0) {
1985 KASSERT((off + len) <= m->m_epg_trllen,
1986 ("off + len > trail (%d + %d > %d, m_off = %d)", off, len,
1987 m->m_epg_trllen, m_off));
1988 error = uiomove(__DECONST(void *, &m->m_epg_trail[off]),
1995 * Copy an mbuf chain into a uio limited by len if set.
1998 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
2000 int error, length, total;
2004 total = min(uio->uio_resid, len);
2006 total = uio->uio_resid;
2008 /* Fill the uio with data from the mbufs. */
2009 for (; m != NULL; m = m->m_next) {
2010 length = min(m->m_len, total - progress);
2012 if ((m->m_flags & M_EXTPG) != 0)
2013 error = m_unmapped_uiomove(m, 0, uio, length);
2015 error = uiomove(mtod(m, void *), length, uio);
2026 * Create a writable copy of the mbuf chain. While doing this
2027 * we compact the chain with a goal of producing a chain with
2028 * at most two mbufs. The second mbuf in this chain is likely
2029 * to be a cluster. The primary purpose of this work is to create
2030 * a writable packet for encryption, compression, etc. The
2031 * secondary goal is to linearize the data so the data can be
2032 * passed to crypto hardware in the most efficient manner possible.
2035 m_unshare(struct mbuf *m0, int how)
2037 struct mbuf *m, *mprev;
2038 struct mbuf *n, *mfirst, *mlast;
2042 for (m = m0; m != NULL; m = mprev->m_next) {
2044 * Regular mbufs are ignored unless there's a cluster
2045 * in front of it that we can use to coalesce. We do
2046 * the latter mainly so later clusters can be coalesced
2047 * also w/o having to handle them specially (i.e. convert
2048 * mbuf+cluster -> cluster). This optimization is heavily
2049 * influenced by the assumption that we're running over
2050 * Ethernet where MCLBYTES is large enough that the max
2051 * packet size will permit lots of coalescing into a
2052 * single cluster. This in turn permits efficient
2053 * crypto operations, especially when using hardware.
2055 if ((m->m_flags & M_EXT) == 0) {
2056 if (mprev && (mprev->m_flags & M_EXT) &&
2057 m->m_len <= M_TRAILINGSPACE(mprev)) {
2058 /* XXX: this ignores mbuf types */
2059 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2060 mtod(m, caddr_t), m->m_len);
2061 mprev->m_len += m->m_len;
2062 mprev->m_next = m->m_next; /* unlink from chain */
2063 m_free(m); /* reclaim mbuf */
2070 * Writable mbufs are left alone (for now).
2072 if (M_WRITABLE(m)) {
2078 * Not writable, replace with a copy or coalesce with
2079 * the previous mbuf if possible (since we have to copy
2080 * it anyway, we try to reduce the number of mbufs and
2081 * clusters so that future work is easier).
2083 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
2084 /* NB: we only coalesce into a cluster or larger */
2085 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
2086 m->m_len <= M_TRAILINGSPACE(mprev)) {
2087 /* XXX: this ignores mbuf types */
2088 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2089 mtod(m, caddr_t), m->m_len);
2090 mprev->m_len += m->m_len;
2091 mprev->m_next = m->m_next; /* unlink from chain */
2092 m_free(m); /* reclaim mbuf */
2097 * Allocate new space to hold the copy and copy the data.
2098 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
2099 * splitting them into clusters. We could just malloc a
2100 * buffer and make it external but too many device drivers
2101 * don't know how to break up the non-contiguous memory when
2104 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2109 if (m->m_flags & M_PKTHDR) {
2110 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
2112 m_move_pkthdr(n, m);
2119 int cc = min(len, MCLBYTES);
2120 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2126 newipsecstat.ips_clcopied++;
2134 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2141 n->m_next = m->m_next;
2143 m0 = mfirst; /* new head of chain */
2145 mprev->m_next = mfirst; /* replace old mbuf */
2146 m_free(m); /* release old mbuf */
2152 #ifdef MBUF_PROFILING
2154 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2155 struct mbufprofile {
2156 uintmax_t wasted[MP_BUCKETS];
2157 uintmax_t used[MP_BUCKETS];
2158 uintmax_t segments[MP_BUCKETS];
2162 m_profile(struct mbuf *m)
2171 if (m->m_flags & M_EXT) {
2172 wasted += MHLEN - sizeof(m->m_ext) +
2173 m->m_ext.ext_size - m->m_len;
2175 if (m->m_flags & M_PKTHDR)
2176 wasted += MHLEN - m->m_len;
2178 wasted += MLEN - m->m_len;
2182 /* be paranoid.. it helps */
2183 if (segments > MP_BUCKETS - 1)
2184 segments = MP_BUCKETS - 1;
2187 if (wasted > 100000)
2189 /* store in the appropriate bucket */
2190 /* don't bother locking. if it's slightly off, so what? */
2191 mbprof.segments[segments]++;
2192 mbprof.used[fls(used)]++;
2193 mbprof.wasted[fls(wasted)]++;
2197 mbprof_handler(SYSCTL_HANDLER_ARGS)
2204 sbuf_new_for_sysctl(&sb, buf, sizeof(buf), req);
2206 p = &mbprof.wasted[0];
2209 "%ju %ju %ju %ju %ju %ju %ju %ju "
2210 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2211 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2212 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2214 p = &mbprof.wasted[16];
2216 "%ju %ju %ju %ju %ju %ju %ju %ju "
2217 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2218 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2219 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2221 p = &mbprof.used[0];
2224 "%ju %ju %ju %ju %ju %ju %ju %ju "
2225 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2226 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2227 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2229 p = &mbprof.used[16];
2231 "%ju %ju %ju %ju %ju %ju %ju %ju "
2232 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2233 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2234 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2236 p = &mbprof.segments[0];
2239 "%ju %ju %ju %ju %ju %ju %ju %ju "
2240 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2241 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2242 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2244 p = &mbprof.segments[16];
2246 "%ju %ju %ju %ju %ju %ju %ju %ju "
2247 "%ju %ju %ju %ju %ju %ju %ju %jju",
2248 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2249 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2252 error = sbuf_finish(&sb);
2258 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2263 error = sysctl_handle_int(oidp, &clear, 0, req);
2264 if (error || !req->newptr)
2268 bzero(&mbprof, sizeof(mbprof));
2274 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile,
2275 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2276 mbprof_handler, "A",
2277 "mbuf profiling statistics");
2279 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr,
2280 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
2281 mbprof_clr_handler, "I",
2282 "clear mbuf profiling statistics");