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) 1982, 1986, 1988, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
67 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
68 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.63 2007/08/09 01:10:04 dillon Exp $
71 #include "opt_param.h"
73 #include "opt_mbuf_stress_test.h"
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/malloc.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/domain.h>
81 #include <sys/objcache.h>
83 #include <sys/protosw.h>
85 #include <sys/thread.h>
86 #include <sys/globaldata.h>
87 #include <sys/serialize.h>
88 #include <sys/thread2.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
95 #include <machine/cpu.h>
99 * mbuf cluster meta-data
104 struct lwkt_serialize mcl_serializer;
108 * mbuf tracking for debugging purposes
112 static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
115 RB_HEAD(mbuf_rb_tree, mbtrack);
116 RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
119 RB_ENTRY(mbtrack) rb_node;
125 mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
134 RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
136 struct mbuf_rb_tree mbuf_track_root;
139 mbuftrack(struct mbuf *m)
144 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
146 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt))
147 panic("mbuftrack: mbuf %p already being tracked\n", m);
152 mbufuntrack(struct mbuf *m)
157 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
159 kprintf("mbufuntrack: mbuf %p was not tracked\n", m);
161 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
162 kfree(mbt, M_MTRACK);
168 mbuftrackid(struct mbuf *m, int trackid)
177 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
179 mbt->trackid = trackid;
188 mbuftrack_callback(struct mbtrack *mbt, void *arg)
190 struct sysctl_req *req = arg;
194 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
196 error = SYSCTL_OUT(req, buf, strlen(buf));
203 mbuftrack_show(SYSCTL_HANDLER_ARGS)
208 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
209 mbuftrack_callback, req);
213 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
214 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
219 #define mbufuntrack(m)
223 static void mbinit(void *);
224 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
226 static u_long mbtypes[MT_NTYPES];
228 struct mbstat mbstat;
237 #ifdef MBUF_STRESS_TEST
238 int m_defragrandomfailures;
241 struct objcache *mbuf_cache, *mbufphdr_cache;
242 struct objcache *mclmeta_cache;
243 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
248 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
249 &max_linkhdr, 0, "");
250 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
251 &max_protohdr, 0, "");
252 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
253 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
254 &max_datalen, 0, "");
255 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
257 SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
258 SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
259 sizeof(mbtypes), "LU", "");
262 * These are read-only because we do not currently have any code
263 * to adjust the objcache limits after the fact. The variables
264 * may only be set as boot-time tunables.
266 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
267 &nmbclusters, 0, "Maximum number of mbuf clusters available");
268 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
269 "Maximum number of mbufs available");
271 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
272 &m_defragpackets, 0, "");
273 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
274 &m_defragbytes, 0, "");
275 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
276 &m_defraguseless, 0, "");
277 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
278 &m_defragfailure, 0, "");
279 #ifdef MBUF_STRESS_TEST
280 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
281 &m_defragrandomfailures, 0, "");
284 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
285 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
286 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
288 static void m_reclaim (void);
289 static void m_mclref(void *arg);
290 static void m_mclfree(void *arg);
293 #define NMBCLUSTERS (512 + maxusers * 16)
296 #define NMBUFS (nmbclusters * 2)
300 * Perform sanity checks of tunables declared above.
303 tunable_mbinit(void *dummy)
306 * This has to be done before VM init.
308 nmbclusters = NMBCLUSTERS;
309 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
311 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
313 if (nmbufs < nmbclusters * 2)
314 nmbufs = nmbclusters * 2;
316 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
317 tunable_mbinit, NULL);
319 /* "number of clusters of pages" */
325 * The mbuf object cache only guarantees that m_next and m_nextpkt are
326 * NULL and that m_data points to the beginning of the data area. In
327 * particular, m_len and m_pkthdr.len are uninitialized. It is the
328 * responsibility of the caller to initialize those fields before use.
331 static boolean_t __inline
332 mbuf_ctor(void *obj, void *private, int ocflags)
334 struct mbuf *m = obj;
338 m->m_data = m->m_dat;
345 * Initialize the mbuf and the packet header fields.
348 mbufphdr_ctor(void *obj, void *private, int ocflags)
350 struct mbuf *m = obj;
354 m->m_data = m->m_pktdat;
355 m->m_flags = M_PKTHDR | M_PHCACHE;
357 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
358 SLIST_INIT(&m->m_pkthdr.tags);
359 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
360 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
366 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
369 mclmeta_ctor(void *obj, void *private, int ocflags)
371 struct mbcluster *cl = obj;
374 if (ocflags & M_NOWAIT)
375 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
377 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
382 lwkt_serialize_init(&cl->mcl_serializer);
387 mclmeta_dtor(void *obj, void *private)
389 struct mbcluster *mcl = obj;
391 KKASSERT(mcl->mcl_refs == 0);
392 kfree(mcl->mcl_data, M_MBUFCL);
396 linkcluster(struct mbuf *m, struct mbcluster *cl)
399 * Add the cluster to the mbuf. The caller will detect that the
400 * mbuf now has an attached cluster.
402 m->m_ext.ext_arg = cl;
403 m->m_ext.ext_buf = cl->mcl_data;
404 m->m_ext.ext_ref = m_mclref;
405 m->m_ext.ext_free = m_mclfree;
406 m->m_ext.ext_size = MCLBYTES;
407 atomic_add_int(&cl->mcl_refs, 1);
409 m->m_data = m->m_ext.ext_buf;
410 m->m_flags |= M_EXT | M_EXT_CLUSTER;
414 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
416 struct mbuf *m = obj;
417 struct mbcluster *cl;
419 mbufphdr_ctor(obj, private, ocflags);
420 cl = objcache_get(mclmeta_cache, ocflags);
423 m->m_flags |= M_CLCACHE;
429 mbufcluster_ctor(void *obj, void *private, int ocflags)
431 struct mbuf *m = obj;
432 struct mbcluster *cl;
434 mbuf_ctor(obj, private, ocflags);
435 cl = objcache_get(mclmeta_cache, ocflags);
438 m->m_flags |= M_CLCACHE;
444 * Used for both the cluster and cluster PHDR caches.
446 * The mbuf may have lost its cluster due to sharing, deal
447 * with the situation by checking M_EXT.
450 mbufcluster_dtor(void *obj, void *private)
452 struct mbuf *m = obj;
453 struct mbcluster *mcl;
455 if (m->m_flags & M_EXT) {
456 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
457 mcl = m->m_ext.ext_arg;
458 KKASSERT(mcl->mcl_refs == 1);
460 objcache_put(mclmeta_cache, mcl);
464 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
465 struct objcache_malloc_args mclmeta_malloc_args =
466 { sizeof(struct mbcluster), M_MCLMETA };
472 mbstat.m_msize = MSIZE;
473 mbstat.m_mclbytes = MCLBYTES;
474 mbstat.m_minclsize = MINCLSIZE;
475 mbstat.m_mlen = MLEN;
476 mbstat.m_mhlen = MHLEN;
478 mbuf_cache = objcache_create("mbuf", nmbufs, 0,
479 mbuf_ctor, NULL, NULL,
480 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
481 mbufphdr_cache = objcache_create("mbuf pkt hdr", nmbufs, 64,
482 mbufphdr_ctor, NULL, NULL,
483 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
484 mclmeta_cache = objcache_create("cluster mbuf", nmbclusters , 0,
485 mclmeta_ctor, mclmeta_dtor, NULL,
486 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
487 mbufcluster_cache = objcache_create("mbuf + cluster", nmbclusters, 0,
488 mbufcluster_ctor, mbufcluster_dtor, NULL,
489 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
490 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
491 nmbclusters, 64, mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
492 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
497 * Return the number of references to this mbuf's data. 0 is returned
498 * if the mbuf is not M_EXT, a reference count is returned if it is
499 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
502 m_sharecount(struct mbuf *m)
504 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
509 case M_EXT | M_EXT_CLUSTER:
510 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
513 return (0); /* to shut up compiler */
517 * change mbuf to new type
520 m_chtype(struct mbuf *m, int type)
524 --mbtypes[m->m_type];
536 SLIST_FOREACH(dp, &domains, dom_next) {
537 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
547 updatestats(struct mbuf *m, int type)
562 m_get(int how, int type)
566 int ocf = MBTOM(how);
570 m = objcache_get(mbuf_cache, ocf);
573 if ((how & MB_TRYWAIT) && ntries++ == 0) {
574 struct objcache *reclaimlist[] = {
576 mbufcluster_cache, mbufphdrcluster_cache
578 const int nreclaims = __arysize(reclaimlist);
580 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
587 updatestats(m, type);
592 m_gethdr(int how, int type)
595 int ocf = MBTOM(how);
600 m = objcache_get(mbufphdr_cache, ocf);
603 if ((how & MB_TRYWAIT) && ntries++ == 0) {
604 struct objcache *reclaimlist[] = {
606 mbufcluster_cache, mbufphdrcluster_cache
608 const int nreclaims = __arysize(reclaimlist);
610 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
617 updatestats(m, type);
622 * Get a mbuf (not a mbuf cluster!) and zero it.
626 m_getclr(int how, int type)
630 m = m_get(how, type);
632 bzero(m->m_data, MLEN);
637 * Returns an mbuf with an attached cluster.
638 * Because many network drivers use this kind of buffers a lot, it is
639 * convenient to keep a small pool of free buffers of this kind.
640 * Even a small size such as 10 gives about 10% improvement in the
641 * forwarding rate in a bridge or router.
644 m_getcl(int how, short type, int flags)
647 int ocflags = MBTOM(how);
652 if (flags & M_PKTHDR)
653 m = objcache_get(mbufphdrcluster_cache, ocflags);
655 m = objcache_get(mbufcluster_cache, ocflags);
658 if ((how & MB_TRYWAIT) && ntries++ == 0) {
659 struct objcache *reclaimlist[1];
661 if (flags & M_PKTHDR)
662 reclaimlist[0] = mbufcluster_cache;
664 reclaimlist[0] = mbufphdrcluster_cache;
665 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
683 * Allocate chain of requested length.
686 m_getc(int len, int how, int type)
688 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
692 n = m_getl(len, how, type, 0, &nsize);
708 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
709 * and return a pointer to the head of the allocated chain. If m0 is
710 * non-null, then we assume that it is a single mbuf or an mbuf chain to
711 * which we want len bytes worth of mbufs and/or clusters attached, and so
712 * if we succeed in allocating it, we will just return a pointer to m0.
714 * If we happen to fail at any point during the allocation, we will free
715 * up everything we have already allocated and return NULL.
717 * Deprecated. Use m_getc() and m_cat() instead.
720 m_getm(struct mbuf *m0, int len, int type, int how)
724 nfirst = m_getc(len, how, type);
727 m_last(m0)->m_next = nfirst;
735 * Adds a cluster to a normal mbuf, M_EXT is set on success.
736 * Deprecated. Use m_getcl() instead.
739 m_mclget(struct mbuf *m, int how)
741 struct mbcluster *mcl;
743 KKASSERT((m->m_flags & M_EXT) == 0);
744 mcl = objcache_get(mclmeta_cache, MBTOM(how));
749 /* leave the m_mbufs count intact for original mbuf */
755 * Updates to mbcluster must be MPSAFE. Only an entity which already has
756 * a reference to the cluster can ref it, so we are in no danger of
757 * racing an add with a subtract. But the operation must still be atomic
758 * since multiple entities may have a reference on the cluster.
760 * m_mclfree() is almost the same but it must contend with two entities
761 * freeing the cluster at the same time. If there is only one reference
762 * count we are the only entity referencing the cluster and no further
763 * locking is required. Otherwise we must protect against a race to 0
764 * with the serializer.
769 struct mbcluster *mcl = arg;
771 atomic_add_int(&mcl->mcl_refs, 1);
777 struct mbcluster *mcl = arg;
779 if (mcl->mcl_refs == 1) {
781 objcache_put(mclmeta_cache, mcl);
783 lwkt_serialize_enter(&mcl->mcl_serializer);
784 if (mcl->mcl_refs > 1) {
785 atomic_subtract_int(&mcl->mcl_refs, 1);
786 lwkt_serialize_exit(&mcl->mcl_serializer);
788 lwkt_serialize_exit(&mcl->mcl_serializer);
789 KKASSERT(mcl->mcl_refs == 1);
791 objcache_put(mclmeta_cache, mcl);
796 extern void db_print_backtrace(void);
799 * Free a single mbuf and any associated external storage. The successor,
800 * if any, is returned.
802 * We do need to check non-first mbuf for m_aux, since some of existing
803 * code does not call M_PREPEND properly.
804 * (example: call to bpf_mtap from drivers)
807 m_free(struct mbuf *m)
811 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
812 --mbtypes[m->m_type];
817 * Make sure the mbuf is in constructed state before returning it
823 KKASSERT(m->m_nextpkt == NULL);
825 if (m->m_nextpkt != NULL) {
827 static int afewtimes = 10;
829 if (afewtimes-- > 0) {
830 kprintf("mfree: m->m_nextpkt != NULL\n");
831 db_print_backtrace();
837 if (m->m_flags & M_PKTHDR) {
838 m_tag_delete_chain(m); /* eliminate XXX JH */
841 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
844 * Clean the M_PKTHDR state so we can return the mbuf to its original
845 * cache. This is based on the PHCACHE flag which tells us whether
846 * the mbuf was originally allocated out of a packet-header cache
847 * or a non-packet-header cache.
849 if (m->m_flags & M_PHCACHE) {
850 m->m_flags |= M_PKTHDR;
851 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
852 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
853 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
854 SLIST_INIT(&m->m_pkthdr.tags);
858 * Handle remaining flags combinations. M_CLCACHE tells us whether
859 * the mbuf was originally allocated from a cluster cache or not,
860 * and is totally separate from whether the mbuf is currently
861 * associated with a cluster.
864 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
865 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
867 * mbuf+cluster cache case. The mbuf was allocated from the
868 * combined mbuf_cluster cache and can be returned to the
869 * cache if the cluster hasn't been shared.
871 if (m_sharecount(m) == 1) {
873 * The cluster has not been shared, we can just
874 * reset the data pointer and return the mbuf
875 * to the cluster cache. Note that the reference
876 * count is left intact (it is still associated with
879 m->m_data = m->m_ext.ext_buf;
880 if (m->m_flags & M_PHCACHE)
881 objcache_put(mbufphdrcluster_cache, m);
883 objcache_put(mbufcluster_cache, m);
887 * Hell. Someone else has a ref on this cluster,
888 * we have to disconnect it which means we can't
889 * put it back into the mbufcluster_cache, we
890 * have to destroy the mbuf.
892 * Other mbuf references to the cluster will typically
893 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
895 * XXX we could try to connect another cluster to
898 m->m_ext.ext_free(m->m_ext.ext_arg);
899 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
900 if (m->m_flags & M_PHCACHE)
901 objcache_dtor(mbufphdrcluster_cache, m);
903 objcache_dtor(mbufcluster_cache, m);
906 case M_EXT | M_EXT_CLUSTER:
908 * Normal cluster associated with an mbuf that was allocated
909 * from the normal mbuf pool rather then the cluster pool.
910 * The cluster has to be independantly disassociated from the
913 if (m_sharecount(m) == 1)
918 * Normal cluster association case, disconnect the cluster from
919 * the mbuf. The cluster may or may not be custom.
921 m->m_ext.ext_free(m->m_ext.ext_arg);
922 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
926 * return the mbuf to the mbuf cache.
928 if (m->m_flags & M_PHCACHE) {
929 m->m_data = m->m_pktdat;
930 objcache_put(mbufphdr_cache, m);
932 m->m_data = m->m_dat;
933 objcache_put(mbuf_cache, m);
939 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
947 m_freem(struct mbuf *m)
956 * mbuf utility routines
960 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
964 m_prepend(struct mbuf *m, int len, int how)
968 if (m->m_flags & M_PKTHDR)
969 mn = m_gethdr(how, m->m_type);
971 mn = m_get(how, m->m_type);
976 if (m->m_flags & M_PKTHDR)
977 M_MOVE_PKTHDR(mn, m);
987 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
988 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
989 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
990 * Note that the copy is read-only, because clusters are not copied,
991 * only their reference counts are incremented.
994 m_copym(const struct mbuf *m, int off0, int len, int wait)
996 struct mbuf *n, **np;
1001 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1002 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1003 if (off == 0 && m->m_flags & M_PKTHDR)
1006 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1016 KASSERT(len == M_COPYALL,
1017 ("m_copym, length > size of mbuf chain"));
1021 * Because we are sharing any cluster attachment below,
1022 * be sure to get an mbuf that does not have a cluster
1023 * associated with it.
1026 n = m_gethdr(wait, m->m_type);
1028 n = m_get(wait, m->m_type);
1033 if (!m_dup_pkthdr(n, m, wait))
1035 if (len == M_COPYALL)
1036 n->m_pkthdr.len -= off0;
1038 n->m_pkthdr.len = len;
1041 n->m_len = min(len, m->m_len - off);
1042 if (m->m_flags & M_EXT) {
1043 KKASSERT((n->m_flags & M_EXT) == 0);
1044 n->m_data = m->m_data + off;
1045 m->m_ext.ext_ref(m->m_ext.ext_arg);
1046 n->m_ext = m->m_ext;
1047 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1049 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1050 (unsigned)n->m_len);
1052 if (len != M_COPYALL)
1068 * Copy an entire packet, including header (which must be present).
1069 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1070 * Note that the copy is read-only, because clusters are not copied,
1071 * only their reference counts are incremented.
1072 * Preserve alignment of the first mbuf so if the creator has left
1073 * some room at the beginning (e.g. for inserting protocol headers)
1074 * the copies also have the room available.
1077 m_copypacket(struct mbuf *m, int how)
1079 struct mbuf *top, *n, *o;
1081 n = m_gethdr(how, m->m_type);
1086 if (!m_dup_pkthdr(n, m, how))
1088 n->m_len = m->m_len;
1089 if (m->m_flags & M_EXT) {
1090 KKASSERT((n->m_flags & M_EXT) == 0);
1091 n->m_data = m->m_data;
1092 m->m_ext.ext_ref(m->m_ext.ext_arg);
1093 n->m_ext = m->m_ext;
1094 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1096 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1097 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1102 o = m_get(how, m->m_type);
1109 n->m_len = m->m_len;
1110 if (m->m_flags & M_EXT) {
1111 KKASSERT((n->m_flags & M_EXT) == 0);
1112 n->m_data = m->m_data;
1113 m->m_ext.ext_ref(m->m_ext.ext_arg);
1114 n->m_ext = m->m_ext;
1115 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
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", __func__));
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 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1187 if (!m_dup_pkthdr(n, m, how))
1190 /* Link it into the new chain */
1194 /* Copy data from original mbuf(s) into new mbuf */
1196 while (n->m_len < nsize && m != NULL) {
1197 int chunk = min(nsize - n->m_len, m->m_len - moff);
1199 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1203 if (moff == m->m_len) {
1209 /* Check correct total mbuf length */
1210 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1211 ("%s: bogus m_pkthdr.len", __func__));
1223 * Concatenate mbuf chain n to m.
1224 * Both chains must be of the same type (e.g. MT_DATA).
1225 * Any m_pkthdr is not updated.
1228 m_cat(struct mbuf *m, struct mbuf *n)
1232 if (m->m_flags & M_EXT ||
1233 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1234 /* just join the two chains */
1238 /* splat the data from one into the other */
1239 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1241 m->m_len += n->m_len;
1247 m_adj(struct mbuf *mp, int req_len)
1253 if ((m = mp) == NULL)
1259 while (m != NULL && len > 0) {
1260 if (m->m_len <= len) {
1271 if (mp->m_flags & M_PKTHDR)
1272 m->m_pkthdr.len -= (req_len - len);
1275 * Trim from tail. Scan the mbuf chain,
1276 * calculating its length and finding the last mbuf.
1277 * If the adjustment only affects this mbuf, then just
1278 * adjust and return. Otherwise, rescan and truncate
1279 * after the remaining size.
1285 if (m->m_next == (struct mbuf *)0)
1289 if (m->m_len >= len) {
1291 if (mp->m_flags & M_PKTHDR)
1292 mp->m_pkthdr.len -= len;
1299 * Correct length for chain is "count".
1300 * Find the mbuf with last data, adjust its length,
1301 * and toss data from remaining mbufs on chain.
1304 if (m->m_flags & M_PKTHDR)
1305 m->m_pkthdr.len = count;
1306 for (; m; m = m->m_next) {
1307 if (m->m_len >= count) {
1314 (m = m->m_next) ->m_len = 0;
1319 * Rearrange an mbuf chain so that len bytes are contiguous
1320 * and in the data area of an mbuf (so that mtod will work for a structure
1321 * of size len). Returns the resulting mbuf chain on success, frees it and
1322 * returns null on failure. If there is room, it will add up to
1323 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1324 * avoid being called next time.
1327 m_pullup(struct mbuf *n, int len)
1334 * If first mbuf has no cluster, and has room for len bytes
1335 * without shifting current data, pullup into it,
1336 * otherwise allocate a new mbuf to prepend to the chain.
1338 if (!(n->m_flags & M_EXT) &&
1339 n->m_data + len < &n->m_dat[MLEN] &&
1341 if (n->m_len >= len)
1349 if (n->m_flags & M_PKTHDR)
1350 m = m_gethdr(MB_DONTWAIT, n->m_type);
1352 m = m_get(MB_DONTWAIT, n->m_type);
1356 if (n->m_flags & M_PKTHDR)
1357 M_MOVE_PKTHDR(m, n);
1359 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1361 count = min(min(max(len, max_protohdr), space), n->m_len);
1362 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1372 } while (len > 0 && n);
1386 * Partition an mbuf chain in two pieces, returning the tail --
1387 * all but the first len0 bytes. In case of failure, it returns NULL and
1388 * attempts to restore the chain to its original state.
1390 * Note that the resulting mbufs might be read-only, because the new
1391 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1392 * the "breaking point" happens to lie within a cluster mbuf. Use the
1393 * M_WRITABLE() macro to check for this case.
1396 m_split(struct mbuf *m0, int len0, int wait)
1399 unsigned len = len0, remain;
1401 for (m = m0; m && len > m->m_len; m = m->m_next)
1405 remain = m->m_len - len;
1406 if (m0->m_flags & M_PKTHDR) {
1407 n = m_gethdr(wait, m0->m_type);
1410 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1411 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1412 m0->m_pkthdr.len = len0;
1413 if (m->m_flags & M_EXT)
1415 if (remain > MHLEN) {
1416 /* m can't be the lead packet */
1418 n->m_next = m_split(m, len, wait);
1419 if (n->m_next == NULL) {
1427 MH_ALIGN(n, remain);
1428 } else if (remain == 0) {
1433 n = m_get(wait, m->m_type);
1439 if (m->m_flags & M_EXT) {
1440 KKASSERT((n->m_flags & M_EXT) == 0);
1441 n->m_data = m->m_data + len;
1442 m->m_ext.ext_ref(m->m_ext.ext_arg);
1443 n->m_ext = m->m_ext;
1444 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1446 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1450 n->m_next = m->m_next;
1456 * Routine to copy from device local memory into mbufs.
1457 * Note: "offset" is ill-defined and always called as 0, so ignore it.
1460 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1461 void (*copy)(volatile const void *from, volatile void *to, size_t length))
1463 struct mbuf *m, *mfirst = NULL, **mtail;
1472 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1477 m->m_len = min(len, nsize);
1479 if (flags & M_PKTHDR) {
1480 if (len + max_linkhdr <= nsize)
1481 m->m_data += max_linkhdr;
1482 m->m_pkthdr.rcvif = ifp;
1483 m->m_pkthdr.len = len;
1487 copy(buf, m->m_data, (unsigned)m->m_len);
1498 * Copy data from a buffer back into the indicated mbuf chain,
1499 * starting "off" bytes from the beginning, extending the mbuf
1500 * chain if necessary.
1503 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
1506 struct mbuf *m = m0, *n;
1511 while (off > (mlen = m->m_len)) {
1514 if (m->m_next == NULL) {
1515 n = m_getclr(MB_DONTWAIT, m->m_type);
1518 n->m_len = min(MLEN, len + off);
1524 mlen = min (m->m_len - off, len);
1525 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1533 if (m->m_next == NULL) {
1534 n = m_get(MB_DONTWAIT, m->m_type);
1537 n->m_len = min(MLEN, len);
1542 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1543 m->m_pkthdr.len = totlen;
1547 m_print(const struct mbuf *m)
1550 const struct mbuf *m2;
1552 len = m->m_pkthdr.len;
1555 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
1563 * "Move" mbuf pkthdr from "from" to "to".
1564 * "from" must have M_PKTHDR set, and "to" must be empty.
1567 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1569 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
1571 to->m_flags |= from->m_flags & M_COPYFLAGS;
1572 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1573 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
1577 * Duplicate "from"'s mbuf pkthdr in "to".
1578 * "from" must have M_PKTHDR set, and "to" must be empty.
1579 * In particular, this does a deep copy of the packet tags.
1582 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
1584 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
1586 to->m_flags = (from->m_flags & M_COPYFLAGS) |
1587 (to->m_flags & ~M_COPYFLAGS);
1588 to->m_pkthdr = from->m_pkthdr;
1589 SLIST_INIT(&to->m_pkthdr.tags);
1590 return (m_tag_copy_chain(to, from, how));
1594 * Defragment a mbuf chain, returning the shortest possible
1595 * chain of mbufs and clusters. If allocation fails and
1596 * this cannot be completed, NULL will be returned, but
1597 * the passed in chain will be unchanged. Upon success,
1598 * the original chain will be freed, and the new chain
1601 * If a non-packet header is passed in, the original
1602 * mbuf (chain?) will be returned unharmed.
1604 * m_defrag_nofree doesn't free the passed in mbuf.
1607 m_defrag(struct mbuf *m0, int how)
1611 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1619 m_defrag_nofree(struct mbuf *m0, int how)
1621 struct mbuf *m_new = NULL, *m_final = NULL;
1622 int progress = 0, length, nsize;
1624 if (!(m0->m_flags & M_PKTHDR))
1627 #ifdef MBUF_STRESS_TEST
1628 if (m_defragrandomfailures) {
1629 int temp = karc4random() & 0xff;
1635 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
1636 if (m_final == NULL)
1638 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
1640 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1645 while (progress < m0->m_pkthdr.len) {
1646 length = m0->m_pkthdr.len - progress;
1647 if (length > MCLBYTES)
1650 if (m_new == NULL) {
1651 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
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)
1666 m_defragbytes += m_final->m_pkthdr.len;
1677 * Move data from uio into mbufs.
1680 m_uiomove(struct uio *uio)
1682 struct mbuf *m; /* current working mbuf */
1683 struct mbuf *head = NULL; /* result mbuf chain */
1684 struct mbuf **mp = &head;
1685 int resid = uio->uio_resid, nsize, flags = M_PKTHDR, error;
1688 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
1690 m->m_pkthdr.len = 0;
1691 /* Leave room for protocol headers. */
1696 m->m_len = min(nsize, resid);
1697 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
1704 head->m_pkthdr.len += m->m_len;
1706 } while (resid > 0);
1716 m_last(struct mbuf *m)
1724 * Return the number of bytes in an mbuf chain.
1725 * If lastm is not NULL, also return the last mbuf.
1728 m_lengthm(struct mbuf *m, struct mbuf **lastm)
1731 struct mbuf *prev = m;
1744 * Like m_lengthm(), except also keep track of mbuf usage.
1747 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
1749 u_int len = 0, mbcnt = 0;
1750 struct mbuf *prev = m;
1755 if (m->m_flags & M_EXT)
1756 mbcnt += m->m_ext.ext_size;