2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_param.h"
38 #include "opt_mbuf_stress_test.h"
39 #include "opt_mbuf_profiling.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/limits.h>
46 #include <sys/malloc.h>
48 #include <sys/sysctl.h>
49 #include <sys/domain.h>
50 #include <sys/protosw.h>
52 #include <sys/vmmeter.h>
55 #include <vm/vm_pageout.h>
56 #include <vm/vm_page.h>
58 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__init,
59 "struct mbuf *", "mbufinfo_t *",
60 "uint32_t", "uint32_t",
61 "uint16_t", "uint16_t",
62 "uint32_t", "uint32_t",
63 "uint32_t", "uint32_t");
65 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr_raw,
66 "uint32_t", "uint32_t",
67 "uint16_t", "uint16_t",
68 "struct mbuf *", "mbufinfo_t *");
70 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr,
71 "uint32_t", "uint32_t",
72 "uint16_t", "uint16_t",
73 "struct mbuf *", "mbufinfo_t *");
75 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get_raw,
76 "uint32_t", "uint32_t",
77 "uint16_t", "uint16_t",
78 "struct mbuf *", "mbufinfo_t *");
80 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
81 "uint32_t", "uint32_t",
82 "uint16_t", "uint16_t",
83 "struct mbuf *", "mbufinfo_t *");
85 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
86 "uint32_t", "uint32_t",
87 "uint16_t", "uint16_t",
88 "uint32_t", "uint32_t",
89 "struct mbuf *", "mbufinfo_t *");
91 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__getjcl,
92 "uint32_t", "uint32_t",
93 "uint16_t", "uint16_t",
94 "uint32_t", "uint32_t",
95 "uint32_t", "uint32_t",
96 "struct mbuf *", "mbufinfo_t *");
98 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
99 "struct mbuf *", "mbufinfo_t *",
100 "uint32_t", "uint32_t",
101 "uint32_t", "uint32_t");
103 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
104 "struct mbuf *", "mbufinfo_t *",
105 "uint32_t", "uint32_t",
106 "uint32_t", "uint32_t",
109 SDT_PROBE_DEFINE(sdt, , , m__cljset);
111 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
112 "struct mbuf *", "mbufinfo_t *");
114 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
115 "struct mbuf *", "mbufinfo_t *");
117 #include <security/mac/mac_framework.h>
123 #ifdef MBUF_STRESS_TEST
128 int m_defragrandomfailures;
132 * sysctl(8) exported objects
134 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
135 &max_linkhdr, 0, "Size of largest link layer header");
136 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
137 &max_protohdr, 0, "Size of largest protocol layer header");
138 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
139 &max_hdr, 0, "Size of largest link plus protocol header");
140 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
141 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
142 #ifdef MBUF_STRESS_TEST
143 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
144 &m_defragpackets, 0, "");
145 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
146 &m_defragbytes, 0, "");
147 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
148 &m_defraguseless, 0, "");
149 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
150 &m_defragfailure, 0, "");
151 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
152 &m_defragrandomfailures, 0, "");
156 * Ensure the correct size of various mbuf parameters. It could be off due
157 * to compiler-induced padding and alignment artifacts.
159 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
160 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
163 * mbuf data storage should be 64-bit aligned regardless of architectural
164 * pointer size; check this is the case with and without a packet header.
166 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
167 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
170 * While the specific values here don't matter too much (i.e., +/- a few
171 * words), we do want to ensure that changes to these values are carefully
172 * reasoned about and properly documented. This is especially the case as
173 * network-protocol and device-driver modules encode these layouts, and must
174 * be recompiled if the structures change. Check these values at compile time
175 * against the ones documented in comments in mbuf.h.
177 * NB: Possibly they should be documented there via #define's and not just
180 #if defined(__LP64__)
181 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
182 CTASSERT(sizeof(struct pkthdr) == 56);
183 CTASSERT(sizeof(struct m_ext) == 160);
185 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
186 CTASSERT(sizeof(struct pkthdr) == 48);
187 #if defined(__powerpc__) && defined(BOOKE)
188 /* PowerPC booke has 64-bit physical pointers. */
189 CTASSERT(sizeof(struct m_ext) == 184);
191 CTASSERT(sizeof(struct m_ext) == 180);
196 * Assert that the queue(3) macros produce code of the same size as an old
197 * plain pointer does.
200 static struct mbuf __used m_assertbuf;
201 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
202 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
203 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
204 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
208 * Attach the cluster from *m to *n, set up m_ext in *n
209 * and bump the refcount of the cluster.
212 mb_dupcl(struct mbuf *n, struct mbuf *m)
214 volatile u_int *refcnt;
216 KASSERT(m->m_flags & (M_EXT|M_EXTPG),
217 ("%s: M_EXT|M_EXTPG not set on %p", __func__, m));
218 KASSERT(!(n->m_flags & (M_EXT|M_EXTPG)),
219 ("%s: M_EXT|M_EXTPG set on %p", __func__, n));
222 * Cache access optimization.
224 * o Regular M_EXT storage doesn't need full copy of m_ext, since
225 * the holder of the 'ext_count' is responsible to carry the free
226 * routine and its arguments.
227 * o M_EXTPG data is split between main part of mbuf and m_ext, the
228 * main part is copied in full, the m_ext part is similar to M_EXT.
229 * o EXT_EXTREF, where 'ext_cnt' doesn't point into mbuf at all, is
230 * special - it needs full copy of m_ext into each mbuf, since any
231 * copy could end up as the last to free.
233 if (m->m_flags & M_EXTPG) {
234 bcopy(&m->m_epg_startcopy, &n->m_epg_startcopy,
235 __rangeof(struct mbuf, m_epg_startcopy, m_epg_endcopy));
236 bcopy(&m->m_ext, &n->m_ext, m_epg_ext_copylen);
237 } else if (m->m_ext.ext_type == EXT_EXTREF)
238 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
240 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
242 n->m_flags |= m->m_flags & (M_RDONLY | M_EXT | M_EXTPG);
244 /* See if this is the mbuf that holds the embedded refcount. */
245 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
246 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
247 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
249 KASSERT(m->m_ext.ext_cnt != NULL,
250 ("%s: no refcounting pointer on %p", __func__, m));
251 refcnt = m->m_ext.ext_cnt;
257 atomic_add_int(refcnt, 1);
261 m_demote_pkthdr(struct mbuf *m)
266 m_tag_delete_chain(m, NULL);
267 m->m_flags &= ~M_PKTHDR;
268 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
272 * Clean up mbuf (chain) from any tags and packet headers.
273 * If "all" is set then the first mbuf in the chain will be
277 m_demote(struct mbuf *m0, int all, int flags)
281 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
282 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
284 if (m->m_flags & M_PKTHDR)
286 m->m_flags = m->m_flags & (M_EXT | M_RDONLY | M_NOFREE |
292 * Sanity checks on mbuf (chain) for use in KASSERT() and general
294 * Returns 0 or panics when bad and 1 on all tests passed.
295 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
299 m_sanity(struct mbuf *m0, int sanitize)
306 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
308 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
311 for (m = m0; m != NULL; m = m->m_next) {
313 * Basic pointer checks. If any of these fails then some
314 * unrelated kernel memory before or after us is trashed.
315 * No way to recover from that.
319 if ((caddr_t)m->m_data < a)
320 M_SANITY_ACTION("m_data outside mbuf data range left");
321 if ((caddr_t)m->m_data > b)
322 M_SANITY_ACTION("m_data outside mbuf data range right");
323 if ((caddr_t)m->m_data + m->m_len > b)
324 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
326 /* m->m_nextpkt may only be set on first mbuf in chain. */
327 if (m != m0 && m->m_nextpkt != NULL) {
329 m_freem(m->m_nextpkt);
330 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
332 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
335 /* packet length (not mbuf length!) calculation */
336 if (m0->m_flags & M_PKTHDR)
339 /* m_tags may only be attached to first mbuf in chain. */
340 if (m != m0 && m->m_flags & M_PKTHDR &&
341 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
343 m_tag_delete_chain(m, NULL);
344 /* put in 0xDEADC0DE perhaps? */
346 M_SANITY_ACTION("m_tags on in-chain mbuf");
349 /* M_PKTHDR may only be set on first mbuf in chain */
350 if (m != m0 && m->m_flags & M_PKTHDR) {
352 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
353 m->m_flags &= ~M_PKTHDR;
354 /* put in 0xDEADCODE and leave hdr flag in */
356 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
360 if (pktlen && pktlen != m->m_pkthdr.len) {
364 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
368 #undef M_SANITY_ACTION
372 * Non-inlined part of m_init().
375 m_pkthdr_init(struct mbuf *m, int how)
380 m->m_data = m->m_pktdat;
381 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
383 m->m_pkthdr.numa_domain = M_NODOM;
386 /* If the label init fails, fail the alloc */
387 error = mac_mbuf_init(m, how);
396 * "Move" mbuf pkthdr from "from" to "to".
397 * "from" must have M_PKTHDR set, and "to" must be empty.
400 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
404 /* see below for why these are not enabled */
406 /* Note: with MAC, this may not be a good assertion. */
407 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
408 ("m_move_pkthdr: to has tags"));
412 * XXXMAC: It could be this should also occur for non-MAC?
414 if (to->m_flags & M_PKTHDR)
415 m_tag_delete_chain(to, NULL);
417 to->m_flags = (from->m_flags & M_COPYFLAGS) |
418 (to->m_flags & (M_EXT | M_EXTPG));
419 if ((to->m_flags & M_EXT) == 0)
420 to->m_data = to->m_pktdat;
421 to->m_pkthdr = from->m_pkthdr; /* especially tags */
422 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
423 from->m_flags &= ~M_PKTHDR;
424 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG) {
425 from->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
426 from->m_pkthdr.snd_tag = NULL;
431 * Duplicate "from"'s mbuf pkthdr in "to".
432 * "from" must have M_PKTHDR set, and "to" must be empty.
433 * In particular, this does a deep copy of the packet tags.
436 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
441 * The mbuf allocator only initializes the pkthdr
442 * when the mbuf is allocated with m_gethdr(). Many users
443 * (e.g. m_copy*, m_prepend) use m_get() and then
444 * smash the pkthdr as needed causing these
445 * assertions to trip. For now just disable them.
448 /* Note: with MAC, this may not be a good assertion. */
449 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
451 MBUF_CHECKSLEEP(how);
453 if (to->m_flags & M_PKTHDR)
454 m_tag_delete_chain(to, NULL);
456 to->m_flags = (from->m_flags & M_COPYFLAGS) |
457 (to->m_flags & (M_EXT | M_EXTPG));
458 if ((to->m_flags & M_EXT) == 0)
459 to->m_data = to->m_pktdat;
460 to->m_pkthdr = from->m_pkthdr;
461 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG)
462 m_snd_tag_ref(from->m_pkthdr.snd_tag);
463 SLIST_INIT(&to->m_pkthdr.tags);
464 return (m_tag_copy_chain(to, from, how));
468 * Lesser-used path for M_PREPEND:
469 * allocate new mbuf to prepend to chain,
473 m_prepend(struct mbuf *m, int len, int how)
477 if (m->m_flags & M_PKTHDR)
478 mn = m_gethdr(how, m->m_type);
480 mn = m_get(how, m->m_type);
485 if (m->m_flags & M_PKTHDR)
486 m_move_pkthdr(mn, m);
496 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
497 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
498 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
499 * Note that the copy is read-only, because clusters are not copied,
500 * only their reference counts are incremented.
503 m_copym(struct mbuf *m, int off0, int len, int wait)
505 struct mbuf *n, **np;
510 KASSERT(off >= 0, ("m_copym, negative off %d", off));
511 KASSERT(len >= 0, ("m_copym, negative len %d", len));
512 MBUF_CHECKSLEEP(wait);
513 if (off == 0 && m->m_flags & M_PKTHDR)
516 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
526 KASSERT(len == M_COPYALL,
527 ("m_copym, length > size of mbuf chain"));
531 n = m_gethdr(wait, m->m_type);
533 n = m_get(wait, m->m_type);
538 if (!m_dup_pkthdr(n, m, wait))
540 if (len == M_COPYALL)
541 n->m_pkthdr.len -= off0;
543 n->m_pkthdr.len = len;
546 n->m_len = min(len, m->m_len - off);
547 if (m->m_flags & (M_EXT|M_EXTPG)) {
548 n->m_data = m->m_data + off;
551 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
553 if (len != M_COPYALL)
567 * Copy an entire packet, including header (which must be present).
568 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
569 * Note that the copy is read-only, because clusters are not copied,
570 * only their reference counts are incremented.
571 * Preserve alignment of the first mbuf so if the creator has left
572 * some room at the beginning (e.g. for inserting protocol headers)
573 * the copies still have the room available.
576 m_copypacket(struct mbuf *m, int how)
578 struct mbuf *top, *n, *o;
580 MBUF_CHECKSLEEP(how);
581 n = m_get(how, m->m_type);
586 if (!m_dup_pkthdr(n, m, how))
589 if (m->m_flags & (M_EXT|M_EXTPG)) {
590 n->m_data = m->m_data;
593 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
594 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
599 o = m_get(how, m->m_type);
607 if (m->m_flags & (M_EXT|M_EXTPG)) {
608 n->m_data = m->m_data;
611 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
623 m_copyfromunmapped(const struct mbuf *m, int off, int len, caddr_t cp)
629 KASSERT(off >= 0, ("m_copyfromunmapped: negative off %d", off));
630 KASSERT(len >= 0, ("m_copyfromunmapped: negative len %d", len));
631 KASSERT(off < m->m_len,
632 ("m_copyfromunmapped: len exceeds mbuf length"));
637 uio.uio_segflg = UIO_SYSSPACE;
640 uio.uio_rw = UIO_READ;
641 error = m_unmapped_uiomove(m, off, &uio, len);
642 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
647 * Copy data from an mbuf chain starting "off" bytes from the beginning,
648 * continuing for "len" bytes, into the indicated buffer.
651 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
655 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
656 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
658 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
665 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
666 count = min(m->m_len - off, len);
667 if ((m->m_flags & M_EXTPG) != 0)
668 m_copyfromunmapped(m, off, count, cp);
670 bcopy(mtod(m, caddr_t) + off, cp, count);
679 * Copy a packet header mbuf chain into a completely new chain, including
680 * copying any mbuf clusters. Use this instead of m_copypacket() when
681 * you need a writable copy of an mbuf chain.
684 m_dup(const struct mbuf *m, int how)
686 struct mbuf **p, *top = NULL;
687 int remain, moff, nsize;
689 MBUF_CHECKSLEEP(how);
695 /* While there's more data, get a new mbuf, tack it on, and fill it */
696 remain = m->m_pkthdr.len;
699 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
702 /* Get the next new mbuf */
703 if (remain >= MINCLSIZE) {
704 n = m_getcl(how, m->m_type, 0);
707 n = m_get(how, m->m_type);
713 if (top == NULL) { /* First one, must be PKTHDR */
714 if (!m_dup_pkthdr(n, m, how)) {
718 if ((n->m_flags & M_EXT) == 0)
720 n->m_flags &= ~M_RDONLY;
724 /* Link it into the new chain */
728 /* Copy data from original mbuf(s) into new mbuf */
729 while (n->m_len < nsize && m != NULL) {
730 int chunk = min(nsize - n->m_len, m->m_len - moff);
732 m_copydata(m, moff, chunk, n->m_data + n->m_len);
736 if (moff == m->m_len) {
742 /* Check correct total mbuf length */
743 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
744 ("%s: bogus m_pkthdr.len", __func__));
754 * Concatenate mbuf chain n to m.
755 * Both chains must be of the same type (e.g. MT_DATA).
756 * Any m_pkthdr is not updated.
759 m_cat(struct mbuf *m, struct mbuf *n)
764 if (!M_WRITABLE(m) ||
765 (n->m_flags & M_EXTPG) != 0 ||
766 M_TRAILINGSPACE(m) < n->m_len) {
767 /* just join the two chains */
771 /* splat the data from one into the other */
772 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
774 m->m_len += n->m_len;
780 * Concatenate two pkthdr mbuf chains.
783 m_catpkt(struct mbuf *m, struct mbuf *n)
789 m->m_pkthdr.len += n->m_pkthdr.len;
796 m_adj(struct mbuf *mp, int req_len)
802 if ((m = mp) == NULL)
808 while (m != NULL && len > 0) {
809 if (m->m_len <= len) {
819 if (mp->m_flags & M_PKTHDR)
820 mp->m_pkthdr.len -= (req_len - len);
823 * Trim from tail. Scan the mbuf chain,
824 * calculating its length and finding the last mbuf.
825 * If the adjustment only affects this mbuf, then just
826 * adjust and return. Otherwise, rescan and truncate
827 * after the remaining size.
833 if (m->m_next == (struct mbuf *)0)
837 if (m->m_len >= len) {
839 if (mp->m_flags & M_PKTHDR)
840 mp->m_pkthdr.len -= len;
847 * Correct length for chain is "count".
848 * Find the mbuf with last data, adjust its length,
849 * and toss data from remaining mbufs on chain.
852 if (m->m_flags & M_PKTHDR)
853 m->m_pkthdr.len = count;
854 for (; m; m = m->m_next) {
855 if (m->m_len >= count) {
857 if (m->m_next != NULL) {
869 m_adj_decap(struct mbuf *mp, int len)
874 if ((mp->m_flags & M_PKTHDR) != 0) {
876 * If flowid was calculated by card from the inner
877 * headers, move flowid to the decapsulated mbuf
878 * chain, otherwise clear. This depends on the
879 * internals of m_adj, which keeps pkthdr as is, in
880 * particular not changing rsstype and flowid.
882 rsstype = mp->m_pkthdr.rsstype;
883 if ((rsstype & M_HASHTYPE_INNER) != 0) {
884 M_HASHTYPE_SET(mp, rsstype & ~M_HASHTYPE_INNER);
886 M_HASHTYPE_CLEAR(mp);
892 * Rearange an mbuf chain so that len bytes are contiguous
893 * and in the data area of an mbuf (so that mtod will work
894 * for a structure of size len). Returns the resulting
895 * mbuf chain on success, frees it and returns null on failure.
896 * If there is room, it will add up to max_protohdr-len extra bytes to the
897 * contiguous region in an attempt to avoid being called next time.
900 m_pullup(struct mbuf *n, int len)
906 KASSERT((n->m_flags & M_EXTPG) == 0,
907 ("%s: unmapped mbuf %p", __func__, n));
910 * If first mbuf has no cluster, and has room for len bytes
911 * without shifting current data, pullup into it,
912 * otherwise allocate a new mbuf to prepend to the chain.
914 if ((n->m_flags & M_EXT) == 0 &&
915 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
924 m = m_get(M_NOWAIT, n->m_type);
927 if (n->m_flags & M_PKTHDR)
930 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
932 count = min(min(max(len, max_protohdr), space), n->m_len);
933 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
943 } while (len > 0 && n);
956 * Like m_pullup(), except a new mbuf is always allocated, and we allow
957 * the amount of empty space before the data in the new mbuf to be specified
958 * (in the event that the caller expects to prepend later).
961 m_copyup(struct mbuf *n, int len, int dstoff)
966 if (len > (MHLEN - dstoff))
968 m = m_get(M_NOWAIT, n->m_type);
971 if (n->m_flags & M_PKTHDR)
974 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
976 count = min(min(max(len, max_protohdr), space), n->m_len);
977 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
987 } while (len > 0 && n);
1000 * Partition an mbuf chain in two pieces, returning the tail --
1001 * all but the first len0 bytes. In case of failure, it returns NULL and
1002 * attempts to restore the chain to its original state.
1004 * Note that the resulting mbufs might be read-only, because the new
1005 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1006 * the "breaking point" happens to lie within a cluster mbuf. Use the
1007 * M_WRITABLE() macro to check for this case.
1010 m_split(struct mbuf *m0, int len0, int wait)
1013 u_int len = len0, remain;
1015 MBUF_CHECKSLEEP(wait);
1016 for (m = m0; m && len > m->m_len; m = m->m_next)
1020 remain = m->m_len - len;
1021 if (m0->m_flags & M_PKTHDR && remain == 0) {
1022 n = m_gethdr(wait, m0->m_type);
1025 n->m_next = m->m_next;
1027 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1028 n->m_pkthdr.snd_tag =
1029 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1030 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1032 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1033 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1034 m0->m_pkthdr.len = len0;
1036 } else if (m0->m_flags & M_PKTHDR) {
1037 n = m_gethdr(wait, m0->m_type);
1040 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1041 n->m_pkthdr.snd_tag =
1042 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1043 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1045 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1046 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1047 m0->m_pkthdr.len = len0;
1048 if (m->m_flags & (M_EXT|M_EXTPG))
1050 if (remain > MHLEN) {
1051 /* m can't be the lead packet */
1053 n->m_next = m_split(m, len, wait);
1054 if (n->m_next == NULL) {
1063 } else if (remain == 0) {
1068 n = m_get(wait, m->m_type);
1074 if (m->m_flags & (M_EXT|M_EXTPG)) {
1075 n->m_data = m->m_data + len;
1078 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1082 n->m_next = m->m_next;
1087 * Routine to copy from device local memory into mbufs.
1088 * Note that `off' argument is offset into first mbuf of target chain from
1089 * which to begin copying the data to.
1092 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1093 void (*copy)(char *from, caddr_t to, u_int len))
1096 struct mbuf *top = NULL, **mp = ⊤
1099 if (off < 0 || off > MHLEN)
1102 while (totlen > 0) {
1103 if (top == NULL) { /* First one, must be PKTHDR */
1104 if (totlen + off >= MINCLSIZE) {
1105 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1108 m = m_gethdr(M_NOWAIT, MT_DATA);
1111 /* Place initial small packet/header at end of mbuf */
1112 if (m && totlen + off + max_linkhdr <= MHLEN) {
1113 m->m_data += max_linkhdr;
1119 m->m_pkthdr.rcvif = ifp;
1120 m->m_pkthdr.len = totlen;
1122 if (totlen + off >= MINCLSIZE) {
1123 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1126 m = m_get(M_NOWAIT, MT_DATA);
1139 m->m_len = len = min(totlen, len);
1141 copy(buf, mtod(m, caddr_t), (u_int)len);
1143 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1153 m_copytounmapped(const struct mbuf *m, int off, int len, c_caddr_t cp)
1159 KASSERT(off >= 0, ("m_copytounmapped: negative off %d", off));
1160 KASSERT(len >= 0, ("m_copytounmapped: negative len %d", len));
1161 KASSERT(off < m->m_len, ("m_copytounmapped: len exceeds mbuf length"));
1162 iov.iov_base = __DECONST(caddr_t, cp);
1164 uio.uio_resid = len;
1166 uio.uio_segflg = UIO_SYSSPACE;
1169 uio.uio_rw = UIO_WRITE;
1170 error = m_unmapped_uiomove(m, off, &uio, len);
1171 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
1176 * Copy data from a buffer back into the indicated mbuf chain,
1177 * starting "off" bytes from the beginning, extending the mbuf
1178 * chain if necessary.
1181 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1184 struct mbuf *m = m0, *n;
1189 while (off > (mlen = m->m_len)) {
1192 if (m->m_next == NULL) {
1193 n = m_get(M_NOWAIT, m->m_type);
1196 bzero(mtod(n, caddr_t), MLEN);
1197 n->m_len = min(MLEN, len + off);
1203 if (m->m_next == NULL && (len > m->m_len - off)) {
1204 m->m_len += min(len - (m->m_len - off),
1205 M_TRAILINGSPACE(m));
1207 mlen = min (m->m_len - off, len);
1208 if ((m->m_flags & M_EXTPG) != 0)
1209 m_copytounmapped(m, off, mlen, cp);
1211 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1219 if (m->m_next == NULL) {
1220 n = m_get(M_NOWAIT, m->m_type);
1223 n->m_len = min(MLEN, len);
1228 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1229 m->m_pkthdr.len = totlen;
1233 * Append the specified data to the indicated mbuf chain,
1234 * Extend the mbuf chain if the new data does not fit in
1237 * Return 1 if able to complete the job; otherwise 0.
1240 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1243 int remainder, space;
1245 for (m = m0; m->m_next != NULL; m = m->m_next)
1248 space = M_TRAILINGSPACE(m);
1251 * Copy into available space.
1253 if (space > remainder)
1255 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1257 cp += space, remainder -= space;
1259 while (remainder > 0) {
1261 * Allocate a new mbuf; could check space
1262 * and allocate a cluster instead.
1264 n = m_get(M_NOWAIT, m->m_type);
1267 n->m_len = min(MLEN, remainder);
1268 bcopy(cp, mtod(n, caddr_t), n->m_len);
1269 cp += n->m_len, remainder -= n->m_len;
1273 if (m0->m_flags & M_PKTHDR)
1274 m0->m_pkthdr.len += len - remainder;
1275 return (remainder == 0);
1279 m_apply_extpg_one(struct mbuf *m, int off, int len,
1280 int (*f)(void *, void *, u_int), void *arg)
1283 u_int i, count, pgoff, pglen;
1286 KASSERT(PMAP_HAS_DMAP,
1287 ("m_apply_extpg_one does not support unmapped mbufs"));
1288 off += mtod(m, vm_offset_t);
1289 if (off < m->m_epg_hdrlen) {
1290 count = min(m->m_epg_hdrlen - off, len);
1291 rval = f(arg, m->m_epg_hdr + off, count);
1297 off -= m->m_epg_hdrlen;
1298 pgoff = m->m_epg_1st_off;
1299 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
1300 pglen = m_epg_pagelen(m, i, pgoff);
1302 count = min(pglen - off, len);
1303 p = (void *)PHYS_TO_DMAP(m->m_epg_pa[i] + pgoff);
1304 rval = f(arg, p, count);
1314 KASSERT(off < m->m_epg_trllen,
1315 ("m_apply_extpg_one: offset beyond trailer"));
1316 KASSERT(len <= m->m_epg_trllen - off,
1317 ("m_apply_extpg_one: length beyond trailer"));
1318 return (f(arg, m->m_epg_trail + off, len));
1323 /* Apply function f to the data in a single mbuf. */
1325 m_apply_one(struct mbuf *m, int off, int len,
1326 int (*f)(void *, void *, u_int), void *arg)
1328 if ((m->m_flags & M_EXTPG) != 0)
1329 return (m_apply_extpg_one(m, off, len, f, arg));
1331 return (f(arg, mtod(m, caddr_t) + off, len));
1335 * Apply function f to the data in an mbuf chain starting "off" bytes from
1336 * the beginning, continuing for "len" bytes.
1339 m_apply(struct mbuf *m, int off, int len,
1340 int (*f)(void *, void *, u_int), void *arg)
1345 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1346 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1348 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1355 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1356 count = min(m->m_len - off, len);
1357 rval = m_apply_one(m, off, count, f, arg);
1368 * Return a pointer to mbuf/offset of location in mbuf chain.
1371 m_getptr(struct mbuf *m, int loc, int *off)
1375 /* Normal end of search. */
1376 if (m->m_len > loc) {
1381 if (m->m_next == NULL) {
1383 /* Point at the end of valid data. */
1396 m_print(const struct mbuf *m, int maxlen)
1400 const struct mbuf *m2;
1403 printf("mbuf: %p\n", m);
1407 if (m->m_flags & M_PKTHDR)
1408 len = m->m_pkthdr.len;
1412 while (m2 != NULL && (len == -1 || len)) {
1414 if (maxlen != -1 && pdata > maxlen)
1416 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1417 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1418 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1419 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1421 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1427 printf("%d bytes unaccounted for.\n", len);
1432 m_fixhdr(struct mbuf *m0)
1436 len = m_length(m0, NULL);
1437 m0->m_pkthdr.len = len;
1442 m_length(struct mbuf *m0, struct mbuf **last)
1448 for (m = m0; m != NULL; m = m->m_next) {
1450 if (m->m_next == NULL)
1459 * Defragment a mbuf chain, returning the shortest possible
1460 * chain of mbufs and clusters. If allocation fails and
1461 * this cannot be completed, NULL will be returned, but
1462 * the passed in chain will be unchanged. Upon success,
1463 * the original chain will be freed, and the new chain
1466 * If a non-packet header is passed in, the original
1467 * mbuf (chain?) will be returned unharmed.
1470 m_defrag(struct mbuf *m0, int how)
1472 struct mbuf *m_new = NULL, *m_final = NULL;
1473 int progress = 0, length;
1475 MBUF_CHECKSLEEP(how);
1476 if (!(m0->m_flags & M_PKTHDR))
1479 m_fixhdr(m0); /* Needed sanity check */
1481 #ifdef MBUF_STRESS_TEST
1482 if (m_defragrandomfailures) {
1483 int temp = arc4random() & 0xff;
1489 if (m0->m_pkthdr.len > MHLEN)
1490 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1492 m_final = m_gethdr(how, MT_DATA);
1494 if (m_final == NULL)
1497 if (m_dup_pkthdr(m_final, m0, how) == 0)
1502 while (progress < m0->m_pkthdr.len) {
1503 length = m0->m_pkthdr.len - progress;
1504 if (length > MCLBYTES)
1507 if (m_new == NULL) {
1509 m_new = m_getcl(how, MT_DATA, 0);
1511 m_new = m_get(how, MT_DATA);
1516 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1518 m_new->m_len = length;
1519 if (m_new != m_final)
1520 m_cat(m_final, m_new);
1523 #ifdef MBUF_STRESS_TEST
1524 if (m0->m_next == NULL)
1529 #ifdef MBUF_STRESS_TEST
1531 m_defragbytes += m0->m_pkthdr.len;
1535 #ifdef MBUF_STRESS_TEST
1544 * Return the number of fragments an mbuf will use. This is usually
1545 * used as a proxy for the number of scatter/gather elements needed by
1546 * a DMA engine to access an mbuf. In general mapped mbufs are
1547 * assumed to be backed by physically contiguous buffers that only
1548 * need a single fragment. Unmapped mbufs, on the other hand, can
1549 * span disjoint physical pages.
1552 frags_per_mbuf(struct mbuf *m)
1556 if ((m->m_flags & M_EXTPG) == 0)
1560 * The header and trailer are counted as a single fragment
1561 * each when present.
1563 * XXX: This overestimates the number of fragments by assuming
1564 * all the backing physical pages are disjoint.
1567 if (m->m_epg_hdrlen != 0)
1569 frags += m->m_epg_npgs;
1570 if (m->m_epg_trllen != 0)
1577 * Defragment an mbuf chain, returning at most maxfrags separate
1578 * mbufs+clusters. If this is not possible NULL is returned and
1579 * the original mbuf chain is left in its present (potentially
1580 * modified) state. We use two techniques: collapsing consecutive
1581 * mbufs and replacing consecutive mbufs by a cluster.
1583 * NB: this should really be named m_defrag but that name is taken
1586 m_collapse(struct mbuf *m0, int how, int maxfrags)
1588 struct mbuf *m, *n, *n2, **prev;
1592 * Calculate the current number of frags.
1595 for (m = m0; m != NULL; m = m->m_next)
1596 curfrags += frags_per_mbuf(m);
1598 * First, try to collapse mbufs. Note that we always collapse
1599 * towards the front so we don't need to deal with moving the
1600 * pkthdr. This may be suboptimal if the first mbuf has much
1601 * less data than the following.
1609 if (M_WRITABLE(m) &&
1610 n->m_len < M_TRAILINGSPACE(m)) {
1611 m_copydata(n, 0, n->m_len,
1612 mtod(m, char *) + m->m_len);
1613 m->m_len += n->m_len;
1614 m->m_next = n->m_next;
1615 curfrags -= frags_per_mbuf(n);
1617 if (curfrags <= maxfrags)
1622 KASSERT(maxfrags > 1,
1623 ("maxfrags %u, but normal collapse failed", maxfrags));
1625 * Collapse consecutive mbufs to a cluster.
1627 prev = &m0->m_next; /* NB: not the first mbuf */
1628 while ((n = *prev) != NULL) {
1629 if ((n2 = n->m_next) != NULL &&
1630 n->m_len + n2->m_len < MCLBYTES) {
1631 m = m_getcl(how, MT_DATA, 0);
1634 m_copydata(n, 0, n->m_len, mtod(m, char *));
1635 m_copydata(n2, 0, n2->m_len,
1636 mtod(m, char *) + n->m_len);
1637 m->m_len = n->m_len + n2->m_len;
1638 m->m_next = n2->m_next;
1640 curfrags += 1; /* For the new cluster */
1641 curfrags -= frags_per_mbuf(n);
1642 curfrags -= frags_per_mbuf(n2);
1645 if (curfrags <= maxfrags)
1648 * Still not there, try the normal collapse
1649 * again before we allocate another cluster.
1656 * No place where we can collapse to a cluster; punt.
1657 * This can occur if, for example, you request 2 frags
1658 * but the packet requires that both be clusters (we
1659 * never reallocate the first mbuf to avoid moving the
1666 #ifdef MBUF_STRESS_TEST
1669 * Fragment an mbuf chain. There's no reason you'd ever want to do
1670 * this in normal usage, but it's great for stress testing various
1673 * If fragmentation is not possible, the original chain will be
1676 * Possible length values:
1677 * 0 no fragmentation will occur
1678 * > 0 each fragment will be of the specified length
1679 * -1 each fragment will be the same random value in length
1680 * -2 each fragment's length will be entirely random
1681 * (Random values range from 1 to 256)
1684 m_fragment(struct mbuf *m0, int how, int length)
1686 struct mbuf *m_first, *m_last;
1687 int divisor = 255, progress = 0, fraglen;
1689 if (!(m0->m_flags & M_PKTHDR))
1692 if (length == 0 || length < -2)
1694 if (length > MCLBYTES)
1696 if (length < 0 && divisor > MCLBYTES)
1699 length = 1 + (arc4random() % divisor);
1703 m_fixhdr(m0); /* Needed sanity check */
1705 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1706 if (m_first == NULL)
1709 if (m_dup_pkthdr(m_first, m0, how) == 0)
1714 while (progress < m0->m_pkthdr.len) {
1716 fraglen = 1 + (arc4random() % divisor);
1717 if (fraglen > m0->m_pkthdr.len - progress)
1718 fraglen = m0->m_pkthdr.len - progress;
1720 if (progress != 0) {
1721 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1725 m_last->m_next = m_new;
1729 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1730 progress += fraglen;
1731 m_last->m_len = fraglen;
1739 /* Return the original chain on failure */
1746 * Free pages from mbuf_ext_pgs, assuming they were allocated via
1747 * vm_page_alloc() and aren't associated with any object. Complement
1748 * to allocator from m_uiotombuf_nomap().
1751 mb_free_mext_pgs(struct mbuf *m)
1756 for (int i = 0; i < m->m_epg_npgs; i++) {
1757 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1758 vm_page_unwire_noq(pg);
1763 static struct mbuf *
1764 m_uiotombuf_nomap(struct uio *uio, int how, int len, int maxseg, int flags)
1766 struct mbuf *m, *mb, *prev;
1767 vm_page_t pg_array[MBUF_PEXT_MAX_PGS];
1768 int error, length, i, needed;
1770 int pflags = malloc2vm_flags(how) | VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP |
1773 MPASS((flags & M_PKTHDR) == 0);
1774 MPASS((how & M_ZERO) == 0);
1777 * len can be zero or an arbitrary large value bound by
1778 * the total data supplied by the uio.
1781 total = MIN(uio->uio_resid, len);
1783 total = uio->uio_resid;
1786 maxseg = MBUF_PEXT_MAX_PGS * PAGE_SIZE;
1789 * If total is zero, return an empty mbuf. This can occur
1790 * for TLS 1.0 connections which send empty fragments as
1791 * a countermeasure against the known-IV weakness in CBC
1794 if (__predict_false(total == 0)) {
1795 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1798 mb->m_epg_flags = EPG_FLAG_ANON;
1803 * Allocate the pages
1807 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1815 mb->m_epg_flags = EPG_FLAG_ANON;
1816 needed = length = MIN(maxseg, total);
1817 for (i = 0; needed > 0; i++, needed -= PAGE_SIZE) {
1819 pg_array[i] = vm_page_alloc(NULL, 0, pflags);
1820 if (pg_array[i] == NULL) {
1821 if (how & M_NOWAIT) {
1828 mb->m_epg_pa[i] = VM_PAGE_TO_PHYS(pg_array[i]);
1831 mb->m_epg_last_len = length - PAGE_SIZE * (mb->m_epg_npgs - 1);
1832 MBUF_EXT_PGS_ASSERT_SANITY(mb);
1834 error = uiomove_fromphys(pg_array, 0, length, uio);
1838 mb->m_ext.ext_size += PAGE_SIZE * mb->m_epg_npgs;
1839 if (flags & M_PKTHDR)
1840 m->m_pkthdr.len += length;
1850 * Copy the contents of uio into a properly sized mbuf chain.
1853 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1855 struct mbuf *m, *mb;
1860 if (flags & M_EXTPG)
1861 return (m_uiotombuf_nomap(uio, how, len, align, flags));
1864 * len can be zero or an arbitrary large value bound by
1865 * the total data supplied by the uio.
1868 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1870 total = uio->uio_resid;
1873 * The smallest unit returned by m_getm2() is a single mbuf
1874 * with pkthdr. We can't align past it.
1880 * Give us the full allocation or nothing.
1881 * If len is zero return the smallest empty mbuf.
1883 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1888 /* Fill all mbufs with uio data and update header information. */
1889 for (mb = m; mb != NULL; mb = mb->m_next) {
1890 length = min(M_TRAILINGSPACE(mb), total - progress);
1892 error = uiomove(mtod(mb, void *), length, uio);
1900 if (flags & M_PKTHDR)
1901 m->m_pkthdr.len += length;
1903 KASSERT(progress == total, ("%s: progress != total", __func__));
1909 * Copy data to/from an unmapped mbuf into a uio limited by len if set.
1912 m_unmapped_uiomove(const struct mbuf *m, int m_off, struct uio *uio, int len)
1915 int error, i, off, pglen, pgoff, seglen, segoff;
1920 /* Skip over any data removed from the front. */
1921 off = mtod(m, vm_offset_t);
1924 if (m->m_epg_hdrlen != 0) {
1925 if (off >= m->m_epg_hdrlen) {
1926 off -= m->m_epg_hdrlen;
1928 seglen = m->m_epg_hdrlen - off;
1930 seglen = min(seglen, len);
1933 error = uiomove(__DECONST(void *,
1934 &m->m_epg_hdr[segoff]), seglen, uio);
1937 pgoff = m->m_epg_1st_off;
1938 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
1939 pglen = m_epg_pagelen(m, i, pgoff);
1945 seglen = pglen - off;
1946 segoff = pgoff + off;
1948 seglen = min(seglen, len);
1950 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1951 error = uiomove_fromphys(&pg, segoff, seglen, uio);
1954 if (len != 0 && error == 0) {
1955 KASSERT((off + len) <= m->m_epg_trllen,
1956 ("off + len > trail (%d + %d > %d, m_off = %d)", off, len,
1957 m->m_epg_trllen, m_off));
1958 error = uiomove(__DECONST(void *, &m->m_epg_trail[off]),
1965 * Copy an mbuf chain into a uio limited by len if set.
1968 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
1970 int error, length, total;
1974 total = min(uio->uio_resid, len);
1976 total = uio->uio_resid;
1978 /* Fill the uio with data from the mbufs. */
1979 for (; m != NULL; m = m->m_next) {
1980 length = min(m->m_len, total - progress);
1982 if ((m->m_flags & M_EXTPG) != 0)
1983 error = m_unmapped_uiomove(m, 0, uio, length);
1985 error = uiomove(mtod(m, void *), length, uio);
1996 * Create a writable copy of the mbuf chain. While doing this
1997 * we compact the chain with a goal of producing a chain with
1998 * at most two mbufs. The second mbuf in this chain is likely
1999 * to be a cluster. The primary purpose of this work is to create
2000 * a writable packet for encryption, compression, etc. The
2001 * secondary goal is to linearize the data so the data can be
2002 * passed to crypto hardware in the most efficient manner possible.
2005 m_unshare(struct mbuf *m0, int how)
2007 struct mbuf *m, *mprev;
2008 struct mbuf *n, *mfirst, *mlast;
2012 for (m = m0; m != NULL; m = mprev->m_next) {
2014 * Regular mbufs are ignored unless there's a cluster
2015 * in front of it that we can use to coalesce. We do
2016 * the latter mainly so later clusters can be coalesced
2017 * also w/o having to handle them specially (i.e. convert
2018 * mbuf+cluster -> cluster). This optimization is heavily
2019 * influenced by the assumption that we're running over
2020 * Ethernet where MCLBYTES is large enough that the max
2021 * packet size will permit lots of coalescing into a
2022 * single cluster. This in turn permits efficient
2023 * crypto operations, especially when using hardware.
2025 if ((m->m_flags & M_EXT) == 0) {
2026 if (mprev && (mprev->m_flags & M_EXT) &&
2027 m->m_len <= M_TRAILINGSPACE(mprev)) {
2028 /* XXX: this ignores mbuf types */
2029 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2030 mtod(m, caddr_t), m->m_len);
2031 mprev->m_len += m->m_len;
2032 mprev->m_next = m->m_next; /* unlink from chain */
2033 m_free(m); /* reclaim mbuf */
2040 * Writable mbufs are left alone (for now).
2042 if (M_WRITABLE(m)) {
2048 * Not writable, replace with a copy or coalesce with
2049 * the previous mbuf if possible (since we have to copy
2050 * it anyway, we try to reduce the number of mbufs and
2051 * clusters so that future work is easier).
2053 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
2054 /* NB: we only coalesce into a cluster or larger */
2055 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
2056 m->m_len <= M_TRAILINGSPACE(mprev)) {
2057 /* XXX: this ignores mbuf types */
2058 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2059 mtod(m, caddr_t), m->m_len);
2060 mprev->m_len += m->m_len;
2061 mprev->m_next = m->m_next; /* unlink from chain */
2062 m_free(m); /* reclaim mbuf */
2067 * Allocate new space to hold the copy and copy the data.
2068 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
2069 * splitting them into clusters. We could just malloc a
2070 * buffer and make it external but too many device drivers
2071 * don't know how to break up the non-contiguous memory when
2074 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2079 if (m->m_flags & M_PKTHDR) {
2080 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
2082 m_move_pkthdr(n, m);
2089 int cc = min(len, MCLBYTES);
2090 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2096 newipsecstat.ips_clcopied++;
2104 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2111 n->m_next = m->m_next;
2113 m0 = mfirst; /* new head of chain */
2115 mprev->m_next = mfirst; /* replace old mbuf */
2116 m_free(m); /* release old mbuf */
2122 #ifdef MBUF_PROFILING
2124 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2125 struct mbufprofile {
2126 uintmax_t wasted[MP_BUCKETS];
2127 uintmax_t used[MP_BUCKETS];
2128 uintmax_t segments[MP_BUCKETS];
2131 #define MP_MAXDIGITS 21 /* strlen("16,000,000,000,000,000,000") == 21 */
2132 #define MP_NUMLINES 6
2133 #define MP_NUMSPERLINE 16
2134 #define MP_EXTRABYTES 64 /* > strlen("used:\nwasted:\nsegments:\n") */
2135 /* work out max space needed and add a bit of spare space too */
2136 #define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
2137 #define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
2139 char mbprofbuf[MP_BUFSIZE];
2142 m_profile(struct mbuf *m)
2151 if (m->m_flags & M_EXT) {
2152 wasted += MHLEN - sizeof(m->m_ext) +
2153 m->m_ext.ext_size - m->m_len;
2155 if (m->m_flags & M_PKTHDR)
2156 wasted += MHLEN - m->m_len;
2158 wasted += MLEN - m->m_len;
2162 /* be paranoid.. it helps */
2163 if (segments > MP_BUCKETS - 1)
2164 segments = MP_BUCKETS - 1;
2167 if (wasted > 100000)
2169 /* store in the appropriate bucket */
2170 /* don't bother locking. if it's slightly off, so what? */
2171 mbprof.segments[segments]++;
2172 mbprof.used[fls(used)]++;
2173 mbprof.wasted[fls(wasted)]++;
2177 mbprof_textify(void)
2183 p = &mbprof.wasted[0];
2185 offset = snprintf(c, MP_MAXLINE + 10,
2187 "%ju %ju %ju %ju %ju %ju %ju %ju "
2188 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2189 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2190 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2192 p = &mbprof.wasted[16];
2194 offset = snprintf(c, MP_MAXLINE,
2195 "%ju %ju %ju %ju %ju %ju %ju %ju "
2196 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2197 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2198 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2200 p = &mbprof.used[0];
2202 offset = snprintf(c, MP_MAXLINE + 10,
2204 "%ju %ju %ju %ju %ju %ju %ju %ju "
2205 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2206 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2207 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2209 p = &mbprof.used[16];
2211 offset = snprintf(c, MP_MAXLINE,
2212 "%ju %ju %ju %ju %ju %ju %ju %ju "
2213 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2214 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2215 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2217 p = &mbprof.segments[0];
2219 offset = snprintf(c, MP_MAXLINE + 10,
2221 "%ju %ju %ju %ju %ju %ju %ju %ju "
2222 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2223 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2224 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2226 p = &mbprof.segments[16];
2228 offset = snprintf(c, MP_MAXLINE,
2229 "%ju %ju %ju %ju %ju %ju %ju %ju "
2230 "%ju %ju %ju %ju %ju %ju %ju %jju",
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]);
2237 mbprof_handler(SYSCTL_HANDLER_ARGS)
2242 error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
2247 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2252 error = sysctl_handle_int(oidp, &clear, 0, req);
2253 if (error || !req->newptr)
2257 bzero(&mbprof, sizeof(mbprof));
2263 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile,
2264 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
2265 mbprof_handler, "A",
2266 "mbuf profiling statistics");
2268 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr,
2269 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
2270 mbprof_clr_handler, "I",
2271 "clear mbuf profiling statistics");