2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 1982, 1986, 1988, 1991, 1993
4 * The Regents of the University of California. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 * must display the following acknowledgement:
16 * This product includes software developed by the University of
17 * California, Berkeley and its contributors.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
35 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
36 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.15 2004/03/27 11:50:45 hsu Exp $
39 #include "opt_param.h"
40 #include "opt_mbuf_stress_test.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
50 #include <sys/thread.h>
51 #include <sys/globaldata.h>
54 #include <vm/vm_kern.h>
55 #include <vm/vm_extern.h>
58 #include <machine/cpu.h>
61 static void mbinit (void *);
62 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbinit, NULL)
68 u_long mbtypes[MT_NTYPES];
70 union mcluster *mclfree;
79 #ifdef MBUF_STRESS_TEST
80 int m_defragrandomfailures;
85 u_int m_mballoc_wid = 0;
86 u_int m_clalloc_wid = 0;
88 SYSCTL_DECL(_kern_ipc);
89 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
91 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
92 &max_protohdr, 0, "");
93 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
94 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
96 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
98 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
99 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
100 sizeof(mbtypes), "LU", "");
101 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
102 &nmbclusters, 0, "Maximum number of mbuf clusters available");
103 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
104 "Maximum number of mbufs available");
105 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
106 &m_defragpackets, 0, "");
107 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
108 &m_defragbytes, 0, "");
109 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
110 &m_defraguseless, 0, "");
111 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
112 &m_defragfailure, 0, "");
113 #ifdef MBUF_STRESS_TEST
114 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
115 &m_defragrandomfailures, 0, "");
118 static void m_reclaim (void);
121 #define NMBCLUSTERS (512 + maxusers * 16)
124 #define NMBUFS (nmbclusters * 4)
128 * Perform sanity checks of tunables declared above.
131 tunable_mbinit(void *dummy)
135 * This has to be done before VM init.
137 nmbclusters = NMBCLUSTERS;
138 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
140 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
142 if (nmbufs < nmbclusters * 2)
143 nmbufs = nmbclusters * 2;
147 SYSINIT(tunable_mbinit, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_mbinit, NULL);
149 /* "number of clusters of pages" */
161 mmbfree = NULL; mclfree = NULL;
162 mbstat.m_msize = MSIZE;
163 mbstat.m_mclbytes = MCLBYTES;
164 mbstat.m_minclsize = MINCLSIZE;
165 mbstat.m_mlen = MLEN;
166 mbstat.m_mhlen = MHLEN;
169 if (m_mballoc(NMB_INIT, M_DONTWAIT) == 0)
171 #if MCLBYTES <= PAGE_SIZE
172 if (m_clalloc(NCL_INIT, M_DONTWAIT) == 0)
175 /* It's OK to call contigmalloc in this context. */
176 if (m_clalloc(16, M_WAIT) == 0)
186 * Allocate at least nmb mbufs and place on mbuf free list.
187 * Must be called at splimp.
200 * If we've hit the mbuf limit, stop allocating from mb_map,
201 * (or trying to) in order to avoid dipping into the section of
202 * mb_map which we've "reserved" for clusters.
204 if ((nmb + mbstat.m_mbufs) > nmbufs)
208 * Once we run out of map space, it will be impossible to get
209 * any more (nothing is ever freed back to the map)
210 * -- however you are not dead as m_reclaim might
211 * still be able to free a substantial amount of space.
213 * XXX Furthermore, we can also work with "recycled" mbufs (when
214 * we're calling with M_WAIT the sleep procedure will be woken
215 * up when an mbuf is freed. See m_mballoc_wait()).
220 nbytes = round_page(nmb * MSIZE);
221 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_NOWAIT);
222 if (p == 0 && how == M_WAIT) {
224 p = (caddr_t)kmem_malloc(mb_map, nbytes, M_WAITOK);
228 * Either the map is now full, or `how' is M_NOWAIT and there
234 nmb = nbytes / MSIZE;
235 for (i = 0; i < nmb; i++) {
236 ((struct mbuf *)p)->m_next = mmbfree;
237 mmbfree = (struct mbuf *)p;
240 mbstat.m_mbufs += nmb;
241 mbtypes[MT_FREE] += nmb;
246 * Once the mb_map has been exhausted and if the call to the allocation macros
247 * (or, in some cases, functions) is with M_WAIT, then it is necessary to rely
248 * solely on reclaimed mbufs. Here we wait for an mbuf to be freed for a
249 * designated (mbuf_wait) time.
252 m_mballoc_wait(int caller, int type)
259 if ((tsleep(&m_mballoc_wid, 0, "mballc", mbuf_wait)) == EWOULDBLOCK)
264 * Now that we (think) that we've got something, we will redo an
265 * MGET, but avoid getting into another instance of m_mballoc_wait()
266 * XXX: We retry to fetch _even_ if the sleep timed out. This is left
267 * this way, purposely, in the [unlikely] case that an mbuf was
268 * freed but the sleep was not awakened in time.
273 MGET(p, M_DONTWAIT, type);
276 MGETHDR(p, M_DONTWAIT, type);
279 panic("m_mballoc_wait: invalid caller (%d)", caller);
283 if (p != NULL) { /* We waited and got something... */
285 /* Wake up another if we have more free. */
293 #if MCLBYTES > PAGE_SIZE
294 static int i_want_my_mcl;
302 tsleep(&i_want_my_mcl, 0, "mclalloc", 0);
304 for (; i_want_my_mcl; i_want_my_mcl--) {
305 if (m_clalloc(1, M_WAIT) == 0)
306 printf("m_clalloc failed even in process context!\n");
311 static struct thread *mclallocthread;
312 static struct kproc_desc mclalloc_kp = {
317 SYSINIT(mclallocthread, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
322 * Allocate some number of mbuf clusters
323 * and place on cluster free list.
324 * Must be called at splimp.
337 * If we've hit the mcluster number limit, stop allocating from
338 * mb_map, (or trying to) in order to avoid dipping into the section
339 * of mb_map which we've "reserved" for mbufs.
341 if ((ncl + mbstat.m_clusters) > nmbclusters)
345 * Once we run out of map space, it will be impossible
346 * to get any more (nothing is ever freed back to the
347 * map). From this point on, we solely rely on freed
353 #if MCLBYTES > PAGE_SIZE
355 i_want_my_mcl += ncl;
356 wakeup(&i_want_my_mcl);
360 p = contigmalloc_map(MCLBYTES * ncl, M_DEVBUF, M_WAITOK, 0ul,
361 ~0ul, PAGE_SIZE, 0, mb_map);
365 p = (caddr_t)kmem_malloc(mb_map, ctob(npg),
366 how != M_WAIT ? M_NOWAIT : M_WAITOK);
367 ncl = ncl * PAGE_SIZE / MCLBYTES;
370 * Either the map is now full, or `how' is M_NOWAIT and there
374 static int last_report ; /* when we did that (in ticks) */
377 if (ticks < last_report || (ticks - last_report) >= hz) {
379 printf("All mbuf clusters exhausted, please see tuning(7).\n");
384 for (i = 0; i < ncl; i++) {
385 ((union mcluster *)p)->mcl_next = mclfree;
386 mclfree = (union mcluster *)p;
390 mbstat.m_clusters += ncl;
395 * Once the mb_map submap has been exhausted and the allocation is called with
396 * M_WAIT, we rely on the mclfree union pointers. If nothing is free, we will
397 * sleep for a designated amount of time (mbuf_wait) or until we're woken up
398 * due to sudden mcluster availability.
406 /* If in interrupt context, and INVARIANTS, maintain sanity and die. */
407 KASSERT(mycpu->gd_intr_nesting_level == 0, ("CLALLOC: CANNOT WAIT IN INTERRUPT"));
409 /* Sleep until something's available or until we expire. */
411 if ((tsleep(&m_clalloc_wid, 0, "mclalc", mbuf_wait)) == EWOULDBLOCK)
415 * Now that we (think) that we've got something, we will redo and
416 * MGET, but avoid getting into another instance of m_clalloc_wait()
418 p = m_mclalloc(M_DONTWAIT);
421 if (p != NULL) { /* We waited and got something... */
423 /* Wake up another if we have more free. */
433 * When MGET fails, ask protocols to free space when short of memory,
434 * then re-attempt to allocate an mbuf.
444 * 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"));
454 (void)m_mballoc(1, i);
463 m->m_data = m->m_dat;
468 static int last_report ; /* when we did that (in ticks) */
472 if (ticks < last_report || (ticks - last_report) >= hz) {
474 printf("All mbufs exhausted, please see tuning(7).\n");
482 * As above; retry an MGETHDR.
492 * Must only do the reclaim if not in an interrupt context.
495 KASSERT(mycpu->gd_intr_nesting_level == 0,
496 ("MBALLOC: CANNOT WAIT IN INTERRUPT"));
502 (void)m_mballoc(1, i);
511 m->m_data = m->m_pktdat;
512 m->m_flags = M_PKTHDR;
513 m->m_pkthdr.rcvif = NULL;
514 SLIST_INIT(&m->m_pkthdr.tags);
515 m->m_pkthdr.csum_flags = 0;
519 static int last_report ; /* when we did that (in ticks) */
523 if (ticks < last_report || (ticks - last_report) >= hz) {
525 printf("All mbufs exhausted, please see tuning(7).\n");
539 for (dp = domains; dp; dp = dp->dom_next)
540 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
548 * Space allocation routines.
549 * These are also available as macros
550 * for critical paths.
561 (void)m_mballoc(1, how);
570 m->m_data = m->m_dat;
575 m = m_retry(how, type);
576 if (m == NULL && how == M_WAIT)
577 m = m_mballoc_wait(MGET_C, type);
591 (void)m_mballoc(1, how);
600 m->m_data = m->m_pktdat;
601 m->m_flags = M_PKTHDR;
602 m->m_pkthdr.rcvif = NULL;
603 SLIST_INIT(&m->m_pkthdr.tags);
604 m->m_pkthdr.csum_flags = 0;
608 m = m_retryhdr(how, type);
609 if (m == NULL && how == M_WAIT)
610 m = m_mballoc_wait(MGETHDR_C, type);
624 bzero(mtod(m, caddr_t), MLEN);
629 * m_getcl() returns an mbuf with an attached cluster.
630 * Because many network drivers use this kind of buffers a lot, it is
631 * convenient to keep a small pool of free buffers of this kind.
632 * Even a small size such as 10 gives about 10% improvement in the
633 * forwarding rate in a bridge or router.
634 * The size of this free list is controlled by the sysctl variable
635 * mcl_pool_max. The list is populated on m_freem(), and used in
636 * m_getcl() if elements are available.
638 static struct mbuf *mcl_pool;
639 static int mcl_pool_now;
640 static int mcl_pool_max = 0;
642 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_max, CTLFLAG_RW, &mcl_pool_max, 0,
643 "Maximum number of mbufs+cluster in free list");
644 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_pool_now, CTLFLAG_RD, &mcl_pool_now, 0,
645 "Current number of mbufs+cluster in free list");
648 m_getcl(int how, short type, int flags)
653 if (flags & M_PKTHDR) {
654 if (type == MT_DATA && mcl_pool) {
656 mcl_pool = mp->m_nextpkt;
659 mp->m_nextpkt = NULL;
660 mp->m_data = mp->m_ext.ext_buf;
661 mp->m_flags = M_PKTHDR|M_EXT;
662 mp->m_pkthdr.rcvif = NULL;
663 mp->m_pkthdr.csum_flags = 0;
666 MGETHDR(mp, how, type);
671 if ( (mp->m_flags & M_EXT) == 0) {
682 * m_getm(m, len, how, type)
684 * This will allocate len-worth of mbufs and/or mbuf clusters (whatever fits
685 * best) and return a pointer to the top of the allocated chain. If m is
686 * non-null, then we assume that it is a single mbuf or an mbuf chain to
687 * which we want len bytes worth of mbufs and/or clusters attached, and so
688 * if we succeed in allocating it, we will just return a pointer to m.
690 * If we happen to fail at any point during the allocation, we will free
691 * up everything we have already allocated and return NULL.
695 m_getm(struct mbuf *m, int len, int how, int type)
697 struct mbuf *top, *tail, *mp, *mtail = NULL;
699 KASSERT(len >= 0, ("len is < 0 in m_getm"));
704 else if (len > MINCLSIZE) {
706 if ((mp->m_flags & M_EXT) == 0) {
712 len -= M_TRAILINGSPACE(mp);
715 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next);
727 if (len > MINCLSIZE) {
729 if ((mp->m_flags & M_EXT) == 0)
734 len -= M_TRAILINGSPACE(mp);
747 * m_mclalloc() - Allocates an mbuf cluster.
759 mp = (caddr_t)mclfree;
761 KKASSERT((struct mbuf *)mp >= mbutl &&
762 (struct mbuf *)mp < mbute);
763 mclrefcnt[mtocl(mp)]++;
765 mclfree = ((union mcluster *)mp)->mcl_next;
771 return(m_clalloc_wait());
776 * m_mclget() - Adds a cluster to a normal mbuf, M_EXT is set on success.
779 m_mclget(struct mbuf *m, int how)
781 m->m_ext.ext_buf = m_mclalloc(how);
782 if (m->m_ext.ext_buf != NULL) {
783 m->m_data = m->m_ext.ext_buf;
785 m->m_ext.ext_free = NULL;
786 m->m_ext.ext_ref = NULL;
787 m->m_ext.ext_size = MCLBYTES;
792 _m_mclfree(caddr_t data)
794 union mcluster *mp = (union mcluster *)data;
796 KASSERT(mclrefcnt[mtocl(mp)] > 0, ("freeing free cluster"));
797 KKASSERT((struct mbuf *)mp >= mbutl &&
798 (struct mbuf *)mp < mbute);
799 if (--mclrefcnt[mtocl(mp)] == 0) {
800 mp->mcl_next = mclfree;
808 m_mclfree(caddr_t mp)
818 * Free a single mbuf and any associated external storage. The successor,
819 * if any, is returned.
821 * We do need to check non-first mbuf for m_aux, since some of existing
822 * code does not call M_PREPEND properly.
823 * (example: call to bpf_mtap from drivers)
826 m_free(struct mbuf *m)
832 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf"));
833 mbtypes[m->m_type]--;
834 if ((m->m_flags & M_PKTHDR) != 0)
835 m_tag_delete_chain(m, NULL);
836 if (m->m_flags & M_EXT) {
837 if (m->m_ext.ext_free != NULL) {
838 m->m_ext.ext_free(m->m_ext.ext_buf, m->m_ext.ext_size);
840 _m_mclfree(m->m_ext.ext_buf); /* inlined */
855 m_freem(struct mbuf *m)
860 * Try to keep a small pool of mbuf+cluster for quick use in
861 * device drivers. A good candidate is a M_PKTHDR buffer with
862 * only one cluster attached. Other mbufs, or those exceeding
863 * the pool size, are just m_free'd in the usual way.
864 * The following code makes sure that m_next, m_type,
865 * m_pkthdr.aux and m_ext.* are properly initialized.
866 * Other fields in the mbuf are initialized in m_getcl()
869 if (mcl_pool_now < mcl_pool_max && m && m->m_next == NULL &&
870 (m->m_flags & (M_PKTHDR|M_EXT)) == (M_PKTHDR|M_EXT) &&
871 m->m_type == MT_DATA && M_EXT_WRITABLE(m) ) {
872 m_tag_delete_chain(m, NULL);
873 m->m_nextpkt = mcl_pool;
884 * Mbuffer utility routines.
888 * Lesser-used path for M_PREPEND:
889 * allocate new mbuf to prepend to chain,
893 m_prepend(m, len, how)
899 MGET(mn, how, m->m_type);
900 if (mn == (struct mbuf *)NULL) {
902 return ((struct mbuf *)NULL);
904 if (m->m_flags & M_PKTHDR)
905 M_MOVE_PKTHDR(mn, m);
915 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
916 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
917 * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
918 * Note that the copy is read-only, because clusters are not copied,
919 * only their reference counts are incremented.
921 #define MCFail (mbstat.m_mcfail)
924 m_copym(m, off0, len, wait)
925 const struct mbuf *m;
929 struct mbuf *n, **np;
934 KASSERT(off >= 0, ("m_copym, negative off %d", off));
935 KASSERT(len >= 0, ("m_copym, negative len %d", len));
936 if (off == 0 && m->m_flags & M_PKTHDR)
939 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
949 KASSERT(len == M_COPYALL,
950 ("m_copym, length > size of mbuf chain"));
953 MGET(n, wait, m->m_type);
958 if (!m_dup_pkthdr(n, m, wait))
960 if (len == M_COPYALL)
961 n->m_pkthdr.len -= off0;
963 n->m_pkthdr.len = len;
966 n->m_len = min(len, m->m_len - off);
967 if (m->m_flags & M_EXT) {
968 n->m_data = m->m_data + off;
969 if (m->m_ext.ext_ref == NULL) {
971 &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
975 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
982 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
984 if (len != M_COPYALL)
1000 * Copy an entire packet, including header (which must be present).
1001 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1002 * Note that the copy is read-only, because clusters are not copied,
1003 * only their reference counts are incremented.
1004 * Preserve alignment of the first mbuf so if the creator has left
1005 * some room at the beginning (e.g. for inserting protocol headers)
1006 * the copies also have the room available.
1009 m_copypacket(m, how)
1013 struct mbuf *top, *n, *o;
1015 MGET(n, how, m->m_type);
1020 if (!m_dup_pkthdr(n, m, how))
1022 n->m_len = m->m_len;
1023 if (m->m_flags & M_EXT) {
1024 n->m_data = m->m_data;
1025 if (m->m_ext.ext_ref == NULL)
1026 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1030 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1034 n->m_ext = m->m_ext;
1035 n->m_flags |= M_EXT;
1037 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1038 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1043 MGET(o, how, m->m_type);
1050 n->m_len = m->m_len;
1051 if (m->m_flags & M_EXT) {
1052 n->m_data = m->m_data;
1053 if (m->m_ext.ext_ref == NULL) {
1055 &mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1059 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1063 n->m_ext = m->m_ext;
1064 n->m_flags |= M_EXT;
1066 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1079 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1080 * continuing for "len" bytes, into the indicated buffer.
1083 m_copydata(m, off, len, cp)
1084 const struct mbuf *m;
1091 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1092 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1094 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1101 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1102 count = min(m->m_len - off, len);
1103 bcopy(mtod(m, caddr_t) + off, cp, count);
1112 * Copy a packet header mbuf chain into a completely new chain, including
1113 * copying any mbuf clusters. Use this instead of m_copypacket() when
1114 * you need a writable copy of an mbuf chain.
1121 struct mbuf **p, *top = NULL;
1122 int remain, moff, nsize;
1127 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __FUNCTION__));
1129 /* While there's more data, get a new mbuf, tack it on, and fill it */
1130 remain = m->m_pkthdr.len;
1133 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1136 /* Get the next new mbuf */
1137 MGET(n, how, m->m_type);
1140 if (top == NULL) { /* first one, must be PKTHDR */
1141 if (!m_dup_pkthdr(n, m, how))
1144 } else /* not the first one */
1146 if (remain >= MINCLSIZE) {
1148 if ((n->m_flags & M_EXT) == 0) {
1156 /* Link it into the new chain */
1160 /* Copy data from original mbuf(s) into new mbuf */
1161 while (n->m_len < nsize && m != NULL) {
1162 int chunk = min(nsize - n->m_len, m->m_len - moff);
1164 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1168 if (moff == m->m_len) {
1174 /* Check correct total mbuf length */
1175 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1176 ("%s: bogus m_pkthdr.len", __FUNCTION__));
1187 * Concatenate mbuf chain n to m.
1188 * Both chains must be of the same type (e.g. MT_DATA).
1189 * Any m_pkthdr is not updated.
1198 if (m->m_flags & M_EXT ||
1199 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1200 /* just join the two chains */
1204 /* splat the data from one into the other */
1205 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1207 m->m_len += n->m_len;
1221 if ((m = mp) == NULL)
1227 while (m != NULL && len > 0) {
1228 if (m->m_len <= len) {
1239 if (mp->m_flags & M_PKTHDR)
1240 m->m_pkthdr.len -= (req_len - len);
1243 * Trim from tail. Scan the mbuf chain,
1244 * calculating its length and finding the last mbuf.
1245 * If the adjustment only affects this mbuf, then just
1246 * adjust and return. Otherwise, rescan and truncate
1247 * after the remaining size.
1253 if (m->m_next == (struct mbuf *)0)
1257 if (m->m_len >= len) {
1259 if (mp->m_flags & M_PKTHDR)
1260 mp->m_pkthdr.len -= len;
1267 * Correct length for chain is "count".
1268 * Find the mbuf with last data, adjust its length,
1269 * and toss data from remaining mbufs on chain.
1272 if (m->m_flags & M_PKTHDR)
1273 m->m_pkthdr.len = count;
1274 for (; m; m = m->m_next) {
1275 if (m->m_len >= count) {
1282 (m = m->m_next) ->m_len = 0;
1287 * Rearange an mbuf chain so that len bytes are contiguous
1288 * and in the data area of an mbuf (so that mtod and dtom
1289 * will work for a structure of size len). Returns the resulting
1290 * mbuf chain on success, frees it and returns null on failure.
1291 * If there is room, it will add up to max_protohdr-len extra bytes to the
1292 * contiguous region in an attempt to avoid being called next time.
1294 #define MPFail (mbstat.m_mpfail)
1306 * If first mbuf has no cluster, and has room for len bytes
1307 * without shifting current data, pullup into it,
1308 * otherwise allocate a new mbuf to prepend to the chain.
1310 if ((n->m_flags & M_EXT) == 0 &&
1311 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1312 if (n->m_len >= len)
1320 MGET(m, M_DONTWAIT, n->m_type);
1324 if (n->m_flags & M_PKTHDR)
1325 M_MOVE_PKTHDR(m, n);
1327 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1329 count = min(min(max(len, max_protohdr), space), n->m_len);
1330 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1340 } while (len > 0 && n);
1354 * Partition an mbuf chain in two pieces, returning the tail --
1355 * all but the first len0 bytes. In case of failure, it returns NULL and
1356 * attempts to restore the chain to its original state.
1358 * Note that the resulting mbufs might be read-only, because the new
1359 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1360 * the "breaking point" happens to lie within a cluster mbuf. Use the
1361 * M_WRITABLE() macro to check for this case.
1364 m_split(m0, len0, wait)
1369 unsigned len = len0, remain;
1371 for (m = m0; m && len > m->m_len; m = m->m_next)
1375 remain = m->m_len - len;
1376 if (m0->m_flags & M_PKTHDR) {
1377 MGETHDR(n, wait, m0->m_type);
1380 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1381 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1382 m0->m_pkthdr.len = len0;
1383 if (m->m_flags & M_EXT)
1385 if (remain > MHLEN) {
1386 /* m can't be the lead packet */
1388 n->m_next = m_split(m, len, wait);
1389 if (n->m_next == 0) {
1397 MH_ALIGN(n, remain);
1398 } else if (remain == 0) {
1403 MGET(n, wait, m->m_type);
1409 if (m->m_flags & M_EXT) {
1410 n->m_flags |= M_EXT;
1411 n->m_ext = m->m_ext;
1412 if (m->m_ext.ext_ref == NULL)
1413 atomic_add_char(&mclrefcnt[mtocl(m->m_ext.ext_buf)], 1);
1417 (*m->m_ext.ext_ref)(m->m_ext.ext_buf,
1421 n->m_data = m->m_data + len;
1423 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1427 n->m_next = m->m_next;
1432 * Routine to copy from device local memory into mbufs.
1435 m_devget(buf, totlen, off0, ifp, copy)
1439 void (*copy) (char *from, caddr_t to, u_int len);
1442 struct mbuf *top = 0, **mp = ⊤
1443 int off = off0, len;
1450 cp += off + 2 * sizeof(u_short);
1451 totlen -= 2 * sizeof(u_short);
1453 MGETHDR(m, M_DONTWAIT, MT_DATA);
1456 m->m_pkthdr.rcvif = ifp;
1457 m->m_pkthdr.len = totlen;
1460 while (totlen > 0) {
1462 MGET(m, M_DONTWAIT, MT_DATA);
1469 len = min(totlen, epkt - cp);
1470 if (len >= MINCLSIZE) {
1471 MCLGET(m, M_DONTWAIT);
1472 if (m->m_flags & M_EXT)
1473 m->m_len = len = min(len, MCLBYTES);
1478 * Place initial small packet/header at end of mbuf.
1480 if (len < m->m_len) {
1481 if (top == 0 && len + max_linkhdr <= m->m_len)
1482 m->m_data += max_linkhdr;
1488 copy(cp, mtod(m, caddr_t), (unsigned)len);
1490 bcopy(cp, mtod(m, caddr_t), (unsigned)len);
1502 * Copy data from a buffer back into the indicated mbuf chain,
1503 * starting "off" bytes from the beginning, extending the mbuf
1504 * chain if necessary.
1507 m_copyback(m0, off, len, cp)
1514 struct mbuf *m = m0, *n;
1519 while (off > (mlen = m->m_len)) {
1522 if (m->m_next == 0) {
1523 n = m_getclr(M_DONTWAIT, m->m_type);
1526 n->m_len = min(MLEN, len + off);
1532 mlen = min (m->m_len - off, len);
1533 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1541 if (m->m_next == 0) {
1542 n = m_get(M_DONTWAIT, m->m_type);
1545 n->m_len = min(MLEN, len);
1550 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1551 m->m_pkthdr.len = totlen;
1555 m_print(const struct mbuf *m)
1558 const struct mbuf *m2;
1560 len = m->m_pkthdr.len;
1563 printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1571 * "Move" mbuf pkthdr from "from" to "to".
1572 * "from" must have M_PKTHDR set, and "to" must be empty.
1575 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1577 KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
1579 to->m_flags = from->m_flags & M_COPYFLAGS;
1580 to->m_data = to->m_pktdat;
1581 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1582 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
1583 from->m_flags &= ~M_PKTHDR;
1587 * Duplicate "from"'s mbuf pkthdr in "to".
1588 * "from" must have M_PKTHDR set, and "to" must be empty.
1589 * In particular, this does a deep copy of the packet tags.
1592 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1594 to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
1595 if ((to->m_flags & M_EXT) == 0)
1596 to->m_data = to->m_pktdat;
1597 to->m_pkthdr = from->m_pkthdr;
1598 SLIST_INIT(&to->m_pkthdr.tags);
1599 return (m_tag_copy_chain(to, from, how));
1603 * Defragment a mbuf chain, returning the shortest possible
1604 * chain of mbufs and clusters. If allocation fails and
1605 * this cannot be completed, NULL will be returned, but
1606 * the passed in chain will be unchanged. Upon success,
1607 * the original chain will be freed, and the new chain
1610 * If a non-packet header is passed in, the original
1611 * mbuf (chain?) will be returned unharmed.
1614 m_defrag(struct mbuf *m0, int how)
1616 struct mbuf *m_new = NULL, *m_final = NULL;
1617 int progress = 0, length;
1619 if (!(m0->m_flags & M_PKTHDR))
1622 #ifdef MBUF_STRESS_TEST
1623 if (m_defragrandomfailures) {
1624 int temp = arc4random() & 0xff;
1630 if (m0->m_pkthdr.len > MHLEN)
1631 m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1633 m_final = m_gethdr(how, MT_DATA);
1635 if (m_final == NULL)
1638 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1643 while (progress < m0->m_pkthdr.len) {
1644 length = m0->m_pkthdr.len - progress;
1645 if (length > MCLBYTES)
1648 if (m_new == NULL) {
1650 m_new = m_getcl(how, MT_DATA, 0);
1652 m_new = m_get(how, MT_DATA);
1657 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1659 m_new->m_len = length;
1660 if (m_new != m_final)
1661 m_cat(m_final, m_new);
1664 if (m0->m_next == NULL)
1669 m_defragbytes += m0->m_pkthdr.len;
1681 * Move data from uio into mbufs.
1682 * A length of zero means copy the whole uio.
1685 m_uiomove(struct uio *uio, int wait, int len0)
1687 struct mbuf *head; /* result mbuf chain */
1688 struct mbuf *m; /* current working mbuf */
1690 int resid, datalen, error;
1692 resid = (len0 == 0) ? uio->uio_resid : min(len0, uio->uio_resid);
1697 if (resid > MHLEN) {
1698 m = m_getcl(wait, MT_DATA, head == NULL ? M_PKTHDR : 0);
1701 if (m->m_flags & M_PKTHDR)
1702 m->m_pkthdr.len = 0;
1705 MGETHDR(m, wait, MT_DATA);
1708 m->m_pkthdr.len = 0;
1709 /* Leave room for protocol headers. */
1713 MGET(m, wait, MT_DATA);
1718 datalen = min(MCLBYTES, resid);
1719 error = uiomove(mtod(m, caddr_t), datalen, uio);
1727 head->m_pkthdr.len += datalen;
1729 } while (resid > 0);