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 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
34 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
35 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.9 2003/07/23 02:30:20 dillon Exp $
38 #include "opt_param.h"
39 #include "opt_mbuf_stress_test.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
44 #include <sys/kernel.h>
45 #include <sys/sysctl.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/thread.h>
49 #include <sys/globaldata.h>
52 #include <vm/vm_kern.h>
53 #include <vm/vm_extern.h>
56 #include <machine/cpu.h>
59 static void mbinit __P((void *));
60 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbinit, NULL)
65 u_long mbtypes[MT_NTYPES];
67 union mcluster *mclfree;
76 #ifdef MBUF_STRESS_TEST
77 int m_defragrandomfailures;
82 u_int m_mballoc_wid = 0;
83 u_int m_clalloc_wid = 0;
85 SYSCTL_DECL(_kern_ipc);
86 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
88 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
89 &max_protohdr, 0, "");
90 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
91 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
93 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
95 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
96 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
97 sizeof(mbtypes), "LU", "");
98 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
99 &nmbclusters, 0, "Maximum number of mbuf clusters available");
100 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
101 "Maximum number of mbufs available");
102 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
103 &m_defragpackets, 0, "");
104 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
105 &m_defragbytes, 0, "");
106 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
107 &m_defraguseless, 0, "");
108 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
109 &m_defragfailure, 0, "");
110 #ifdef MBUF_STRESS_TEST
111 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
112 &m_defragrandomfailures, 0, "");
115 static void m_reclaim __P((void));
118 #define NMBCLUSTERS (512 + maxusers * 16)
121 #define NMBUFS (nmbclusters * 4)
125 * Perform sanity checks of tunables declared above.
128 tunable_mbinit(void *dummy)
132 * This has to be done before VM init.
134 nmbclusters = NMBCLUSTERS;
135 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
137 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
139 if (nmbufs < nmbclusters * 2)
140 nmbufs = nmbclusters * 2;
144 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
146 /* "number of clusters of pages" */
158 mmbfree = NULL; mclfree = NULL;
159 mbstat.m_msize = MSIZE;
160 mbstat.m_mclbytes = MCLBYTES;
161 mbstat.m_minclsize = MINCLSIZE;
162 mbstat.m_mlen = MLEN;
163 mbstat.m_mhlen = MHLEN;
166 if (m_mballoc(NMB_INIT, M_DONTWAIT) == 0)
168 #if MCLBYTES <= PAGE_SIZE
169 if (m_clalloc(NCL_INIT, M_DONTWAIT) == 0)
172 /* It's OK to call contigmalloc in this context. */
173 if (m_clalloc(16, M_WAIT) == 0)
183 * Allocate at least nmb mbufs and place on mbuf free list.
184 * Must be called at splimp.
197 * If we've hit the mbuf limit, stop allocating from mb_map,
198 * (or trying to) in order to avoid dipping into the section of
199 * mb_map which we've "reserved" for clusters.
201 if ((nmb + mbstat.m_mbufs) > nmbufs)
205 * Once we run out of map space, it will be impossible to get
206 * any more (nothing is ever freed back to the map)
207 * -- however you are not dead as m_reclaim might
208 * still be able to free a substantial amount of space.
210 * XXX Furthermore, we can also work with "recycled" mbufs (when
211 * we're calling with M_WAIT the sleep procedure will be woken
212 * up when an mbuf is freed. See m_mballoc_wait()).
217 nbytes = round_page(nmb * MSIZE);
218 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_NOWAIT);
219 if (p == 0 && how == M_WAIT) {
221 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_WAITOK);
225 * Either the map is now full, or `how' is M_NOWAIT and there
231 nmb = nbytes / MSIZE;
232 for (i = 0; i < nmb; i++) {
233 ((struct mbuf *)p)->m_next = mmbfree;
234 mmbfree = (struct mbuf *)p;
237 mbstat.m_mbufs += nmb;
238 mbtypes[MT_FREE] += nmb;
243 * Once the mb_map has been exhausted and if the call to the allocation macros
244 * (or, in some cases, functions) is with M_WAIT, then it is necessary to rely
245 * solely on reclaimed mbufs. Here we wait for an mbuf to be freed for a
246 * designated (mbuf_wait) time.
249 m_mballoc_wait(int caller, int type)
256 if ((tsleep(&m_mballoc_wid, 0, "mballc", mbuf_wait)) == EWOULDBLOCK)
261 * Now that we (think) that we've got something, we will redo an
262 * MGET, but avoid getting into another instance of m_mballoc_wait()
263 * XXX: We retry to fetch _even_ if the sleep timed out. This is left
264 * this way, purposely, in the [unlikely] case that an mbuf was
265 * freed but the sleep was not awakened in time.
270 MGET(p, M_DONTWAIT, type);
273 MGETHDR(p, M_DONTWAIT, type);
276 panic("m_mballoc_wait: invalid caller (%d)", caller);
280 if (p != NULL) { /* We waited and got something... */
282 /* Wake up another if we have more free. */
290 #if MCLBYTES > PAGE_SIZE
291 static int i_want_my_mcl;
299 tsleep(&i_want_my_mcl, 0, "mclalloc", 0);
301 for (; i_want_my_mcl; i_want_my_mcl--) {
302 if (m_clalloc(1, M_WAIT) == 0)
303 printf("m_clalloc failed even in process context!\n");
308 static struct thread *mclallocthread;
309 static struct kproc_desc mclalloc_kp = {
314 SYSINIT(mclallocthread, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
319 * Allocate some number of mbuf clusters
320 * and place on cluster free list.
321 * Must be called at splimp.
334 * If we've hit the mcluster number limit, stop allocating from
335 * mb_map, (or trying to) in order to avoid dipping into the section
336 * of mb_map which we've "reserved" for mbufs.
338 if ((ncl + mbstat.m_clusters) > nmbclusters)
342 * Once we run out of map space, it will be impossible
343 * to get any more (nothing is ever freed back to the
344 * map). From this point on, we solely rely on freed
350 #if MCLBYTES > PAGE_SIZE
352 i_want_my_mcl += ncl;
353 wakeup(&i_want_my_mcl);
357 p = contigmalloc1(MCLBYTES * ncl, M_DEVBUF, M_WAITOK, 0ul,
358 ~0ul, PAGE_SIZE, 0, mb_map);
362 p = (caddr_t)kmem_malloc(mb_map, ctob(npg),
363 how != M_WAIT ? M_NOWAIT : M_WAITOK);
364 ncl = ncl * PAGE_SIZE / MCLBYTES;
367 * Either the map is now full, or `how' is M_NOWAIT and there
371 static int last_report ; /* when we did that (in ticks) */
374 if (ticks < last_report || (ticks - last_report) >= hz) {
376 printf("All mbuf clusters exhausted, please see tuning(7).\n");
381 for (i = 0; i < ncl; i++) {
382 ((union mcluster *)p)->mcl_next = mclfree;
383 mclfree = (union mcluster *)p;
387 mbstat.m_clusters += ncl;
392 * Once the mb_map submap has been exhausted and the allocation is called with
393 * M_WAIT, we rely on the mclfree union pointers. If nothing is free, we will
394 * sleep for a designated amount of time (mbuf_wait) or until we're woken up
395 * due to sudden mcluster availability.
404 /* If in interrupt context, and INVARIANTS, maintain sanity and die. */
405 KASSERT(mycpu->gd_intr_nesting_level == 0, ("CLALLOC: CANNOT WAIT IN INTERRUPT"));
408 /* Sleep until something's available or until we expire. */
410 if ((tsleep(&m_clalloc_wid, 0, "mclalc", mbuf_wait)) == EWOULDBLOCK)
414 * Now that we (think) that we've got something, we will redo and
415 * MGET, but avoid getting into another instance of m_clalloc_wait()
417 p = m_mclalloc(M_DONTWAIT);
420 if (p != NULL) { /* We waited and got something... */
422 /* Wake up another if we have more free. */
432 * When MGET fails, ask protocols to free space when short of memory,
433 * then re-attempt to allocate an mbuf.
443 * Must only do the reclaim if not in an interrupt context.
447 KASSERT(mycpu->gd_intr_nesting_level == 0,
448 ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
455 (void)m_mballoc(1, i);
464 m->m_data = m->m_dat;
469 static int last_report ; /* when we did that (in ticks) */
473 if (ticks < last_report || (ticks - last_report) >= hz) {
475 printf("All mbufs exhausted, please see tuning(7).\n");
483 * As above; retry an MGETHDR.
493 * Must only do the reclaim if not in an interrupt context.
497 KASSERT(mycpu->gd_intr_nesting_level == 0,
498 ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
505 (void)m_mballoc(1, i);
514 m->m_data = m->m_pktdat;
515 m->m_flags = M_PKTHDR;
516 m->m_pkthdr.rcvif = NULL;
517 SLIST_INIT(&m->m_pkthdr.tags);
518 m->m_pkthdr.csum_flags = 0;
522 static int last_report ; /* when we did that (in ticks) */
526 if (ticks < last_report || (ticks - last_report) >= hz) {
528 printf("All mbufs exhausted, please see tuning(7).\n");
538 register struct domain *dp;
539 register struct protosw *pr;
542 for (dp = domains; dp; dp = dp->dom_next)
543 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
551 * Space allocation routines.
552 * These are also available as macros
553 * for critical paths.
564 (void)m_mballoc(1, how);
573 m->m_data = m->m_dat;
578 m = m_retry(how, type);
579 if (m == NULL && how == M_WAIT)
580 m = m_mballoc_wait(MGET_C, type);
594 (void)m_mballoc(1, how);
603 m->m_data = m->m_pktdat;
604 m->m_flags = M_PKTHDR;
605 m->m_pkthdr.rcvif = NULL;
606 SLIST_INIT(&m->m_pkthdr.tags);
607 m->m_pkthdr.csum_flags = 0;
611 m = m_retryhdr(how, type);
612 if (m == NULL && how == M_WAIT)
613 m = m_mballoc_wait(MGETHDR_C, type);
622 register struct mbuf *m;
627 bzero(mtod(m, caddr_t), MLEN);
632 * m_getcl() returns an mbuf with an attached cluster.
633 * Because many network drivers use this kind of buffers a lot, it is
634 * convenient to keep a small pool of free buffers of this kind.
635 * Even a small size such as 10 gives about 10% improvement in the
636 * forwarding rate in a bridge or router.
637 * The size of this free list is controlled by the sysctl variable
638 * mcl_pool_max. The list is populated on m_freem(), and used in
639 * m_getcl() if elements are available.
641 static struct mbuf *mcl_pool;
642 static int mcl_pool_now;
643 static int mcl_pool_max = 0;
645 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_max, CTLFLAG_RW, &mcl_pool_max, 0,
646 "Maximum number of mbufs+cluster in free list");
647 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_now, CTLFLAG_RD, &mcl_pool_now, 0,
648 "Current number of mbufs+cluster in free list");
651 m_getcl(int how, short type, int flags)
656 if (flags & M_PKTHDR) {
657 if (type == MT_DATA && mcl_pool) {
659 mcl_pool = mp->m_nextpkt;
662 mp->m_nextpkt = NULL;
663 mp->m_data = mp->m_ext.ext_buf;
664 mp->m_flags = M_PKTHDR|M_EXT;
665 mp->m_pkthdr.rcvif = NULL;
666 mp->m_pkthdr.csum_flags = 0;
669 MGETHDR(mp, how, type);
674 if ( (mp->m_flags & M_EXT) == 0) {
685 * m_getm(m, len, how, type)
687 * This will allocate len-worth of mbufs and/or mbuf clusters (whatever fits
688 * best) and return a pointer to the top of the allocated chain. If m is
689 * non-null, then we assume that it is a single mbuf or an mbuf chain to
690 * which we want len bytes worth of mbufs and/or clusters attached, and so
691 * if we succeed in allocating it, we will just return a pointer to m.
693 * If we happen to fail at any point during the allocation, we will free
694 * up everything we have already allocated and return NULL.
698 m_getm(struct mbuf *m, int len, int how, int type)
700 struct mbuf *top, *tail, *mp, *mtail = NULL;
702 KASSERT(len >= 0, ("len is < 0 in m_getm"));
707 else if (len > MINCLSIZE) {
709 if ((mp->m_flags & M_EXT) == 0) {
715 len -= M_TRAILINGSPACE(mp);
718 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
730 if (len > MINCLSIZE) {
732 if ((mp->m_flags & M_EXT) == 0)
737 len -= M_TRAILINGSPACE(mp);
750 * m_mclalloc() - Allocates an mbuf cluster.
762 mp = (caddr_t)mclfree;
764 mclrefcnt[mtocl(mp)]++;
766 mclfree = ((union mcluster *)mp)->mcl_next;
772 return(m_clalloc_wait());
777 * m_mclget() - Adds a cluster to a normal mbuf, M_EXT is set on success.
780 m_mclget(struct mbuf *m, int how)
782 m->m_ext.ext_buf = m_mclalloc(how);
783 if (m->m_ext.ext_buf != NULL) {
784 m->m_data = m->m_ext.ext_buf;
786 m->m_ext.ext_free = NULL;
787 m->m_ext.ext_ref = NULL;
788 m->m_ext.ext_size = MCLBYTES;
793 _m_mclfree(caddr_t data)
795 union mcluster *mp = (union mcluster *)data;
797 KASSERT(mclrefcnt[mtocl(mp)] > 0, ("freeing free cluster"));
798 if (--mclrefcnt[mtocl(mp)] == 0) {
799 mp->mcl_next = mclfree;
807 m_mclfree(caddr_t mp)
817 * Free a single mbuf and any associated external storage. The successor,
818 * if any, is returned.
820 * We do need to check non-first mbuf for m_aux, since some of existing
821 * code does not call M_PREPEND properly.
822 * (example: call to bpf_mtap from drivers)
825 m_free(struct mbuf *m)
831 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf"));
832 mbtypes[m->m_type]--;
833 if ((m->m_flags & M_PKTHDR) != 0)
834 m_tag_delete_chain(m, NULL);
835 if (m->m_flags & M_EXT) {
836 if (m->m_ext.ext_free != NULL) {
837 m->m_ext.ext_free(m->m_ext.ext_buf, m->m_ext.ext_size);
839 _m_mclfree(m->m_ext.ext_buf); /* inlined */
854 m_freem(struct mbuf *m)
859 * Try to keep a small pool of mbuf+cluster for quick use in
860 * device drivers. A good candidate is a M_PKTHDR buffer with
861 * only one cluster attached. Other mbufs, or those exceeding
862 * the pool size, are just m_free'd in the usual way.
863 * The following code makes sure that m_next, m_type,
864 * m_pkthdr.aux and m_ext.* are properly initialized.
865 * Other fields in the mbuf are initialized in m_getcl()
868 if (mcl_pool_now < mcl_pool_max && m && m->m_next == NULL &&
869 (m->m_flags & (M_PKTHDR|M_EXT)) == (M_PKTHDR|M_EXT) &&
870 m->m_type == MT_DATA && M_EXT_WRITABLE(m) ) {
871 m_tag_delete_chain(m, NULL);
872 m->m_nextpkt = mcl_pool;
883 * Mbuffer utility routines.
887 * Lesser-used path for M_PREPEND:
888 * allocate new mbuf to prepend to chain,
892 m_prepend(m, len, how)
893 register struct mbuf *m;
898 MGET(mn, how, m->m_type);
899 if (mn == (struct mbuf *)NULL) {
901 return ((struct mbuf *)NULL);
903 if (m->m_flags & M_PKTHDR)
904 M_MOVE_PKTHDR(mn, m);
914 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
915 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
916 * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
917 * Note that the copy is read-only, because clusters are not copied,
918 * only their reference counts are incremented.
920 #define MCFail (mbstat.m_mcfail)
923 m_copym(m, off0, len, wait)
924 const struct mbuf *m;
928 register struct mbuf *n, **np;
929 register int off = off0;
933 KASSERT(off >= 0, ("m_copym, negative off %d", off));
934 KASSERT(len >= 0, ("m_copym, negative len %d", len));
935 if (off == 0 && m->m_flags & M_PKTHDR)
938 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
948 KASSERT(len == M_COPYALL,
949 ("m_copym, length > size of mbuf chain"));
952 MGET(n, wait, m->m_type);
957 if (!m_dup_pkthdr(n, m, wait))
959 if (len == M_COPYALL)
960 n->m_pkthdr.len -= off0;
962 n->m_pkthdr.len = len;
965 n->m_len = min(len, m->m_len - off);
966 if (m->m_flags & M_EXT) {
967 n->m_data = m->m_data + off;
968 if (m->m_ext.ext_ref == NULL) {
970 &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
974 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
981 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
983 if (len != M_COPYALL)
999 * Copy an entire packet, including header (which must be present).
1000 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1001 * Note that the copy is read-only, because clusters are not copied,
1002 * only their reference counts are incremented.
1003 * Preserve alignment of the first mbuf so if the creator has left
1004 * some room at the beginning (e.g. for inserting protocol headers)
1005 * the copies also have the room available.
1008 m_copypacket(m, how)
1012 struct mbuf *top, *n, *o;
1014 MGET(n, how, m->m_type);
1019 if (!m_dup_pkthdr(n, m, how))
1021 n->m_len = m->m_len;
1022 if (m->m_flags & M_EXT) {
1023 n->m_data = m->m_data;
1024 if (m->m_ext.ext_ref == NULL)
1025 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1029 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1033 n->m_ext = m->m_ext;
1034 n->m_flags |= M_EXT;
1036 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1037 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1042 MGET(o, how, m->m_type);
1049 n->m_len = m->m_len;
1050 if (m->m_flags & M_EXT) {
1051 n->m_data = m->m_data;
1052 if (m->m_ext.ext_ref == NULL) {
1054 &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1058 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1062 n->m_ext = m->m_ext;
1063 n->m_flags |= M_EXT;
1065 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1078 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1079 * continuing for "len" bytes, into the indicated buffer.
1082 m_copydata(m, off, len, cp)
1083 const struct mbuf *m;
1088 register unsigned count;
1090 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1091 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1093 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1100 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1101 count = min(m->m_len - off, len);
1102 bcopy(mtod(m, caddr_t) + off, cp, count);
1111 * Copy a packet header mbuf chain into a completely new chain, including
1112 * copying any mbuf clusters. Use this instead of m_copypacket() when
1113 * you need a writable copy of an mbuf chain.
1120 struct mbuf **p, *top = NULL;
1121 int remain, moff, nsize;
1126 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __FUNCTION__));
1128 /* While there's more data, get a new mbuf, tack it on, and fill it */
1129 remain = m->m_pkthdr.len;
1132 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1135 /* Get the next new mbuf */
1136 MGET(n, how, m->m_type);
1139 if (top == NULL) { /* first one, must be PKTHDR */
1140 if (!m_dup_pkthdr(n, m, how))
1143 } else /* not the first one */
1145 if (remain >= MINCLSIZE) {
1147 if ((n->m_flags & M_EXT) == 0) {
1155 /* Link it into the new chain */
1159 /* Copy data from original mbuf(s) into new mbuf */
1160 while (n->m_len < nsize && m != NULL) {
1161 int chunk = min(nsize - n->m_len, m->m_len - moff);
1163 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1167 if (moff == m->m_len) {
1173 /* Check correct total mbuf length */
1174 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1175 ("%s: bogus m_pkthdr.len", __FUNCTION__));
1186 * Concatenate mbuf chain n to m.
1187 * Both chains must be of the same type (e.g. MT_DATA).
1188 * Any m_pkthdr is not updated.
1192 register struct mbuf *m, *n;
1197 if (m->m_flags & M_EXT ||
1198 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1199 /* just join the two chains */
1203 /* splat the data from one into the other */
1204 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1206 m->m_len += n->m_len;
1216 register int len = req_len;
1217 register struct mbuf *m;
1220 if ((m = mp) == NULL)
1226 while (m != NULL && len > 0) {
1227 if (m->m_len <= len) {
1238 if (mp->m_flags & M_PKTHDR)
1239 m->m_pkthdr.len -= (req_len - len);
1242 * Trim from tail. Scan the mbuf chain,
1243 * calculating its length and finding the last mbuf.
1244 * If the adjustment only affects this mbuf, then just
1245 * adjust and return. Otherwise, rescan and truncate
1246 * after the remaining size.
1252 if (m->m_next == (struct mbuf *)0)
1256 if (m->m_len >= len) {
1258 if (mp->m_flags & M_PKTHDR)
1259 mp->m_pkthdr.len -= len;
1266 * Correct length for chain is "count".
1267 * Find the mbuf with last data, adjust its length,
1268 * and toss data from remaining mbufs on chain.
1271 if (m->m_flags & M_PKTHDR)
1272 m->m_pkthdr.len = count;
1273 for (; m; m = m->m_next) {
1274 if (m->m_len >= count) {
1281 (m = m->m_next) ->m_len = 0;
1286 * Rearange an mbuf chain so that len bytes are contiguous
1287 * and in the data area of an mbuf (so that mtod and dtom
1288 * will work for a structure of size len). Returns the resulting
1289 * mbuf chain on success, frees it and returns null on failure.
1290 * If there is room, it will add up to max_protohdr-len extra bytes to the
1291 * contiguous region in an attempt to avoid being called next time.
1293 #define MPFail (mbstat.m_mpfail)
1297 register struct mbuf *n;
1300 register struct mbuf *m;
1305 * If first mbuf has no cluster, and has room for len bytes
1306 * without shifting current data, pullup into it,
1307 * otherwise allocate a new mbuf to prepend to the chain.
1309 if ((n->m_flags & M_EXT) == 0 &&
1310 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1311 if (n->m_len >= len)
1319 MGET(m, M_DONTWAIT, n->m_type);
1323 if (n->m_flags & M_PKTHDR)
1324 M_MOVE_PKTHDR(m, n);
1326 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1328 count = min(min(max(len, max_protohdr), space), n->m_len);
1329 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1339 } while (len > 0 && n);
1353 * Partition an mbuf chain in two pieces, returning the tail --
1354 * all but the first len0 bytes. In case of failure, it returns NULL and
1355 * attempts to restore the chain to its original state.
1357 * Note that the resulting mbufs might be read-only, because the new
1358 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1359 * the "breaking point" happens to lie within a cluster mbuf. Use the
1360 * M_WRITABLE() macro to check for this case.
1363 m_split(m0, len0, wait)
1364 register struct mbuf *m0;
1367 register struct mbuf *m, *n;
1368 unsigned len = len0, remain;
1370 for (m = m0; m && len > m->m_len; m = m->m_next)
1374 remain = m->m_len - len;
1375 if (m0->m_flags & M_PKTHDR) {
1376 MGETHDR(n, wait, m0->m_type);
1379 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1380 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1381 m0->m_pkthdr.len = len0;
1382 if (m->m_flags & M_EXT)
1384 if (remain > MHLEN) {
1385 /* m can't be the lead packet */
1387 n->m_next = m_split(m, len, wait);
1388 if (n->m_next == 0) {
1396 MH_ALIGN(n, remain);
1397 } else if (remain == 0) {
1402 MGET(n, wait, m->m_type);
1408 if (m->m_flags & M_EXT) {
1409 n->m_flags |= M_EXT;
1410 n->m_ext = m->m_ext;
1411 if (m->m_ext.ext_ref == NULL)
1412 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1416 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1420 n->m_data = m->m_data + len;
1422 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1426 n->m_next = m->m_next;
1431 * Routine to copy from device local memory into mbufs.
1434 m_devget(buf, totlen, off0, ifp, copy)
1438 void (*copy) __P((char *from, caddr_t to, u_int len));
1440 register struct mbuf *m;
1441 struct mbuf *top = 0, **mp = ⊤
1442 register int off = off0, len;
1449 cp += off + 2 * sizeof(u_short);
1450 totlen -= 2 * sizeof(u_short);
1452 MGETHDR(m, M_DONTWAIT, MT_DATA);
1455 m->m_pkthdr.rcvif = ifp;
1456 m->m_pkthdr.len = totlen;
1459 while (totlen > 0) {
1461 MGET(m, M_DONTWAIT, MT_DATA);
1468 len = min(totlen, epkt - cp);
1469 if (len >= MINCLSIZE) {
1470 MCLGET(m, M_DONTWAIT);
1471 if (m->m_flags & M_EXT)
1472 m->m_len = len = min(len, MCLBYTES);
1477 * Place initial small packet/header at end of mbuf.
1479 if (len < m->m_len) {
1480 if (top == 0 && len + max_linkhdr <= m->m_len)
1481 m->m_data += max_linkhdr;
1487 copy(cp, mtod(m, caddr_t), (unsigned)len);
1489 bcopy(cp, mtod(m, caddr_t), (unsigned)len);
1501 * Copy data from a buffer back into the indicated mbuf chain,
1502 * starting "off" bytes from the beginning, extending the mbuf
1503 * chain if necessary.
1506 m_copyback(m0, off, len, cp)
1513 register struct mbuf *m = m0, *n;
1518 while (off > (mlen = m->m_len)) {
1521 if (m->m_next == 0) {
1522 n = m_getclr(M_DONTWAIT, m->m_type);
1525 n->m_len = min(MLEN, len + off);
1531 mlen = min (m->m_len - off, len);
1532 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1540 if (m->m_next == 0) {
1541 n = m_get(M_DONTWAIT, m->m_type);
1544 n->m_len = min(MLEN, len);
1549 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1550 m->m_pkthdr.len = totlen;
1554 m_print(const struct mbuf *m)
1557 const struct mbuf *m2;
1559 len = m->m_pkthdr.len;
1562 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1570 * "Move" mbuf pkthdr from "from" to "to".
1571 * "from" must have M_PKTHDR set, and "to" must be empty.
1574 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1576 KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
1578 to->m_flags = from->m_flags & M_COPYFLAGS;
1579 to->m_data = to->m_pktdat;
1580 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1581 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
1582 from->m_flags &= ~M_PKTHDR;
1586 * Duplicate "from"'s mbuf pkthdr in "to".
1587 * "from" must have M_PKTHDR set, and "to" must be empty.
1588 * In particular, this does a deep copy of the packet tags.
1591 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1593 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1594 if ((to->m_flags & M_EXT) == 0)
1595 to->m_data = to->m_pktdat;
1596 to->m_pkthdr = from->m_pkthdr;
1597 SLIST_INIT(&to->m_pkthdr.tags);
1598 return (m_tag_copy_chain(to, from, how));
1602 * Defragment a mbuf chain, returning the shortest possible
1603 * chain of mbufs and clusters. If allocation fails and
1604 * this cannot be completed, NULL will be returned, but
1605 * the passed in chain will be unchanged. Upon success,
1606 * the original chain will be freed, and the new chain
1609 * If a non-packet header is passed in, the original
1610 * mbuf (chain?) will be returned unharmed.
1613 m_defrag(struct mbuf *m0, int how)
1615 struct mbuf *m_new = NULL, *m_final = NULL;
1616 int progress = 0, length;
1618 if (!(m0->m_flags & M_PKTHDR))
1621 #ifdef MBUF_STRESS_TEST
1622 if (m_defragrandomfailures) {
1623 int temp = arc4random() & 0xff;
1629 if (m0->m_pkthdr.len > MHLEN)
1630 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1632 m_final = m_gethdr(how, MT_DATA);
1634 if (m_final == NULL)
1637 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1642 while (progress < m0->m_pkthdr.len) {
1643 length = m0->m_pkthdr.len - progress;
1644 if (length > MCLBYTES)
1647 if (m_new == NULL) {
1649 m_new = m_getcl(how, MT_DATA, 0);
1651 m_new = m_get(how, MT_DATA);
1656 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1658 m_new->m_len = length;
1659 if (m_new != m_final)
1660 m_cat(m_final, m_new);
1663 if (m0->m_next == NULL)
1668 m_defragbytes += m0->m_pkthdr.len;