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>
56 #include <vm/vm_pageout.h>
57 #include <vm/vm_page.h>
59 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__init,
60 "struct mbuf *", "mbufinfo_t *",
61 "uint32_t", "uint32_t",
62 "uint16_t", "uint16_t",
63 "uint32_t", "uint32_t",
64 "uint32_t", "uint32_t");
66 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__gethdr,
67 "uint32_t", "uint32_t",
68 "uint16_t", "uint16_t",
69 "struct mbuf *", "mbufinfo_t *");
71 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
72 "uint32_t", "uint32_t",
73 "uint16_t", "uint16_t",
74 "struct mbuf *", "mbufinfo_t *");
76 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
77 "uint32_t", "uint32_t",
78 "uint16_t", "uint16_t",
79 "uint32_t", "uint32_t",
80 "struct mbuf *", "mbufinfo_t *");
82 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__getjcl,
83 "uint32_t", "uint32_t",
84 "uint16_t", "uint16_t",
85 "uint32_t", "uint32_t",
86 "uint32_t", "uint32_t",
87 "struct mbuf *", "mbufinfo_t *");
89 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
90 "struct mbuf *", "mbufinfo_t *",
91 "uint32_t", "uint32_t",
92 "uint32_t", "uint32_t");
94 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
95 "struct mbuf *", "mbufinfo_t *",
96 "uint32_t", "uint32_t",
97 "uint32_t", "uint32_t",
100 SDT_PROBE_DEFINE(sdt, , , m__cljset);
102 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
103 "struct mbuf *", "mbufinfo_t *");
105 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
106 "struct mbuf *", "mbufinfo_t *");
108 #include <security/mac/mac_framework.h>
114 #ifdef MBUF_STRESS_TEST
119 int m_defragrandomfailures;
123 * sysctl(8) exported objects
125 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
126 &max_linkhdr, 0, "Size of largest link layer header");
127 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
128 &max_protohdr, 0, "Size of largest protocol layer header");
129 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
130 &max_hdr, 0, "Size of largest link plus protocol header");
131 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
132 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
133 #ifdef MBUF_STRESS_TEST
134 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
135 &m_defragpackets, 0, "");
136 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
137 &m_defragbytes, 0, "");
138 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
139 &m_defraguseless, 0, "");
140 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
141 &m_defragfailure, 0, "");
142 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
143 &m_defragrandomfailures, 0, "");
147 * Ensure the correct size of various mbuf parameters. It could be off due
148 * to compiler-induced padding and alignment artifacts.
150 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
151 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
154 * mbuf data storage should be 64-bit aligned regardless of architectural
155 * pointer size; check this is the case with and without a packet header.
157 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
158 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
161 * While the specific values here don't matter too much (i.e., +/- a few
162 * words), we do want to ensure that changes to these values are carefully
163 * reasoned about and properly documented. This is especially the case as
164 * network-protocol and device-driver modules encode these layouts, and must
165 * be recompiled if the structures change. Check these values at compile time
166 * against the ones documented in comments in mbuf.h.
168 * NB: Possibly they should be documented there via #define's and not just
171 #if defined(__LP64__)
172 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
173 CTASSERT(sizeof(struct pkthdr) == 56);
174 CTASSERT(sizeof(struct m_ext) == 160);
176 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
177 CTASSERT(sizeof(struct pkthdr) == 48);
178 #if defined(__powerpc__) && defined(BOOKE)
179 /* PowerPC booke has 64-bit physical pointers. */
180 CTASSERT(sizeof(struct m_ext) == 184);
182 CTASSERT(sizeof(struct m_ext) == 180);
187 * Assert that the queue(3) macros produce code of the same size as an old
188 * plain pointer does.
191 static struct mbuf __used m_assertbuf;
192 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
193 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
194 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
195 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
199 * Attach the cluster from *m to *n, set up m_ext in *n
200 * and bump the refcount of the cluster.
203 mb_dupcl(struct mbuf *n, struct mbuf *m)
205 volatile u_int *refcnt;
207 KASSERT(m->m_flags & (M_EXT|M_EXTPG),
208 ("%s: M_EXT|M_EXTPG not set on %p", __func__, m));
209 KASSERT(!(n->m_flags & (M_EXT|M_EXTPG)),
210 ("%s: M_EXT|M_EXTPG set on %p", __func__, n));
213 * Cache access optimization.
215 * o Regular M_EXT storage doesn't need full copy of m_ext, since
216 * the holder of the 'ext_count' is responsible to carry the free
217 * routine and its arguments.
218 * o M_EXTPG data is split between main part of mbuf and m_ext, the
219 * main part is copied in full, the m_ext part is similar to M_EXT.
220 * o EXT_EXTREF, where 'ext_cnt' doesn't point into mbuf at all, is
221 * special - it needs full copy of m_ext into each mbuf, since any
222 * copy could end up as the last to free.
224 if (m->m_flags & M_EXTPG) {
225 bcopy(&m->m_epg_startcopy, &n->m_epg_startcopy,
226 __rangeof(struct mbuf, m_epg_startcopy, m_epg_endcopy));
227 bcopy(&m->m_ext, &n->m_ext, m_epg_ext_copylen);
228 } else if (m->m_ext.ext_type == EXT_EXTREF)
229 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
231 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
233 n->m_flags |= m->m_flags & (M_RDONLY | M_EXT | M_EXTPG);
235 /* See if this is the mbuf that holds the embedded refcount. */
236 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
237 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
238 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
240 KASSERT(m->m_ext.ext_cnt != NULL,
241 ("%s: no refcounting pointer on %p", __func__, m));
242 refcnt = m->m_ext.ext_cnt;
248 atomic_add_int(refcnt, 1);
252 m_demote_pkthdr(struct mbuf *m)
256 M_ASSERT_NO_SND_TAG(m);
258 m_tag_delete_chain(m, NULL);
259 m->m_flags &= ~M_PKTHDR;
260 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
264 * Clean up mbuf (chain) from any tags and packet headers.
265 * If "all" is set then the first mbuf in the chain will be
269 m_demote(struct mbuf *m0, int all, int flags)
273 flags |= M_DEMOTEFLAGS;
275 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
276 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
278 if (m->m_flags & M_PKTHDR)
285 * Sanity checks on mbuf (chain) for use in KASSERT() and general
287 * Returns 0 or panics when bad and 1 on all tests passed.
288 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
292 m_sanity(struct mbuf *m0, int sanitize)
299 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
301 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
304 for (m = m0; m != NULL; m = m->m_next) {
306 * Basic pointer checks. If any of these fails then some
307 * unrelated kernel memory before or after us is trashed.
308 * No way to recover from that.
312 if ((caddr_t)m->m_data < a)
313 M_SANITY_ACTION("m_data outside mbuf data range left");
314 if ((caddr_t)m->m_data > b)
315 M_SANITY_ACTION("m_data outside mbuf data range right");
316 if ((caddr_t)m->m_data + m->m_len > b)
317 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
319 /* m->m_nextpkt may only be set on first mbuf in chain. */
320 if (m != m0 && m->m_nextpkt != NULL) {
322 m_freem(m->m_nextpkt);
323 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
325 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
328 /* packet length (not mbuf length!) calculation */
329 if (m0->m_flags & M_PKTHDR)
332 /* m_tags may only be attached to first mbuf in chain. */
333 if (m != m0 && m->m_flags & M_PKTHDR &&
334 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
336 m_tag_delete_chain(m, NULL);
337 /* put in 0xDEADC0DE perhaps? */
339 M_SANITY_ACTION("m_tags on in-chain mbuf");
342 /* M_PKTHDR may only be set on first mbuf in chain */
343 if (m != m0 && m->m_flags & M_PKTHDR) {
345 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
346 m->m_flags &= ~M_PKTHDR;
347 /* put in 0xDEADCODE and leave hdr flag in */
349 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
353 if (pktlen && pktlen != m->m_pkthdr.len) {
357 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
361 #undef M_SANITY_ACTION
365 * Non-inlined part of m_init().
368 m_pkthdr_init(struct mbuf *m, int how)
373 m->m_data = m->m_pktdat;
374 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
376 m->m_pkthdr.numa_domain = M_NODOM;
379 /* If the label init fails, fail the alloc */
380 error = mac_mbuf_init(m, how);
389 * "Move" mbuf pkthdr from "from" to "to".
390 * "from" must have M_PKTHDR set, and "to" must be empty.
393 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
397 /* see below for why these are not enabled */
399 /* Note: with MAC, this may not be a good assertion. */
400 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
401 ("m_move_pkthdr: to has tags"));
405 * XXXMAC: It could be this should also occur for non-MAC?
407 if (to->m_flags & M_PKTHDR)
408 m_tag_delete_chain(to, NULL);
410 to->m_flags = (from->m_flags & M_COPYFLAGS) |
411 (to->m_flags & (M_EXT | M_EXTPG));
412 if ((to->m_flags & M_EXT) == 0)
413 to->m_data = to->m_pktdat;
414 to->m_pkthdr = from->m_pkthdr; /* especially tags */
415 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
416 from->m_flags &= ~M_PKTHDR;
417 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG) {
418 from->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
419 from->m_pkthdr.snd_tag = NULL;
424 * Duplicate "from"'s mbuf pkthdr in "to".
425 * "from" must have M_PKTHDR set, and "to" must be empty.
426 * In particular, this does a deep copy of the packet tags.
429 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
434 * The mbuf allocator only initializes the pkthdr
435 * when the mbuf is allocated with m_gethdr(). Many users
436 * (e.g. m_copy*, m_prepend) use m_get() and then
437 * smash the pkthdr as needed causing these
438 * assertions to trip. For now just disable them.
441 /* Note: with MAC, this may not be a good assertion. */
442 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
444 MBUF_CHECKSLEEP(how);
446 if (to->m_flags & M_PKTHDR)
447 m_tag_delete_chain(to, NULL);
449 to->m_flags = (from->m_flags & M_COPYFLAGS) |
450 (to->m_flags & (M_EXT | M_EXTPG));
451 if ((to->m_flags & M_EXT) == 0)
452 to->m_data = to->m_pktdat;
453 to->m_pkthdr = from->m_pkthdr;
454 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG)
455 m_snd_tag_ref(from->m_pkthdr.snd_tag);
456 SLIST_INIT(&to->m_pkthdr.tags);
457 return (m_tag_copy_chain(to, from, how));
461 * Lesser-used path for M_PREPEND:
462 * allocate new mbuf to prepend to chain,
466 m_prepend(struct mbuf *m, int len, int how)
470 if (m->m_flags & M_PKTHDR)
471 mn = m_gethdr(how, m->m_type);
473 mn = m_get(how, m->m_type);
478 if (m->m_flags & M_PKTHDR)
479 m_move_pkthdr(mn, m);
489 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
490 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
491 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
492 * Note that the copy is read-only, because clusters are not copied,
493 * only their reference counts are incremented.
496 m_copym(struct mbuf *m, int off0, int len, int wait)
498 struct mbuf *n, **np;
503 KASSERT(off >= 0, ("m_copym, negative off %d", off));
504 KASSERT(len >= 0, ("m_copym, negative len %d", len));
505 MBUF_CHECKSLEEP(wait);
506 if (off == 0 && m->m_flags & M_PKTHDR)
509 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
519 KASSERT(len == M_COPYALL,
520 ("m_copym, length > size of mbuf chain"));
524 n = m_gethdr(wait, m->m_type);
526 n = m_get(wait, m->m_type);
531 if (!m_dup_pkthdr(n, m, wait))
533 if (len == M_COPYALL)
534 n->m_pkthdr.len -= off0;
536 n->m_pkthdr.len = len;
539 n->m_len = min(len, m->m_len - off);
540 if (m->m_flags & (M_EXT|M_EXTPG)) {
541 n->m_data = m->m_data + off;
544 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
546 if (len != M_COPYALL)
560 * Copy an entire packet, including header (which must be present).
561 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
562 * Note that the copy is read-only, because clusters are not copied,
563 * only their reference counts are incremented.
564 * Preserve alignment of the first mbuf so if the creator has left
565 * some room at the beginning (e.g. for inserting protocol headers)
566 * the copies still have the room available.
569 m_copypacket(struct mbuf *m, int how)
571 struct mbuf *top, *n, *o;
573 MBUF_CHECKSLEEP(how);
574 n = m_get(how, m->m_type);
579 if (!m_dup_pkthdr(n, m, how))
582 if (m->m_flags & (M_EXT|M_EXTPG)) {
583 n->m_data = m->m_data;
586 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
587 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
592 o = m_get(how, m->m_type);
600 if (m->m_flags & (M_EXT|M_EXTPG)) {
601 n->m_data = m->m_data;
604 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
616 m_copyfromunmapped(const struct mbuf *m, int off, int len, caddr_t cp)
622 KASSERT(off >= 0, ("m_copyfromunmapped: negative off %d", off));
623 KASSERT(len >= 0, ("m_copyfromunmapped: negative len %d", len));
624 KASSERT(off < m->m_len,
625 ("m_copyfromunmapped: len exceeds mbuf length"));
630 uio.uio_segflg = UIO_SYSSPACE;
633 uio.uio_rw = UIO_READ;
634 error = m_unmapped_uiomove(m, off, &uio, len);
635 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
640 * Copy data from an mbuf chain starting "off" bytes from the beginning,
641 * continuing for "len" bytes, into the indicated buffer.
644 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
648 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
649 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
651 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
658 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
659 count = min(m->m_len - off, len);
660 if ((m->m_flags & M_EXTPG) != 0)
661 m_copyfromunmapped(m, off, count, cp);
663 bcopy(mtod(m, caddr_t) + off, cp, count);
672 * Copy a packet header mbuf chain into a completely new chain, including
673 * copying any mbuf clusters. Use this instead of m_copypacket() when
674 * you need a writable copy of an mbuf chain.
677 m_dup(const struct mbuf *m, int how)
679 struct mbuf **p, *top = NULL;
680 int remain, moff, nsize;
682 MBUF_CHECKSLEEP(how);
688 /* While there's more data, get a new mbuf, tack it on, and fill it */
689 remain = m->m_pkthdr.len;
692 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
695 /* Get the next new mbuf */
696 if (remain >= MINCLSIZE) {
697 n = m_getcl(how, m->m_type, 0);
700 n = m_get(how, m->m_type);
706 if (top == NULL) { /* First one, must be PKTHDR */
707 if (!m_dup_pkthdr(n, m, how)) {
711 if ((n->m_flags & M_EXT) == 0)
713 n->m_flags &= ~M_RDONLY;
717 /* Link it into the new chain */
721 /* Copy data from original mbuf(s) into new mbuf */
722 while (n->m_len < nsize && m != NULL) {
723 int chunk = min(nsize - n->m_len, m->m_len - moff);
725 m_copydata(m, moff, chunk, n->m_data + n->m_len);
729 if (moff == m->m_len) {
735 /* Check correct total mbuf length */
736 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
737 ("%s: bogus m_pkthdr.len", __func__));
747 * Concatenate mbuf chain n to m.
748 * Both chains must be of the same type (e.g. MT_DATA).
749 * Any m_pkthdr is not updated.
752 m_cat(struct mbuf *m, struct mbuf *n)
757 if (!M_WRITABLE(m) ||
758 (n->m_flags & M_EXTPG) != 0 ||
759 M_TRAILINGSPACE(m) < n->m_len) {
760 /* just join the two chains */
764 /* splat the data from one into the other */
765 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
767 m->m_len += n->m_len;
773 * Concatenate two pkthdr mbuf chains.
776 m_catpkt(struct mbuf *m, struct mbuf *n)
782 m->m_pkthdr.len += n->m_pkthdr.len;
789 m_adj(struct mbuf *mp, int req_len)
795 if ((m = mp) == NULL)
801 while (m != NULL && len > 0) {
802 if (m->m_len <= len) {
812 if (mp->m_flags & M_PKTHDR)
813 mp->m_pkthdr.len -= (req_len - len);
816 * Trim from tail. Scan the mbuf chain,
817 * calculating its length and finding the last mbuf.
818 * If the adjustment only affects this mbuf, then just
819 * adjust and return. Otherwise, rescan and truncate
820 * after the remaining size.
826 if (m->m_next == (struct mbuf *)0)
830 if (m->m_len >= len) {
832 if (mp->m_flags & M_PKTHDR)
833 mp->m_pkthdr.len -= len;
840 * Correct length for chain is "count".
841 * Find the mbuf with last data, adjust its length,
842 * and toss data from remaining mbufs on chain.
845 if (m->m_flags & M_PKTHDR)
846 m->m_pkthdr.len = count;
847 for (; m; m = m->m_next) {
848 if (m->m_len >= count) {
850 if (m->m_next != NULL) {
862 m_adj_decap(struct mbuf *mp, int len)
867 if ((mp->m_flags & M_PKTHDR) != 0) {
869 * If flowid was calculated by card from the inner
870 * headers, move flowid to the decapsulated mbuf
871 * chain, otherwise clear. This depends on the
872 * internals of m_adj, which keeps pkthdr as is, in
873 * particular not changing rsstype and flowid.
875 rsstype = mp->m_pkthdr.rsstype;
876 if ((rsstype & M_HASHTYPE_INNER) != 0) {
877 M_HASHTYPE_SET(mp, rsstype & ~M_HASHTYPE_INNER);
879 M_HASHTYPE_CLEAR(mp);
885 * Rearange an mbuf chain so that len bytes are contiguous
886 * and in the data area of an mbuf (so that mtod will work
887 * for a structure of size len). Returns the resulting
888 * mbuf chain on success, frees it and returns null on failure.
889 * If there is room, it will add up to max_protohdr-len extra bytes to the
890 * contiguous region in an attempt to avoid being called next time.
893 m_pullup(struct mbuf *n, int len)
899 KASSERT((n->m_flags & M_EXTPG) == 0,
900 ("%s: unmapped mbuf %p", __func__, n));
903 * If first mbuf has no cluster, and has room for len bytes
904 * without shifting current data, pullup into it,
905 * otherwise allocate a new mbuf to prepend to the chain.
907 if ((n->m_flags & M_EXT) == 0 &&
908 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
917 m = m_get(M_NOWAIT, n->m_type);
920 if (n->m_flags & M_PKTHDR)
923 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
925 count = min(min(max(len, max_protohdr), space), n->m_len);
926 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
936 } while (len > 0 && n);
949 * Like m_pullup(), except a new mbuf is always allocated, and we allow
950 * the amount of empty space before the data in the new mbuf to be specified
951 * (in the event that the caller expects to prepend later).
954 m_copyup(struct mbuf *n, int len, int dstoff)
959 if (len > (MHLEN - dstoff))
961 m = m_get(M_NOWAIT, n->m_type);
964 if (n->m_flags & M_PKTHDR)
967 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
969 count = min(min(max(len, max_protohdr), space), n->m_len);
970 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
980 } while (len > 0 && n);
993 * Partition an mbuf chain in two pieces, returning the tail --
994 * all but the first len0 bytes. In case of failure, it returns NULL and
995 * attempts to restore the chain to its original state.
997 * Note that the resulting mbufs might be read-only, because the new
998 * mbuf can end up sharing an mbuf cluster with the original mbuf if
999 * the "breaking point" happens to lie within a cluster mbuf. Use the
1000 * M_WRITABLE() macro to check for this case.
1003 m_split(struct mbuf *m0, int len0, int wait)
1006 u_int len = len0, remain;
1008 MBUF_CHECKSLEEP(wait);
1009 for (m = m0; m && len > m->m_len; m = m->m_next)
1013 remain = m->m_len - len;
1014 if (m0->m_flags & M_PKTHDR && remain == 0) {
1015 n = m_gethdr(wait, m0->m_type);
1018 n->m_next = m->m_next;
1020 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1021 n->m_pkthdr.snd_tag =
1022 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1023 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1025 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1026 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1027 m0->m_pkthdr.len = len0;
1029 } else if (m0->m_flags & M_PKTHDR) {
1030 n = m_gethdr(wait, m0->m_type);
1033 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1034 n->m_pkthdr.snd_tag =
1035 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1036 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1038 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1039 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1040 m0->m_pkthdr.len = len0;
1041 if (m->m_flags & (M_EXT|M_EXTPG))
1043 if (remain > MHLEN) {
1044 /* m can't be the lead packet */
1046 n->m_next = m_split(m, len, wait);
1047 if (n->m_next == NULL) {
1056 } else if (remain == 0) {
1061 n = m_get(wait, m->m_type);
1067 if (m->m_flags & (M_EXT|M_EXTPG)) {
1068 n->m_data = m->m_data + len;
1071 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1075 n->m_next = m->m_next;
1080 * Routine to copy from device local memory into mbufs.
1081 * Note that `off' argument is offset into first mbuf of target chain from
1082 * which to begin copying the data to.
1085 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1086 void (*copy)(char *from, caddr_t to, u_int len))
1089 struct mbuf *top = NULL, **mp = ⊤
1092 if (off < 0 || off > MHLEN)
1095 while (totlen > 0) {
1096 if (top == NULL) { /* First one, must be PKTHDR */
1097 if (totlen + off >= MINCLSIZE) {
1098 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1101 m = m_gethdr(M_NOWAIT, MT_DATA);
1104 /* Place initial small packet/header at end of mbuf */
1105 if (m && totlen + off + max_linkhdr <= MHLEN) {
1106 m->m_data += max_linkhdr;
1112 m->m_pkthdr.rcvif = ifp;
1113 m->m_pkthdr.len = totlen;
1115 if (totlen + off >= MINCLSIZE) {
1116 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1119 m = m_get(M_NOWAIT, MT_DATA);
1132 m->m_len = len = min(totlen, len);
1134 copy(buf, mtod(m, caddr_t), (u_int)len);
1136 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1146 m_copytounmapped(const struct mbuf *m, int off, int len, c_caddr_t cp)
1152 KASSERT(off >= 0, ("m_copytounmapped: negative off %d", off));
1153 KASSERT(len >= 0, ("m_copytounmapped: negative len %d", len));
1154 KASSERT(off < m->m_len, ("m_copytounmapped: len exceeds mbuf length"));
1155 iov.iov_base = __DECONST(caddr_t, cp);
1157 uio.uio_resid = len;
1159 uio.uio_segflg = UIO_SYSSPACE;
1162 uio.uio_rw = UIO_WRITE;
1163 error = m_unmapped_uiomove(m, off, &uio, len);
1164 KASSERT(error == 0, ("m_unmapped_uiomove failed: off %d, len %d", off,
1169 * Copy data from a buffer back into the indicated mbuf chain,
1170 * starting "off" bytes from the beginning, extending the mbuf
1171 * chain if necessary.
1174 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1177 struct mbuf *m = m0, *n;
1182 while (off > (mlen = m->m_len)) {
1185 if (m->m_next == NULL) {
1186 n = m_get(M_NOWAIT, m->m_type);
1189 bzero(mtod(n, caddr_t), MLEN);
1190 n->m_len = min(MLEN, len + off);
1196 if (m->m_next == NULL && (len > m->m_len - off)) {
1197 m->m_len += min(len - (m->m_len - off),
1198 M_TRAILINGSPACE(m));
1200 mlen = min (m->m_len - off, len);
1201 if ((m->m_flags & M_EXTPG) != 0)
1202 m_copytounmapped(m, off, mlen, cp);
1204 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1212 if (m->m_next == NULL) {
1213 n = m_get(M_NOWAIT, m->m_type);
1216 n->m_len = min(MLEN, len);
1221 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1222 m->m_pkthdr.len = totlen;
1226 * Append the specified data to the indicated mbuf chain,
1227 * Extend the mbuf chain if the new data does not fit in
1230 * Return 1 if able to complete the job; otherwise 0.
1233 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1236 int remainder, space;
1238 for (m = m0; m->m_next != NULL; m = m->m_next)
1241 space = M_TRAILINGSPACE(m);
1244 * Copy into available space.
1246 if (space > remainder)
1248 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1250 cp += space, remainder -= space;
1252 while (remainder > 0) {
1254 * Allocate a new mbuf; could check space
1255 * and allocate a cluster instead.
1257 n = m_get(M_NOWAIT, m->m_type);
1260 n->m_len = min(MLEN, remainder);
1261 bcopy(cp, mtod(n, caddr_t), n->m_len);
1262 cp += n->m_len, remainder -= n->m_len;
1266 if (m0->m_flags & M_PKTHDR)
1267 m0->m_pkthdr.len += len - remainder;
1268 return (remainder == 0);
1272 m_apply_extpg_one(struct mbuf *m, int off, int len,
1273 int (*f)(void *, void *, u_int), void *arg)
1276 u_int i, count, pgoff, pglen;
1279 KASSERT(PMAP_HAS_DMAP,
1280 ("m_apply_extpg_one does not support unmapped mbufs"));
1281 off += mtod(m, vm_offset_t);
1282 if (off < m->m_epg_hdrlen) {
1283 count = min(m->m_epg_hdrlen - off, len);
1284 rval = f(arg, m->m_epg_hdr + off, count);
1290 off -= m->m_epg_hdrlen;
1291 pgoff = m->m_epg_1st_off;
1292 for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
1293 pglen = m_epg_pagelen(m, i, pgoff);
1295 count = min(pglen - off, len);
1296 p = (void *)PHYS_TO_DMAP(m->m_epg_pa[i] + pgoff);
1297 rval = f(arg, p, count);
1307 KASSERT(off < m->m_epg_trllen,
1308 ("m_apply_extpg_one: offset beyond trailer"));
1309 KASSERT(len <= m->m_epg_trllen - off,
1310 ("m_apply_extpg_one: length beyond trailer"));
1311 return (f(arg, m->m_epg_trail + off, len));
1316 /* Apply function f to the data in a single mbuf. */
1318 m_apply_one(struct mbuf *m, int off, int len,
1319 int (*f)(void *, void *, u_int), void *arg)
1321 if ((m->m_flags & M_EXTPG) != 0)
1322 return (m_apply_extpg_one(m, off, len, f, arg));
1324 return (f(arg, mtod(m, caddr_t) + off, len));
1328 * Apply function f to the data in an mbuf chain starting "off" bytes from
1329 * the beginning, continuing for "len" bytes.
1332 m_apply(struct mbuf *m, int off, int len,
1333 int (*f)(void *, void *, u_int), void *arg)
1338 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1339 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1341 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1348 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1349 count = min(m->m_len - off, len);
1350 rval = m_apply_one(m, off, count, f, arg);
1361 * Return a pointer to mbuf/offset of location in mbuf chain.
1364 m_getptr(struct mbuf *m, int loc, int *off)
1368 /* Normal end of search. */
1369 if (m->m_len > loc) {
1374 if (m->m_next == NULL) {
1376 /* Point at the end of valid data. */
1389 m_print(const struct mbuf *m, int maxlen)
1393 const struct mbuf *m2;
1396 printf("mbuf: %p\n", m);
1400 if (m->m_flags & M_PKTHDR)
1401 len = m->m_pkthdr.len;
1405 while (m2 != NULL && (len == -1 || len)) {
1407 if (maxlen != -1 && pdata > maxlen)
1409 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1410 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1411 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1412 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1414 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1420 printf("%d bytes unaccounted for.\n", len);
1425 m_fixhdr(struct mbuf *m0)
1429 len = m_length(m0, NULL);
1430 m0->m_pkthdr.len = len;
1435 m_length(struct mbuf *m0, struct mbuf **last)
1441 for (m = m0; m != NULL; m = m->m_next) {
1443 if (m->m_next == NULL)
1452 * Defragment a mbuf chain, returning the shortest possible
1453 * chain of mbufs and clusters. If allocation fails and
1454 * this cannot be completed, NULL will be returned, but
1455 * the passed in chain will be unchanged. Upon success,
1456 * the original chain will be freed, and the new chain
1459 * If a non-packet header is passed in, the original
1460 * mbuf (chain?) will be returned unharmed.
1463 m_defrag(struct mbuf *m0, int how)
1465 struct mbuf *m_new = NULL, *m_final = NULL;
1466 int progress = 0, length;
1468 MBUF_CHECKSLEEP(how);
1469 if (!(m0->m_flags & M_PKTHDR))
1472 m_fixhdr(m0); /* Needed sanity check */
1474 #ifdef MBUF_STRESS_TEST
1475 if (m_defragrandomfailures) {
1476 int temp = arc4random() & 0xff;
1482 if (m0->m_pkthdr.len > MHLEN)
1483 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1485 m_final = m_gethdr(how, MT_DATA);
1487 if (m_final == NULL)
1490 if (m_dup_pkthdr(m_final, m0, how) == 0)
1495 while (progress < m0->m_pkthdr.len) {
1496 length = m0->m_pkthdr.len - progress;
1497 if (length > MCLBYTES)
1500 if (m_new == NULL) {
1502 m_new = m_getcl(how, MT_DATA, 0);
1504 m_new = m_get(how, MT_DATA);
1509 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1511 m_new->m_len = length;
1512 if (m_new != m_final)
1513 m_cat(m_final, m_new);
1516 #ifdef MBUF_STRESS_TEST
1517 if (m0->m_next == NULL)
1522 #ifdef MBUF_STRESS_TEST
1524 m_defragbytes += m0->m_pkthdr.len;
1528 #ifdef MBUF_STRESS_TEST
1537 * Return the number of fragments an mbuf will use. This is usually
1538 * used as a proxy for the number of scatter/gather elements needed by
1539 * a DMA engine to access an mbuf. In general mapped mbufs are
1540 * assumed to be backed by physically contiguous buffers that only
1541 * need a single fragment. Unmapped mbufs, on the other hand, can
1542 * span disjoint physical pages.
1545 frags_per_mbuf(struct mbuf *m)
1549 if ((m->m_flags & M_EXTPG) == 0)
1553 * The header and trailer are counted as a single fragment
1554 * each when present.
1556 * XXX: This overestimates the number of fragments by assuming
1557 * all the backing physical pages are disjoint.
1560 if (m->m_epg_hdrlen != 0)
1562 frags += m->m_epg_npgs;
1563 if (m->m_epg_trllen != 0)
1570 * Defragment an mbuf chain, returning at most maxfrags separate
1571 * mbufs+clusters. If this is not possible NULL is returned and
1572 * the original mbuf chain is left in its present (potentially
1573 * modified) state. We use two techniques: collapsing consecutive
1574 * mbufs and replacing consecutive mbufs by a cluster.
1576 * NB: this should really be named m_defrag but that name is taken
1579 m_collapse(struct mbuf *m0, int how, int maxfrags)
1581 struct mbuf *m, *n, *n2, **prev;
1585 * Calculate the current number of frags.
1588 for (m = m0; m != NULL; m = m->m_next)
1589 curfrags += frags_per_mbuf(m);
1591 * First, try to collapse mbufs. Note that we always collapse
1592 * towards the front so we don't need to deal with moving the
1593 * pkthdr. This may be suboptimal if the first mbuf has much
1594 * less data than the following.
1602 if (M_WRITABLE(m) &&
1603 n->m_len < M_TRAILINGSPACE(m)) {
1604 m_copydata(n, 0, n->m_len,
1605 mtod(m, char *) + m->m_len);
1606 m->m_len += n->m_len;
1607 m->m_next = n->m_next;
1608 curfrags -= frags_per_mbuf(n);
1610 if (curfrags <= maxfrags)
1615 KASSERT(maxfrags > 1,
1616 ("maxfrags %u, but normal collapse failed", maxfrags));
1618 * Collapse consecutive mbufs to a cluster.
1620 prev = &m0->m_next; /* NB: not the first mbuf */
1621 while ((n = *prev) != NULL) {
1622 if ((n2 = n->m_next) != NULL &&
1623 n->m_len + n2->m_len < MCLBYTES) {
1624 m = m_getcl(how, MT_DATA, 0);
1627 m_copydata(n, 0, n->m_len, mtod(m, char *));
1628 m_copydata(n2, 0, n2->m_len,
1629 mtod(m, char *) + n->m_len);
1630 m->m_len = n->m_len + n2->m_len;
1631 m->m_next = n2->m_next;
1633 curfrags += 1; /* For the new cluster */
1634 curfrags -= frags_per_mbuf(n);
1635 curfrags -= frags_per_mbuf(n2);
1638 if (curfrags <= maxfrags)
1641 * Still not there, try the normal collapse
1642 * again before we allocate another cluster.
1649 * No place where we can collapse to a cluster; punt.
1650 * This can occur if, for example, you request 2 frags
1651 * but the packet requires that both be clusters (we
1652 * never reallocate the first mbuf to avoid moving the
1659 #ifdef MBUF_STRESS_TEST
1662 * Fragment an mbuf chain. There's no reason you'd ever want to do
1663 * this in normal usage, but it's great for stress testing various
1666 * If fragmentation is not possible, the original chain will be
1669 * Possible length values:
1670 * 0 no fragmentation will occur
1671 * > 0 each fragment will be of the specified length
1672 * -1 each fragment will be the same random value in length
1673 * -2 each fragment's length will be entirely random
1674 * (Random values range from 1 to 256)
1677 m_fragment(struct mbuf *m0, int how, int length)
1679 struct mbuf *m_first, *m_last;
1680 int divisor = 255, progress = 0, fraglen;
1682 if (!(m0->m_flags & M_PKTHDR))
1685 if (length == 0 || length < -2)
1687 if (length > MCLBYTES)
1689 if (length < 0 && divisor > MCLBYTES)
1692 length = 1 + (arc4random() % divisor);
1696 m_fixhdr(m0); /* Needed sanity check */
1698 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1699 if (m_first == NULL)
1702 if (m_dup_pkthdr(m_first, m0, how) == 0)
1707 while (progress < m0->m_pkthdr.len) {
1709 fraglen = 1 + (arc4random() % divisor);
1710 if (fraglen > m0->m_pkthdr.len - progress)
1711 fraglen = m0->m_pkthdr.len - progress;
1713 if (progress != 0) {
1714 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1718 m_last->m_next = m_new;
1722 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1723 progress += fraglen;
1724 m_last->m_len = fraglen;
1732 /* Return the original chain on failure */
1739 * Free pages from mbuf_ext_pgs, assuming they were allocated via
1740 * vm_page_alloc() and aren't associated with any object. Complement
1741 * to allocator from m_uiotombuf_nomap().
1744 mb_free_mext_pgs(struct mbuf *m)
1749 for (int i = 0; i < m->m_epg_npgs; i++) {
1750 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1751 vm_page_unwire_noq(pg);
1756 static struct mbuf *
1757 m_uiotombuf_nomap(struct uio *uio, int how, int len, int maxseg, int flags)
1759 struct mbuf *m, *mb, *prev;
1760 vm_page_t pg_array[MBUF_PEXT_MAX_PGS];
1761 int error, length, i, needed;
1763 int pflags = malloc2vm_flags(how) | VM_ALLOC_NODUMP | VM_ALLOC_WIRED;
1765 MPASS((flags & M_PKTHDR) == 0);
1766 MPASS((how & M_ZERO) == 0);
1769 * len can be zero or an arbitrary large value bound by
1770 * the total data supplied by the uio.
1773 total = MIN(uio->uio_resid, len);
1775 total = uio->uio_resid;
1778 maxseg = MBUF_PEXT_MAX_PGS * PAGE_SIZE;
1781 * If total is zero, return an empty mbuf. This can occur
1782 * for TLS 1.0 connections which send empty fragments as
1783 * a countermeasure against the known-IV weakness in CBC
1786 if (__predict_false(total == 0)) {
1787 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1790 mb->m_epg_flags = EPG_FLAG_ANON;
1795 * Allocate the pages
1799 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1807 mb->m_epg_flags = EPG_FLAG_ANON;
1808 needed = length = MIN(maxseg, total);
1809 for (i = 0; needed > 0; i++, needed -= PAGE_SIZE) {
1811 pg_array[i] = vm_page_alloc_noobj(pflags);
1812 if (pg_array[i] == NULL) {
1813 if (how & M_NOWAIT) {
1820 mb->m_epg_pa[i] = VM_PAGE_TO_PHYS(pg_array[i]);
1823 mb->m_epg_last_len = length - PAGE_SIZE * (mb->m_epg_npgs - 1);
1824 MBUF_EXT_PGS_ASSERT_SANITY(mb);
1826 error = uiomove_fromphys(pg_array, 0, length, uio);
1830 mb->m_ext.ext_size += PAGE_SIZE * mb->m_epg_npgs;
1831 if (flags & M_PKTHDR)
1832 m->m_pkthdr.len += length;
1842 * Copy the contents of uio into a properly sized mbuf chain.
1845 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1847 struct mbuf *m, *mb;
1852 if (flags & M_EXTPG)
1853 return (m_uiotombuf_nomap(uio, how, len, align, flags));
1856 * len can be zero or an arbitrary large value bound by
1857 * the total data supplied by the uio.
1860 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1862 total = uio->uio_resid;
1865 * The smallest unit returned by m_getm2() is a single mbuf
1866 * with pkthdr. We can't align past it.
1872 * Give us the full allocation or nothing.
1873 * If len is zero return the smallest empty mbuf.
1875 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1880 /* Fill all mbufs with uio data and update header information. */
1881 for (mb = m; mb != NULL; mb = mb->m_next) {
1882 length = min(M_TRAILINGSPACE(mb), total - progress);
1884 error = uiomove(mtod(mb, void *), length, uio);
1892 if (flags & M_PKTHDR)
1893 m->m_pkthdr.len += length;
1895 KASSERT(progress == total, ("%s: progress != total", __func__));
1901 * Copy data to/from an unmapped mbuf into a uio limited by len if set.
1904 m_unmapped_uiomove(const struct mbuf *m, int m_off, struct uio *uio, int len)
1907 int error, i, off, pglen, pgoff, seglen, segoff;
1912 /* Skip over any data removed from the front. */
1913 off = mtod(m, vm_offset_t);
1916 if (m->m_epg_hdrlen != 0) {
1917 if (off >= m->m_epg_hdrlen) {
1918 off -= m->m_epg_hdrlen;
1920 seglen = m->m_epg_hdrlen - off;
1922 seglen = min(seglen, len);
1925 error = uiomove(__DECONST(void *,
1926 &m->m_epg_hdr[segoff]), seglen, uio);
1929 pgoff = m->m_epg_1st_off;
1930 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
1931 pglen = m_epg_pagelen(m, i, pgoff);
1937 seglen = pglen - off;
1938 segoff = pgoff + off;
1940 seglen = min(seglen, len);
1942 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1943 error = uiomove_fromphys(&pg, segoff, seglen, uio);
1946 if (len != 0 && error == 0) {
1947 KASSERT((off + len) <= m->m_epg_trllen,
1948 ("off + len > trail (%d + %d > %d, m_off = %d)", off, len,
1949 m->m_epg_trllen, m_off));
1950 error = uiomove(__DECONST(void *, &m->m_epg_trail[off]),
1957 * Copy an mbuf chain into a uio limited by len if set.
1960 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
1962 int error, length, total;
1966 total = min(uio->uio_resid, len);
1968 total = uio->uio_resid;
1970 /* Fill the uio with data from the mbufs. */
1971 for (; m != NULL; m = m->m_next) {
1972 length = min(m->m_len, total - progress);
1974 if ((m->m_flags & M_EXTPG) != 0)
1975 error = m_unmapped_uiomove(m, 0, uio, length);
1977 error = uiomove(mtod(m, void *), length, uio);
1988 * Create a writable copy of the mbuf chain. While doing this
1989 * we compact the chain with a goal of producing a chain with
1990 * at most two mbufs. The second mbuf in this chain is likely
1991 * to be a cluster. The primary purpose of this work is to create
1992 * a writable packet for encryption, compression, etc. The
1993 * secondary goal is to linearize the data so the data can be
1994 * passed to crypto hardware in the most efficient manner possible.
1997 m_unshare(struct mbuf *m0, int how)
1999 struct mbuf *m, *mprev;
2000 struct mbuf *n, *mfirst, *mlast;
2004 for (m = m0; m != NULL; m = mprev->m_next) {
2006 * Regular mbufs are ignored unless there's a cluster
2007 * in front of it that we can use to coalesce. We do
2008 * the latter mainly so later clusters can be coalesced
2009 * also w/o having to handle them specially (i.e. convert
2010 * mbuf+cluster -> cluster). This optimization is heavily
2011 * influenced by the assumption that we're running over
2012 * Ethernet where MCLBYTES is large enough that the max
2013 * packet size will permit lots of coalescing into a
2014 * single cluster. This in turn permits efficient
2015 * crypto operations, especially when using hardware.
2017 if ((m->m_flags & M_EXT) == 0) {
2018 if (mprev && (mprev->m_flags & M_EXT) &&
2019 m->m_len <= M_TRAILINGSPACE(mprev)) {
2020 /* XXX: this ignores mbuf types */
2021 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2022 mtod(m, caddr_t), m->m_len);
2023 mprev->m_len += m->m_len;
2024 mprev->m_next = m->m_next; /* unlink from chain */
2025 m_free(m); /* reclaim mbuf */
2032 * Writable mbufs are left alone (for now).
2034 if (M_WRITABLE(m)) {
2040 * Not writable, replace with a copy or coalesce with
2041 * the previous mbuf if possible (since we have to copy
2042 * it anyway, we try to reduce the number of mbufs and
2043 * clusters so that future work is easier).
2045 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
2046 /* NB: we only coalesce into a cluster or larger */
2047 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
2048 m->m_len <= M_TRAILINGSPACE(mprev)) {
2049 /* XXX: this ignores mbuf types */
2050 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2051 mtod(m, caddr_t), m->m_len);
2052 mprev->m_len += m->m_len;
2053 mprev->m_next = m->m_next; /* unlink from chain */
2054 m_free(m); /* reclaim mbuf */
2059 * Allocate new space to hold the copy and copy the data.
2060 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
2061 * splitting them into clusters. We could just malloc a
2062 * buffer and make it external but too many device drivers
2063 * don't know how to break up the non-contiguous memory when
2066 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2071 if (m->m_flags & M_PKTHDR) {
2072 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
2074 m_move_pkthdr(n, m);
2081 int cc = min(len, MCLBYTES);
2082 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2088 newipsecstat.ips_clcopied++;
2096 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2103 n->m_next = m->m_next;
2105 m0 = mfirst; /* new head of chain */
2107 mprev->m_next = mfirst; /* replace old mbuf */
2108 m_free(m); /* release old mbuf */
2114 #ifdef MBUF_PROFILING
2116 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2117 struct mbufprofile {
2118 uintmax_t wasted[MP_BUCKETS];
2119 uintmax_t used[MP_BUCKETS];
2120 uintmax_t segments[MP_BUCKETS];
2124 m_profile(struct mbuf *m)
2133 if (m->m_flags & M_EXT) {
2134 wasted += MHLEN - sizeof(m->m_ext) +
2135 m->m_ext.ext_size - m->m_len;
2137 if (m->m_flags & M_PKTHDR)
2138 wasted += MHLEN - m->m_len;
2140 wasted += MLEN - m->m_len;
2144 /* be paranoid.. it helps */
2145 if (segments > MP_BUCKETS - 1)
2146 segments = MP_BUCKETS - 1;
2149 if (wasted > 100000)
2151 /* store in the appropriate bucket */
2152 /* don't bother locking. if it's slightly off, so what? */
2153 mbprof.segments[segments]++;
2154 mbprof.used[fls(used)]++;
2155 mbprof.wasted[fls(wasted)]++;
2159 mbprof_handler(SYSCTL_HANDLER_ARGS)
2166 sbuf_new_for_sysctl(&sb, buf, sizeof(buf), req);
2168 p = &mbprof.wasted[0];
2171 "%ju %ju %ju %ju %ju %ju %ju %ju "
2172 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2173 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2174 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2176 p = &mbprof.wasted[16];
2178 "%ju %ju %ju %ju %ju %ju %ju %ju "
2179 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2180 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2181 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2183 p = &mbprof.used[0];
2186 "%ju %ju %ju %ju %ju %ju %ju %ju "
2187 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2188 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2189 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2191 p = &mbprof.used[16];
2193 "%ju %ju %ju %ju %ju %ju %ju %ju "
2194 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2195 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2196 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2198 p = &mbprof.segments[0];
2201 "%ju %ju %ju %ju %ju %ju %ju %ju "
2202 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2203 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2204 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2206 p = &mbprof.segments[16];
2208 "%ju %ju %ju %ju %ju %ju %ju %ju "
2209 "%ju %ju %ju %ju %ju %ju %ju %jju",
2210 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2211 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2214 error = sbuf_finish(&sb);
2220 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2225 error = sysctl_handle_int(oidp, &clear, 0, req);
2226 if (error || !req->newptr)
2230 bzero(&mbprof, sizeof(mbprof));
2236 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile,
2237 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2238 mbprof_handler, "A",
2239 "mbuf profiling statistics");
2241 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr,
2242 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
2243 mbprof_clr_handler, "I",
2244 "clear mbuf profiling statistics");