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
32 #include <sys/cdefs.h>
33 #include "opt_param.h"
34 #include "opt_mbuf_stress_test.h"
35 #include "opt_mbuf_profiling.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/limits.h>
42 #include <sys/malloc.h>
44 #include <sys/sysctl.h>
45 #include <sys/domain.h>
46 #include <sys/protosw.h>
48 #include <sys/vmmeter.h>
52 #include <vm/vm_pageout.h>
53 #include <vm/vm_page.h>
55 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__init,
56 "struct mbuf *", "mbufinfo_t *",
57 "uint32_t", "uint32_t",
58 "uint16_t", "uint16_t",
59 "uint32_t", "uint32_t",
60 "uint32_t", "uint32_t");
62 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr_raw,
63 "uint32_t", "uint32_t",
64 "uint16_t", "uint16_t",
65 "struct mbuf *", "mbufinfo_t *");
67 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr,
68 "uint32_t", "uint32_t",
69 "uint16_t", "uint16_t",
70 "struct mbuf *", "mbufinfo_t *");
72 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get_raw,
73 "uint32_t", "uint32_t",
74 "uint16_t", "uint16_t",
75 "struct mbuf *", "mbufinfo_t *");
77 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
78 "uint32_t", "uint32_t",
79 "uint16_t", "uint16_t",
80 "struct mbuf *", "mbufinfo_t *");
82 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
83 "uint32_t", "uint32_t",
84 "uint16_t", "uint16_t",
85 "uint32_t", "uint32_t",
86 "struct mbuf *", "mbufinfo_t *");
88 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__getjcl,
89 "uint32_t", "uint32_t",
90 "uint16_t", "uint16_t",
91 "uint32_t", "uint32_t",
92 "uint32_t", "uint32_t",
93 "struct mbuf *", "mbufinfo_t *");
95 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
96 "struct mbuf *", "mbufinfo_t *",
97 "uint32_t", "uint32_t",
98 "uint32_t", "uint32_t");
100 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
101 "struct mbuf *", "mbufinfo_t *",
102 "uint32_t", "uint32_t",
103 "uint32_t", "uint32_t",
106 SDT_PROBE_DEFINE(sdt, , , m__cljset);
108 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
109 "struct mbuf *", "mbufinfo_t *");
111 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
112 "struct mbuf *", "mbufinfo_t *");
114 #include <security/mac/mac_framework.h>
117 * Provide minimum possible defaults for link and protocol header space,
118 * assuming IPv4 over Ethernet. Enabling IPv6, IEEE802.11 or some other
119 * protocol may grow these values.
121 u_int max_linkhdr = 16;
122 u_int max_protohdr = 40;
123 u_int max_hdr = 16 + 40;
124 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
125 &max_linkhdr, 16, "Size of largest link layer header");
126 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
127 &max_protohdr, 40, "Size of largest protocol layer header");
128 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
129 &max_hdr, 16 + 40, "Size of largest link plus protocol header");
135 max_hdr = max_linkhdr + max_protohdr;
136 MPASS(max_hdr <= MHLEN);
140 max_linkhdr_grow(u_int new)
143 if (new > max_linkhdr) {
150 max_protohdr_grow(u_int new)
153 if (new > max_protohdr) {
159 #ifdef MBUF_STRESS_TEST
164 int m_defragrandomfailures;
166 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
167 &m_defragpackets, 0, "");
168 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
169 &m_defragbytes, 0, "");
170 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
171 &m_defraguseless, 0, "");
172 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
173 &m_defragfailure, 0, "");
174 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
175 &m_defragrandomfailures, 0, "");
179 * Ensure the correct size of various mbuf parameters. It could be off due
180 * to compiler-induced padding and alignment artifacts.
182 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
183 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
186 * mbuf data storage should be 64-bit aligned regardless of architectural
187 * pointer size; check this is the case with and without a packet header.
189 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
190 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
193 * While the specific values here don't matter too much (i.e., +/- a few
194 * words), we do want to ensure that changes to these values are carefully
195 * reasoned about and properly documented. This is especially the case as
196 * network-protocol and device-driver modules encode these layouts, and must
197 * be recompiled if the structures change. Check these values at compile time
198 * against the ones documented in comments in mbuf.h.
200 * NB: Possibly they should be documented there via #define's and not just
203 #if defined(__LP64__)
204 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
205 CTASSERT(sizeof(struct pkthdr) == 64);
206 CTASSERT(sizeof(struct m_ext) == 160);
208 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
209 CTASSERT(sizeof(struct pkthdr) == 56);
210 #if defined(__powerpc__) && defined(BOOKE)
211 /* PowerPC booke has 64-bit physical pointers. */
212 CTASSERT(sizeof(struct m_ext) == 176);
214 CTASSERT(sizeof(struct m_ext) == 172);
219 * Assert that the queue(3) macros produce code of the same size as an old
220 * plain pointer does.
223 static struct mbuf __used m_assertbuf;
224 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
225 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
226 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
227 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
231 * Attach the cluster from *m to *n, set up m_ext in *n
232 * and bump the refcount of the cluster.
235 mb_dupcl(struct mbuf *n, struct mbuf *m)
237 volatile u_int *refcnt;
239 KASSERT(m->m_flags & (M_EXT|M_EXTPG),
240 ("%s: M_EXT|M_EXTPG not set on %p", __func__, m));
241 KASSERT(!(n->m_flags & (M_EXT|M_EXTPG)),
242 ("%s: M_EXT|M_EXTPG set on %p", __func__, n));
245 * Cache access optimization.
247 * o Regular M_EXT storage doesn't need full copy of m_ext, since
248 * the holder of the 'ext_count' is responsible to carry the free
249 * routine and its arguments.
250 * o M_EXTPG data is split between main part of mbuf and m_ext, the
251 * main part is copied in full, the m_ext part is similar to M_EXT.
252 * o EXT_EXTREF, where 'ext_cnt' doesn't point into mbuf at all, is
253 * special - it needs full copy of m_ext into each mbuf, since any
254 * copy could end up as the last to free.
256 if (m->m_flags & M_EXTPG) {
257 bcopy(&m->m_epg_startcopy, &n->m_epg_startcopy,
258 __rangeof(struct mbuf, m_epg_startcopy, m_epg_endcopy));
259 bcopy(&m->m_ext, &n->m_ext, m_epg_ext_copylen);
260 } else if (m->m_ext.ext_type == EXT_EXTREF)
261 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
263 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
265 n->m_flags |= m->m_flags & (M_RDONLY | M_EXT | M_EXTPG);
267 /* See if this is the mbuf that holds the embedded refcount. */
268 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
269 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
270 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
272 KASSERT(m->m_ext.ext_cnt != NULL,
273 ("%s: no refcounting pointer on %p", __func__, m));
274 refcnt = m->m_ext.ext_cnt;
280 atomic_add_int(refcnt, 1);
284 m_demote_pkthdr(struct mbuf *m)
288 M_ASSERT_NO_SND_TAG(m);
290 m_tag_delete_chain(m, NULL);
291 m->m_flags &= ~M_PKTHDR;
292 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
296 * Clean up mbuf (chain) from any tags and packet headers.
297 * If "all" is set then the first mbuf in the chain will be
301 m_demote(struct mbuf *m0, int all, int flags)
305 flags |= M_DEMOTEFLAGS;
307 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
308 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
310 if (m->m_flags & M_PKTHDR)
317 * Sanity checks on mbuf (chain) for use in KASSERT() and general
319 * Returns 0 or panics when bad and 1 on all tests passed.
320 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
324 m_sanity(struct mbuf *m0, int sanitize)
331 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
333 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
336 for (m = m0; m != NULL; m = m->m_next) {
338 * Basic pointer checks. If any of these fails then some
339 * unrelated kernel memory before or after us is trashed.
340 * No way to recover from that.
344 if ((caddr_t)m->m_data < a)
345 M_SANITY_ACTION("m_data outside mbuf data range left");
346 if ((caddr_t)m->m_data > b)
347 M_SANITY_ACTION("m_data outside mbuf data range right");
348 if ((caddr_t)m->m_data + m->m_len > b)
349 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
351 /* m->m_nextpkt may only be set on first mbuf in chain. */
352 if (m != m0 && m->m_nextpkt != NULL) {
354 m_freem(m->m_nextpkt);
355 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
357 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
360 /* packet length (not mbuf length!) calculation */
361 if (m0->m_flags & M_PKTHDR)
364 /* m_tags may only be attached to first mbuf in chain. */
365 if (m != m0 && m->m_flags & M_PKTHDR &&
366 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
368 m_tag_delete_chain(m, NULL);
369 /* put in 0xDEADC0DE perhaps? */
371 M_SANITY_ACTION("m_tags on in-chain mbuf");
374 /* M_PKTHDR may only be set on first mbuf in chain */
375 if (m != m0 && m->m_flags & M_PKTHDR) {
377 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
378 m->m_flags &= ~M_PKTHDR;
379 /* put in 0xDEADCODE and leave hdr flag in */
381 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
385 if (pktlen && pktlen != m->m_pkthdr.len) {
389 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
393 #undef M_SANITY_ACTION
397 * Non-inlined part of m_init().
400 m_pkthdr_init(struct mbuf *m, int how)
405 m->m_data = m->m_pktdat;
406 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
408 m->m_pkthdr.numa_domain = M_NODOM;
411 /* If the label init fails, fail the alloc */
412 error = mac_mbuf_init(m, how);
421 * "Move" mbuf pkthdr from "from" to "to".
422 * "from" must have M_PKTHDR set, and "to" must be empty.
425 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
429 /* see below for why these are not enabled */
431 /* Note: with MAC, this may not be a good assertion. */
432 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
433 ("m_move_pkthdr: to has tags"));
437 * XXXMAC: It could be this should also occur for non-MAC?
439 if (to->m_flags & M_PKTHDR)
440 m_tag_delete_chain(to, NULL);
442 to->m_flags = (from->m_flags & M_COPYFLAGS) |
443 (to->m_flags & (M_EXT | M_EXTPG));
444 if ((to->m_flags & M_EXT) == 0)
445 to->m_data = to->m_pktdat;
446 to->m_pkthdr = from->m_pkthdr; /* especially tags */
447 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
448 from->m_flags &= ~M_PKTHDR;
449 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG) {
450 from->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
451 from->m_pkthdr.snd_tag = NULL;
456 * Duplicate "from"'s mbuf pkthdr in "to".
457 * "from" must have M_PKTHDR set, and "to" must be empty.
458 * In particular, this does a deep copy of the packet tags.
461 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
466 * The mbuf allocator only initializes the pkthdr
467 * when the mbuf is allocated with m_gethdr(). Many users
468 * (e.g. m_copy*, m_prepend) use m_get() and then
469 * smash the pkthdr as needed causing these
470 * assertions to trip. For now just disable them.
473 /* Note: with MAC, this may not be a good assertion. */
474 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
476 MBUF_CHECKSLEEP(how);
478 if (to->m_flags & M_PKTHDR)
479 m_tag_delete_chain(to, NULL);
481 to->m_flags = (from->m_flags & M_COPYFLAGS) |
482 (to->m_flags & (M_EXT | M_EXTPG));
483 if ((to->m_flags & M_EXT) == 0)
484 to->m_data = to->m_pktdat;
485 to->m_pkthdr = from->m_pkthdr;
486 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG)
487 m_snd_tag_ref(from->m_pkthdr.snd_tag);
488 SLIST_INIT(&to->m_pkthdr.tags);
489 return (m_tag_copy_chain(to, from, how));
493 * Lesser-used path for M_PREPEND:
494 * allocate new mbuf to prepend to chain,
498 m_prepend(struct mbuf *m, int len, int how)
502 if (m->m_flags & M_PKTHDR)
503 mn = m_gethdr(how, m->m_type);
505 mn = m_get(how, m->m_type);
510 if (m->m_flags & M_PKTHDR)
511 m_move_pkthdr(mn, m);
521 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
522 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
523 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
524 * Note that the copy is read-only, because clusters are not copied,
525 * only their reference counts are incremented.
528 m_copym(struct mbuf *m, int off0, int len, int wait)
530 struct mbuf *n, **np;
535 KASSERT(off >= 0, ("m_copym, negative off %d", off));
536 KASSERT(len >= 0, ("m_copym, negative len %d", len));
537 MBUF_CHECKSLEEP(wait);
538 if (off == 0 && m->m_flags & M_PKTHDR)
541 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
551 KASSERT(len == M_COPYALL,
552 ("m_copym, length > size of mbuf chain"));
556 n = m_gethdr(wait, m->m_type);
558 n = m_get(wait, m->m_type);
563 if (!m_dup_pkthdr(n, m, wait))
565 if (len == M_COPYALL)
566 n->m_pkthdr.len -= off0;
568 n->m_pkthdr.len = len;
571 n->m_len = min(len, m->m_len - off);
572 if (m->m_flags & (M_EXT|M_EXTPG)) {
573 n->m_data = m->m_data + off;
576 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
578 if (len != M_COPYALL)
592 * Copy an entire packet, including header (which must be present).
593 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
594 * Note that the copy is read-only, because clusters are not copied,
595 * only their reference counts are incremented.
596 * Preserve alignment of the first mbuf so if the creator has left
597 * some room at the beginning (e.g. for inserting protocol headers)
598 * the copies still have the room available.
601 m_copypacket(struct mbuf *m, int how)
603 struct mbuf *top, *n, *o;
605 MBUF_CHECKSLEEP(how);
606 n = m_get(how, m->m_type);
611 if (!m_dup_pkthdr(n, m, how))
614 if (m->m_flags & (M_EXT|M_EXTPG)) {
615 n->m_data = m->m_data;
618 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
619 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
624 o = m_get(how, m->m_type);
632 if (m->m_flags & (M_EXT|M_EXTPG)) {
633 n->m_data = m->m_data;
636 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
648 m_copyfromunmapped(const struct mbuf *m, int off, int len, caddr_t cp)
652 int error __diagused;
654 KASSERT(off >= 0, ("m_copyfromunmapped: negative off %d", off));
655 KASSERT(len >= 0, ("m_copyfromunmapped: negative len %d", len));
656 KASSERT(off < m->m_len,
657 ("m_copyfromunmapped: len exceeds mbuf length"));
662 uio.uio_segflg = UIO_SYSSPACE;
665 uio.uio_rw = UIO_READ;
666 error = m_unmapped_uiomove(m, off, &uio, len);
667 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
672 * Copy data from an mbuf chain starting "off" bytes from the beginning,
673 * continuing for "len" bytes, into the indicated buffer.
676 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
680 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
681 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
683 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
690 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
691 count = min(m->m_len - off, len);
692 if ((m->m_flags & M_EXTPG) != 0)
693 m_copyfromunmapped(m, off, count, cp);
695 bcopy(mtod(m, caddr_t) + off, cp, count);
704 * Copy a packet header mbuf chain into a completely new chain, including
705 * copying any mbuf clusters. Use this instead of m_copypacket() when
706 * you need a writable copy of an mbuf chain.
709 m_dup(const struct mbuf *m, int how)
711 struct mbuf **p, *top = NULL;
712 int remain, moff, nsize;
714 MBUF_CHECKSLEEP(how);
720 /* While there's more data, get a new mbuf, tack it on, and fill it */
721 remain = m->m_pkthdr.len;
724 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
727 /* Get the next new mbuf */
728 if (remain >= MINCLSIZE) {
729 n = m_getcl(how, m->m_type, 0);
732 n = m_get(how, m->m_type);
738 if (top == NULL) { /* First one, must be PKTHDR */
739 if (!m_dup_pkthdr(n, m, how)) {
743 if ((n->m_flags & M_EXT) == 0)
745 n->m_flags &= ~M_RDONLY;
749 /* Link it into the new chain */
753 /* Copy data from original mbuf(s) into new mbuf */
754 while (n->m_len < nsize && m != NULL) {
755 int chunk = min(nsize - n->m_len, m->m_len - moff);
757 m_copydata(m, moff, chunk, n->m_data + n->m_len);
761 if (moff == m->m_len) {
767 /* Check correct total mbuf length */
768 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
769 ("%s: bogus m_pkthdr.len", __func__));
779 * Concatenate mbuf chain n to m.
780 * Both chains must be of the same type (e.g. MT_DATA).
781 * Any m_pkthdr is not updated.
784 m_cat(struct mbuf *m, struct mbuf *n)
789 if (!M_WRITABLE(m) ||
790 (n->m_flags & M_EXTPG) != 0 ||
791 M_TRAILINGSPACE(m) < n->m_len) {
792 /* just join the two chains */
796 /* splat the data from one into the other */
797 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
799 m->m_len += n->m_len;
805 * Concatenate two pkthdr mbuf chains.
808 m_catpkt(struct mbuf *m, struct mbuf *n)
814 m->m_pkthdr.len += n->m_pkthdr.len;
821 m_adj(struct mbuf *mp, int req_len)
827 if ((m = mp) == NULL)
833 while (m != NULL && len > 0) {
834 if (m->m_len <= len) {
844 if (mp->m_flags & M_PKTHDR)
845 mp->m_pkthdr.len -= (req_len - len);
848 * Trim from tail. Scan the mbuf chain,
849 * calculating its length and finding the last mbuf.
850 * If the adjustment only affects this mbuf, then just
851 * adjust and return. Otherwise, rescan and truncate
852 * after the remaining size.
858 if (m->m_next == (struct mbuf *)0)
862 if (m->m_len >= len) {
864 if (mp->m_flags & M_PKTHDR)
865 mp->m_pkthdr.len -= len;
872 * Correct length for chain is "count".
873 * Find the mbuf with last data, adjust its length,
874 * and toss data from remaining mbufs on chain.
877 if (m->m_flags & M_PKTHDR)
878 m->m_pkthdr.len = count;
879 for (; m; m = m->m_next) {
880 if (m->m_len >= count) {
882 if (m->m_next != NULL) {
894 m_adj_decap(struct mbuf *mp, int len)
899 if ((mp->m_flags & M_PKTHDR) != 0) {
901 * If flowid was calculated by card from the inner
902 * headers, move flowid to the decapsulated mbuf
903 * chain, otherwise clear. This depends on the
904 * internals of m_adj, which keeps pkthdr as is, in
905 * particular not changing rsstype and flowid.
907 rsstype = mp->m_pkthdr.rsstype;
908 if ((rsstype & M_HASHTYPE_INNER) != 0) {
909 M_HASHTYPE_SET(mp, rsstype & ~M_HASHTYPE_INNER);
911 M_HASHTYPE_CLEAR(mp);
917 * Rearange an mbuf chain so that len bytes are contiguous
918 * and in the data area of an mbuf (so that mtod will work
919 * for a structure of size len). Returns the resulting
920 * mbuf chain on success, frees it and returns null on failure.
921 * If there is room, it will add up to max_protohdr-len extra bytes to the
922 * contiguous region in an attempt to avoid being called next time.
925 m_pullup(struct mbuf *n, int len)
931 KASSERT((n->m_flags & M_EXTPG) == 0,
932 ("%s: unmapped mbuf %p", __func__, n));
935 * If first mbuf has no cluster, and has room for len bytes
936 * without shifting current data, pullup into it,
937 * otherwise allocate a new mbuf to prepend to the chain.
939 if ((n->m_flags & M_EXT) == 0 &&
940 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
949 m = m_get(M_NOWAIT, n->m_type);
952 if (n->m_flags & M_PKTHDR)
955 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
957 count = min(min(max(len, max_protohdr), space), n->m_len);
958 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
968 } while (len > 0 && n);
981 * Like m_pullup(), except a new mbuf is always allocated, and we allow
982 * the amount of empty space before the data in the new mbuf to be specified
983 * (in the event that the caller expects to prepend later).
986 m_copyup(struct mbuf *n, int len, int dstoff)
991 if (len > (MHLEN - dstoff))
993 m = m_get(M_NOWAIT, n->m_type);
996 if (n->m_flags & M_PKTHDR)
999 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1001 count = min(min(max(len, max_protohdr), space), n->m_len);
1002 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1012 } while (len > 0 && n);
1025 * Partition an mbuf chain in two pieces, returning the tail --
1026 * all but the first len0 bytes. In case of failure, it returns NULL and
1027 * attempts to restore the chain to its original state.
1029 * Note that the resulting mbufs might be read-only, because the new
1030 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1031 * the "breaking point" happens to lie within a cluster mbuf. Use the
1032 * M_WRITABLE() macro to check for this case.
1035 m_split(struct mbuf *m0, int len0, int wait)
1038 u_int len = len0, remain;
1040 MBUF_CHECKSLEEP(wait);
1041 for (m = m0; m && len > m->m_len; m = m->m_next)
1045 remain = m->m_len - len;
1046 if (m0->m_flags & M_PKTHDR && remain == 0) {
1047 n = m_gethdr(wait, m0->m_type);
1050 n->m_next = m->m_next;
1052 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1053 n->m_pkthdr.snd_tag =
1054 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1055 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1057 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1058 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1059 m0->m_pkthdr.len = len0;
1061 } else if (m0->m_flags & M_PKTHDR) {
1062 n = m_gethdr(wait, m0->m_type);
1065 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1066 n->m_pkthdr.snd_tag =
1067 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1068 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1070 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1071 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1072 m0->m_pkthdr.len = len0;
1073 if (m->m_flags & (M_EXT|M_EXTPG))
1075 if (remain > MHLEN) {
1076 /* m can't be the lead packet */
1078 n->m_next = m_split(m, len, wait);
1079 if (n->m_next == NULL) {
1088 } else if (remain == 0) {
1093 n = m_get(wait, m->m_type);
1099 if (m->m_flags & (M_EXT|M_EXTPG)) {
1100 n->m_data = m->m_data + len;
1103 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1107 n->m_next = m->m_next;
1112 * Routine to copy from device local memory into mbufs.
1113 * Note that `off' argument is offset into first mbuf of target chain from
1114 * which to begin copying the data to.
1117 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1118 void (*copy)(char *from, caddr_t to, u_int len))
1121 struct mbuf *top = NULL, **mp = ⊤
1124 if (off < 0 || off > MHLEN)
1127 while (totlen > 0) {
1128 if (top == NULL) { /* First one, must be PKTHDR */
1129 if (totlen + off >= MINCLSIZE) {
1130 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1133 m = m_gethdr(M_NOWAIT, MT_DATA);
1136 /* Place initial small packet/header at end of mbuf */
1137 if (m && totlen + off + max_linkhdr <= MHLEN) {
1138 m->m_data += max_linkhdr;
1144 m->m_pkthdr.rcvif = ifp;
1145 m->m_pkthdr.len = totlen;
1147 if (totlen + off >= MINCLSIZE) {
1148 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1151 m = m_get(M_NOWAIT, MT_DATA);
1164 m->m_len = len = min(totlen, len);
1166 copy(buf, mtod(m, caddr_t), (u_int)len);
1168 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1178 m_copytounmapped(const struct mbuf *m, int off, int len, c_caddr_t cp)
1182 int error __diagused;
1184 KASSERT(off >= 0, ("m_copytounmapped: negative off %d", off));
1185 KASSERT(len >= 0, ("m_copytounmapped: negative len %d", len));
1186 KASSERT(off < m->m_len, ("m_copytounmapped: len exceeds mbuf length"));
1187 iov.iov_base = __DECONST(caddr_t, cp);
1189 uio.uio_resid = len;
1191 uio.uio_segflg = UIO_SYSSPACE;
1194 uio.uio_rw = UIO_WRITE;
1195 error = m_unmapped_uiomove(m, off, &uio, len);
1196 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
1201 * Copy data from a buffer back into the indicated mbuf chain,
1202 * starting "off" bytes from the beginning, extending the mbuf
1203 * chain if necessary.
1206 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1209 struct mbuf *m = m0, *n;
1214 while (off > (mlen = m->m_len)) {
1217 if (m->m_next == NULL) {
1218 n = m_get(M_NOWAIT, m->m_type);
1221 bzero(mtod(n, caddr_t), MLEN);
1222 n->m_len = min(MLEN, len + off);
1228 if (m->m_next == NULL && (len > m->m_len - off)) {
1229 m->m_len += min(len - (m->m_len - off),
1230 M_TRAILINGSPACE(m));
1232 mlen = min (m->m_len - off, len);
1233 if ((m->m_flags & M_EXTPG) != 0)
1234 m_copytounmapped(m, off, mlen, cp);
1236 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1244 if (m->m_next == NULL) {
1245 n = m_get(M_NOWAIT, m->m_type);
1248 n->m_len = min(MLEN, len);
1253 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1254 m->m_pkthdr.len = totlen;
1258 * Append the specified data to the indicated mbuf chain,
1259 * Extend the mbuf chain if the new data does not fit in
1262 * Return 1 if able to complete the job; otherwise 0.
1265 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1268 int remainder, space;
1270 for (m = m0; m->m_next != NULL; m = m->m_next)
1273 space = M_TRAILINGSPACE(m);
1276 * Copy into available space.
1278 if (space > remainder)
1280 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1282 cp += space, remainder -= space;
1284 while (remainder > 0) {
1286 * Allocate a new mbuf; could check space
1287 * and allocate a cluster instead.
1289 n = m_get(M_NOWAIT, m->m_type);
1292 n->m_len = min(MLEN, remainder);
1293 bcopy(cp, mtod(n, caddr_t), n->m_len);
1294 cp += n->m_len, remainder -= n->m_len;
1298 if (m0->m_flags & M_PKTHDR)
1299 m0->m_pkthdr.len += len - remainder;
1300 return (remainder == 0);
1304 m_apply_extpg_one(struct mbuf *m, int off, int len,
1305 int (*f)(void *, void *, u_int), void *arg)
1308 u_int i, count, pgoff, pglen;
1311 KASSERT(PMAP_HAS_DMAP,
1312 ("m_apply_extpg_one does not support unmapped mbufs"));
1313 off += mtod(m, vm_offset_t);
1314 if (off < m->m_epg_hdrlen) {
1315 count = min(m->m_epg_hdrlen - off, len);
1316 rval = f(arg, m->m_epg_hdr + off, count);
1322 off -= m->m_epg_hdrlen;
1323 pgoff = m->m_epg_1st_off;
1324 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
1325 pglen = m_epg_pagelen(m, i, pgoff);
1327 count = min(pglen - off, len);
1328 p = (void *)PHYS_TO_DMAP(m->m_epg_pa[i] + pgoff + off);
1329 rval = f(arg, p, count);
1339 KASSERT(off < m->m_epg_trllen,
1340 ("m_apply_extpg_one: offset beyond trailer"));
1341 KASSERT(len <= m->m_epg_trllen - off,
1342 ("m_apply_extpg_one: length beyond trailer"));
1343 return (f(arg, m->m_epg_trail + off, len));
1348 /* Apply function f to the data in a single mbuf. */
1350 m_apply_one(struct mbuf *m, int off, int len,
1351 int (*f)(void *, void *, u_int), void *arg)
1353 if ((m->m_flags & M_EXTPG) != 0)
1354 return (m_apply_extpg_one(m, off, len, f, arg));
1356 return (f(arg, mtod(m, caddr_t) + off, len));
1360 * Apply function f to the data in an mbuf chain starting "off" bytes from
1361 * the beginning, continuing for "len" bytes.
1364 m_apply(struct mbuf *m, int off, int len,
1365 int (*f)(void *, void *, u_int), void *arg)
1370 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1371 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1373 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1380 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1381 count = min(m->m_len - off, len);
1382 rval = m_apply_one(m, off, count, f, arg);
1393 * Return a pointer to mbuf/offset of location in mbuf chain.
1396 m_getptr(struct mbuf *m, int loc, int *off)
1400 /* Normal end of search. */
1401 if (m->m_len > loc) {
1406 if (m->m_next == NULL) {
1408 /* Point at the end of valid data. */
1421 m_print(const struct mbuf *m, int maxlen)
1425 const struct mbuf *m2;
1428 printf("mbuf: %p\n", m);
1432 if (m->m_flags & M_PKTHDR)
1433 len = m->m_pkthdr.len;
1437 while (m2 != NULL && (len == -1 || len)) {
1439 if (maxlen != -1 && pdata > maxlen)
1441 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1442 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1443 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1444 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1446 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1452 printf("%d bytes unaccounted for.\n", len);
1457 m_fixhdr(struct mbuf *m0)
1461 len = m_length(m0, NULL);
1462 m0->m_pkthdr.len = len;
1467 m_length(struct mbuf *m0, struct mbuf **last)
1473 for (m = m0; m != NULL; m = m->m_next) {
1475 if (m->m_next == NULL)
1484 * Defragment a mbuf chain, returning the shortest possible
1485 * chain of mbufs and clusters. If allocation fails and
1486 * this cannot be completed, NULL will be returned, but
1487 * the passed in chain will be unchanged. Upon success,
1488 * the original chain will be freed, and the new chain
1491 * If a non-packet header is passed in, the original
1492 * mbuf (chain?) will be returned unharmed.
1495 m_defrag(struct mbuf *m0, int how)
1497 struct mbuf *m_new = NULL, *m_final = NULL;
1498 int progress = 0, length;
1500 MBUF_CHECKSLEEP(how);
1501 if (!(m0->m_flags & M_PKTHDR))
1504 m_fixhdr(m0); /* Needed sanity check */
1506 #ifdef MBUF_STRESS_TEST
1507 if (m_defragrandomfailures) {
1508 int temp = arc4random() & 0xff;
1514 if (m0->m_pkthdr.len > MHLEN)
1515 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1517 m_final = m_gethdr(how, MT_DATA);
1519 if (m_final == NULL)
1522 if (m_dup_pkthdr(m_final, m0, how) == 0)
1527 while (progress < m0->m_pkthdr.len) {
1528 length = m0->m_pkthdr.len - progress;
1529 if (length > MCLBYTES)
1532 if (m_new == NULL) {
1534 m_new = m_getcl(how, MT_DATA, 0);
1536 m_new = m_get(how, MT_DATA);
1541 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1543 m_new->m_len = length;
1544 if (m_new != m_final)
1545 m_cat(m_final, m_new);
1548 #ifdef MBUF_STRESS_TEST
1549 if (m0->m_next == NULL)
1554 #ifdef MBUF_STRESS_TEST
1556 m_defragbytes += m0->m_pkthdr.len;
1560 #ifdef MBUF_STRESS_TEST
1569 * Return the number of fragments an mbuf will use. This is usually
1570 * used as a proxy for the number of scatter/gather elements needed by
1571 * a DMA engine to access an mbuf. In general mapped mbufs are
1572 * assumed to be backed by physically contiguous buffers that only
1573 * need a single fragment. Unmapped mbufs, on the other hand, can
1574 * span disjoint physical pages.
1577 frags_per_mbuf(struct mbuf *m)
1581 if ((m->m_flags & M_EXTPG) == 0)
1585 * The header and trailer are counted as a single fragment
1586 * each when present.
1588 * XXX: This overestimates the number of fragments by assuming
1589 * all the backing physical pages are disjoint.
1592 if (m->m_epg_hdrlen != 0)
1594 frags += m->m_epg_npgs;
1595 if (m->m_epg_trllen != 0)
1602 * Defragment an mbuf chain, returning at most maxfrags separate
1603 * mbufs+clusters. If this is not possible NULL is returned and
1604 * the original mbuf chain is left in its present (potentially
1605 * modified) state. We use two techniques: collapsing consecutive
1606 * mbufs and replacing consecutive mbufs by a cluster.
1608 * NB: this should really be named m_defrag but that name is taken
1611 m_collapse(struct mbuf *m0, int how, int maxfrags)
1613 struct mbuf *m, *n, *n2, **prev;
1617 * Calculate the current number of frags.
1620 for (m = m0; m != NULL; m = m->m_next)
1621 curfrags += frags_per_mbuf(m);
1623 * First, try to collapse mbufs. Note that we always collapse
1624 * towards the front so we don't need to deal with moving the
1625 * pkthdr. This may be suboptimal if the first mbuf has much
1626 * less data than the following.
1634 if (M_WRITABLE(m) &&
1635 n->m_len < M_TRAILINGSPACE(m)) {
1636 m_copydata(n, 0, n->m_len,
1637 mtod(m, char *) + m->m_len);
1638 m->m_len += n->m_len;
1639 m->m_next = n->m_next;
1640 curfrags -= frags_per_mbuf(n);
1642 if (curfrags <= maxfrags)
1647 KASSERT(maxfrags > 1,
1648 ("maxfrags %u, but normal collapse failed", maxfrags));
1650 * Collapse consecutive mbufs to a cluster.
1652 prev = &m0->m_next; /* NB: not the first mbuf */
1653 while ((n = *prev) != NULL) {
1654 if ((n2 = n->m_next) != NULL &&
1655 n->m_len + n2->m_len < MCLBYTES) {
1656 m = m_getcl(how, MT_DATA, 0);
1659 m_copydata(n, 0, n->m_len, mtod(m, char *));
1660 m_copydata(n2, 0, n2->m_len,
1661 mtod(m, char *) + n->m_len);
1662 m->m_len = n->m_len + n2->m_len;
1663 m->m_next = n2->m_next;
1665 curfrags += 1; /* For the new cluster */
1666 curfrags -= frags_per_mbuf(n);
1667 curfrags -= frags_per_mbuf(n2);
1670 if (curfrags <= maxfrags)
1673 * Still not there, try the normal collapse
1674 * again before we allocate another cluster.
1681 * No place where we can collapse to a cluster; punt.
1682 * This can occur if, for example, you request 2 frags
1683 * but the packet requires that both be clusters (we
1684 * never reallocate the first mbuf to avoid moving the
1691 #ifdef MBUF_STRESS_TEST
1694 * Fragment an mbuf chain. There's no reason you'd ever want to do
1695 * this in normal usage, but it's great for stress testing various
1698 * If fragmentation is not possible, the original chain will be
1701 * Possible length values:
1702 * 0 no fragmentation will occur
1703 * > 0 each fragment will be of the specified length
1704 * -1 each fragment will be the same random value in length
1705 * -2 each fragment's length will be entirely random
1706 * (Random values range from 1 to 256)
1709 m_fragment(struct mbuf *m0, int how, int length)
1711 struct mbuf *m_first, *m_last;
1712 int divisor = 255, progress = 0, fraglen;
1714 if (!(m0->m_flags & M_PKTHDR))
1717 if (length == 0 || length < -2)
1719 if (length > MCLBYTES)
1721 if (length < 0 && divisor > MCLBYTES)
1724 length = 1 + (arc4random() % divisor);
1728 m_fixhdr(m0); /* Needed sanity check */
1730 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1731 if (m_first == NULL)
1734 if (m_dup_pkthdr(m_first, m0, how) == 0)
1739 while (progress < m0->m_pkthdr.len) {
1741 fraglen = 1 + (arc4random() % divisor);
1742 if (fraglen > m0->m_pkthdr.len - progress)
1743 fraglen = m0->m_pkthdr.len - progress;
1745 if (progress != 0) {
1746 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1750 m_last->m_next = m_new;
1754 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1755 progress += fraglen;
1756 m_last->m_len = fraglen;
1764 /* Return the original chain on failure */
1771 * Free pages from mbuf_ext_pgs, assuming they were allocated via
1772 * vm_page_alloc() and aren't associated with any object. Complement
1773 * to allocator from m_uiotombuf_nomap().
1776 mb_free_mext_pgs(struct mbuf *m)
1781 for (int i = 0; i < m->m_epg_npgs; i++) {
1782 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1783 vm_page_unwire_noq(pg);
1788 static struct mbuf *
1789 m_uiotombuf_nomap(struct uio *uio, int how, int len, int maxseg, int flags)
1791 struct mbuf *m, *mb, *prev;
1792 vm_page_t pg_array[MBUF_PEXT_MAX_PGS];
1793 int error, length, i, needed;
1795 int pflags = malloc2vm_flags(how) | VM_ALLOC_NODUMP | VM_ALLOC_WIRED;
1797 MPASS((flags & M_PKTHDR) == 0);
1798 MPASS((how & M_ZERO) == 0);
1801 * len can be zero or an arbitrary large value bound by
1802 * the total data supplied by the uio.
1805 total = MIN(uio->uio_resid, len);
1807 total = uio->uio_resid;
1810 maxseg = MBUF_PEXT_MAX_PGS * PAGE_SIZE;
1813 * If total is zero, return an empty mbuf. This can occur
1814 * for TLS 1.0 connections which send empty fragments as
1815 * a countermeasure against the known-IV weakness in CBC
1818 if (__predict_false(total == 0)) {
1819 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1822 mb->m_epg_flags = EPG_FLAG_ANON;
1827 * Allocate the pages
1831 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1839 mb->m_epg_flags = EPG_FLAG_ANON;
1840 needed = length = MIN(maxseg, total);
1841 for (i = 0; needed > 0; i++, needed -= PAGE_SIZE) {
1843 pg_array[i] = vm_page_alloc_noobj(pflags);
1844 if (pg_array[i] == NULL) {
1845 if (how & M_NOWAIT) {
1852 mb->m_epg_pa[i] = VM_PAGE_TO_PHYS(pg_array[i]);
1855 mb->m_epg_last_len = length - PAGE_SIZE * (mb->m_epg_npgs - 1);
1856 MBUF_EXT_PGS_ASSERT_SANITY(mb);
1858 error = uiomove_fromphys(pg_array, 0, length, uio);
1862 mb->m_ext.ext_size += PAGE_SIZE * mb->m_epg_npgs;
1863 if (flags & M_PKTHDR)
1864 m->m_pkthdr.len += length;
1874 * Copy the contents of uio into a properly sized mbuf chain.
1877 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1879 struct mbuf *m, *mb;
1884 if (flags & M_EXTPG)
1885 return (m_uiotombuf_nomap(uio, how, len, align, flags));
1888 * len can be zero or an arbitrary large value bound by
1889 * the total data supplied by the uio.
1892 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1894 total = uio->uio_resid;
1897 * The smallest unit returned by m_getm2() is a single mbuf
1898 * with pkthdr. We can't align past it.
1904 * Give us the full allocation or nothing.
1905 * If len is zero return the smallest empty mbuf.
1907 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1912 /* Fill all mbufs with uio data and update header information. */
1913 for (mb = m; mb != NULL; mb = mb->m_next) {
1914 length = min(M_TRAILINGSPACE(mb), total - progress);
1916 error = uiomove(mtod(mb, void *), length, uio);
1924 if (flags & M_PKTHDR) {
1925 m->m_pkthdr.len += length;
1926 m->m_pkthdr.memlen += MSIZE;
1927 if (mb->m_flags & M_EXT)
1928 m->m_pkthdr.memlen += mb->m_ext.ext_size;
1931 KASSERT(progress == total, ("%s: progress != total", __func__));
1937 * Copy data to/from an unmapped mbuf into a uio limited by len if set.
1940 m_unmapped_uiomove(const struct mbuf *m, int m_off, struct uio *uio, int len)
1943 int error, i, off, pglen, pgoff, seglen, segoff;
1948 /* Skip over any data removed from the front. */
1949 off = mtod(m, vm_offset_t);
1952 if (m->m_epg_hdrlen != 0) {
1953 if (off >= m->m_epg_hdrlen) {
1954 off -= m->m_epg_hdrlen;
1956 seglen = m->m_epg_hdrlen - off;
1958 seglen = min(seglen, len);
1961 error = uiomove(__DECONST(void *,
1962 &m->m_epg_hdr[segoff]), seglen, uio);
1965 pgoff = m->m_epg_1st_off;
1966 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
1967 pglen = m_epg_pagelen(m, i, pgoff);
1973 seglen = pglen - off;
1974 segoff = pgoff + off;
1976 seglen = min(seglen, len);
1978 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1979 error = uiomove_fromphys(&pg, segoff, seglen, uio);
1982 if (len != 0 && error == 0) {
1983 KASSERT((off + len) <= m->m_epg_trllen,
1984 ("off + len > trail (%d + %d > %d, m_off = %d)", off, len,
1985 m->m_epg_trllen, m_off));
1986 error = uiomove(__DECONST(void *, &m->m_epg_trail[off]),
1993 * Copy an mbuf chain into a uio limited by len if set.
1996 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
1998 int error, length, total;
2002 total = min(uio->uio_resid, len);
2004 total = uio->uio_resid;
2006 /* Fill the uio with data from the mbufs. */
2007 for (; m != NULL; m = m->m_next) {
2008 length = min(m->m_len, total - progress);
2010 if ((m->m_flags & M_EXTPG) != 0)
2011 error = m_unmapped_uiomove(m, 0, uio, length);
2013 error = uiomove(mtod(m, void *), length, uio);
2024 * Create a writable copy of the mbuf chain. While doing this
2025 * we compact the chain with a goal of producing a chain with
2026 * at most two mbufs. The second mbuf in this chain is likely
2027 * to be a cluster. The primary purpose of this work is to create
2028 * a writable packet for encryption, compression, etc. The
2029 * secondary goal is to linearize the data so the data can be
2030 * passed to crypto hardware in the most efficient manner possible.
2033 m_unshare(struct mbuf *m0, int how)
2035 struct mbuf *m, *mprev;
2036 struct mbuf *n, *mfirst, *mlast;
2040 for (m = m0; m != NULL; m = mprev->m_next) {
2042 * Regular mbufs are ignored unless there's a cluster
2043 * in front of it that we can use to coalesce. We do
2044 * the latter mainly so later clusters can be coalesced
2045 * also w/o having to handle them specially (i.e. convert
2046 * mbuf+cluster -> cluster). This optimization is heavily
2047 * influenced by the assumption that we're running over
2048 * Ethernet where MCLBYTES is large enough that the max
2049 * packet size will permit lots of coalescing into a
2050 * single cluster. This in turn permits efficient
2051 * crypto operations, especially when using hardware.
2053 if ((m->m_flags & M_EXT) == 0) {
2054 if (mprev && (mprev->m_flags & M_EXT) &&
2055 m->m_len <= M_TRAILINGSPACE(mprev)) {
2056 /* XXX: this ignores mbuf types */
2057 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2058 mtod(m, caddr_t), m->m_len);
2059 mprev->m_len += m->m_len;
2060 mprev->m_next = m->m_next; /* unlink from chain */
2061 m_free(m); /* reclaim mbuf */
2068 * Writable mbufs are left alone (for now).
2070 if (M_WRITABLE(m)) {
2076 * Not writable, replace with a copy or coalesce with
2077 * the previous mbuf if possible (since we have to copy
2078 * it anyway, we try to reduce the number of mbufs and
2079 * clusters so that future work is easier).
2081 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
2082 /* NB: we only coalesce into a cluster or larger */
2083 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
2084 m->m_len <= M_TRAILINGSPACE(mprev)) {
2085 /* XXX: this ignores mbuf types */
2086 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2087 mtod(m, caddr_t), m->m_len);
2088 mprev->m_len += m->m_len;
2089 mprev->m_next = m->m_next; /* unlink from chain */
2090 m_free(m); /* reclaim mbuf */
2095 * Allocate new space to hold the copy and copy the data.
2096 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
2097 * splitting them into clusters. We could just malloc a
2098 * buffer and make it external but too many device drivers
2099 * don't know how to break up the non-contiguous memory when
2102 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2107 if (m->m_flags & M_PKTHDR) {
2108 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
2110 m_move_pkthdr(n, m);
2117 int cc = min(len, MCLBYTES);
2118 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2124 newipsecstat.ips_clcopied++;
2132 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2139 n->m_next = m->m_next;
2141 m0 = mfirst; /* new head of chain */
2143 mprev->m_next = mfirst; /* replace old mbuf */
2144 m_free(m); /* release old mbuf */
2150 #ifdef MBUF_PROFILING
2152 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2153 struct mbufprofile {
2154 uintmax_t wasted[MP_BUCKETS];
2155 uintmax_t used[MP_BUCKETS];
2156 uintmax_t segments[MP_BUCKETS];
2160 m_profile(struct mbuf *m)
2169 if (m->m_flags & M_EXT) {
2170 wasted += MHLEN - sizeof(m->m_ext) +
2171 m->m_ext.ext_size - m->m_len;
2173 if (m->m_flags & M_PKTHDR)
2174 wasted += MHLEN - m->m_len;
2176 wasted += MLEN - m->m_len;
2180 /* be paranoid.. it helps */
2181 if (segments > MP_BUCKETS - 1)
2182 segments = MP_BUCKETS - 1;
2185 if (wasted > 100000)
2187 /* store in the appropriate bucket */
2188 /* don't bother locking. if it's slightly off, so what? */
2189 mbprof.segments[segments]++;
2190 mbprof.used[fls(used)]++;
2191 mbprof.wasted[fls(wasted)]++;
2195 mbprof_handler(SYSCTL_HANDLER_ARGS)
2202 sbuf_new_for_sysctl(&sb, buf, sizeof(buf), req);
2204 p = &mbprof.wasted[0];
2207 "%ju %ju %ju %ju %ju %ju %ju %ju "
2208 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2209 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2210 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2212 p = &mbprof.wasted[16];
2214 "%ju %ju %ju %ju %ju %ju %ju %ju "
2215 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2216 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2217 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2219 p = &mbprof.used[0];
2222 "%ju %ju %ju %ju %ju %ju %ju %ju "
2223 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2224 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2225 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2227 p = &mbprof.used[16];
2229 "%ju %ju %ju %ju %ju %ju %ju %ju "
2230 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2231 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2232 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2234 p = &mbprof.segments[0];
2237 "%ju %ju %ju %ju %ju %ju %ju %ju "
2238 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2239 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2240 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2242 p = &mbprof.segments[16];
2244 "%ju %ju %ju %ju %ju %ju %ju %ju "
2245 "%ju %ju %ju %ju %ju %ju %ju %jju",
2246 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2247 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2250 error = sbuf_finish(&sb);
2256 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2261 error = sysctl_handle_int(oidp, &clear, 0, req);
2262 if (error || !req->newptr)
2266 bzero(&mbprof, sizeof(mbprof));
2272 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile,
2273 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2274 mbprof_handler, "A",
2275 "mbuf profiling statistics");
2277 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr,
2278 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
2279 mbprof_clr_handler, "I",
2280 "clear mbuf profiling statistics");