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,
66 "uint32_t", "uint32_t",
67 "uint16_t", "uint16_t",
68 "struct mbuf *", "mbufinfo_t *");
70 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__get,
71 "uint32_t", "uint32_t",
72 "uint16_t", "uint16_t",
73 "struct mbuf *", "mbufinfo_t *");
75 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__getcl,
76 "uint32_t", "uint32_t",
77 "uint16_t", "uint16_t",
78 "uint32_t", "uint32_t",
79 "struct mbuf *", "mbufinfo_t *");
81 SDT_PROBE_DEFINE5_XLATE(sdt, , , m__getjcl,
82 "uint32_t", "uint32_t",
83 "uint16_t", "uint16_t",
84 "uint32_t", "uint32_t",
85 "uint32_t", "uint32_t",
86 "struct mbuf *", "mbufinfo_t *");
88 SDT_PROBE_DEFINE3_XLATE(sdt, , , m__clget,
89 "struct mbuf *", "mbufinfo_t *",
90 "uint32_t", "uint32_t",
91 "uint32_t", "uint32_t");
93 SDT_PROBE_DEFINE4_XLATE(sdt, , , m__cljget,
94 "struct mbuf *", "mbufinfo_t *",
95 "uint32_t", "uint32_t",
96 "uint32_t", "uint32_t",
99 SDT_PROBE_DEFINE(sdt, , , m__cljset);
101 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__free,
102 "struct mbuf *", "mbufinfo_t *");
104 SDT_PROBE_DEFINE1_XLATE(sdt, , , m__freem,
105 "struct mbuf *", "mbufinfo_t *");
107 #include <security/mac/mac_framework.h>
113 #ifdef MBUF_STRESS_TEST
118 int m_defragrandomfailures;
122 * sysctl(8) exported objects
124 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
125 &max_linkhdr, 0, "Size of largest link layer header");
126 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
127 &max_protohdr, 0, "Size of largest protocol layer header");
128 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
129 &max_hdr, 0, "Size of largest link plus protocol header");
130 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
131 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
132 #ifdef MBUF_STRESS_TEST
133 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
134 &m_defragpackets, 0, "");
135 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
136 &m_defragbytes, 0, "");
137 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
138 &m_defraguseless, 0, "");
139 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
140 &m_defragfailure, 0, "");
141 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
142 &m_defragrandomfailures, 0, "");
146 * Ensure the correct size of various mbuf parameters. It could be off due
147 * to compiler-induced padding and alignment artifacts.
149 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
150 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
153 * mbuf data storage should be 64-bit aligned regardless of architectural
154 * pointer size; check this is the case with and without a packet header.
156 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
157 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
160 * While the specific values here don't matter too much (i.e., +/- a few
161 * words), we do want to ensure that changes to these values are carefully
162 * reasoned about and properly documented. This is especially the case as
163 * network-protocol and device-driver modules encode these layouts, and must
164 * be recompiled if the structures change. Check these values at compile time
165 * against the ones documented in comments in mbuf.h.
167 * NB: Possibly they should be documented there via #define's and not just
170 #if defined(__LP64__)
171 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
172 CTASSERT(sizeof(struct pkthdr) == 56);
173 CTASSERT(sizeof(struct m_ext) == 160);
175 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
176 CTASSERT(sizeof(struct pkthdr) == 48);
177 #if defined(__powerpc__) && defined(BOOKE)
178 /* PowerPC booke has 64-bit physical pointers. */
179 CTASSERT(sizeof(struct m_ext) == 184);
181 CTASSERT(sizeof(struct m_ext) == 180);
186 * Assert that the queue(3) macros produce code of the same size as an old
187 * plain pointer does.
190 static struct mbuf __used m_assertbuf;
191 CTASSERT(sizeof(m_assertbuf.m_slist) == sizeof(m_assertbuf.m_next));
192 CTASSERT(sizeof(m_assertbuf.m_stailq) == sizeof(m_assertbuf.m_next));
193 CTASSERT(sizeof(m_assertbuf.m_slistpkt) == sizeof(m_assertbuf.m_nextpkt));
194 CTASSERT(sizeof(m_assertbuf.m_stailqpkt) == sizeof(m_assertbuf.m_nextpkt));
198 * Attach the cluster from *m to *n, set up m_ext in *n
199 * and bump the refcount of the cluster.
202 mb_dupcl(struct mbuf *n, struct mbuf *m)
204 volatile u_int *refcnt;
206 KASSERT(m->m_flags & (M_EXT|M_EXTPG),
207 ("%s: M_EXT|M_EXTPG not set on %p", __func__, m));
208 KASSERT(!(n->m_flags & (M_EXT|M_EXTPG)),
209 ("%s: M_EXT|M_EXTPG set on %p", __func__, n));
212 * Cache access optimization.
214 * o Regular M_EXT storage doesn't need full copy of m_ext, since
215 * the holder of the 'ext_count' is responsible to carry the free
216 * routine and its arguments.
217 * o M_EXTPG data is split between main part of mbuf and m_ext, the
218 * main part is copied in full, the m_ext part is similar to M_EXT.
219 * o EXT_EXTREF, where 'ext_cnt' doesn't point into mbuf at all, is
220 * special - it needs full copy of m_ext into each mbuf, since any
221 * copy could end up as the last to free.
223 if (m->m_flags & M_EXTPG) {
224 bcopy(&m->m_epg_startcopy, &n->m_epg_startcopy,
225 __rangeof(struct mbuf, m_epg_startcopy, m_epg_endcopy));
226 bcopy(&m->m_ext, &n->m_ext, m_epg_ext_copylen);
227 } else if (m->m_ext.ext_type == EXT_EXTREF)
228 bcopy(&m->m_ext, &n->m_ext, sizeof(struct m_ext));
230 bcopy(&m->m_ext, &n->m_ext, m_ext_copylen);
232 n->m_flags |= m->m_flags & (M_RDONLY | M_EXT | M_EXTPG);
234 /* See if this is the mbuf that holds the embedded refcount. */
235 if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
236 refcnt = n->m_ext.ext_cnt = &m->m_ext.ext_count;
237 n->m_ext.ext_flags &= ~EXT_FLAG_EMBREF;
239 KASSERT(m->m_ext.ext_cnt != NULL,
240 ("%s: no refcounting pointer on %p", __func__, m));
241 refcnt = m->m_ext.ext_cnt;
247 atomic_add_int(refcnt, 1);
251 m_demote_pkthdr(struct mbuf *m)
256 m_tag_delete_chain(m, NULL);
257 m->m_flags &= ~M_PKTHDR;
258 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
262 * Clean up mbuf (chain) from any tags and packet headers.
263 * If "all" is set then the first mbuf in the chain will be
267 m_demote(struct mbuf *m0, int all, int flags)
271 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
272 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
274 if (m->m_flags & M_PKTHDR)
276 m->m_flags = m->m_flags & (M_EXT | M_RDONLY | M_NOFREE |
282 * Sanity checks on mbuf (chain) for use in KASSERT() and general
284 * Returns 0 or panics when bad and 1 on all tests passed.
285 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
289 m_sanity(struct mbuf *m0, int sanitize)
296 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
298 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
301 for (m = m0; m != NULL; m = m->m_next) {
303 * Basic pointer checks. If any of these fails then some
304 * unrelated kernel memory before or after us is trashed.
305 * No way to recover from that.
309 if ((caddr_t)m->m_data < a)
310 M_SANITY_ACTION("m_data outside mbuf data range left");
311 if ((caddr_t)m->m_data > b)
312 M_SANITY_ACTION("m_data outside mbuf data range right");
313 if ((caddr_t)m->m_data + m->m_len > b)
314 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
316 /* m->m_nextpkt may only be set on first mbuf in chain. */
317 if (m != m0 && m->m_nextpkt != NULL) {
319 m_freem(m->m_nextpkt);
320 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
322 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
325 /* packet length (not mbuf length!) calculation */
326 if (m0->m_flags & M_PKTHDR)
329 /* m_tags may only be attached to first mbuf in chain. */
330 if (m != m0 && m->m_flags & M_PKTHDR &&
331 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
333 m_tag_delete_chain(m, NULL);
334 /* put in 0xDEADC0DE perhaps? */
336 M_SANITY_ACTION("m_tags on in-chain mbuf");
339 /* M_PKTHDR may only be set on first mbuf in chain */
340 if (m != m0 && m->m_flags & M_PKTHDR) {
342 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
343 m->m_flags &= ~M_PKTHDR;
344 /* put in 0xDEADCODE and leave hdr flag in */
346 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
350 if (pktlen && pktlen != m->m_pkthdr.len) {
354 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
358 #undef M_SANITY_ACTION
362 * Non-inlined part of m_init().
365 m_pkthdr_init(struct mbuf *m, int how)
370 m->m_data = m->m_pktdat;
371 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
373 m->m_pkthdr.numa_domain = M_NODOM;
376 /* If the label init fails, fail the alloc */
377 error = mac_mbuf_init(m, how);
386 * "Move" mbuf pkthdr from "from" to "to".
387 * "from" must have M_PKTHDR set, and "to" must be empty.
390 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
394 /* see below for why these are not enabled */
396 /* Note: with MAC, this may not be a good assertion. */
397 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
398 ("m_move_pkthdr: to has tags"));
402 * XXXMAC: It could be this should also occur for non-MAC?
404 if (to->m_flags & M_PKTHDR)
405 m_tag_delete_chain(to, NULL);
407 to->m_flags = (from->m_flags & M_COPYFLAGS) |
408 (to->m_flags & (M_EXT | M_EXTPG));
409 if ((to->m_flags & M_EXT) == 0)
410 to->m_data = to->m_pktdat;
411 to->m_pkthdr = from->m_pkthdr; /* especially tags */
412 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
413 from->m_flags &= ~M_PKTHDR;
414 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG) {
415 from->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
416 from->m_pkthdr.snd_tag = NULL;
421 * Duplicate "from"'s mbuf pkthdr in "to".
422 * "from" must have M_PKTHDR set, and "to" must be empty.
423 * In particular, this does a deep copy of the packet tags.
426 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
431 * The mbuf allocator only initializes the pkthdr
432 * when the mbuf is allocated with m_gethdr(). Many users
433 * (e.g. m_copy*, m_prepend) use m_get() and then
434 * smash the pkthdr as needed causing these
435 * assertions to trip. For now just disable them.
438 /* Note: with MAC, this may not be a good assertion. */
439 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
441 MBUF_CHECKSLEEP(how);
443 if (to->m_flags & M_PKTHDR)
444 m_tag_delete_chain(to, NULL);
446 to->m_flags = (from->m_flags & M_COPYFLAGS) |
447 (to->m_flags & (M_EXT | M_EXTPG));
448 if ((to->m_flags & M_EXT) == 0)
449 to->m_data = to->m_pktdat;
450 to->m_pkthdr = from->m_pkthdr;
451 if (from->m_pkthdr.csum_flags & CSUM_SND_TAG)
452 m_snd_tag_ref(from->m_pkthdr.snd_tag);
453 SLIST_INIT(&to->m_pkthdr.tags);
454 return (m_tag_copy_chain(to, from, how));
458 * Lesser-used path for M_PREPEND:
459 * allocate new mbuf to prepend to chain,
463 m_prepend(struct mbuf *m, int len, int how)
467 if (m->m_flags & M_PKTHDR)
468 mn = m_gethdr(how, m->m_type);
470 mn = m_get(how, m->m_type);
475 if (m->m_flags & M_PKTHDR)
476 m_move_pkthdr(mn, m);
486 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
487 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
488 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
489 * Note that the copy is read-only, because clusters are not copied,
490 * only their reference counts are incremented.
493 m_copym(struct mbuf *m, int off0, int len, int wait)
495 struct mbuf *n, **np;
500 KASSERT(off >= 0, ("m_copym, negative off %d", off));
501 KASSERT(len >= 0, ("m_copym, negative len %d", len));
502 MBUF_CHECKSLEEP(wait);
503 if (off == 0 && m->m_flags & M_PKTHDR)
506 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
516 KASSERT(len == M_COPYALL,
517 ("m_copym, length > size of mbuf chain"));
521 n = m_gethdr(wait, m->m_type);
523 n = m_get(wait, m->m_type);
528 if (!m_dup_pkthdr(n, m, wait))
530 if (len == M_COPYALL)
531 n->m_pkthdr.len -= off0;
533 n->m_pkthdr.len = len;
536 n->m_len = min(len, m->m_len - off);
537 if (m->m_flags & (M_EXT|M_EXTPG)) {
538 n->m_data = m->m_data + off;
541 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
543 if (len != M_COPYALL)
557 * Copy an entire packet, including header (which must be present).
558 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
559 * Note that the copy is read-only, because clusters are not copied,
560 * only their reference counts are incremented.
561 * Preserve alignment of the first mbuf so if the creator has left
562 * some room at the beginning (e.g. for inserting protocol headers)
563 * the copies still have the room available.
566 m_copypacket(struct mbuf *m, int how)
568 struct mbuf *top, *n, *o;
570 MBUF_CHECKSLEEP(how);
571 n = m_get(how, m->m_type);
576 if (!m_dup_pkthdr(n, m, how))
579 if (m->m_flags & (M_EXT|M_EXTPG)) {
580 n->m_data = m->m_data;
583 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
584 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
589 o = m_get(how, m->m_type);
597 if (m->m_flags & (M_EXT|M_EXTPG)) {
598 n->m_data = m->m_data;
601 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
613 m_copyfromunmapped(const struct mbuf *m, int off, int len, caddr_t cp)
619 KASSERT(off >= 0, ("m_copyfromunmapped: negative off %d", off));
620 KASSERT(len >= 0, ("m_copyfromunmapped: negative len %d", len));
621 KASSERT(off < m->m_len,
622 ("m_copyfromunmapped: len exceeds mbuf length"));
627 uio.uio_segflg = UIO_SYSSPACE;
630 uio.uio_rw = UIO_READ;
631 error = m_unmappedtouio(m, off, &uio, len);
632 KASSERT(error == 0, ("m_unmappedtouio failed: off %d, len %d", off,
637 * Copy data from an mbuf chain starting "off" bytes from the beginning,
638 * continuing for "len" bytes, into the indicated buffer.
641 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
645 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
646 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
648 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
655 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
656 count = min(m->m_len - off, len);
657 if ((m->m_flags & M_EXTPG) != 0)
658 m_copyfromunmapped(m, off, count, cp);
660 bcopy(mtod(m, caddr_t) + off, cp, count);
669 * Copy a packet header mbuf chain into a completely new chain, including
670 * copying any mbuf clusters. Use this instead of m_copypacket() when
671 * you need a writable copy of an mbuf chain.
674 m_dup(const struct mbuf *m, int how)
676 struct mbuf **p, *top = NULL;
677 int remain, moff, nsize;
679 MBUF_CHECKSLEEP(how);
685 /* While there's more data, get a new mbuf, tack it on, and fill it */
686 remain = m->m_pkthdr.len;
689 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
692 /* Get the next new mbuf */
693 if (remain >= MINCLSIZE) {
694 n = m_getcl(how, m->m_type, 0);
697 n = m_get(how, m->m_type);
703 if (top == NULL) { /* First one, must be PKTHDR */
704 if (!m_dup_pkthdr(n, m, how)) {
708 if ((n->m_flags & M_EXT) == 0)
710 n->m_flags &= ~M_RDONLY;
714 /* Link it into the new chain */
718 /* Copy data from original mbuf(s) into new mbuf */
719 while (n->m_len < nsize && m != NULL) {
720 int chunk = min(nsize - n->m_len, m->m_len - moff);
722 m_copydata(m, moff, chunk, n->m_data + n->m_len);
726 if (moff == m->m_len) {
732 /* Check correct total mbuf length */
733 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
734 ("%s: bogus m_pkthdr.len", __func__));
744 * Concatenate mbuf chain n to m.
745 * Both chains must be of the same type (e.g. MT_DATA).
746 * Any m_pkthdr is not updated.
749 m_cat(struct mbuf *m, struct mbuf *n)
754 if (!M_WRITABLE(m) ||
755 (n->m_flags & M_EXTPG) != 0 ||
756 M_TRAILINGSPACE(m) < n->m_len) {
757 /* just join the two chains */
761 /* splat the data from one into the other */
762 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
764 m->m_len += n->m_len;
770 * Concatenate two pkthdr mbuf chains.
773 m_catpkt(struct mbuf *m, struct mbuf *n)
779 m->m_pkthdr.len += n->m_pkthdr.len;
786 m_adj(struct mbuf *mp, int req_len)
792 if ((m = mp) == NULL)
798 while (m != NULL && len > 0) {
799 if (m->m_len <= len) {
809 if (mp->m_flags & M_PKTHDR)
810 mp->m_pkthdr.len -= (req_len - len);
813 * Trim from tail. Scan the mbuf chain,
814 * calculating its length and finding the last mbuf.
815 * If the adjustment only affects this mbuf, then just
816 * adjust and return. Otherwise, rescan and truncate
817 * after the remaining size.
823 if (m->m_next == (struct mbuf *)0)
827 if (m->m_len >= len) {
829 if (mp->m_flags & M_PKTHDR)
830 mp->m_pkthdr.len -= len;
837 * Correct length for chain is "count".
838 * Find the mbuf with last data, adjust its length,
839 * and toss data from remaining mbufs on chain.
842 if (m->m_flags & M_PKTHDR)
843 m->m_pkthdr.len = count;
844 for (; m; m = m->m_next) {
845 if (m->m_len >= count) {
847 if (m->m_next != NULL) {
859 m_adj_decap(struct mbuf *mp, int len)
864 if ((mp->m_flags & M_PKTHDR) != 0) {
866 * If flowid was calculated by card from the inner
867 * headers, move flowid to the decapsulated mbuf
868 * chain, otherwise clear. This depends on the
869 * internals of m_adj, which keeps pkthdr as is, in
870 * particular not changing rsstype and flowid.
872 rsstype = mp->m_pkthdr.rsstype;
873 if ((rsstype & M_HASHTYPE_INNER) != 0) {
874 M_HASHTYPE_SET(mp, rsstype & ~M_HASHTYPE_INNER);
876 M_HASHTYPE_CLEAR(mp);
882 * Rearange an mbuf chain so that len bytes are contiguous
883 * and in the data area of an mbuf (so that mtod will work
884 * for a structure of size len). Returns the resulting
885 * mbuf chain on success, frees it and returns null on failure.
886 * If there is room, it will add up to max_protohdr-len extra bytes to the
887 * contiguous region in an attempt to avoid being called next time.
890 m_pullup(struct mbuf *n, int len)
896 KASSERT((n->m_flags & M_EXTPG) == 0,
897 ("%s: unmapped mbuf %p", __func__, n));
900 * If first mbuf has no cluster, and has room for len bytes
901 * without shifting current data, pullup into it,
902 * otherwise allocate a new mbuf to prepend to the chain.
904 if ((n->m_flags & M_EXT) == 0 &&
905 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
914 m = m_get(M_NOWAIT, n->m_type);
917 if (n->m_flags & M_PKTHDR)
920 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
922 count = min(min(max(len, max_protohdr), space), n->m_len);
923 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
933 } while (len > 0 && n);
946 * Like m_pullup(), except a new mbuf is always allocated, and we allow
947 * the amount of empty space before the data in the new mbuf to be specified
948 * (in the event that the caller expects to prepend later).
951 m_copyup(struct mbuf *n, int len, int dstoff)
956 if (len > (MHLEN - dstoff))
958 m = m_get(M_NOWAIT, n->m_type);
961 if (n->m_flags & M_PKTHDR)
964 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
966 count = min(min(max(len, max_protohdr), space), n->m_len);
967 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
977 } while (len > 0 && n);
990 * Partition an mbuf chain in two pieces, returning the tail --
991 * all but the first len0 bytes. In case of failure, it returns NULL and
992 * attempts to restore the chain to its original state.
994 * Note that the resulting mbufs might be read-only, because the new
995 * mbuf can end up sharing an mbuf cluster with the original mbuf if
996 * the "breaking point" happens to lie within a cluster mbuf. Use the
997 * M_WRITABLE() macro to check for this case.
1000 m_split(struct mbuf *m0, int len0, int wait)
1003 u_int len = len0, remain;
1005 MBUF_CHECKSLEEP(wait);
1006 for (m = m0; m && len > m->m_len; m = m->m_next)
1010 remain = m->m_len - len;
1011 if (m0->m_flags & M_PKTHDR && remain == 0) {
1012 n = m_gethdr(wait, m0->m_type);
1015 n->m_next = m->m_next;
1017 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1018 n->m_pkthdr.snd_tag =
1019 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1020 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1022 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1023 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1024 m0->m_pkthdr.len = len0;
1026 } else if (m0->m_flags & M_PKTHDR) {
1027 n = m_gethdr(wait, m0->m_type);
1030 if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG) {
1031 n->m_pkthdr.snd_tag =
1032 m_snd_tag_ref(m0->m_pkthdr.snd_tag);
1033 n->m_pkthdr.csum_flags |= CSUM_SND_TAG;
1035 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1036 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1037 m0->m_pkthdr.len = len0;
1038 if (m->m_flags & (M_EXT|M_EXTPG))
1040 if (remain > MHLEN) {
1041 /* m can't be the lead packet */
1043 n->m_next = m_split(m, len, wait);
1044 if (n->m_next == NULL) {
1053 } else if (remain == 0) {
1058 n = m_get(wait, m->m_type);
1064 if (m->m_flags & (M_EXT|M_EXTPG)) {
1065 n->m_data = m->m_data + len;
1068 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1072 n->m_next = m->m_next;
1077 * Routine to copy from device local memory into mbufs.
1078 * Note that `off' argument is offset into first mbuf of target chain from
1079 * which to begin copying the data to.
1082 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1083 void (*copy)(char *from, caddr_t to, u_int len))
1086 struct mbuf *top = NULL, **mp = ⊤
1089 if (off < 0 || off > MHLEN)
1092 while (totlen > 0) {
1093 if (top == NULL) { /* First one, must be PKTHDR */
1094 if (totlen + off >= MINCLSIZE) {
1095 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1098 m = m_gethdr(M_NOWAIT, MT_DATA);
1101 /* Place initial small packet/header at end of mbuf */
1102 if (m && totlen + off + max_linkhdr <= MHLEN) {
1103 m->m_data += max_linkhdr;
1109 m->m_pkthdr.rcvif = ifp;
1110 m->m_pkthdr.len = totlen;
1112 if (totlen + off >= MINCLSIZE) {
1113 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1116 m = m_get(M_NOWAIT, MT_DATA);
1129 m->m_len = len = min(totlen, len);
1131 copy(buf, mtod(m, caddr_t), (u_int)len);
1133 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1143 * Copy data from a buffer back into the indicated mbuf chain,
1144 * starting "off" bytes from the beginning, extending the mbuf
1145 * chain if necessary.
1148 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1151 struct mbuf *m = m0, *n;
1156 while (off > (mlen = m->m_len)) {
1159 if (m->m_next == NULL) {
1160 n = m_get(M_NOWAIT, m->m_type);
1163 bzero(mtod(n, caddr_t), MLEN);
1164 n->m_len = min(MLEN, len + off);
1170 if (m->m_next == NULL && (len > m->m_len - off)) {
1171 m->m_len += min(len - (m->m_len - off),
1172 M_TRAILINGSPACE(m));
1174 mlen = min (m->m_len - off, len);
1175 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1183 if (m->m_next == NULL) {
1184 n = m_get(M_NOWAIT, m->m_type);
1187 n->m_len = min(MLEN, len);
1192 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1193 m->m_pkthdr.len = totlen;
1197 * Append the specified data to the indicated mbuf chain,
1198 * Extend the mbuf chain if the new data does not fit in
1201 * Return 1 if able to complete the job; otherwise 0.
1204 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1207 int remainder, space;
1209 for (m = m0; m->m_next != NULL; m = m->m_next)
1212 space = M_TRAILINGSPACE(m);
1215 * Copy into available space.
1217 if (space > remainder)
1219 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1221 cp += space, remainder -= space;
1223 while (remainder > 0) {
1225 * Allocate a new mbuf; could check space
1226 * and allocate a cluster instead.
1228 n = m_get(M_NOWAIT, m->m_type);
1231 n->m_len = min(MLEN, remainder);
1232 bcopy(cp, mtod(n, caddr_t), n->m_len);
1233 cp += n->m_len, remainder -= n->m_len;
1237 if (m0->m_flags & M_PKTHDR)
1238 m0->m_pkthdr.len += len - remainder;
1239 return (remainder == 0);
1243 * Apply function f to the data in an mbuf chain starting "off" bytes from
1244 * the beginning, continuing for "len" bytes.
1247 m_apply(struct mbuf *m, int off, int len,
1248 int (*f)(void *, void *, u_int), void *arg)
1253 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1254 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1256 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1263 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1264 count = min(m->m_len - off, len);
1265 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1276 * Return a pointer to mbuf/offset of location in mbuf chain.
1279 m_getptr(struct mbuf *m, int loc, int *off)
1283 /* Normal end of search. */
1284 if (m->m_len > loc) {
1289 if (m->m_next == NULL) {
1291 /* Point at the end of valid data. */
1304 m_print(const struct mbuf *m, int maxlen)
1308 const struct mbuf *m2;
1311 printf("mbuf: %p\n", m);
1315 if (m->m_flags & M_PKTHDR)
1316 len = m->m_pkthdr.len;
1320 while (m2 != NULL && (len == -1 || len)) {
1322 if (maxlen != -1 && pdata > maxlen)
1324 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1325 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1326 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1327 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1329 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1335 printf("%d bytes unaccounted for.\n", len);
1340 m_fixhdr(struct mbuf *m0)
1344 len = m_length(m0, NULL);
1345 m0->m_pkthdr.len = len;
1350 m_length(struct mbuf *m0, struct mbuf **last)
1356 for (m = m0; m != NULL; m = m->m_next) {
1358 if (m->m_next == NULL)
1367 * Defragment a mbuf chain, returning the shortest possible
1368 * chain of mbufs and clusters. If allocation fails and
1369 * this cannot be completed, NULL will be returned, but
1370 * the passed in chain will be unchanged. Upon success,
1371 * the original chain will be freed, and the new chain
1374 * If a non-packet header is passed in, the original
1375 * mbuf (chain?) will be returned unharmed.
1378 m_defrag(struct mbuf *m0, int how)
1380 struct mbuf *m_new = NULL, *m_final = NULL;
1381 int progress = 0, length;
1383 MBUF_CHECKSLEEP(how);
1384 if (!(m0->m_flags & M_PKTHDR))
1387 m_fixhdr(m0); /* Needed sanity check */
1389 #ifdef MBUF_STRESS_TEST
1390 if (m_defragrandomfailures) {
1391 int temp = arc4random() & 0xff;
1397 if (m0->m_pkthdr.len > MHLEN)
1398 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1400 m_final = m_gethdr(how, MT_DATA);
1402 if (m_final == NULL)
1405 if (m_dup_pkthdr(m_final, m0, how) == 0)
1410 while (progress < m0->m_pkthdr.len) {
1411 length = m0->m_pkthdr.len - progress;
1412 if (length > MCLBYTES)
1415 if (m_new == NULL) {
1417 m_new = m_getcl(how, MT_DATA, 0);
1419 m_new = m_get(how, MT_DATA);
1424 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1426 m_new->m_len = length;
1427 if (m_new != m_final)
1428 m_cat(m_final, m_new);
1431 #ifdef MBUF_STRESS_TEST
1432 if (m0->m_next == NULL)
1437 #ifdef MBUF_STRESS_TEST
1439 m_defragbytes += m0->m_pkthdr.len;
1443 #ifdef MBUF_STRESS_TEST
1452 * Return the number of fragments an mbuf will use. This is usually
1453 * used as a proxy for the number of scatter/gather elements needed by
1454 * a DMA engine to access an mbuf. In general mapped mbufs are
1455 * assumed to be backed by physically contiguous buffers that only
1456 * need a single fragment. Unmapped mbufs, on the other hand, can
1457 * span disjoint physical pages.
1460 frags_per_mbuf(struct mbuf *m)
1464 if ((m->m_flags & M_EXTPG) == 0)
1468 * The header and trailer are counted as a single fragment
1469 * each when present.
1471 * XXX: This overestimates the number of fragments by assuming
1472 * all the backing physical pages are disjoint.
1475 if (m->m_epg_hdrlen != 0)
1477 frags += m->m_epg_npgs;
1478 if (m->m_epg_trllen != 0)
1485 * Defragment an mbuf chain, returning at most maxfrags separate
1486 * mbufs+clusters. If this is not possible NULL is returned and
1487 * the original mbuf chain is left in its present (potentially
1488 * modified) state. We use two techniques: collapsing consecutive
1489 * mbufs and replacing consecutive mbufs by a cluster.
1491 * NB: this should really be named m_defrag but that name is taken
1494 m_collapse(struct mbuf *m0, int how, int maxfrags)
1496 struct mbuf *m, *n, *n2, **prev;
1500 * Calculate the current number of frags.
1503 for (m = m0; m != NULL; m = m->m_next)
1504 curfrags += frags_per_mbuf(m);
1506 * First, try to collapse mbufs. Note that we always collapse
1507 * towards the front so we don't need to deal with moving the
1508 * pkthdr. This may be suboptimal if the first mbuf has much
1509 * less data than the following.
1517 if (M_WRITABLE(m) &&
1518 n->m_len < M_TRAILINGSPACE(m)) {
1519 m_copydata(n, 0, n->m_len,
1520 mtod(m, char *) + m->m_len);
1521 m->m_len += n->m_len;
1522 m->m_next = n->m_next;
1523 curfrags -= frags_per_mbuf(n);
1525 if (curfrags <= maxfrags)
1530 KASSERT(maxfrags > 1,
1531 ("maxfrags %u, but normal collapse failed", maxfrags));
1533 * Collapse consecutive mbufs to a cluster.
1535 prev = &m0->m_next; /* NB: not the first mbuf */
1536 while ((n = *prev) != NULL) {
1537 if ((n2 = n->m_next) != NULL &&
1538 n->m_len + n2->m_len < MCLBYTES) {
1539 m = m_getcl(how, MT_DATA, 0);
1542 m_copydata(n, 0, n->m_len, mtod(m, char *));
1543 m_copydata(n2, 0, n2->m_len,
1544 mtod(m, char *) + n->m_len);
1545 m->m_len = n->m_len + n2->m_len;
1546 m->m_next = n2->m_next;
1548 curfrags += 1; /* For the new cluster */
1549 curfrags -= frags_per_mbuf(n);
1550 curfrags -= frags_per_mbuf(n2);
1553 if (curfrags <= maxfrags)
1556 * Still not there, try the normal collapse
1557 * again before we allocate another cluster.
1564 * No place where we can collapse to a cluster; punt.
1565 * This can occur if, for example, you request 2 frags
1566 * but the packet requires that both be clusters (we
1567 * never reallocate the first mbuf to avoid moving the
1574 #ifdef MBUF_STRESS_TEST
1577 * Fragment an mbuf chain. There's no reason you'd ever want to do
1578 * this in normal usage, but it's great for stress testing various
1581 * If fragmentation is not possible, the original chain will be
1584 * Possible length values:
1585 * 0 no fragmentation will occur
1586 * > 0 each fragment will be of the specified length
1587 * -1 each fragment will be the same random value in length
1588 * -2 each fragment's length will be entirely random
1589 * (Random values range from 1 to 256)
1592 m_fragment(struct mbuf *m0, int how, int length)
1594 struct mbuf *m_first, *m_last;
1595 int divisor = 255, progress = 0, fraglen;
1597 if (!(m0->m_flags & M_PKTHDR))
1600 if (length == 0 || length < -2)
1602 if (length > MCLBYTES)
1604 if (length < 0 && divisor > MCLBYTES)
1607 length = 1 + (arc4random() % divisor);
1611 m_fixhdr(m0); /* Needed sanity check */
1613 m_first = m_getcl(how, MT_DATA, M_PKTHDR);
1614 if (m_first == NULL)
1617 if (m_dup_pkthdr(m_first, m0, how) == 0)
1622 while (progress < m0->m_pkthdr.len) {
1624 fraglen = 1 + (arc4random() % divisor);
1625 if (fraglen > m0->m_pkthdr.len - progress)
1626 fraglen = m0->m_pkthdr.len - progress;
1628 if (progress != 0) {
1629 struct mbuf *m_new = m_getcl(how, MT_DATA, 0);
1633 m_last->m_next = m_new;
1637 m_copydata(m0, progress, fraglen, mtod(m_last, caddr_t));
1638 progress += fraglen;
1639 m_last->m_len = fraglen;
1647 /* Return the original chain on failure */
1654 * Free pages from mbuf_ext_pgs, assuming they were allocated via
1655 * vm_page_alloc() and aren't associated with any object. Complement
1656 * to allocator from m_uiotombuf_nomap().
1659 mb_free_mext_pgs(struct mbuf *m)
1664 for (int i = 0; i < m->m_epg_npgs; i++) {
1665 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1666 vm_page_unwire_noq(pg);
1671 static struct mbuf *
1672 m_uiotombuf_nomap(struct uio *uio, int how, int len, int maxseg, int flags)
1674 struct mbuf *m, *mb, *prev;
1675 vm_page_t pg_array[MBUF_PEXT_MAX_PGS];
1676 int error, length, i, needed;
1678 int pflags = malloc2vm_flags(how) | VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP |
1681 MPASS((flags & M_PKTHDR) == 0);
1682 MPASS((how & M_ZERO) == 0);
1685 * len can be zero or an arbitrary large value bound by
1686 * the total data supplied by the uio.
1689 total = MIN(uio->uio_resid, len);
1691 total = uio->uio_resid;
1694 maxseg = MBUF_PEXT_MAX_PGS * PAGE_SIZE;
1697 * If total is zero, return an empty mbuf. This can occur
1698 * for TLS 1.0 connections which send empty fragments as
1699 * a countermeasure against the known-IV weakness in CBC
1702 if (__predict_false(total == 0)) {
1703 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1706 mb->m_epg_flags = EPG_FLAG_ANON;
1711 * Allocate the pages
1715 mb = mb_alloc_ext_pgs(how, mb_free_mext_pgs);
1723 mb->m_epg_flags = EPG_FLAG_ANON;
1724 needed = length = MIN(maxseg, total);
1725 for (i = 0; needed > 0; i++, needed -= PAGE_SIZE) {
1727 pg_array[i] = vm_page_alloc(NULL, 0, pflags);
1728 if (pg_array[i] == NULL) {
1729 if (how & M_NOWAIT) {
1736 mb->m_epg_pa[i] = VM_PAGE_TO_PHYS(pg_array[i]);
1739 mb->m_epg_last_len = length - PAGE_SIZE * (mb->m_epg_npgs - 1);
1740 MBUF_EXT_PGS_ASSERT_SANITY(mb);
1742 error = uiomove_fromphys(pg_array, 0, length, uio);
1746 mb->m_ext.ext_size += PAGE_SIZE * mb->m_epg_npgs;
1747 if (flags & M_PKTHDR)
1748 m->m_pkthdr.len += length;
1758 * Copy the contents of uio into a properly sized mbuf chain.
1761 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1763 struct mbuf *m, *mb;
1768 if (flags & M_EXTPG)
1769 return (m_uiotombuf_nomap(uio, how, len, align, flags));
1772 * len can be zero or an arbitrary large value bound by
1773 * the total data supplied by the uio.
1776 total = (uio->uio_resid < len) ? uio->uio_resid : len;
1778 total = uio->uio_resid;
1781 * The smallest unit returned by m_getm2() is a single mbuf
1782 * with pkthdr. We can't align past it.
1788 * Give us the full allocation or nothing.
1789 * If len is zero return the smallest empty mbuf.
1791 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1796 /* Fill all mbufs with uio data and update header information. */
1797 for (mb = m; mb != NULL; mb = mb->m_next) {
1798 length = min(M_TRAILINGSPACE(mb), total - progress);
1800 error = uiomove(mtod(mb, void *), length, uio);
1808 if (flags & M_PKTHDR)
1809 m->m_pkthdr.len += length;
1811 KASSERT(progress == total, ("%s: progress != total", __func__));
1817 * Copy data from an unmapped mbuf into a uio limited by len if set.
1820 m_unmappedtouio(const struct mbuf *m, int m_off, struct uio *uio, int len)
1823 int error, i, off, pglen, pgoff, seglen, segoff;
1828 /* Skip over any data removed from the front. */
1829 off = mtod(m, vm_offset_t);
1832 if (m->m_epg_hdrlen != 0) {
1833 if (off >= m->m_epg_hdrlen) {
1834 off -= m->m_epg_hdrlen;
1836 seglen = m->m_epg_hdrlen - off;
1838 seglen = min(seglen, len);
1841 error = uiomove(__DECONST(void *,
1842 &m->m_epg_hdr[segoff]), seglen, uio);
1845 pgoff = m->m_epg_1st_off;
1846 for (i = 0; i < m->m_epg_npgs && error == 0 && len > 0; i++) {
1847 pglen = m_epg_pagelen(m, i, pgoff);
1853 seglen = pglen - off;
1854 segoff = pgoff + off;
1856 seglen = min(seglen, len);
1858 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
1859 error = uiomove_fromphys(&pg, segoff, seglen, uio);
1862 if (len != 0 && error == 0) {
1863 KASSERT((off + len) <= m->m_epg_trllen,
1864 ("off + len > trail (%d + %d > %d, m_off = %d)", off, len,
1865 m->m_epg_trllen, m_off));
1866 error = uiomove(__DECONST(void *, &m->m_epg_trail[off]),
1873 * Copy an mbuf chain into a uio limited by len if set.
1876 m_mbuftouio(struct uio *uio, const struct mbuf *m, int len)
1878 int error, length, total;
1882 total = min(uio->uio_resid, len);
1884 total = uio->uio_resid;
1886 /* Fill the uio with data from the mbufs. */
1887 for (; m != NULL; m = m->m_next) {
1888 length = min(m->m_len, total - progress);
1890 if ((m->m_flags & M_EXTPG) != 0)
1891 error = m_unmappedtouio(m, 0, uio, length);
1893 error = uiomove(mtod(m, void *), length, uio);
1904 * Create a writable copy of the mbuf chain. While doing this
1905 * we compact the chain with a goal of producing a chain with
1906 * at most two mbufs. The second mbuf in this chain is likely
1907 * to be a cluster. The primary purpose of this work is to create
1908 * a writable packet for encryption, compression, etc. The
1909 * secondary goal is to linearize the data so the data can be
1910 * passed to crypto hardware in the most efficient manner possible.
1913 m_unshare(struct mbuf *m0, int how)
1915 struct mbuf *m, *mprev;
1916 struct mbuf *n, *mfirst, *mlast;
1920 for (m = m0; m != NULL; m = mprev->m_next) {
1922 * Regular mbufs are ignored unless there's a cluster
1923 * in front of it that we can use to coalesce. We do
1924 * the latter mainly so later clusters can be coalesced
1925 * also w/o having to handle them specially (i.e. convert
1926 * mbuf+cluster -> cluster). This optimization is heavily
1927 * influenced by the assumption that we're running over
1928 * Ethernet where MCLBYTES is large enough that the max
1929 * packet size will permit lots of coalescing into a
1930 * single cluster. This in turn permits efficient
1931 * crypto operations, especially when using hardware.
1933 if ((m->m_flags & M_EXT) == 0) {
1934 if (mprev && (mprev->m_flags & M_EXT) &&
1935 m->m_len <= M_TRAILINGSPACE(mprev)) {
1936 /* XXX: this ignores mbuf types */
1937 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1938 mtod(m, caddr_t), m->m_len);
1939 mprev->m_len += m->m_len;
1940 mprev->m_next = m->m_next; /* unlink from chain */
1941 m_free(m); /* reclaim mbuf */
1948 * Writable mbufs are left alone (for now).
1950 if (M_WRITABLE(m)) {
1956 * Not writable, replace with a copy or coalesce with
1957 * the previous mbuf if possible (since we have to copy
1958 * it anyway, we try to reduce the number of mbufs and
1959 * clusters so that future work is easier).
1961 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1962 /* NB: we only coalesce into a cluster or larger */
1963 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1964 m->m_len <= M_TRAILINGSPACE(mprev)) {
1965 /* XXX: this ignores mbuf types */
1966 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1967 mtod(m, caddr_t), m->m_len);
1968 mprev->m_len += m->m_len;
1969 mprev->m_next = m->m_next; /* unlink from chain */
1970 m_free(m); /* reclaim mbuf */
1975 * Allocate new space to hold the copy and copy the data.
1976 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1977 * splitting them into clusters. We could just malloc a
1978 * buffer and make it external but too many device drivers
1979 * don't know how to break up the non-contiguous memory when
1982 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
1987 if (m->m_flags & M_PKTHDR) {
1988 KASSERT(mprev == NULL, ("%s: m0 %p, m %p has M_PKTHDR",
1990 m_move_pkthdr(n, m);
1997 int cc = min(len, MCLBYTES);
1998 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2004 newipsecstat.ips_clcopied++;
2012 n = m_getcl(how, m->m_type, m->m_flags & M_COPYFLAGS);
2019 n->m_next = m->m_next;
2021 m0 = mfirst; /* new head of chain */
2023 mprev->m_next = mfirst; /* replace old mbuf */
2024 m_free(m); /* release old mbuf */
2030 #ifdef MBUF_PROFILING
2032 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
2033 struct mbufprofile {
2034 uintmax_t wasted[MP_BUCKETS];
2035 uintmax_t used[MP_BUCKETS];
2036 uintmax_t segments[MP_BUCKETS];
2039 #define MP_MAXDIGITS 21 /* strlen("16,000,000,000,000,000,000") == 21 */
2040 #define MP_NUMLINES 6
2041 #define MP_NUMSPERLINE 16
2042 #define MP_EXTRABYTES 64 /* > strlen("used:\nwasted:\nsegments:\n") */
2043 /* work out max space needed and add a bit of spare space too */
2044 #define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
2045 #define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
2047 char mbprofbuf[MP_BUFSIZE];
2050 m_profile(struct mbuf *m)
2059 if (m->m_flags & M_EXT) {
2060 wasted += MHLEN - sizeof(m->m_ext) +
2061 m->m_ext.ext_size - m->m_len;
2063 if (m->m_flags & M_PKTHDR)
2064 wasted += MHLEN - m->m_len;
2066 wasted += MLEN - m->m_len;
2070 /* be paranoid.. it helps */
2071 if (segments > MP_BUCKETS - 1)
2072 segments = MP_BUCKETS - 1;
2075 if (wasted > 100000)
2077 /* store in the appropriate bucket */
2078 /* don't bother locking. if it's slightly off, so what? */
2079 mbprof.segments[segments]++;
2080 mbprof.used[fls(used)]++;
2081 mbprof.wasted[fls(wasted)]++;
2085 mbprof_textify(void)
2091 p = &mbprof.wasted[0];
2093 offset = snprintf(c, MP_MAXLINE + 10,
2095 "%ju %ju %ju %ju %ju %ju %ju %ju "
2096 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2097 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2098 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2100 p = &mbprof.wasted[16];
2102 offset = snprintf(c, MP_MAXLINE,
2103 "%ju %ju %ju %ju %ju %ju %ju %ju "
2104 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2105 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2106 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2108 p = &mbprof.used[0];
2110 offset = snprintf(c, MP_MAXLINE + 10,
2112 "%ju %ju %ju %ju %ju %ju %ju %ju "
2113 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2114 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2115 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2117 p = &mbprof.used[16];
2119 offset = snprintf(c, MP_MAXLINE,
2120 "%ju %ju %ju %ju %ju %ju %ju %ju "
2121 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2122 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2123 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2125 p = &mbprof.segments[0];
2127 offset = snprintf(c, MP_MAXLINE + 10,
2129 "%ju %ju %ju %ju %ju %ju %ju %ju "
2130 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2131 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2132 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2134 p = &mbprof.segments[16];
2136 offset = snprintf(c, MP_MAXLINE,
2137 "%ju %ju %ju %ju %ju %ju %ju %ju "
2138 "%ju %ju %ju %ju %ju %ju %ju %jju",
2139 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2140 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2145 mbprof_handler(SYSCTL_HANDLER_ARGS)
2150 error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
2155 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2160 error = sysctl_handle_int(oidp, &clear, 0, req);
2161 if (error || !req->newptr)
2165 bzero(&mbprof, sizeof(mbprof));
2171 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile,
2172 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
2173 mbprof_handler, "A",
2174 "mbuf profiling statistics");
2176 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr,
2177 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
2178 mbprof_clr_handler, "I",
2179 "clear mbuf profiling statistics");