2 * Copyright (c) 1982, 1986, 1988, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include "opt_param.h"
36 #include "opt_mbuf_stress_test.h"
37 #include "opt_mbuf_profiling.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/limits.h>
44 #include <sys/malloc.h>
46 #include <sys/sysctl.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
55 #ifdef MBUF_STRESS_TEST
60 int m_defragrandomfailures;
64 * sysctl(8) exported objects
66 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
67 &max_linkhdr, 0, "Size of largest link layer header");
68 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
69 &max_protohdr, 0, "Size of largest protocol layer header");
70 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
71 &max_hdr, 0, "Size of largest link plus protocol header");
72 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
73 &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
74 #ifdef MBUF_STRESS_TEST
75 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
76 &m_defragpackets, 0, "");
77 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
78 &m_defragbytes, 0, "");
79 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
80 &m_defraguseless, 0, "");
81 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
82 &m_defragfailure, 0, "");
83 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
84 &m_defragrandomfailures, 0, "");
88 * m_get2() allocates minimum mbuf that would fit "size" argument.
91 m_get2(int size, int how, short type, int flags)
99 if (size <= MHLEN || (size <= MLEN && (flags & M_PKTHDR) == 0))
100 return (uma_zalloc_arg(zone_mbuf, &args, how));
101 if (size <= MCLBYTES)
102 return (uma_zalloc_arg(zone_pack, &args, how));
104 if (size > MJUMPAGESIZE)
107 m = uma_zalloc_arg(zone_mbuf, &args, how);
111 n = uma_zalloc_arg(zone_jumbop, m, how);
113 uma_zfree(zone_mbuf, m);
121 * m_getjcl() returns an mbuf with a cluster of the specified size attached.
122 * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
125 m_getjcl(int how, short type, int flags, int size)
131 if (size == MCLBYTES)
132 return m_getcl(how, type, flags);
137 m = uma_zalloc_arg(zone_mbuf, &args, how);
141 zone = m_getzone(size);
142 n = uma_zalloc_arg(zone, m, how);
144 uma_zfree(zone_mbuf, m);
151 * Allocate a given length worth of mbufs and/or clusters (whatever fits
152 * best) and return a pointer to the top of the allocated chain. If an
153 * existing mbuf chain is provided, then we will append the new chain
154 * to the existing one but still return the top of the newly allocated
158 m_getm2(struct mbuf *m, int len, int how, short type, int flags)
160 struct mbuf *mb, *nm = NULL, *mtail = NULL;
162 KASSERT(len >= 0, ("%s: len is < 0", __func__));
164 /* Validate flags. */
165 flags &= (M_PKTHDR | M_EOR);
167 /* Packet header mbuf must be first in chain. */
168 if ((flags & M_PKTHDR) && m != NULL)
171 /* Loop and append maximum sized mbufs to the chain tail. */
174 mb = m_getjcl(how, type, (flags & M_PKTHDR),
176 else if (len >= MINCLSIZE)
177 mb = m_getcl(how, type, (flags & M_PKTHDR));
178 else if (flags & M_PKTHDR)
179 mb = m_gethdr(how, type);
181 mb = m_get(how, type);
183 /* Fail the whole operation if one mbuf can't be allocated. */
191 len -= (mb->m_flags & M_EXT) ? mb->m_ext.ext_size :
192 ((mb->m_flags & M_PKTHDR) ? MHLEN : MLEN);
198 flags &= ~M_PKTHDR; /* Only valid on the first mbuf. */
201 mtail->m_flags |= M_EOR; /* Only valid on the last mbuf. */
203 /* If mbuf was supplied, append new chain to the end of it. */
205 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
208 mtail->m_flags &= ~M_EOR;
216 * Free an entire chain of mbufs and associated external buffers, if
220 m_freem(struct mbuf *mb)
228 * Configure a provided mbuf to refer to the provided external storage
229 * buffer and setup a reference count for said buffer. If the setting
230 * up of the reference count fails, the M_EXT bit will not be set. If
231 * successfull, the M_EXT bit is set in the mbuf's flags.
234 * mb The existing mbuf to which to attach the provided buffer.
235 * buf The address of the provided external storage buffer.
236 * size The size of the provided buffer.
237 * freef A pointer to a routine that is responsible for freeing the
238 * provided external storage buffer.
239 * args A pointer to an argument structure (of any type) to be passed
240 * to the provided freef routine (may be NULL).
241 * flags Any other flags to be passed to the provided mbuf.
242 * type The type that the external storage buffer should be
249 m_extadd(struct mbuf *mb, caddr_t buf, u_int size,
250 void (*freef)(void *, void *), void *arg1, void *arg2, int flags, int type,
253 KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
255 if (type != EXT_EXTREF)
256 mb->m_ext.ref_cnt = uma_zalloc(zone_ext_refcnt, wait);
258 if (mb->m_ext.ref_cnt == NULL)
261 *(mb->m_ext.ref_cnt) = 1;
262 mb->m_flags |= (M_EXT | flags);
263 mb->m_ext.ext_buf = buf;
264 mb->m_data = mb->m_ext.ext_buf;
265 mb->m_ext.ext_size = size;
266 mb->m_ext.ext_free = freef;
267 mb->m_ext.ext_arg1 = arg1;
268 mb->m_ext.ext_arg2 = arg2;
269 mb->m_ext.ext_type = type;
275 * Non-directly-exported function to clean up after mbufs with M_EXT
276 * storage attached to them if the reference count hits 1.
279 mb_free_ext(struct mbuf *m)
283 KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
284 KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
288 * check if the header is embedded in the cluster
290 skipmbuf = (m->m_flags & M_NOFREE);
292 /* Free attached storage if this mbuf is the only reference to it. */
293 if (*(m->m_ext.ref_cnt) == 1 ||
294 atomic_fetchadd_int(m->m_ext.ref_cnt, -1) == 1) {
295 switch (m->m_ext.ext_type) {
296 case EXT_PACKET: /* The packet zone is special. */
297 if (*(m->m_ext.ref_cnt) == 0)
298 *(m->m_ext.ref_cnt) = 1;
299 uma_zfree(zone_pack, m);
300 return; /* Job done. */
302 uma_zfree(zone_clust, m->m_ext.ext_buf);
305 uma_zfree(zone_jumbop, m->m_ext.ext_buf);
308 uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
311 uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
317 *(m->m_ext.ref_cnt) = 0;
318 uma_zfree(zone_ext_refcnt, __DEVOLATILE(u_int *,
322 KASSERT(m->m_ext.ext_free != NULL,
323 ("%s: ext_free not set", __func__));
324 (*(m->m_ext.ext_free))(m->m_ext.ext_arg1,
328 KASSERT(m->m_ext.ext_type == 0,
329 ("%s: unknown ext_type", __func__));
336 * Free this mbuf back to the mbuf zone with all m_ext
337 * information purged.
339 m->m_ext.ext_buf = NULL;
340 m->m_ext.ext_free = NULL;
341 m->m_ext.ext_arg1 = NULL;
342 m->m_ext.ext_arg2 = NULL;
343 m->m_ext.ref_cnt = NULL;
344 m->m_ext.ext_size = 0;
345 m->m_ext.ext_type = 0;
346 m->m_flags &= ~M_EXT;
347 uma_zfree(zone_mbuf, m);
351 * Attach the cluster from *m to *n, set up m_ext in *n
352 * and bump the refcount of the cluster.
355 mb_dupcl(struct mbuf *n, struct mbuf *m)
357 KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
358 KASSERT(m->m_ext.ref_cnt != NULL, ("%s: ref_cnt not set", __func__));
359 KASSERT((n->m_flags & M_EXT) == 0, ("%s: M_EXT set", __func__));
361 if (*(m->m_ext.ref_cnt) == 1)
362 *(m->m_ext.ref_cnt) += 1;
364 atomic_add_int(m->m_ext.ref_cnt, 1);
365 n->m_ext.ext_buf = m->m_ext.ext_buf;
366 n->m_ext.ext_free = m->m_ext.ext_free;
367 n->m_ext.ext_arg1 = m->m_ext.ext_arg1;
368 n->m_ext.ext_arg2 = m->m_ext.ext_arg2;
369 n->m_ext.ext_size = m->m_ext.ext_size;
370 n->m_ext.ref_cnt = m->m_ext.ref_cnt;
371 n->m_ext.ext_type = m->m_ext.ext_type;
373 n->m_flags |= m->m_flags & M_RDONLY;
377 * Clean up mbuf (chain) from any tags and packet headers.
378 * If "all" is set then the first mbuf in the chain will be
382 m_demote(struct mbuf *m0, int all)
386 for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
387 if (m->m_flags & M_PKTHDR) {
388 m_tag_delete_chain(m, NULL);
389 m->m_flags &= ~M_PKTHDR;
390 bzero(&m->m_pkthdr, sizeof(struct pkthdr));
392 if (m != m0 && m->m_nextpkt != NULL) {
393 KASSERT(m->m_nextpkt == NULL,
394 ("%s: m_nextpkt not NULL", __func__));
395 m_freem(m->m_nextpkt);
398 m->m_flags = m->m_flags & (M_EXT|M_RDONLY|M_NOFREE);
403 * Sanity checks on mbuf (chain) for use in KASSERT() and general
405 * Returns 0 or panics when bad and 1 on all tests passed.
406 * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
410 m_sanity(struct mbuf *m0, int sanitize)
417 #define M_SANITY_ACTION(s) panic("mbuf %p: " s, m)
419 #define M_SANITY_ACTION(s) printf("mbuf %p: " s, m)
422 for (m = m0; m != NULL; m = m->m_next) {
424 * Basic pointer checks. If any of these fails then some
425 * unrelated kernel memory before or after us is trashed.
426 * No way to recover from that.
428 a = ((m->m_flags & M_EXT) ? m->m_ext.ext_buf :
429 ((m->m_flags & M_PKTHDR) ? (caddr_t)(&m->m_pktdat) :
430 (caddr_t)(&m->m_dat)) );
431 b = (caddr_t)(a + (m->m_flags & M_EXT ? m->m_ext.ext_size :
432 ((m->m_flags & M_PKTHDR) ? MHLEN : MLEN)));
433 if ((caddr_t)m->m_data < a)
434 M_SANITY_ACTION("m_data outside mbuf data range left");
435 if ((caddr_t)m->m_data > b)
436 M_SANITY_ACTION("m_data outside mbuf data range right");
437 if ((caddr_t)m->m_data + m->m_len > b)
438 M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
439 if ((m->m_flags & M_PKTHDR) && m->m_pkthdr.header) {
440 if ((caddr_t)m->m_pkthdr.header < a ||
441 (caddr_t)m->m_pkthdr.header > b)
442 M_SANITY_ACTION("m_pkthdr.header outside mbuf data range");
445 /* m->m_nextpkt may only be set on first mbuf in chain. */
446 if (m != m0 && m->m_nextpkt != NULL) {
448 m_freem(m->m_nextpkt);
449 m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
451 M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
454 /* packet length (not mbuf length!) calculation */
455 if (m0->m_flags & M_PKTHDR)
458 /* m_tags may only be attached to first mbuf in chain. */
459 if (m != m0 && m->m_flags & M_PKTHDR &&
460 !SLIST_EMPTY(&m->m_pkthdr.tags)) {
462 m_tag_delete_chain(m, NULL);
463 /* put in 0xDEADC0DE perhaps? */
465 M_SANITY_ACTION("m_tags on in-chain mbuf");
468 /* M_PKTHDR may only be set on first mbuf in chain */
469 if (m != m0 && m->m_flags & M_PKTHDR) {
471 bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
472 m->m_flags &= ~M_PKTHDR;
473 /* put in 0xDEADCODE and leave hdr flag in */
475 M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
479 if (pktlen && pktlen != m->m_pkthdr.len) {
483 M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
487 #undef M_SANITY_ACTION
492 * "Move" mbuf pkthdr from "from" to "to".
493 * "from" must have M_PKTHDR set, and "to" must be empty.
496 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
500 /* see below for why these are not enabled */
502 /* Note: with MAC, this may not be a good assertion. */
503 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
504 ("m_move_pkthdr: to has tags"));
508 * XXXMAC: It could be this should also occur for non-MAC?
510 if (to->m_flags & M_PKTHDR)
511 m_tag_delete_chain(to, NULL);
513 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
514 if ((to->m_flags & M_EXT) == 0)
515 to->m_data = to->m_pktdat;
516 to->m_pkthdr = from->m_pkthdr; /* especially tags */
517 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
518 from->m_flags &= ~M_PKTHDR;
522 * Duplicate "from"'s mbuf pkthdr in "to".
523 * "from" must have M_PKTHDR set, and "to" must be empty.
524 * In particular, this does a deep copy of the packet tags.
527 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
532 * The mbuf allocator only initializes the pkthdr
533 * when the mbuf is allocated with m_gethdr(). Many users
534 * (e.g. m_copy*, m_prepend) use m_get() and then
535 * smash the pkthdr as needed causing these
536 * assertions to trip. For now just disable them.
539 /* Note: with MAC, this may not be a good assertion. */
540 KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
542 MBUF_CHECKSLEEP(how);
544 if (to->m_flags & M_PKTHDR)
545 m_tag_delete_chain(to, NULL);
547 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
548 if ((to->m_flags & M_EXT) == 0)
549 to->m_data = to->m_pktdat;
550 to->m_pkthdr = from->m_pkthdr;
551 SLIST_INIT(&to->m_pkthdr.tags);
552 return (m_tag_copy_chain(to, from, MBTOM(how)));
556 * Lesser-used path for M_PREPEND:
557 * allocate new mbuf to prepend to chain,
561 m_prepend(struct mbuf *m, int len, int how)
565 if (m->m_flags & M_PKTHDR)
566 mn = m_gethdr(how, m->m_type);
568 mn = m_get(how, m->m_type);
573 if (m->m_flags & M_PKTHDR)
574 m_move_pkthdr(mn, m);
577 if(m->m_flags & M_PKTHDR) {
589 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
590 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
591 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
592 * Note that the copy is read-only, because clusters are not copied,
593 * only their reference counts are incremented.
596 m_copym(struct mbuf *m, int off0, int len, int wait)
598 struct mbuf *n, **np;
603 KASSERT(off >= 0, ("m_copym, negative off %d", off));
604 KASSERT(len >= 0, ("m_copym, negative len %d", len));
605 MBUF_CHECKSLEEP(wait);
606 if (off == 0 && m->m_flags & M_PKTHDR)
609 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
619 KASSERT(len == M_COPYALL,
620 ("m_copym, length > size of mbuf chain"));
624 n = m_gethdr(wait, m->m_type);
626 n = m_get(wait, m->m_type);
631 if (!m_dup_pkthdr(n, m, wait))
633 if (len == M_COPYALL)
634 n->m_pkthdr.len -= off0;
636 n->m_pkthdr.len = len;
639 n->m_len = min(len, m->m_len - off);
640 if (m->m_flags & M_EXT) {
641 n->m_data = m->m_data + off;
644 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
646 if (len != M_COPYALL)
660 * Returns mbuf chain with new head for the prepending case.
661 * Copies from mbuf (chain) n from off for len to mbuf (chain) m
662 * either prepending or appending the data.
663 * The resulting mbuf (chain) m is fully writeable.
664 * m is destination (is made writeable)
665 * n is source, off is offset in source, len is len from offset
666 * dir, 0 append, 1 prepend
667 * how, wait or nowait
671 m_bcopyxxx(void *s, void *t, u_int len)
673 bcopy(s, t, (size_t)len);
678 m_copymdata(struct mbuf *m, struct mbuf *n, int off, int len,
681 struct mbuf *mm, *x, *z, *prev = NULL;
686 KASSERT(m != NULL && n != NULL, ("m_copymdata, no target or source"));
687 KASSERT(off >= 0, ("m_copymdata, negative off %d", off));
688 KASSERT(len >= 0, ("m_copymdata, negative len %d", len));
689 KASSERT(prep == 0 || prep == 1, ("m_copymdata, unknown direction %d", prep));
698 for (z = n; z != NULL; z = z->m_next)
700 if (len == M_COPYALL)
702 if (off + len > nlen || len < 1)
705 if (!M_WRITABLE(mm)) {
706 /* XXX: Use proper m_xxx function instead. */
707 x = m_getcl(how, MT_DATA, mm->m_flags);
710 bcopy(mm->m_ext.ext_buf, x->m_ext.ext_buf, x->m_ext.ext_size);
711 p = x->m_ext.ext_buf + (mm->m_data - mm->m_ext.ext_buf);
721 * Append/prepend the data. Allocating mbufs as necessary.
723 /* Shortcut if enough free space in first/last mbuf. */
724 if (!prep && M_TRAILINGSPACE(mm) >= len) {
725 m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t) +
728 mm->m_pkthdr.len += len;
731 if (prep && M_LEADINGSPACE(mm) >= len) {
732 mm->m_data = mtod(mm, caddr_t) - len;
733 m_apply(n, off, len, m_bcopyxxx, mtod(mm, caddr_t));
735 mm->m_pkthdr.len += len;
739 /* Expand first/last mbuf to cluster if possible. */
740 if (!prep && !(mm->m_flags & M_EXT) && len > M_TRAILINGSPACE(mm)) {
741 bcopy(mm->m_data, &buf, mm->m_len);
743 if (!(mm->m_flags & M_EXT))
745 bcopy(&buf, mm->m_ext.ext_buf, mm->m_len);
746 mm->m_data = mm->m_ext.ext_buf;
747 mm->m_pkthdr.header = NULL;
749 if (prep && !(mm->m_flags & M_EXT) && len > M_LEADINGSPACE(mm)) {
750 bcopy(mm->m_data, &buf, mm->m_len);
752 if (!(mm->m_flags & M_EXT))
754 bcopy(&buf, (caddr_t *)mm->m_ext.ext_buf +
755 mm->m_ext.ext_size - mm->m_len, mm->m_len);
756 mm->m_data = (caddr_t)mm->m_ext.ext_buf +
757 mm->m_ext.ext_size - mm->m_len;
758 mm->m_pkthdr.header = NULL;
761 /* Append/prepend as many mbuf (clusters) as necessary to fit len. */
762 if (!prep && len > M_TRAILINGSPACE(mm)) {
763 if (!m_getm(mm, len - M_TRAILINGSPACE(mm), how, MT_DATA))
766 if (prep && len > M_LEADINGSPACE(mm)) {
767 if (!(z = m_getm(NULL, len - M_LEADINGSPACE(mm), how, MT_DATA)))
770 for (x = z; x != NULL; x = x->m_next) {
771 i += x->m_flags & M_EXT ? x->m_ext.ext_size :
772 (x->m_flags & M_PKTHDR ? MHLEN : MLEN);
776 z->m_data += i - len;
777 m_move_pkthdr(mm, z);
782 /* Seek to start position in source mbuf. Optimization for long chains. */
790 /* Copy data into target mbuf. */
793 KASSERT(z != NULL, ("m_copymdata, falling off target edge"));
794 i = M_TRAILINGSPACE(z);
795 m_apply(n, off, i, m_bcopyxxx, mtod(z, caddr_t) + z->m_len);
797 /* fixup pkthdr.len if necessary */
798 if ((prep ? mm : m)->m_flags & M_PKTHDR)
799 (prep ? mm : m)->m_pkthdr.len += i;
804 return (prep ? mm : m);
808 * Copy an entire packet, including header (which must be present).
809 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
810 * Note that the copy is read-only, because clusters are not copied,
811 * only their reference counts are incremented.
812 * Preserve alignment of the first mbuf so if the creator has left
813 * some room at the beginning (e.g. for inserting protocol headers)
814 * the copies still have the room available.
817 m_copypacket(struct mbuf *m, int how)
819 struct mbuf *top, *n, *o;
821 MBUF_CHECKSLEEP(how);
822 n = m_get(how, m->m_type);
827 if (!m_dup_pkthdr(n, m, how))
830 if (m->m_flags & M_EXT) {
831 n->m_data = m->m_data;
834 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
835 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
840 o = m_get(how, m->m_type);
848 if (m->m_flags & M_EXT) {
849 n->m_data = m->m_data;
852 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
864 * Copy data from an mbuf chain starting "off" bytes from the beginning,
865 * continuing for "len" bytes, into the indicated buffer.
868 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
872 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
873 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
875 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
882 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
883 count = min(m->m_len - off, len);
884 bcopy(mtod(m, caddr_t) + off, cp, count);
893 * Copy a packet header mbuf chain into a completely new chain, including
894 * copying any mbuf clusters. Use this instead of m_copypacket() when
895 * you need a writable copy of an mbuf chain.
898 m_dup(struct mbuf *m, int how)
900 struct mbuf **p, *top = NULL;
901 int remain, moff, nsize;
903 MBUF_CHECKSLEEP(how);
909 /* While there's more data, get a new mbuf, tack it on, and fill it */
910 remain = m->m_pkthdr.len;
913 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
916 /* Get the next new mbuf */
917 if (remain >= MINCLSIZE) {
918 n = m_getcl(how, m->m_type, 0);
921 n = m_get(how, m->m_type);
927 if (top == NULL) { /* First one, must be PKTHDR */
928 if (!m_dup_pkthdr(n, m, how)) {
932 if ((n->m_flags & M_EXT) == 0)
937 /* Link it into the new chain */
941 /* Copy data from original mbuf(s) into new mbuf */
942 while (n->m_len < nsize && m != NULL) {
943 int chunk = min(nsize - n->m_len, m->m_len - moff);
945 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
949 if (moff == m->m_len) {
955 /* Check correct total mbuf length */
956 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
957 ("%s: bogus m_pkthdr.len", __func__));
967 * Concatenate mbuf chain n to m.
968 * Both chains must be of the same type (e.g. MT_DATA).
969 * Any m_pkthdr is not updated.
972 m_cat(struct mbuf *m, struct mbuf *n)
977 if (!M_WRITABLE(m) ||
978 M_TRAILINGSPACE(m) < n->m_len) {
979 /* just join the two chains */
983 /* splat the data from one into the other */
984 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
986 m->m_len += n->m_len;
992 m_adj(struct mbuf *mp, int req_len)
998 if ((m = mp) == NULL)
1004 while (m != NULL && len > 0) {
1005 if (m->m_len <= len) {
1015 if (mp->m_flags & M_PKTHDR)
1016 mp->m_pkthdr.len -= (req_len - len);
1019 * Trim from tail. Scan the mbuf chain,
1020 * calculating its length and finding the last mbuf.
1021 * If the adjustment only affects this mbuf, then just
1022 * adjust and return. Otherwise, rescan and truncate
1023 * after the remaining size.
1029 if (m->m_next == (struct mbuf *)0)
1033 if (m->m_len >= len) {
1035 if (mp->m_flags & M_PKTHDR)
1036 mp->m_pkthdr.len -= len;
1043 * Correct length for chain is "count".
1044 * Find the mbuf with last data, adjust its length,
1045 * and toss data from remaining mbufs on chain.
1048 if (m->m_flags & M_PKTHDR)
1049 m->m_pkthdr.len = count;
1050 for (; m; m = m->m_next) {
1051 if (m->m_len >= count) {
1053 if (m->m_next != NULL) {
1065 * Rearange an mbuf chain so that len bytes are contiguous
1066 * and in the data area of an mbuf (so that mtod will work
1067 * for a structure of size len). Returns the resulting
1068 * mbuf chain on success, frees it and returns null on failure.
1069 * If there is room, it will add up to max_protohdr-len extra bytes to the
1070 * contiguous region in an attempt to avoid being called next time.
1073 m_pullup(struct mbuf *n, int len)
1080 * If first mbuf has no cluster, and has room for len bytes
1081 * without shifting current data, pullup into it,
1082 * otherwise allocate a new mbuf to prepend to the chain.
1084 if ((n->m_flags & M_EXT) == 0 &&
1085 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1086 if (n->m_len >= len)
1094 m = m_get(M_NOWAIT, n->m_type);
1097 if (n->m_flags & M_PKTHDR)
1098 m_move_pkthdr(m, n);
1100 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1102 count = min(min(max(len, max_protohdr), space), n->m_len);
1103 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1113 } while (len > 0 && n);
1126 * Like m_pullup(), except a new mbuf is always allocated, and we allow
1127 * the amount of empty space before the data in the new mbuf to be specified
1128 * (in the event that the caller expects to prepend later).
1133 m_copyup(struct mbuf *n, int len, int dstoff)
1138 if (len > (MHLEN - dstoff))
1140 m = m_get(M_NOWAIT, n->m_type);
1143 if (n->m_flags & M_PKTHDR)
1144 m_move_pkthdr(m, n);
1145 m->m_data += dstoff;
1146 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1148 count = min(min(max(len, max_protohdr), space), n->m_len);
1149 memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1159 } while (len > 0 && n);
1173 * Partition an mbuf chain in two pieces, returning the tail --
1174 * all but the first len0 bytes. In case of failure, it returns NULL and
1175 * attempts to restore the chain to its original state.
1177 * Note that the resulting mbufs might be read-only, because the new
1178 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1179 * the "breaking point" happens to lie within a cluster mbuf. Use the
1180 * M_WRITABLE() macro to check for this case.
1183 m_split(struct mbuf *m0, int len0, int wait)
1186 u_int len = len0, remain;
1188 MBUF_CHECKSLEEP(wait);
1189 for (m = m0; m && len > m->m_len; m = m->m_next)
1193 remain = m->m_len - len;
1194 if (m0->m_flags & M_PKTHDR && remain == 0) {
1195 n = m_gethdr(wait, m0->m_type);
1197 n->m_next = m->m_next;
1199 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1200 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1201 m0->m_pkthdr.len = len0;
1203 } else if (m0->m_flags & M_PKTHDR) {
1204 n = m_gethdr(wait, m0->m_type);
1207 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1208 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1209 m0->m_pkthdr.len = len0;
1210 if (m->m_flags & M_EXT)
1212 if (remain > MHLEN) {
1213 /* m can't be the lead packet */
1215 n->m_next = m_split(m, len, wait);
1216 if (n->m_next == NULL) {
1224 MH_ALIGN(n, remain);
1225 } else if (remain == 0) {
1230 n = m_get(wait, m->m_type);
1236 if (m->m_flags & M_EXT) {
1237 n->m_data = m->m_data + len;
1240 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1244 n->m_next = m->m_next;
1249 * Routine to copy from device local memory into mbufs.
1250 * Note that `off' argument is offset into first mbuf of target chain from
1251 * which to begin copying the data to.
1254 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1255 void (*copy)(char *from, caddr_t to, u_int len))
1258 struct mbuf *top = NULL, **mp = ⊤
1261 if (off < 0 || off > MHLEN)
1264 while (totlen > 0) {
1265 if (top == NULL) { /* First one, must be PKTHDR */
1266 if (totlen + off >= MINCLSIZE) {
1267 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1270 m = m_gethdr(M_NOWAIT, MT_DATA);
1273 /* Place initial small packet/header at end of mbuf */
1274 if (m && totlen + off + max_linkhdr <= MLEN) {
1275 m->m_data += max_linkhdr;
1281 m->m_pkthdr.rcvif = ifp;
1282 m->m_pkthdr.len = totlen;
1284 if (totlen + off >= MINCLSIZE) {
1285 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1288 m = m_get(M_NOWAIT, MT_DATA);
1301 m->m_len = len = min(totlen, len);
1303 copy(buf, mtod(m, caddr_t), (u_int)len);
1305 bcopy(buf, mtod(m, caddr_t), (u_int)len);
1315 * Copy data from a buffer back into the indicated mbuf chain,
1316 * starting "off" bytes from the beginning, extending the mbuf
1317 * chain if necessary.
1320 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1323 struct mbuf *m = m0, *n;
1328 while (off > (mlen = m->m_len)) {
1331 if (m->m_next == NULL) {
1332 n = m_get(M_NOWAIT, m->m_type);
1335 bzero(mtod(n, caddr_t), MLEN);
1336 n->m_len = min(MLEN, len + off);
1342 if (m->m_next == NULL && (len > m->m_len - off)) {
1343 m->m_len += min(len - (m->m_len - off),
1344 M_TRAILINGSPACE(m));
1346 mlen = min (m->m_len - off, len);
1347 bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1355 if (m->m_next == NULL) {
1356 n = m_get(M_NOWAIT, m->m_type);
1359 n->m_len = min(MLEN, len);
1364 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1365 m->m_pkthdr.len = totlen;
1369 * Append the specified data to the indicated mbuf chain,
1370 * Extend the mbuf chain if the new data does not fit in
1373 * Return 1 if able to complete the job; otherwise 0.
1376 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1379 int remainder, space;
1381 for (m = m0; m->m_next != NULL; m = m->m_next)
1384 space = M_TRAILINGSPACE(m);
1387 * Copy into available space.
1389 if (space > remainder)
1391 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1393 cp += space, remainder -= space;
1395 while (remainder > 0) {
1397 * Allocate a new mbuf; could check space
1398 * and allocate a cluster instead.
1400 n = m_get(M_NOWAIT, m->m_type);
1403 n->m_len = min(MLEN, remainder);
1404 bcopy(cp, mtod(n, caddr_t), n->m_len);
1405 cp += n->m_len, remainder -= n->m_len;
1409 if (m0->m_flags & M_PKTHDR)
1410 m0->m_pkthdr.len += len - remainder;
1411 return (remainder == 0);
1415 * Apply function f to the data in an mbuf chain starting "off" bytes from
1416 * the beginning, continuing for "len" bytes.
1419 m_apply(struct mbuf *m, int off, int len,
1420 int (*f)(void *, void *, u_int), void *arg)
1425 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1426 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1428 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1435 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1436 count = min(m->m_len - off, len);
1437 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1448 * Return a pointer to mbuf/offset of location in mbuf chain.
1451 m_getptr(struct mbuf *m, int loc, int *off)
1455 /* Normal end of search. */
1456 if (m->m_len > loc) {
1461 if (m->m_next == NULL) {
1463 /* Point at the end of valid data. */
1476 m_print(const struct mbuf *m, int maxlen)
1480 const struct mbuf *m2;
1483 printf("mbuf: %p\n", m);
1487 if (m->m_flags & M_PKTHDR)
1488 len = m->m_pkthdr.len;
1492 while (m2 != NULL && (len == -1 || len)) {
1494 if (maxlen != -1 && pdata > maxlen)
1496 printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1497 m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1498 "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1499 "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1501 printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1507 printf("%d bytes unaccounted for.\n", len);
1512 m_fixhdr(struct mbuf *m0)
1516 len = m_length(m0, NULL);
1517 m0->m_pkthdr.len = len;
1522 m_length(struct mbuf *m0, struct mbuf **last)
1528 for (m = m0; m != NULL; m = m->m_next) {
1530 if (m->m_next == NULL)
1539 * Defragment a mbuf chain, returning the shortest possible
1540 * chain of mbufs and clusters. If allocation fails and
1541 * this cannot be completed, NULL will be returned, but
1542 * the passed in chain will be unchanged. Upon success,
1543 * the original chain will be freed, and the new chain
1546 * If a non-packet header is passed in, the original
1547 * mbuf (chain?) will be returned unharmed.
1550 m_defrag(struct mbuf *m0, int how)
1552 struct mbuf *m_new = NULL, *m_final = NULL;
1553 int progress = 0, length;
1555 MBUF_CHECKSLEEP(how);
1556 if (!(m0->m_flags & M_PKTHDR))
1559 m_fixhdr(m0); /* Needed sanity check */
1561 #ifdef MBUF_STRESS_TEST
1562 if (m_defragrandomfailures) {
1563 int temp = arc4random() & 0xff;
1569 if (m0->m_pkthdr.len > MHLEN)
1570 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1572 m_final = m_gethdr(how, MT_DATA);
1574 if (m_final == NULL)
1577 if (m_dup_pkthdr(m_final, m0, how) == 0)
1582 while (progress < m0->m_pkthdr.len) {
1583 length = m0->m_pkthdr.len - progress;
1584 if (length > MCLBYTES)
1587 if (m_new == NULL) {
1589 m_new = m_getcl(how, MT_DATA, 0);
1591 m_new = m_get(how, MT_DATA);
1596 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1598 m_new->m_len = length;
1599 if (m_new != m_final)
1600 m_cat(m_final, m_new);
1603 #ifdef MBUF_STRESS_TEST
1604 if (m0->m_next == NULL)
1609 #ifdef MBUF_STRESS_TEST
1611 m_defragbytes += m0->m_pkthdr.len;
1615 #ifdef MBUF_STRESS_TEST
1624 * Defragment an mbuf chain, returning at most maxfrags separate
1625 * mbufs+clusters. If this is not possible NULL is returned and
1626 * the original mbuf chain is left in it's present (potentially
1627 * modified) state. We use two techniques: collapsing consecutive
1628 * mbufs and replacing consecutive mbufs by a cluster.
1630 * NB: this should really be named m_defrag but that name is taken
1633 m_collapse(struct mbuf *m0, int how, int maxfrags)
1635 struct mbuf *m, *n, *n2, **prev;
1639 * Calculate the current number of frags.
1642 for (m = m0; m != NULL; m = m->m_next)
1645 * First, try to collapse mbufs. Note that we always collapse
1646 * towards the front so we don't need to deal with moving the
1647 * pkthdr. This may be suboptimal if the first mbuf has much
1648 * less data than the following.
1656 if (M_WRITABLE(m) &&
1657 n->m_len < M_TRAILINGSPACE(m)) {
1658 bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1660 m->m_len += n->m_len;
1661 m->m_next = n->m_next;
1663 if (--curfrags <= maxfrags)
1668 KASSERT(maxfrags > 1,
1669 ("maxfrags %u, but normal collapse failed", maxfrags));
1671 * Collapse consecutive mbufs to a cluster.
1673 prev = &m0->m_next; /* NB: not the first mbuf */
1674 while ((n = *prev) != NULL) {
1675 if ((n2 = n->m_next) != NULL &&
1676 n->m_len + n2->m_len < MCLBYTES) {
1677 m = m_getcl(how, MT_DATA, 0);
1680 bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1681 bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1683 m->m_len = n->m_len + n2->m_len;
1684 m->m_next = n2->m_next;
1688 if (--curfrags <= maxfrags) /* +1 cl -2 mbufs */
1691 * Still not there, try the normal collapse
1692 * again before we allocate another cluster.
1699 * No place where we can collapse to a cluster; punt.
1700 * This can occur if, for example, you request 2 frags
1701 * but the packet requires that both be clusters (we
1702 * never reallocate the first mbuf to avoid moving the
1709 #ifdef MBUF_STRESS_TEST
1712 * Fragment an mbuf chain. There's no reason you'd ever want to do
1713 * this in normal usage, but it's great for stress testing various
1716 * If fragmentation is not possible, the original chain will be
1719 * Possible length values:
1720 * 0 no fragmentation will occur
1721 * > 0 each fragment will be of the specified length
1722 * -1 each fragment will be the same random value in length
1723 * -2 each fragment's length will be entirely random
1724 * (Random values range from 1 to 256)
1727 m_fragment(struct mbuf *m0, int how, int length)
1729 struct mbuf *m_new = NULL, *m_final = NULL;
1732 if (!(m0->m_flags & M_PKTHDR))
1735 if ((length == 0) || (length < -2))
1738 m_fixhdr(m0); /* Needed sanity check */
1740 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1742 if (m_final == NULL)
1745 if (m_dup_pkthdr(m_final, m0, how) == 0)
1751 length = 1 + (arc4random() & 255);
1753 while (progress < m0->m_pkthdr.len) {
1759 fraglen = 1 + (arc4random() & 255);
1760 if (fraglen > m0->m_pkthdr.len - progress)
1761 fraglen = m0->m_pkthdr.len - progress;
1763 if (fraglen > MCLBYTES)
1766 if (m_new == NULL) {
1767 m_new = m_getcl(how, MT_DATA, 0);
1772 m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1773 progress += fraglen;
1774 m_new->m_len = fraglen;
1775 if (m_new != m_final)
1776 m_cat(m_final, m_new);
1785 /* Return the original chain on failure */
1792 * Copy the contents of uio into a properly sized mbuf chain.
1795 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1797 struct mbuf *m, *mb;
1803 * len can be zero or an arbitrary large value bound by
1804 * the total data supplied by the uio.
1807 total = min(uio->uio_resid, len);
1809 total = uio->uio_resid;
1812 * The smallest unit returned by m_getm2() is a single mbuf
1813 * with pkthdr. We can't align past it.
1819 * Give us the full allocation or nothing.
1820 * If len is zero return the smallest empty mbuf.
1822 m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1827 /* Fill all mbufs with uio data and update header information. */
1828 for (mb = m; mb != NULL; mb = mb->m_next) {
1829 length = min(M_TRAILINGSPACE(mb), total - progress);
1831 error = uiomove(mtod(mb, void *), length, uio);
1839 if (flags & M_PKTHDR)
1840 m->m_pkthdr.len += length;
1842 KASSERT(progress == total, ("%s: progress != total", __func__));
1848 * Copy an mbuf chain into a uio limited by len if set.
1851 m_mbuftouio(struct uio *uio, struct mbuf *m, int len)
1853 int error, length, total;
1857 total = min(uio->uio_resid, len);
1859 total = uio->uio_resid;
1861 /* Fill the uio with data from the mbufs. */
1862 for (; m != NULL; m = m->m_next) {
1863 length = min(m->m_len, total - progress);
1865 error = uiomove(mtod(m, void *), length, uio);
1876 * Set the m_data pointer of a newly-allocated mbuf
1877 * to place an object of the specified size at the
1878 * end of the mbuf, longword aligned.
1881 m_align(struct mbuf *m, int len)
1884 const char *msg = "%s: not a virgin mbuf";
1888 if (m->m_flags & M_EXT) {
1889 KASSERT(m->m_data == m->m_ext.ext_buf, (msg, __func__));
1890 adjust = m->m_ext.ext_size - len;
1891 } else if (m->m_flags & M_PKTHDR) {
1892 KASSERT(m->m_data == m->m_pktdat, (msg, __func__));
1893 adjust = MHLEN - len;
1895 KASSERT(m->m_data == m->m_dat, (msg, __func__));
1896 adjust = MLEN - len;
1899 m->m_data += adjust &~ (sizeof(long)-1);
1903 * Create a writable copy of the mbuf chain. While doing this
1904 * we compact the chain with a goal of producing a chain with
1905 * at most two mbufs. The second mbuf in this chain is likely
1906 * to be a cluster. The primary purpose of this work is to create
1907 * a writable packet for encryption, compression, etc. The
1908 * secondary goal is to linearize the data so the data can be
1909 * passed to crypto hardware in the most efficient manner possible.
1912 m_unshare(struct mbuf *m0, int how)
1914 struct mbuf *m, *mprev;
1915 struct mbuf *n, *mfirst, *mlast;
1919 for (m = m0; m != NULL; m = mprev->m_next) {
1921 * Regular mbufs are ignored unless there's a cluster
1922 * in front of it that we can use to coalesce. We do
1923 * the latter mainly so later clusters can be coalesced
1924 * also w/o having to handle them specially (i.e. convert
1925 * mbuf+cluster -> cluster). This optimization is heavily
1926 * influenced by the assumption that we're running over
1927 * Ethernet where MCLBYTES is large enough that the max
1928 * packet size will permit lots of coalescing into a
1929 * single cluster. This in turn permits efficient
1930 * crypto operations, especially when using hardware.
1932 if ((m->m_flags & M_EXT) == 0) {
1933 if (mprev && (mprev->m_flags & M_EXT) &&
1934 m->m_len <= M_TRAILINGSPACE(mprev)) {
1935 /* XXX: this ignores mbuf types */
1936 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1937 mtod(m, caddr_t), m->m_len);
1938 mprev->m_len += m->m_len;
1939 mprev->m_next = m->m_next; /* unlink from chain */
1940 m_free(m); /* reclaim mbuf */
1942 newipsecstat.ips_mbcoalesced++;
1950 * Writable mbufs are left alone (for now).
1952 if (M_WRITABLE(m)) {
1958 * Not writable, replace with a copy or coalesce with
1959 * the previous mbuf if possible (since we have to copy
1960 * it anyway, we try to reduce the number of mbufs and
1961 * clusters so that future work is easier).
1963 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1964 /* NB: we only coalesce into a cluster or larger */
1965 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1966 m->m_len <= M_TRAILINGSPACE(mprev)) {
1967 /* XXX: this ignores mbuf types */
1968 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1969 mtod(m, caddr_t), m->m_len);
1970 mprev->m_len += m->m_len;
1971 mprev->m_next = m->m_next; /* unlink from chain */
1972 m_free(m); /* reclaim mbuf */
1974 newipsecstat.ips_clcoalesced++;
1980 * Allocate new space to hold the copy and copy the data.
1981 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1982 * splitting them into clusters. We could just malloc a
1983 * buffer and make it external but too many device drivers
1984 * don't know how to break up the non-contiguous memory when
1987 n = m_getcl(how, m->m_type, m->m_flags);
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);
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)
2092 p = &mbprof.wasted[0];
2094 offset = snprintf(c, MP_MAXLINE + 10,
2096 "%ju %ju %ju %ju %ju %ju %ju %ju "
2097 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2098 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2099 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2101 p = &mbprof.wasted[16];
2103 offset = snprintf(c, MP_MAXLINE,
2104 "%ju %ju %ju %ju %ju %ju %ju %ju "
2105 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2106 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2107 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2109 p = &mbprof.used[0];
2111 offset = snprintf(c, MP_MAXLINE + 10,
2113 "%ju %ju %ju %ju %ju %ju %ju %ju "
2114 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2115 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2116 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2118 p = &mbprof.used[16];
2120 offset = snprintf(c, MP_MAXLINE,
2121 "%ju %ju %ju %ju %ju %ju %ju %ju "
2122 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2123 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2124 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2126 p = &mbprof.segments[0];
2128 offset = snprintf(c, MP_MAXLINE + 10,
2130 "%ju %ju %ju %ju %ju %ju %ju %ju "
2131 "%ju %ju %ju %ju %ju %ju %ju %ju\n",
2132 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2133 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2135 p = &mbprof.segments[16];
2137 offset = snprintf(c, MP_MAXLINE,
2138 "%ju %ju %ju %ju %ju %ju %ju %ju "
2139 "%ju %ju %ju %ju %ju %ju %ju %jju",
2140 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2141 p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2146 mbprof_handler(SYSCTL_HANDLER_ARGS)
2151 error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
2156 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2161 error = sysctl_handle_int(oidp, &clear, 0, req);
2162 if (error || !req->newptr)
2166 bzero(&mbprof, sizeof(mbprof));
2173 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile, CTLTYPE_STRING|CTLFLAG_RD,
2174 NULL, 0, mbprof_handler, "A", "mbuf profiling statistics");
2176 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr, CTLTYPE_INT|CTLFLAG_RW,
2177 NULL, 0, mbprof_clr_handler, "I", "clear mbuf profiling statistics");