2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
37 * License terms: all terms for the DragonFly license above plus the following:
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
52 * Copyright (c) 1982, 1986, 1988, 1991, 1993
53 * The Regents of the University of California. All rights reserved.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
83 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
84 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
85 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.22 2004/07/29 08:46:21 dillon Exp $
88 #include "opt_param.h"
89 #include "opt_mbuf_stress_test.h"
90 #include <sys/param.h>
91 #include <sys/systm.h>
92 #include <sys/malloc.h>
94 #include <sys/kernel.h>
95 #include <sys/sysctl.h>
96 #include <sys/domain.h>
97 #include <sys/protosw.h>
99 #include <sys/thread.h>
100 #include <sys/globaldata.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_extern.h>
107 #include <machine/cpu.h>
110 static void mbinit (void *);
111 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbinit, NULL)
116 struct mbstat mbstat;
117 u_long mbtypes[MT_NTYPES];
118 struct mbuf *mmbfree;
119 union mcluster *mclfree;
128 #ifdef MBUF_STRESS_TEST
129 int m_defragrandomfailures;
134 u_int m_mballoc_wid = 0;
135 u_int m_clalloc_wid = 0;
137 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
138 &max_linkhdr, 0, "");
139 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
140 &max_protohdr, 0, "");
141 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
142 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
143 &max_datalen, 0, "");
144 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
146 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
147 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
148 sizeof(mbtypes), "LU", "");
149 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
150 &nmbclusters, 0, "Maximum number of mbuf clusters available");
151 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
152 "Maximum number of mbufs available");
153 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
154 &m_defragpackets, 0, "");
155 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
156 &m_defragbytes, 0, "");
157 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
158 &m_defraguseless, 0, "");
159 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
160 &m_defragfailure, 0, "");
161 #ifdef MBUF_STRESS_TEST
162 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
163 &m_defragrandomfailures, 0, "");
166 static void m_reclaim (void);
169 #define NMBCLUSTERS (512 + maxusers * 16)
172 #define NMBUFS (nmbclusters * 4)
176 * Perform sanity checks of tunables declared above.
179 tunable_mbinit(void *dummy)
183 * This has to be done before VM init.
185 nmbclusters = NMBCLUSTERS;
186 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
188 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
190 if (nmbufs < nmbclusters * 2)
191 nmbufs = nmbclusters * 2;
195 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
197 /* "number of clusters of pages" */
208 mmbfree = NULL; mclfree = NULL;
209 mbstat.m_msize = MSIZE;
210 mbstat.m_mclbytes = MCLBYTES;
211 mbstat.m_minclsize = MINCLSIZE;
212 mbstat.m_mlen = MLEN;
213 mbstat.m_mhlen = MHLEN;
216 if (m_mballoc(NMB_INIT, MB_DONTWAIT) == 0)
218 #if MCLBYTES <= PAGE_SIZE
219 if (m_clalloc(NCL_INIT, MB_DONTWAIT) == 0)
222 /* It's OK to call contigmalloc in this context. */
223 if (m_clalloc(16, MB_WAIT) == 0)
233 * Allocate at least nmb mbufs and place on mbuf free list.
234 * Must be called at splimp.
238 m_mballoc(int nmb, int how)
245 * If we've hit the mbuf limit, stop allocating from mb_map,
246 * (or trying to) in order to avoid dipping into the section of
247 * mb_map which we've "reserved" for clusters.
249 if ((nmb + mbstat.m_mbufs) > nmbufs)
253 * Once we run out of map space, it will be impossible to get
254 * any more (nothing is ever freed back to the map)
255 * -- however you are not dead as m_reclaim might
256 * still be able to free a substantial amount of space.
258 * XXX Furthermore, we can also work with "recycled" mbufs (when
259 * we're calling with MB_WAIT the sleep procedure will be woken
260 * up when an mbuf is freed. See m_mballoc_wait()).
265 nbytes = round_page(nmb * MSIZE);
266 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_NOWAIT);
267 if (p == 0 && how == MB_WAIT) {
269 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_WAITOK);
273 * Either the map is now full, or `how' is M_NOWAIT and there
279 nmb = nbytes / MSIZE;
280 for (i = 0; i < nmb; i++) {
281 ((struct mbuf *)p)->m_next = mmbfree;
282 mmbfree = (struct mbuf *)p;
285 mbstat.m_mbufs += nmb;
286 mbtypes[MT_FREE] += nmb;
291 * Once the mb_map has been exhausted and if the call to the allocation macros
292 * (or, in some cases, functions) is with MB_WAIT, then it is necessary to rely
293 * solely on reclaimed mbufs. Here we wait for an mbuf to be freed for a
294 * designated (mbuf_wait) time.
297 m_mballoc_wait(int caller, int type)
304 if ((tsleep(&m_mballoc_wid, 0, "mballc", mbuf_wait)) == EWOULDBLOCK)
309 * Now that we (think) that we've got something, we will redo an
310 * MGET, but avoid getting into another instance of m_mballoc_wait()
311 * XXX: We retry to fetch _even_ if the sleep timed out. This is left
312 * this way, purposely, in the [unlikely] case that an mbuf was
313 * freed but the sleep was not awakened in time.
318 MGET(p, MB_DONTWAIT, type);
321 MGETHDR(p, MB_DONTWAIT, type);
324 panic("m_mballoc_wait: invalid caller (%d)", caller);
328 if (p != NULL) { /* We waited and got something... */
330 /* Wake up another if we have more free. */
338 #if MCLBYTES > PAGE_SIZE
339 static int i_want_my_mcl;
347 tsleep(&i_want_my_mcl, 0, "mclalloc", 0);
349 for (; i_want_my_mcl; i_want_my_mcl--) {
350 if (m_clalloc(1, MB_WAIT) == 0)
351 printf("m_clalloc failed even in process context!\n");
356 static struct thread *mclallocthread;
357 static struct kproc_desc mclalloc_kp = {
362 SYSINIT(mclallocthread, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
367 * Allocate some number of mbuf clusters
368 * and place on cluster free list.
369 * Must be called at splimp.
373 m_clalloc(int ncl, int how)
380 * If we've hit the mcluster number limit, stop allocating from
381 * mb_map, (or trying to) in order to avoid dipping into the section
382 * of mb_map which we've "reserved" for mbufs.
384 if ((ncl + mbstat.m_clusters) > nmbclusters)
388 * Once we run out of map space, it will be impossible
389 * to get any more (nothing is ever freed back to the
390 * map). From this point on, we solely rely on freed
396 #if MCLBYTES > PAGE_SIZE
397 if (how != MB_WAIT) {
398 i_want_my_mcl += ncl;
399 wakeup(&i_want_my_mcl);
403 p = contigmalloc_map(MCLBYTES * ncl, M_DEVBUF, M_WAITOK, 0ul,
404 ~0ul, PAGE_SIZE, 0, mb_map);
408 p = (caddr_t)kmem_malloc(mb_map, ctob(npg),
409 how != MB_WAIT ? M_NOWAIT : M_WAITOK);
410 ncl = ncl * PAGE_SIZE / MCLBYTES;
413 * Either the map is now full, or `how' is M_NOWAIT and there
417 static int last_report ; /* when we did that (in ticks) */
420 if (ticks < last_report || (ticks - last_report) >= hz) {
422 printf("All mbuf clusters exhausted, please see tuning(7).\n");
427 for (i = 0; i < ncl; i++) {
428 ((union mcluster *)p)->mcl_next = mclfree;
429 mclfree = (union mcluster *)p;
433 mbstat.m_clusters += ncl;
438 * Once the mb_map submap has been exhausted and the allocation is called with
439 * MB_WAIT, we rely on the mclfree union pointers. If nothing is free, we will
440 * sleep for a designated amount of time (mbuf_wait) or until we're woken up
441 * due to sudden mcluster availability.
449 /* If in interrupt context, and INVARIANTS, maintain sanity and die. */
450 KASSERT(mycpu->gd_intr_nesting_level == 0, ("CLALLOC: CANNOT WAIT IN INTERRUPT"));
452 /* Sleep until something's available or until we expire. */
454 if ((tsleep(&m_clalloc_wid, 0, "mclalc", mbuf_wait)) == EWOULDBLOCK)
458 * Now that we (think) that we've got something, we will redo and
459 * MGET, but avoid getting into another instance of m_clalloc_wait()
461 p = m_mclalloc(MB_DONTWAIT);
464 if (p != NULL) { /* We waited and got something... */
466 /* Wake up another if we have more free. */
476 * When MGET fails, ask protocols to free space when short of memory,
477 * then re-attempt to allocate an mbuf.
480 m_retry(int i, int t)
486 * Must only do the reclaim if not in an interrupt context.
489 KASSERT(mycpu->gd_intr_nesting_level == 0,
490 ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
496 (void)m_mballoc(1, i);
505 m->m_data = m->m_dat;
510 static int last_report ; /* when we did that (in ticks) */
514 if (ticks < last_report || (ticks - last_report) >= hz) {
516 printf("All mbufs exhausted, please see tuning(7).\n");
524 * As above; retry an MGETHDR.
527 m_retryhdr(int i, int t)
533 * Must only do the reclaim if not in an interrupt context.
536 KASSERT(mycpu->gd_intr_nesting_level == 0,
537 ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
543 (void)m_mballoc(1, i);
552 m->m_data = m->m_pktdat;
553 m->m_flags = M_PKTHDR;
554 m->m_pkthdr.rcvif = NULL;
555 SLIST_INIT(&m->m_pkthdr.tags);
556 m->m_pkthdr.csum_flags = 0;
560 static int last_report ; /* when we did that (in ticks) */
564 if (ticks < last_report || (ticks - last_report) >= hz) {
566 printf("All mbufs exhausted, please see tuning(7).\n");
580 for (dp = domains; dp; dp = dp->dom_next) {
581 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
591 * Space allocation routines.
592 * These are also available as macros
593 * for critical paths.
596 m_get(int how, int type)
603 (void)m_mballoc(1, how);
612 m->m_data = m->m_dat;
617 m = m_retry(how, type);
618 if (m == NULL && how == MB_WAIT)
619 m = m_mballoc_wait(MGET_C, type);
625 m_gethdr(int how, int type)
632 (void)m_mballoc(1, how);
641 m->m_data = m->m_pktdat;
642 m->m_flags = M_PKTHDR;
643 m->m_pkthdr.rcvif = NULL;
644 SLIST_INIT(&m->m_pkthdr.tags);
645 m->m_pkthdr.csum_flags = 0;
649 m = m_retryhdr(how, type);
650 if (m == NULL && how == MB_WAIT)
651 m = m_mballoc_wait(MGETHDR_C, type);
657 m_getclr(int how, int type)
664 bzero(mtod(m, caddr_t), MLEN);
669 * m_getcl() returns an mbuf with an attached cluster.
670 * Because many network drivers use this kind of buffers a lot, it is
671 * convenient to keep a small pool of free buffers of this kind.
672 * Even a small size such as 10 gives about 10% improvement in the
673 * forwarding rate in a bridge or router.
674 * The size of this free list is controlled by the sysctl variable
675 * mcl_pool_max. The list is populated on m_freem(), and used in
676 * m_getcl() if elements are available.
678 static struct mbuf *mcl_pool;
679 static int mcl_pool_now;
680 static int mcl_pool_max = 10;
682 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_max, CTLFLAG_RW, &mcl_pool_max, 0,
683 "Maximum number of mbufs+cluster in free list");
684 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_now, CTLFLAG_RD, &mcl_pool_now, 0,
685 "Current number of mbufs+cluster in free list");
688 m_getcl(int how, short type, int flags)
693 if (flags & M_PKTHDR) {
694 if (type == MT_DATA && mcl_pool) {
696 mcl_pool = mp->m_nextpkt;
699 mp->m_nextpkt = NULL;
700 mp->m_data = mp->m_ext.ext_buf;
701 mp->m_flags = M_PKTHDR|M_EXT;
702 mp->m_pkthdr.rcvif = NULL;
703 mp->m_pkthdr.csum_flags = 0;
706 MGETHDR(mp, how, type);
711 if ( (mp->m_flags & M_EXT) == 0) {
722 * m_getm(m, len, how, type)
724 * This will allocate len-worth of mbufs and/or mbuf clusters (whatever fits
725 * best) and return a pointer to the top of the allocated chain. If m is
726 * non-null, then we assume that it is a single mbuf or an mbuf chain to
727 * which we want len bytes worth of mbufs and/or clusters attached, and so
728 * if we succeed in allocating it, we will just return a pointer to m.
730 * If we happen to fail at any point during the allocation, we will free
731 * up everything we have already allocated and return NULL.
735 m_getm(struct mbuf *m, int len, int how, int type)
737 struct mbuf *top, *tail, *mp, *mtail = NULL;
739 KASSERT(len >= 0, ("len is < 0 in m_getm"));
744 else if (len > MINCLSIZE) {
746 if ((mp->m_flags & M_EXT) == 0) {
752 len -= M_TRAILINGSPACE(mp);
755 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
767 if (len > MINCLSIZE) {
769 if ((mp->m_flags & M_EXT) == 0)
774 len -= M_TRAILINGSPACE(mp);
787 * m_mclalloc() - Allocates an mbuf cluster.
799 mp = (caddr_t)mclfree;
801 KKASSERT((struct mbuf *)mp >= mbutl &&
802 (struct mbuf *)mp < mbute);
803 mclrefcnt[mtocl(mp)]++;
805 mclfree = ((union mcluster *)mp)->mcl_next;
811 return(m_clalloc_wait());
816 * m_mclget() - Adds a cluster to a normal mbuf, M_EXT is set on success.
819 m_mclget(struct mbuf *m, int how)
821 m->m_ext.ext_buf = m_mclalloc(how);
822 if (m->m_ext.ext_buf != NULL) {
823 m->m_data = m->m_ext.ext_buf;
825 KKASSERT((m->m_flags & M_EXT_OLD) == 0);
826 m->m_ext.ext_nfree.any = NULL;
827 m->m_ext.ext_nref.any = NULL;
828 m->m_ext.ext_size = MCLBYTES;
833 _m_mclfree(caddr_t data)
835 union mcluster *mp = (union mcluster *)data;
837 KASSERT(mclrefcnt[mtocl(mp)] > 0, ("freeing free cluster"));
838 KKASSERT((struct mbuf *)mp >= mbutl &&
839 (struct mbuf *)mp < mbute);
840 if (--mclrefcnt[mtocl(mp)] == 0) {
841 mp->mcl_next = mclfree;
849 m_mclfree(caddr_t mp)
857 * Helper routines for M_EXT reference/free
860 m_extref(const struct mbuf *m)
862 if (m->m_flags & M_EXT_OLD) {
863 if (m->m_ext.ext_nref.old == NULL) {
864 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
867 (*m->m_ext.ext_nref.old)(m->m_ext.ext_buf,
872 if (m->m_ext.ext_nref.new == NULL) {
873 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
876 (*m->m_ext.ext_nref.new)(m->m_ext.ext_arg);
883 m_extfree(struct mbuf *m)
885 if (m->m_flags & M_EXT_OLD) {
886 if (m->m_ext.ext_nfree.old != NULL) {
887 m->m_ext.ext_nfree.old(m->m_ext.ext_buf,
890 _m_mclfree(m->m_ext.ext_buf);
893 if (m->m_ext.ext_nfree.new != NULL) {
894 m->m_ext.ext_nfree.new(m->m_ext.ext_arg);
896 _m_mclfree(m->m_ext.ext_buf);
905 * Free a single mbuf and any associated external storage. The successor,
906 * if any, is returned.
908 * We do need to check non-first mbuf for m_aux, since some of existing
909 * code does not call M_PREPEND properly.
910 * (example: call to bpf_mtap from drivers)
913 m_free(struct mbuf *m)
919 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf"));
920 mbtypes[m->m_type]--;
921 if ((m->m_flags & M_PKTHDR) != 0)
922 m_tag_delete_chain(m, NULL);
923 if (m->m_flags & M_EXT) {
938 m_freem(struct mbuf *m)
943 * Try to keep a small pool of mbuf+cluster for quick use in
944 * device drivers. A good candidate is a M_PKTHDR buffer with
945 * only one cluster attached. Other mbufs, or those exceeding
946 * the pool size, are just m_free'd in the usual way.
947 * The following code makes sure that m_next, m_type,
948 * m_pkthdr.aux and m_ext.* are properly initialized.
949 * Other fields in the mbuf are initialized in m_getcl()
952 if (mcl_pool_now < mcl_pool_max && m && m->m_next == NULL &&
953 (m->m_flags & (M_PKTHDR|M_EXT)) == (M_PKTHDR|M_EXT) &&
954 m->m_type == MT_DATA && M_EXT_WRITABLE(m) ) {
955 m_tag_delete_chain(m, NULL);
956 m->m_nextpkt = mcl_pool;
967 * Mbuffer utility routines.
971 * Lesser-used path for M_PREPEND:
972 * allocate new mbuf to prepend to chain,
976 m_prepend(struct mbuf *m, int len, int how)
980 MGET(mn, how, m->m_type);
981 if (mn == (struct mbuf *)NULL) {
983 return ((struct mbuf *)NULL);
985 if (m->m_flags & M_PKTHDR)
986 M_MOVE_PKTHDR(mn, m);
996 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
997 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
998 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
999 * Note that the copy is read-only, because clusters are not copied,
1000 * only their reference counts are incremented.
1002 #define MCFail (mbstat.m_mcfail)
1005 m_copym(const struct mbuf *m, int off0, int len, int wait)
1007 struct mbuf *n, **np;
1012 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1013 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1014 if (off == 0 && m->m_flags & M_PKTHDR)
1017 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1027 KASSERT(len == M_COPYALL,
1028 ("m_copym, length > size of mbuf chain"));
1031 MGET(n, wait, m->m_type);
1036 if (!m_dup_pkthdr(n, m, wait))
1038 if (len == M_COPYALL)
1039 n->m_pkthdr.len -= off0;
1041 n->m_pkthdr.len = len;
1044 n->m_len = min(len, m->m_len - off);
1045 if (m->m_flags & M_EXT) {
1046 n->m_data = m->m_data + off;
1048 n->m_ext = m->m_ext;
1049 n->m_flags |= m->m_flags & (M_EXT | M_EXT_OLD);
1051 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1052 (unsigned)n->m_len);
1054 if (len != M_COPYALL)
1070 * Copy an entire packet, including header (which must be present).
1071 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1072 * Note that the copy is read-only, because clusters are not copied,
1073 * only their reference counts are incremented.
1074 * Preserve alignment of the first mbuf so if the creator has left
1075 * some room at the beginning (e.g. for inserting protocol headers)
1076 * the copies also have the room available.
1079 m_copypacket(struct mbuf *m, int how)
1081 struct mbuf *top, *n, *o;
1083 MGET(n, how, m->m_type);
1088 if (!m_dup_pkthdr(n, m, how))
1090 n->m_len = m->m_len;
1091 if (m->m_flags & M_EXT) {
1092 n->m_data = m->m_data;
1094 n->m_ext = m->m_ext;
1095 n->m_flags |= m->m_flags & (M_EXT | M_EXT_OLD);
1097 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1098 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1103 MGET(o, how, m->m_type);
1110 n->m_len = m->m_len;
1111 if (m->m_flags & M_EXT) {
1112 n->m_data = m->m_data;
1114 n->m_ext = m->m_ext;
1115 n->m_flags |= m->m_flags & (M_EXT | M_EXT_OLD);
1117 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1130 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1131 * continuing for "len" bytes, into the indicated buffer.
1134 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1138 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1139 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1141 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1148 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1149 count = min(m->m_len - off, len);
1150 bcopy(mtod(m, caddr_t) + off, cp, count);
1159 * Copy a packet header mbuf chain into a completely new chain, including
1160 * copying any mbuf clusters. Use this instead of m_copypacket() when
1161 * you need a writable copy of an mbuf chain.
1164 m_dup(struct mbuf *m, int how)
1166 struct mbuf **p, *top = NULL;
1167 int remain, moff, nsize;
1172 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __FUNCTION__));
1174 /* While there's more data, get a new mbuf, tack it on, and fill it */
1175 remain = m->m_pkthdr.len;
1178 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1181 /* Get the next new mbuf */
1182 MGET(n, how, m->m_type);
1185 if (top == NULL) { /* first one, must be PKTHDR */
1186 if (!m_dup_pkthdr(n, m, how))
1189 } else /* not the first one */
1191 if (remain >= MINCLSIZE) {
1193 if ((n->m_flags & M_EXT) == 0) {
1201 /* Link it into the new chain */
1205 /* Copy data from original mbuf(s) into new mbuf */
1206 while (n->m_len < nsize && m != NULL) {
1207 int chunk = min(nsize - n->m_len, m->m_len - moff);
1209 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1213 if (moff == m->m_len) {
1219 /* Check correct total mbuf length */
1220 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1221 ("%s: bogus m_pkthdr.len", __FUNCTION__));
1232 * Concatenate mbuf chain n to m.
1233 * Both chains must be of the same type (e.g. MT_DATA).
1234 * Any m_pkthdr is not updated.
1237 m_cat(struct mbuf *m, struct mbuf *n)
1242 if (m->m_flags & M_EXT ||
1243 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1244 /* just join the two chains */
1248 /* splat the data from one into the other */
1249 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1251 m->m_len += n->m_len;
1257 m_adj(struct mbuf *mp, int req_len)
1263 if ((m = mp) == NULL)
1269 while (m != NULL && len > 0) {
1270 if (m->m_len <= len) {
1281 if (mp->m_flags & M_PKTHDR)
1282 m->m_pkthdr.len -= (req_len - len);
1285 * Trim from tail. Scan the mbuf chain,
1286 * calculating its length and finding the last mbuf.
1287 * If the adjustment only affects this mbuf, then just
1288 * adjust and return. Otherwise, rescan and truncate
1289 * after the remaining size.
1295 if (m->m_next == (struct mbuf *)0)
1299 if (m->m_len >= len) {
1301 if (mp->m_flags & M_PKTHDR)
1302 mp->m_pkthdr.len -= len;
1309 * Correct length for chain is "count".
1310 * Find the mbuf with last data, adjust its length,
1311 * and toss data from remaining mbufs on chain.
1314 if (m->m_flags & M_PKTHDR)
1315 m->m_pkthdr.len = count;
1316 for (; m; m = m->m_next) {
1317 if (m->m_len >= count) {
1324 (m = m->m_next) ->m_len = 0;
1329 * Rearange an mbuf chain so that len bytes are contiguous
1330 * and in the data area of an mbuf (so that mtod will work for a structure
1331 * of size len). Returns the resulting mbuf chain on success, frees it and
1332 * returns null on failure. If there is room, it will add up to
1333 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1334 * avoid being called next time.
1336 #define MPFail (mbstat.m_mpfail)
1339 m_pullup(struct mbuf *n, int len)
1346 * If first mbuf has no cluster, and has room for len bytes
1347 * without shifting current data, pullup into it,
1348 * otherwise allocate a new mbuf to prepend to the chain.
1350 if ((n->m_flags & M_EXT) == 0 &&
1351 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1352 if (n->m_len >= len)
1360 MGET(m, MB_DONTWAIT, n->m_type);
1364 if (n->m_flags & M_PKTHDR)
1365 M_MOVE_PKTHDR(m, n);
1367 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1369 count = min(min(max(len, max_protohdr), space), n->m_len);
1370 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1380 } while (len > 0 && n);
1394 * Partition an mbuf chain in two pieces, returning the tail --
1395 * all but the first len0 bytes. In case of failure, it returns NULL and
1396 * attempts to restore the chain to its original state.
1398 * Note that the resulting mbufs might be read-only, because the new
1399 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1400 * the "breaking point" happens to lie within a cluster mbuf. Use the
1401 * M_WRITABLE() macro to check for this case.
1404 m_split(struct mbuf *m0, int len0, int wait)
1407 unsigned len = len0, remain;
1409 for (m = m0; m && len > m->m_len; m = m->m_next)
1413 remain = m->m_len - len;
1414 if (m0->m_flags & M_PKTHDR) {
1415 MGETHDR(n, wait, m0->m_type);
1418 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1419 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1420 m0->m_pkthdr.len = len0;
1421 if (m->m_flags & M_EXT)
1423 if (remain > MHLEN) {
1424 /* m can't be the lead packet */
1426 n->m_next = m_split(m, len, wait);
1427 if (n->m_next == 0) {
1435 MH_ALIGN(n, remain);
1436 } else if (remain == 0) {
1441 MGET(n, wait, m->m_type);
1447 if (m->m_flags & M_EXT) {
1448 n->m_data = m->m_data + len;
1450 n->m_ext = m->m_ext;
1451 n->m_flags |= m->m_flags & (M_EXT | M_EXT_OLD);
1453 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1457 n->m_next = m->m_next;
1462 * Routine to copy from device local memory into mbufs.
1465 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
1466 void (*copy) (char *from, caddr_t to, u_int len))
1469 struct mbuf *top = 0, **mp = ⊤
1470 int off = off0, len;
1477 cp += off + 2 * sizeof(u_short);
1478 totlen -= 2 * sizeof(u_short);
1480 MGETHDR(m, MB_DONTWAIT, MT_DATA);
1483 m->m_pkthdr.rcvif = ifp;
1484 m->m_pkthdr.len = totlen;
1487 while (totlen > 0) {
1489 MGET(m, MB_DONTWAIT, MT_DATA);
1496 len = min(totlen, epkt - cp);
1497 if (len >= MINCLSIZE) {
1498 MCLGET(m, MB_DONTWAIT);
1499 if (m->m_flags & M_EXT)
1500 m->m_len = len = min(len, MCLBYTES);
1505 * Place initial small packet/header at end of mbuf.
1507 if (len < m->m_len) {
1508 if (top == 0 && len + max_linkhdr <= m->m_len)
1509 m->m_data += max_linkhdr;
1515 copy(cp, mtod(m, caddr_t), (unsigned)len);
1517 bcopy(cp, mtod(m, caddr_t), (unsigned)len);
1529 * Copy data from a buffer back into the indicated mbuf chain,
1530 * starting "off" bytes from the beginning, extending the mbuf
1531 * chain if necessary.
1534 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
1537 struct mbuf *m = m0, *n;
1542 while (off > (mlen = m->m_len)) {
1545 if (m->m_next == 0) {
1546 n = m_getclr(MB_DONTWAIT, m->m_type);
1549 n->m_len = min(MLEN, len + off);
1555 mlen = min (m->m_len - off, len);
1556 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1564 if (m->m_next == 0) {
1565 n = m_get(MB_DONTWAIT, m->m_type);
1568 n->m_len = min(MLEN, len);
1573 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1574 m->m_pkthdr.len = totlen;
1578 m_print(const struct mbuf *m)
1581 const struct mbuf *m2;
1583 len = m->m_pkthdr.len;
1586 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1594 * "Move" mbuf pkthdr from "from" to "to".
1595 * "from" must have M_PKTHDR set, and "to" must be empty.
1598 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1600 KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
1602 to->m_flags = from->m_flags & M_COPYFLAGS;
1603 to->m_data = to->m_pktdat;
1604 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1605 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
1606 from->m_flags &= ~M_PKTHDR;
1610 * Duplicate "from"'s mbuf pkthdr in "to".
1611 * "from" must have M_PKTHDR set, and "to" must be empty.
1612 * In particular, this does a deep copy of the packet tags.
1615 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1617 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1618 if ((to->m_flags & M_EXT) == 0)
1619 to->m_data = to->m_pktdat;
1620 to->m_pkthdr = from->m_pkthdr;
1621 SLIST_INIT(&to->m_pkthdr.tags);
1622 return (m_tag_copy_chain(to, from, how));
1626 * Defragment a mbuf chain, returning the shortest possible
1627 * chain of mbufs and clusters. If allocation fails and
1628 * this cannot be completed, NULL will be returned, but
1629 * the passed in chain will be unchanged. Upon success,
1630 * the original chain will be freed, and the new chain
1633 * If a non-packet header is passed in, the original
1634 * mbuf (chain?) will be returned unharmed.
1637 m_defrag(struct mbuf *m0, int how)
1639 struct mbuf *m_new = NULL, *m_final = NULL;
1640 int progress = 0, length;
1642 if (!(m0->m_flags & M_PKTHDR))
1645 #ifdef MBUF_STRESS_TEST
1646 if (m_defragrandomfailures) {
1647 int temp = arc4random() & 0xff;
1653 if (m0->m_pkthdr.len > MHLEN)
1654 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1656 m_final = m_gethdr(how, MT_DATA);
1658 if (m_final == NULL)
1661 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1666 while (progress < m0->m_pkthdr.len) {
1667 length = m0->m_pkthdr.len - progress;
1668 if (length > MCLBYTES)
1671 if (m_new == NULL) {
1673 m_new = m_getcl(how, MT_DATA, 0);
1675 m_new = m_get(how, MT_DATA);
1680 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1682 m_new->m_len = length;
1683 if (m_new != m_final)
1684 m_cat(m_final, m_new);
1687 if (m0->m_next == NULL)
1692 m_defragbytes += m0->m_pkthdr.len;
1704 * Move data from uio into mbufs.
1705 * A length of zero means copy the whole uio.
1708 m_uiomove(struct uio *uio, int wait, int len0)
1710 struct mbuf *head; /* result mbuf chain */
1711 struct mbuf *m; /* current working mbuf */
1713 int resid, datalen, error;
1715 resid = (len0 == 0) ? uio->uio_resid : min(len0, uio->uio_resid);
1720 if (resid > MHLEN) {
1721 m = m_getcl(wait, MT_DATA, head == NULL ? M_PKTHDR : 0);
1724 if (m->m_flags & M_PKTHDR)
1725 m->m_pkthdr.len = 0;
1728 MGETHDR(m, wait, MT_DATA);
1731 m->m_pkthdr.len = 0;
1732 /* Leave room for protocol headers. */
1736 MGET(m, wait, MT_DATA);
1741 datalen = min(MCLBYTES, resid);
1742 error = uiomove(mtod(m, caddr_t), datalen, uio);
1750 head->m_pkthdr.len += datalen;
1752 } while (resid > 0);