usr.sbin/makefs/ffs: Remove m_buf::b_is_hammer2
[dragonfly.git] / sys / kern / uipc_mbuf.c
blobd0330c8f434452ada16a6d8511957a6c6568b19a
1 /*
2 * (MPSAFE)
4 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
5 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
6 *
7 * This code is derived from software contributed to The DragonFly Project
8 * by Jeffrey M. Hsu.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
37 * Copyright (c) 1982, 1986, 1988, 1991, 1993
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
42 * are met:
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * SUCH DAMAGE.
64 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
65 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
68 #include "opt_param.h"
69 #include "opt_mbuf_stress_test.h"
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/file.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/domain.h>
78 #include <sys/objcache.h>
79 #include <sys/tree.h>
80 #include <sys/protosw.h>
81 #include <sys/uio.h>
82 #include <sys/thread.h>
83 #include <sys/proc.h>
84 #include <sys/globaldata.h>
86 #include <sys/spinlock2.h>
88 #include <machine/atomic.h>
89 #include <machine/limits.h>
91 #include <vm/vm.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
95 #ifdef INVARIANTS
96 #include <machine/cpu.h>
97 #endif
100 * mbuf cluster meta-data
102 struct mbcluster {
103 int32_t mcl_refs;
104 void *mcl_data;
108 * mbuf tracking for debugging purposes
110 #ifdef MBUF_DEBUG
112 static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
114 struct mbctrack;
115 RB_HEAD(mbuf_rb_tree, mbtrack);
116 RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
118 struct mbtrack {
119 RB_ENTRY(mbtrack) rb_node;
120 int trackid;
121 struct mbuf *m;
124 static int
125 mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
127 if (mb1->m < mb2->m)
128 return(-1);
129 if (mb1->m > mb2->m)
130 return(1);
131 return(0);
134 RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
136 struct mbuf_rb_tree mbuf_track_root;
137 static struct spinlock mbuf_track_spin = SPINLOCK_INITIALIZER(mbuf_track_spin, "mbuf_track_spin");
139 static void
140 mbuftrack(struct mbuf *m)
142 struct mbtrack *mbt;
144 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
145 spin_lock(&mbuf_track_spin);
146 mbt->m = m;
147 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt)) {
148 spin_unlock(&mbuf_track_spin);
149 panic("mbuftrack: mbuf %p already being tracked", m);
151 spin_unlock(&mbuf_track_spin);
154 static void
155 mbufuntrack(struct mbuf *m)
157 struct mbtrack *mbt;
159 spin_lock(&mbuf_track_spin);
160 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
161 if (mbt == NULL) {
162 spin_unlock(&mbuf_track_spin);
163 panic("mbufuntrack: mbuf %p was not tracked", m);
164 } else {
165 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
166 spin_unlock(&mbuf_track_spin);
167 kfree(mbt, M_MTRACK);
171 void
172 mbuftrackid(struct mbuf *m, int trackid)
174 struct mbtrack *mbt;
175 struct mbuf *n;
177 spin_lock(&mbuf_track_spin);
178 while (m) {
179 n = m->m_nextpkt;
180 while (m) {
181 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
182 if (mbt == NULL) {
183 spin_unlock(&mbuf_track_spin);
184 panic("mbuftrackid: mbuf %p not tracked", m);
186 mbt->trackid = trackid;
187 m = m->m_next;
189 m = n;
191 spin_unlock(&mbuf_track_spin);
194 static int
195 mbuftrack_callback(struct mbtrack *mbt, void *arg)
197 struct sysctl_req *req = arg;
198 char buf[64];
199 int error;
201 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
203 spin_unlock(&mbuf_track_spin);
204 error = SYSCTL_OUT(req, buf, strlen(buf));
205 spin_lock(&mbuf_track_spin);
206 if (error)
207 return(-error);
208 return(0);
211 static int
212 mbuftrack_show(SYSCTL_HANDLER_ARGS)
214 int error;
216 spin_lock(&mbuf_track_spin);
217 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
218 mbuftrack_callback, req);
219 spin_unlock(&mbuf_track_spin);
220 return (-error);
222 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
223 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
225 #else
227 #define mbuftrack(m)
228 #define mbufuntrack(m)
230 #endif
232 static void mbinit(void *);
233 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL);
235 struct mbtypes_stat {
236 u_long stats[MT_NTYPES];
237 } __cachealign;
239 static struct mbtypes_stat mbtypes[SMP_MAXCPU];
241 static struct mbstat mbstat[SMP_MAXCPU] __cachealign;
242 int max_linkhdr;
243 int max_protohdr;
244 int max_hdr;
245 int max_datalen;
246 int m_defragpackets;
247 int m_defragbytes;
248 int m_defraguseless;
249 int m_defragfailure;
250 #ifdef MBUF_STRESS_TEST
251 int m_defragrandomfailures;
252 #endif
254 struct objcache *mbuf_cache, *mbufphdr_cache;
255 struct objcache *mclmeta_cache, *mjclmeta_cache;
256 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
257 struct objcache *mbufjcluster_cache, *mbufphdrjcluster_cache;
259 struct lock mbupdate_lk = LOCK_INITIALIZER("mbupdate", 0, LK_CANRECURSE);
261 int nmbclusters;
262 static int nmbjclusters;
263 int nmbufs;
265 static int mjclph_cachefrac;
266 static int mjcl_cachefrac;
267 static int mclph_cachefrac;
268 static int mcl_cachefrac;
270 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
271 &max_linkhdr, 0, "Max size of a link-level header");
272 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
273 &max_protohdr, 0, "Max size of a protocol header");
274 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0,
275 "Max size of link+protocol headers");
276 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
277 &max_datalen, 0, "Max data payload size without headers");
278 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
279 &mbuf_wait, 0, "Time in ticks to sleep after failed mbuf allocations");
280 static int do_mbstat(SYSCTL_HANDLER_ARGS);
282 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
283 0, 0, do_mbstat, "S,mbstat", "mbuf usage statistics");
285 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
287 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
288 0, 0, do_mbtypes, "LU", "");
290 static int
291 do_mbstat(SYSCTL_HANDLER_ARGS)
293 struct mbstat mbstat_total;
294 struct mbstat *mbstat_totalp;
295 int i;
297 bzero(&mbstat_total, sizeof(mbstat_total));
298 mbstat_totalp = &mbstat_total;
300 for (i = 0; i < ncpus; i++) {
301 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
302 mbstat_total.m_clusters += mbstat[i].m_clusters;
303 mbstat_total.m_jclusters += mbstat[i].m_jclusters;
304 mbstat_total.m_clfree += mbstat[i].m_clfree;
305 mbstat_total.m_drops += mbstat[i].m_drops;
306 mbstat_total.m_wait += mbstat[i].m_wait;
307 mbstat_total.m_drain += mbstat[i].m_drain;
308 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
309 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
313 * The following fields are not cumulative fields so just
314 * get their values once.
316 mbstat_total.m_msize = mbstat[0].m_msize;
317 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
318 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
319 mbstat_total.m_mlen = mbstat[0].m_mlen;
320 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
322 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
325 static int
326 do_mbtypes(SYSCTL_HANDLER_ARGS)
328 u_long totals[MT_NTYPES];
329 int i, j;
331 for (i = 0; i < MT_NTYPES; i++)
332 totals[i] = 0;
334 for (i = 0; i < ncpus; i++) {
335 for (j = 0; j < MT_NTYPES; j++)
336 totals[j] += mbtypes[i].stats[j];
339 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
343 * The variables may be set as boot-time tunables or live. Setting these
344 * values too low can deadlock your network. Network interfaces may also
345 * adjust nmbclusters and/or nmbjclusters to account for preloading the
346 * hardware rings.
348 static int sysctl_nmbclusters(SYSCTL_HANDLER_ARGS);
349 static int sysctl_nmbjclusters(SYSCTL_HANDLER_ARGS);
350 static int sysctl_nmbufs(SYSCTL_HANDLER_ARGS);
351 SYSCTL_PROC(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLTYPE_INT | CTLFLAG_RW,
352 0, 0, sysctl_nmbclusters, "I",
353 "Maximum number of mbuf clusters available");
354 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjclusters, CTLTYPE_INT | CTLFLAG_RW,
355 0, 0, sysctl_nmbjclusters, "I",
356 "Maximum number of mbuf jclusters available");
357 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbufs, CTLTYPE_INT | CTLFLAG_RW,
358 0, 0, sysctl_nmbufs, "I",
359 "Maximum number of mbufs available");
361 SYSCTL_INT(_kern_ipc, OID_AUTO, mjclph_cachefrac, CTLFLAG_RD,
362 &mjclph_cachefrac, 0,
363 "Fraction of cacheable mbuf jclusters w/ pkthdr");
364 SYSCTL_INT(_kern_ipc, OID_AUTO, mjcl_cachefrac, CTLFLAG_RD,
365 &mjcl_cachefrac, 0,
366 "Fraction of cacheable mbuf jclusters");
367 SYSCTL_INT(_kern_ipc, OID_AUTO, mclph_cachefrac, CTLFLAG_RD,
368 &mclph_cachefrac, 0,
369 "Fraction of cacheable mbuf clusters w/ pkthdr");
370 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_cachefrac, CTLFLAG_RD,
371 &mcl_cachefrac, 0, "Fraction of cacheable mbuf clusters");
373 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
374 &m_defragpackets, 0, "Number of defragment packets");
375 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
376 &m_defragbytes, 0, "Number of defragment bytes");
377 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
378 &m_defraguseless, 0, "Number of useless defragment mbuf chain operations");
379 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
380 &m_defragfailure, 0, "Number of failed defragment mbuf chain operations");
381 #ifdef MBUF_STRESS_TEST
382 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
383 &m_defragrandomfailures, 0, "");
384 #endif
386 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
387 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
388 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
390 static void m_reclaim (void);
391 static void m_mclref(void *arg);
392 static void m_mclfree(void *arg);
393 static void m_mjclfree(void *arg);
395 static void mbupdatelimits(void);
398 * Generally scale default mbufs to maxproc.
400 * NOTE: Default NMBUFS must take into account a possible DOS attack
401 * using fd passing on unix domain sockets.
403 #ifndef NMBCLUSTERS
404 #define NMBCLUSTERS (512 + maxproc * 4)
405 #endif
406 #ifndef BASE_CACHEFRAC
407 #define BASE_CACHEFRAC 16
408 #endif
409 #ifndef MJCLPH_CACHEFRAC
410 #define MJCLPH_CACHEFRAC (BASE_CACHEFRAC * 2)
411 #endif
412 #ifndef MJCL_CACHEFRAC
413 #define MJCL_CACHEFRAC (BASE_CACHEFRAC * 2)
414 #endif
415 #ifndef MCLPH_CACHEFRAC
416 #define MCLPH_CACHEFRAC (BASE_CACHEFRAC * 2)
417 #endif
418 #ifndef MCL_CACHEFRAC
419 #define MCL_CACHEFRAC (BASE_CACHEFRAC * 2)
420 #endif
421 #ifndef NMBJCLUSTERS
422 #define NMBJCLUSTERS (NMBCLUSTERS / 4)
423 #endif
424 #ifndef NMBUFS
425 #define NMBUFS (nmbclusters / 2 + maxfiles)
426 #endif
428 #define NMBCLUSTERS_MIN (NMBCLUSTERS / 2)
429 #define NMBJCLUSTERS_MIN (NMBJCLUSTERS / 2)
430 #define NMBUFS_MIN (NMBUFS / 2)
433 * Perform sanity checks of tunables declared above.
435 static void
436 tunable_mbinit(void *dummy)
439 * This has to be done before VM init.
441 nmbclusters = NMBCLUSTERS;
442 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
443 mjclph_cachefrac = MJCLPH_CACHEFRAC;
444 TUNABLE_INT_FETCH("kern.ipc.mjclph_cachefrac", &mjclph_cachefrac);
445 mjcl_cachefrac = MJCL_CACHEFRAC;
446 TUNABLE_INT_FETCH("kern.ipc.mjcl_cachefrac", &mjcl_cachefrac);
447 mclph_cachefrac = MCLPH_CACHEFRAC;
448 TUNABLE_INT_FETCH("kern.ipc.mclph_cachefrac", &mclph_cachefrac);
449 mcl_cachefrac = MCL_CACHEFRAC;
450 TUNABLE_INT_FETCH("kern.ipc.mcl_cachefrac", &mcl_cachefrac);
453 * WARNING! each mcl cache feeds two mbuf caches, so the minimum
454 * cachefrac is 2. For safety, use 3.
456 if (mjclph_cachefrac < 3)
457 mjclph_cachefrac = 3;
458 if (mjcl_cachefrac < 3)
459 mjcl_cachefrac = 3;
460 if (mclph_cachefrac < 3)
461 mclph_cachefrac = 3;
462 if (mcl_cachefrac < 3)
463 mcl_cachefrac = 3;
465 nmbjclusters = NMBJCLUSTERS;
466 TUNABLE_INT_FETCH("kern.ipc.nmbjclusters", &nmbjclusters);
468 nmbufs = NMBUFS;
469 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
471 /* Sanity checks */
472 if (nmbufs < nmbclusters * 2)
473 nmbufs = nmbclusters * 2;
475 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
476 tunable_mbinit, NULL);
478 static void
479 mbinclimit(int *limit, int inc, int minlim)
481 int new_limit;
483 lockmgr(&mbupdate_lk, LK_EXCLUSIVE);
485 new_limit = *limit + inc;
486 if (new_limit < minlim)
487 new_limit = minlim;
489 if (*limit != new_limit) {
490 *limit = new_limit;
491 mbupdatelimits();
494 lockmgr(&mbupdate_lk, LK_RELEASE);
497 static int
498 mbsetlimit(int *limit, int new_limit, int minlim)
500 if (new_limit < minlim)
501 return EINVAL;
503 lockmgr(&mbupdate_lk, LK_EXCLUSIVE);
504 mbinclimit(limit, new_limit - *limit, minlim);
505 lockmgr(&mbupdate_lk, LK_RELEASE);
506 return 0;
509 static int
510 sysctl_mblimit(SYSCTL_HANDLER_ARGS, int *limit, int minlim)
512 int error, value;
514 value = *limit;
515 error = sysctl_handle_int(oidp, &value, 0, req);
516 if (error || req->newptr == NULL)
517 return error;
519 return mbsetlimit(limit, value, minlim);
523 * Sysctl support to update nmbclusters, nmbjclusters, and nmbufs.
525 static int
526 sysctl_nmbclusters(SYSCTL_HANDLER_ARGS)
528 return sysctl_mblimit(oidp, arg1, arg2, req, &nmbclusters,
529 NMBCLUSTERS_MIN);
532 static int
533 sysctl_nmbjclusters(SYSCTL_HANDLER_ARGS)
535 return sysctl_mblimit(oidp, arg1, arg2, req, &nmbjclusters,
536 NMBJCLUSTERS_MIN);
539 static int
540 sysctl_nmbufs(SYSCTL_HANDLER_ARGS)
542 return sysctl_mblimit(oidp, arg1, arg2, req, &nmbufs, NMBUFS_MIN);
545 void
546 mcl_inclimit(int inc)
548 mbinclimit(&nmbclusters, inc, NMBCLUSTERS_MIN);
551 void
552 mjcl_inclimit(int inc)
554 mbinclimit(&nmbjclusters, inc, NMBJCLUSTERS_MIN);
557 void
558 mb_inclimit(int inc)
560 mbinclimit(&nmbufs, inc, NMBUFS_MIN);
563 /* "number of clusters of pages" */
564 #define NCL_INIT 1
566 #define NMB_INIT 16
569 * The mbuf object cache only guarantees that m_next and m_nextpkt are
570 * NULL and that m_data points to the beginning of the data area. In
571 * particular, m_len and m_pkthdr.len are uninitialized. It is the
572 * responsibility of the caller to initialize those fields before use.
574 static __inline boolean_t
575 mbuf_ctor(void *obj, void *private, int ocflags)
577 struct mbuf *m = obj;
579 m->m_next = NULL;
580 m->m_nextpkt = NULL;
581 m->m_data = m->m_dat;
582 m->m_flags = 0;
584 return (TRUE);
588 * Initialize the mbuf and the packet header fields.
590 static boolean_t
591 mbufphdr_ctor(void *obj, void *private, int ocflags)
593 struct mbuf *m = obj;
595 m->m_next = NULL;
596 m->m_nextpkt = NULL;
597 m->m_data = m->m_pktdat;
598 m->m_flags = M_PKTHDR | M_PHCACHE;
600 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
601 SLIST_INIT(&m->m_pkthdr.tags);
602 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
603 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
605 return (TRUE);
609 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
611 static boolean_t
612 mclmeta_ctor(void *obj, void *private, int ocflags)
614 struct mbcluster *cl = obj;
615 void *buf;
617 if (ocflags & M_NOWAIT)
618 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
619 else
620 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
621 if (buf == NULL)
622 return (FALSE);
623 cl->mcl_refs = 0;
624 cl->mcl_data = buf;
625 return (TRUE);
628 static boolean_t
629 mjclmeta_ctor(void *obj, void *private, int ocflags)
631 struct mbcluster *cl = obj;
632 void *buf;
634 if (ocflags & M_NOWAIT)
635 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_NOWAIT | M_ZERO);
636 else
637 buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_INTWAIT | M_ZERO);
638 if (buf == NULL)
639 return (FALSE);
640 cl->mcl_refs = 0;
641 cl->mcl_data = buf;
642 return (TRUE);
645 static void
646 mclmeta_dtor(void *obj, void *private)
648 struct mbcluster *mcl = obj;
650 KKASSERT(mcl->mcl_refs == 0);
651 kfree(mcl->mcl_data, M_MBUFCL);
654 static void
655 linkjcluster(struct mbuf *m, struct mbcluster *cl, uint size)
658 * Add the cluster to the mbuf. The caller will detect that the
659 * mbuf now has an attached cluster.
661 m->m_ext.ext_arg = cl;
662 m->m_ext.ext_buf = cl->mcl_data;
663 m->m_ext.ext_ref = m_mclref;
664 if (size != MCLBYTES)
665 m->m_ext.ext_free = m_mjclfree;
666 else
667 m->m_ext.ext_free = m_mclfree;
668 m->m_ext.ext_size = size;
669 atomic_add_int(&cl->mcl_refs, 1);
671 m->m_data = m->m_ext.ext_buf;
672 m->m_flags |= M_EXT | M_EXT_CLUSTER;
675 static void
676 linkcluster(struct mbuf *m, struct mbcluster *cl)
678 linkjcluster(m, cl, MCLBYTES);
681 static boolean_t
682 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
684 struct mbuf *m = obj;
685 struct mbcluster *cl;
687 mbufphdr_ctor(obj, private, ocflags);
688 cl = objcache_get(mclmeta_cache, ocflags);
689 if (cl == NULL) {
690 ++mbstat[mycpu->gd_cpuid].m_drops;
691 return (FALSE);
693 m->m_flags |= M_CLCACHE;
694 linkcluster(m, cl);
695 return (TRUE);
698 static boolean_t
699 mbufphdrjcluster_ctor(void *obj, void *private, int ocflags)
701 struct mbuf *m = obj;
702 struct mbcluster *cl;
704 mbufphdr_ctor(obj, private, ocflags);
705 cl = objcache_get(mjclmeta_cache, ocflags);
706 if (cl == NULL) {
707 ++mbstat[mycpu->gd_cpuid].m_drops;
708 return (FALSE);
710 m->m_flags |= M_CLCACHE;
711 linkjcluster(m, cl, MJUMPAGESIZE);
712 return (TRUE);
715 static boolean_t
716 mbufcluster_ctor(void *obj, void *private, int ocflags)
718 struct mbuf *m = obj;
719 struct mbcluster *cl;
721 mbuf_ctor(obj, private, ocflags);
722 cl = objcache_get(mclmeta_cache, ocflags);
723 if (cl == NULL) {
724 ++mbstat[mycpu->gd_cpuid].m_drops;
725 return (FALSE);
727 m->m_flags |= M_CLCACHE;
728 linkcluster(m, cl);
729 return (TRUE);
732 static boolean_t
733 mbufjcluster_ctor(void *obj, void *private, int ocflags)
735 struct mbuf *m = obj;
736 struct mbcluster *cl;
738 mbuf_ctor(obj, private, ocflags);
739 cl = objcache_get(mjclmeta_cache, ocflags);
740 if (cl == NULL) {
741 ++mbstat[mycpu->gd_cpuid].m_drops;
742 return (FALSE);
744 m->m_flags |= M_CLCACHE;
745 linkjcluster(m, cl, MJUMPAGESIZE);
746 return (TRUE);
750 * Used for both the cluster and cluster PHDR caches.
752 * The mbuf may have lost its cluster due to sharing, deal
753 * with the situation by checking M_EXT.
755 static void
756 mbufcluster_dtor(void *obj, void *private)
758 struct mbuf *m = obj;
759 struct mbcluster *mcl;
761 if (m->m_flags & M_EXT) {
762 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
763 mcl = m->m_ext.ext_arg;
764 KKASSERT(mcl->mcl_refs == 1);
765 mcl->mcl_refs = 0;
766 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES)
767 objcache_put(mjclmeta_cache, mcl);
768 else
769 objcache_put(mclmeta_cache, mcl);
773 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
774 struct objcache_malloc_args mclmeta_malloc_args =
775 { sizeof(struct mbcluster), M_MCLMETA };
777 /* ARGSUSED*/
778 static void
779 mbinit(void *dummy)
781 int mb_limit, cl_limit, ncl_limit, jcl_limit;
782 int limit;
783 int i;
786 * Initialize statistics
788 for (i = 0; i < ncpus; i++) {
789 mbstat[i].m_msize = MSIZE;
790 mbstat[i].m_mclbytes = MCLBYTES;
791 mbstat[i].m_mjumpagesize = MJUMPAGESIZE;
792 mbstat[i].m_minclsize = MINCLSIZE;
793 mbstat[i].m_mlen = MLEN;
794 mbstat[i].m_mhlen = MHLEN;
798 * Create object caches and save cluster limits, which will
799 * be used to adjust backing kmalloc pools' limit later.
802 mb_limit = cl_limit = 0;
804 limit = nmbufs;
805 mbuf_cache = objcache_create("mbuf",
806 limit, nmbufs / BASE_CACHEFRAC,
807 mbuf_ctor, NULL, NULL,
808 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
809 mb_limit += limit;
811 limit = nmbufs;
812 mbufphdr_cache = objcache_create("mbuf pkthdr",
813 limit, nmbufs / BASE_CACHEFRAC,
814 mbufphdr_ctor, NULL, NULL,
815 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
816 mb_limit += limit;
818 ncl_limit = nmbclusters;
819 mclmeta_cache = objcache_create("mbuf cluster",
820 ncl_limit, nmbclusters / BASE_CACHEFRAC,
821 mclmeta_ctor, mclmeta_dtor, NULL,
822 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
823 cl_limit += ncl_limit;
825 jcl_limit = nmbjclusters;
826 mjclmeta_cache = objcache_create("mbuf jcluster",
827 jcl_limit, nmbjclusters / BASE_CACHEFRAC,
828 mjclmeta_ctor, mclmeta_dtor, NULL,
829 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
830 cl_limit += jcl_limit;
832 limit = nmbclusters;
833 mbufcluster_cache = objcache_create("mbuf+cl",
834 limit, nmbclusters / mcl_cachefrac,
835 mbufcluster_ctor, mbufcluster_dtor, NULL,
836 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
837 mb_limit += limit;
839 limit = nmbclusters;
840 mbufphdrcluster_cache = objcache_create("mbuf pkthdr+cl",
841 limit, nmbclusters / mclph_cachefrac,
842 mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
843 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
844 mb_limit += limit;
846 limit = nmbjclusters;
847 mbufjcluster_cache = objcache_create("mbuf+jcl",
848 limit, nmbjclusters / mjcl_cachefrac,
849 mbufjcluster_ctor, mbufcluster_dtor, NULL,
850 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
851 mb_limit += limit;
853 limit = nmbjclusters;
854 mbufphdrjcluster_cache = objcache_create("mbuf pkthdr+jcl",
855 limit, nmbjclusters / mjclph_cachefrac,
856 mbufphdrjcluster_ctor, mbufcluster_dtor, NULL,
857 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
858 mb_limit += limit;
861 * Adjust backing kmalloc pools' limit
863 * NOTE: We raise the limit by another 1/8 to take the effect
864 * of loosememuse into account.
866 cl_limit += cl_limit / 8;
867 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
868 mclmeta_malloc_args.objsize * (size_t)cl_limit);
869 kmalloc_raise_limit(M_MBUFCL,
870 (MCLBYTES * (size_t)ncl_limit) +
871 (MJUMPAGESIZE * (size_t)jcl_limit));
873 mb_limit += mb_limit / 8;
874 kmalloc_raise_limit(mbuf_malloc_args.mtype,
875 mbuf_malloc_args.objsize * (size_t)mb_limit);
879 * Adjust mbuf limits after changes have been made
881 * Caller must hold mbupdate_lk
883 static void
884 mbupdatelimits(void)
886 int mb_limit, cl_limit, ncl_limit, jcl_limit;
887 int limit;
889 KASSERT(lockstatus(&mbupdate_lk, curthread) != 0,
890 ("mbupdate_lk is not held"));
893 * Figure out adjustments to object caches after nmbufs, nmbclusters,
894 * or nmbjclusters has been modified.
896 mb_limit = cl_limit = 0;
898 limit = nmbufs;
899 objcache_set_cluster_limit(mbuf_cache, limit);
900 mb_limit += limit;
902 limit = nmbufs;
903 objcache_set_cluster_limit(mbufphdr_cache, limit);
904 mb_limit += limit;
906 ncl_limit = nmbclusters;
907 objcache_set_cluster_limit(mclmeta_cache, ncl_limit);
908 cl_limit += ncl_limit;
910 jcl_limit = nmbjclusters;
911 objcache_set_cluster_limit(mjclmeta_cache, jcl_limit);
912 cl_limit += jcl_limit;
914 limit = nmbclusters;
915 objcache_set_cluster_limit(mbufcluster_cache, limit);
916 mb_limit += limit;
918 limit = nmbclusters;
919 objcache_set_cluster_limit(mbufphdrcluster_cache, limit);
920 mb_limit += limit;
922 limit = nmbjclusters;
923 objcache_set_cluster_limit(mbufjcluster_cache, limit);
924 mb_limit += limit;
926 limit = nmbjclusters;
927 objcache_set_cluster_limit(mbufphdrjcluster_cache, limit);
928 mb_limit += limit;
931 * Adjust backing kmalloc pools' limit
933 * NOTE: We raise the limit by another 1/8 to take the effect
934 * of loosememuse into account.
936 cl_limit += cl_limit / 8;
937 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
938 mclmeta_malloc_args.objsize * (size_t)cl_limit);
939 kmalloc_raise_limit(M_MBUFCL,
940 (MCLBYTES * (size_t)ncl_limit) +
941 (MJUMPAGESIZE * (size_t)jcl_limit));
942 mb_limit += mb_limit / 8;
943 kmalloc_raise_limit(mbuf_malloc_args.mtype,
944 mbuf_malloc_args.objsize * (size_t)mb_limit);
948 * Return the number of references to this mbuf's data. 0 is returned
949 * if the mbuf is not M_EXT, a reference count is returned if it is
950 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
953 m_sharecount(struct mbuf *m)
955 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
956 case 0:
957 return (0);
958 case M_EXT:
959 return (99);
960 case M_EXT | M_EXT_CLUSTER:
961 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
963 /* NOTREACHED */
964 return (0); /* to shut up compiler */
968 * change mbuf to new type
970 void
971 m_chtype(struct mbuf *m, int type)
973 struct globaldata *gd = mycpu;
975 ++mbtypes[gd->gd_cpuid].stats[type];
976 --mbtypes[gd->gd_cpuid].stats[m->m_type];
977 m->m_type = type;
980 static void
981 m_reclaim(void)
983 struct domain *dp;
984 struct protosw *pr;
986 kprintf("Debug: m_reclaim() called\n");
988 SLIST_FOREACH(dp, &domains, dom_next) {
989 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
990 if (pr->pr_drain)
991 (*pr->pr_drain)();
994 ++mbstat[mycpu->gd_cpuid].m_drain;
997 static __inline void
998 updatestats(struct mbuf *m, int type)
1000 struct globaldata *gd = mycpu;
1002 m->m_type = type;
1003 mbuftrack(m);
1004 #ifdef MBUF_DEBUG
1005 KASSERT(m->m_next == NULL, ("mbuf %p: bad m_next in get", m));
1006 KASSERT(m->m_nextpkt == NULL, ("mbuf %p: bad m_nextpkt in get", m));
1007 #endif
1009 ++mbtypes[gd->gd_cpuid].stats[type];
1010 ++mbstat[gd->gd_cpuid].m_mbufs;
1015 * Allocate an mbuf.
1017 struct mbuf *
1018 m_get(int how, int type)
1020 struct mbuf *m;
1021 int ntries = 0;
1022 int ocf = MB_OCFLAG(how);
1024 retryonce:
1026 m = objcache_get(mbuf_cache, ocf);
1028 if (m == NULL) {
1029 if ((ocf & M_WAITOK) && ntries++ == 0) {
1030 struct objcache *reclaimlist[] = {
1031 mbufphdr_cache,
1032 mbufcluster_cache,
1033 mbufphdrcluster_cache,
1034 mbufjcluster_cache,
1035 mbufphdrjcluster_cache
1037 const int nreclaims = NELEM(reclaimlist);
1039 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
1040 m_reclaim();
1041 goto retryonce;
1043 ++mbstat[mycpu->gd_cpuid].m_drops;
1044 return (NULL);
1046 #ifdef MBUF_DEBUG
1047 KASSERT(m->m_data == m->m_dat, ("mbuf %p: bad m_data in get", m));
1048 #endif
1049 m->m_len = 0;
1051 updatestats(m, type);
1052 return (m);
1055 struct mbuf *
1056 m_gethdr(int how, int type)
1058 struct mbuf *m;
1059 int ocf = MB_OCFLAG(how);
1060 int ntries = 0;
1062 retryonce:
1064 m = objcache_get(mbufphdr_cache, ocf);
1066 if (m == NULL) {
1067 if ((ocf & M_WAITOK) && ntries++ == 0) {
1068 struct objcache *reclaimlist[] = {
1069 mbuf_cache,
1070 mbufcluster_cache, mbufphdrcluster_cache,
1071 mbufjcluster_cache, mbufphdrjcluster_cache
1073 const int nreclaims = NELEM(reclaimlist);
1075 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
1076 m_reclaim();
1077 goto retryonce;
1079 ++mbstat[mycpu->gd_cpuid].m_drops;
1080 return (NULL);
1082 #ifdef MBUF_DEBUG
1083 KASSERT(m->m_data == m->m_pktdat, ("mbuf %p: bad m_data in get", m));
1084 #endif
1085 m->m_len = 0;
1086 m->m_pkthdr.len = 0;
1088 updatestats(m, type);
1089 return (m);
1093 * Get a mbuf (not a mbuf cluster!) and zero it.
1094 * Deprecated.
1096 struct mbuf *
1097 m_getclr(int how, int type)
1099 struct mbuf *m;
1101 m = m_get(how, type);
1102 if (m != NULL)
1103 bzero(m->m_data, MLEN);
1104 return (m);
1107 static struct mbuf *
1108 m_getcl_cache(int how, short type, int flags, struct objcache *mbclc,
1109 struct objcache *mbphclc, u_long *cl_stats)
1111 struct mbuf *m = NULL;
1112 int ocflags = MB_OCFLAG(how);
1113 int ntries = 0;
1115 retryonce:
1117 if (flags & M_PKTHDR)
1118 m = objcache_get(mbphclc, ocflags);
1119 else
1120 m = objcache_get(mbclc, ocflags);
1122 if (m == NULL) {
1123 if ((ocflags & M_WAITOK) && ntries++ == 0) {
1124 struct objcache *reclaimlist[1];
1126 if (flags & M_PKTHDR)
1127 reclaimlist[0] = mbclc;
1128 else
1129 reclaimlist[0] = mbphclc;
1130 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
1131 m_reclaim();
1132 goto retryonce;
1134 ++mbstat[mycpu->gd_cpuid].m_drops;
1135 return (NULL);
1138 #ifdef MBUF_DEBUG
1139 KASSERT(m->m_data == m->m_ext.ext_buf,
1140 ("mbuf %p: bad m_data in get", m));
1141 #endif
1142 m->m_type = type;
1143 m->m_len = 0;
1144 m->m_pkthdr.len = 0; /* just do it unconditonally */
1146 mbuftrack(m);
1148 ++mbtypes[mycpu->gd_cpuid].stats[type];
1149 ++(*cl_stats);
1150 return (m);
1153 struct mbuf *
1154 m_getjcl(int how, short type, int flags, size_t size)
1156 struct objcache *mbclc, *mbphclc;
1157 u_long *cl_stats;
1159 switch (size) {
1160 case MCLBYTES:
1161 mbclc = mbufcluster_cache;
1162 mbphclc = mbufphdrcluster_cache;
1163 cl_stats = &mbstat[mycpu->gd_cpuid].m_clusters;
1164 break;
1166 default:
1167 mbclc = mbufjcluster_cache;
1168 mbphclc = mbufphdrjcluster_cache;
1169 cl_stats = &mbstat[mycpu->gd_cpuid].m_jclusters;
1170 break;
1172 return m_getcl_cache(how, type, flags, mbclc, mbphclc, cl_stats);
1176 * Returns an mbuf with an attached cluster.
1177 * Because many network drivers use this kind of buffers a lot, it is
1178 * convenient to keep a small pool of free buffers of this kind.
1179 * Even a small size such as 10 gives about 10% improvement in the
1180 * forwarding rate in a bridge or router.
1182 struct mbuf *
1183 m_getcl(int how, short type, int flags)
1185 return m_getcl_cache(how, type, flags,
1186 mbufcluster_cache, mbufphdrcluster_cache,
1187 &mbstat[mycpu->gd_cpuid].m_clusters);
1191 * Allocate chain of requested length.
1193 struct mbuf *
1194 m_getc(int len, int how, int type)
1196 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
1197 int nsize;
1199 while (len > 0) {
1200 n = m_getl(len, how, type, 0, &nsize);
1201 if (n == NULL)
1202 goto failed;
1203 n->m_len = 0;
1204 *ntail = n;
1205 ntail = &n->m_next;
1206 len -= nsize;
1208 return (nfirst);
1210 failed:
1211 m_freem(nfirst);
1212 return (NULL);
1216 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
1217 * and return a pointer to the head of the allocated chain. If m0 is
1218 * non-null, then we assume that it is a single mbuf or an mbuf chain to
1219 * which we want len bytes worth of mbufs and/or clusters attached, and so
1220 * if we succeed in allocating it, we will just return a pointer to m0.
1222 * If we happen to fail at any point during the allocation, we will free
1223 * up everything we have already allocated and return NULL.
1225 * Deprecated. Use m_getc() and m_cat() instead.
1227 struct mbuf *
1228 m_getm(struct mbuf *m0, int len, int type, int how)
1230 struct mbuf *nfirst;
1232 nfirst = m_getc(len, how, type);
1234 if (m0 != NULL) {
1235 m_last(m0)->m_next = nfirst;
1236 return (m0);
1239 return (nfirst);
1243 * Adds a cluster to a normal mbuf, M_EXT is set on success.
1244 * Deprecated. Use m_getcl() instead.
1246 void
1247 m_mclget(struct mbuf *m, int how)
1249 struct mbcluster *mcl;
1251 KKASSERT((m->m_flags & M_EXT) == 0);
1252 mcl = objcache_get(mclmeta_cache, MB_OCFLAG(how));
1253 if (mcl != NULL) {
1254 linkcluster(m, mcl);
1255 ++mbstat[mycpu->gd_cpuid].m_clusters;
1256 } else {
1257 ++mbstat[mycpu->gd_cpuid].m_drops;
1262 * Updates to mbcluster must be MPSAFE. Only an entity which already has
1263 * a reference to the cluster can ref it, so we are in no danger of
1264 * racing an add with a subtract. But the operation must still be atomic
1265 * since multiple entities may have a reference on the cluster.
1267 * m_mclfree() is almost the same but it must contend with two entities
1268 * freeing the cluster at the same time.
1270 static void
1271 m_mclref(void *arg)
1273 struct mbcluster *mcl = arg;
1275 atomic_add_int(&mcl->mcl_refs, 1);
1279 * When dereferencing a cluster we have to deal with a N->0 race, where
1280 * N entities free their references simultaniously. To do this we use
1281 * atomic_fetchadd_int().
1283 static void
1284 m_mclfree(void *arg)
1286 struct mbcluster *mcl = arg;
1288 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1289 --mbstat[mycpu->gd_cpuid].m_clusters;
1290 objcache_put(mclmeta_cache, mcl);
1294 static void
1295 m_mjclfree(void *arg)
1297 struct mbcluster *mcl = arg;
1299 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1300 --mbstat[mycpu->gd_cpuid].m_jclusters;
1301 objcache_put(mjclmeta_cache, mcl);
1306 * Free a single mbuf and any associated external storage. The successor,
1307 * if any, is returned.
1309 * We do need to check non-first mbuf for m_aux, since some of existing
1310 * code does not call M_PREPEND properly.
1311 * (example: call to bpf_mtap from drivers)
1314 #ifdef MBUF_DEBUG
1316 struct mbuf *
1317 _m_free(struct mbuf *m, const char *func)
1319 #else
1321 struct mbuf *
1322 m_free(struct mbuf *m)
1324 #endif
1326 struct mbuf *n;
1327 struct globaldata *gd = mycpu;
1329 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
1330 KASSERT(M_TRAILINGSPACE(m) >= 0, ("overflowed mbuf %p", m));
1331 --mbtypes[gd->gd_cpuid].stats[m->m_type];
1333 n = m->m_next;
1336 * Make sure the mbuf is in constructed state before returning it
1337 * to the objcache.
1339 m->m_next = NULL;
1340 mbufuntrack(m);
1341 #ifdef MBUF_DEBUG
1342 m->m_hdr.mh_lastfunc = func;
1343 #endif
1344 #ifdef notyet
1345 KKASSERT(m->m_nextpkt == NULL);
1346 #else
1347 if (m->m_nextpkt != NULL) {
1348 static int afewtimes = 10;
1350 if (afewtimes-- > 0) {
1351 kprintf("mfree: m->m_nextpkt != NULL\n");
1352 print_backtrace(-1);
1354 m->m_nextpkt = NULL;
1356 #endif
1357 if (m->m_flags & M_PKTHDR) {
1358 m_tag_delete_chain(m); /* eliminate XXX JH */
1361 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
1364 * Clean the M_PKTHDR state so we can return the mbuf to its original
1365 * cache. This is based on the PHCACHE flag which tells us whether
1366 * the mbuf was originally allocated out of a packet-header cache
1367 * or a non-packet-header cache.
1369 if (m->m_flags & M_PHCACHE) {
1370 m->m_flags |= M_PKTHDR;
1371 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
1372 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
1373 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
1374 SLIST_INIT(&m->m_pkthdr.tags);
1378 * Handle remaining flags combinations. M_CLCACHE tells us whether
1379 * the mbuf was originally allocated from a cluster cache or not,
1380 * and is totally separate from whether the mbuf is currently
1381 * associated with a cluster.
1383 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
1384 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
1386 * mbuf+cluster cache case. The mbuf was allocated from the
1387 * combined mbuf_cluster cache and can be returned to the
1388 * cache if the cluster hasn't been shared.
1390 if (m_sharecount(m) == 1) {
1392 * The cluster has not been shared, we can just
1393 * reset the data pointer and return the mbuf
1394 * to the cluster cache. Note that the reference
1395 * count is left intact (it is still associated with
1396 * an mbuf).
1398 m->m_data = m->m_ext.ext_buf;
1399 if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES) {
1400 if (m->m_flags & M_PHCACHE)
1401 objcache_put(mbufphdrjcluster_cache, m);
1402 else
1403 objcache_put(mbufjcluster_cache, m);
1404 --mbstat[mycpu->gd_cpuid].m_jclusters;
1405 } else {
1406 if (m->m_flags & M_PHCACHE)
1407 objcache_put(mbufphdrcluster_cache, m);
1408 else
1409 objcache_put(mbufcluster_cache, m);
1410 --mbstat[mycpu->gd_cpuid].m_clusters;
1412 } else {
1414 * Hell. Someone else has a ref on this cluster,
1415 * we have to disconnect it which means we can't
1416 * put it back into the mbufcluster_cache, we
1417 * have to destroy the mbuf.
1419 * Other mbuf references to the cluster will typically
1420 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
1422 * XXX we could try to connect another cluster to
1423 * it.
1425 m->m_ext.ext_free(m->m_ext.ext_arg);
1426 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1427 if (m->m_ext.ext_size == MCLBYTES) {
1428 if (m->m_flags & M_PHCACHE)
1429 objcache_dtor(mbufphdrcluster_cache, m);
1430 else
1431 objcache_dtor(mbufcluster_cache, m);
1432 } else {
1433 if (m->m_flags & M_PHCACHE)
1434 objcache_dtor(mbufphdrjcluster_cache, m);
1435 else
1436 objcache_dtor(mbufjcluster_cache, m);
1439 break;
1440 case M_EXT | M_EXT_CLUSTER:
1441 case M_EXT:
1443 * Normal cluster association case, disconnect the cluster from
1444 * the mbuf. The cluster may or may not be custom.
1446 m->m_ext.ext_free(m->m_ext.ext_arg);
1447 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1448 /* fall through */
1449 case 0:
1451 * return the mbuf to the mbuf cache.
1453 if (m->m_flags & M_PHCACHE) {
1454 m->m_data = m->m_pktdat;
1455 objcache_put(mbufphdr_cache, m);
1456 } else {
1457 m->m_data = m->m_dat;
1458 objcache_put(mbuf_cache, m);
1460 --mbstat[mycpu->gd_cpuid].m_mbufs;
1461 break;
1462 default:
1463 if (!panicstr)
1464 panic("bad mbuf flags %p %08x", m, m->m_flags);
1465 break;
1467 return (n);
1470 #ifdef MBUF_DEBUG
1472 void
1473 _m_freem(struct mbuf *m, const char *func)
1475 while (m)
1476 m = _m_free(m, func);
1479 #else
1481 void
1482 m_freem(struct mbuf *m)
1484 while (m)
1485 m = m_free(m);
1488 #endif
1490 void
1491 m_extadd(struct mbuf *m, caddr_t buf, u_int size, void (*reff)(void *),
1492 void (*freef)(void *), void *arg)
1494 m->m_ext.ext_arg = arg;
1495 m->m_ext.ext_buf = buf;
1496 m->m_ext.ext_ref = reff;
1497 m->m_ext.ext_free = freef;
1498 m->m_ext.ext_size = size;
1499 reff(arg);
1500 m->m_data = buf;
1501 m->m_flags |= M_EXT;
1505 * mbuf utility routines
1509 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1510 * copy junk along.
1512 struct mbuf *
1513 m_prepend(struct mbuf *m, int len, int how)
1515 struct mbuf *mn;
1517 if (m->m_flags & M_PKTHDR)
1518 mn = m_gethdr(how, m->m_type);
1519 else
1520 mn = m_get(how, m->m_type);
1521 if (mn == NULL) {
1522 m_freem(m);
1523 return (NULL);
1525 if (m->m_flags & M_PKTHDR)
1526 M_MOVE_PKTHDR(mn, m);
1527 mn->m_next = m;
1528 m = mn;
1529 if (len < MHLEN)
1530 MH_ALIGN(m, len);
1531 m->m_len = len;
1532 return (m);
1536 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1537 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
1538 * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
1539 * Note that the copy is read-only, because clusters are not copied,
1540 * only their reference counts are incremented.
1542 struct mbuf *
1543 m_copym(const struct mbuf *m, int off0, int len, int wait)
1545 struct mbuf *n, **np;
1546 int off = off0;
1547 struct mbuf *top;
1548 int copyhdr = 0;
1550 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1551 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1552 if (off == 0 && (m->m_flags & M_PKTHDR))
1553 copyhdr = 1;
1554 while (off > 0) {
1555 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1556 if (off < m->m_len)
1557 break;
1558 off -= m->m_len;
1559 m = m->m_next;
1561 np = &top;
1562 top = NULL;
1563 while (len > 0) {
1564 if (m == NULL) {
1565 KASSERT(len == M_COPYALL,
1566 ("m_copym, length > size of mbuf chain"));
1567 break;
1570 * Because we are sharing any cluster attachment below,
1571 * be sure to get an mbuf that does not have a cluster
1572 * associated with it.
1574 if (copyhdr)
1575 n = m_gethdr(wait, m->m_type);
1576 else
1577 n = m_get(wait, m->m_type);
1578 *np = n;
1579 if (n == NULL)
1580 goto nospace;
1581 if (copyhdr) {
1582 if (!m_dup_pkthdr(n, m, wait))
1583 goto nospace;
1584 if (len == M_COPYALL)
1585 n->m_pkthdr.len -= off0;
1586 else
1587 n->m_pkthdr.len = len;
1588 copyhdr = 0;
1590 n->m_len = min(len, m->m_len - off);
1591 if (m->m_flags & M_EXT) {
1592 KKASSERT((n->m_flags & M_EXT) == 0);
1593 n->m_data = m->m_data + off;
1594 m->m_ext.ext_ref(m->m_ext.ext_arg);
1595 n->m_ext = m->m_ext;
1596 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1597 } else {
1598 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1599 (unsigned)n->m_len);
1601 if (len != M_COPYALL)
1602 len -= n->m_len;
1603 off = 0;
1604 m = m->m_next;
1605 np = &n->m_next;
1607 if (top == NULL)
1608 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1609 return (top);
1610 nospace:
1611 m_freem(top);
1612 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1613 return (NULL);
1617 * Copy an entire packet, including header (which must be present).
1618 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1619 * Note that the copy is read-only, because clusters are not copied,
1620 * only their reference counts are incremented.
1621 * Preserve alignment of the first mbuf so if the creator has left
1622 * some room at the beginning (e.g. for inserting protocol headers)
1623 * the copies also have the room available.
1625 struct mbuf *
1626 m_copypacket(struct mbuf *m, int how)
1628 struct mbuf *top, *n, *o;
1630 n = m_gethdr(how, m->m_type);
1631 top = n;
1632 if (!n)
1633 goto nospace;
1635 if (!m_dup_pkthdr(n, m, how))
1636 goto nospace;
1637 n->m_len = m->m_len;
1638 if (m->m_flags & M_EXT) {
1639 KKASSERT((n->m_flags & M_EXT) == 0);
1640 n->m_data = m->m_data;
1641 m->m_ext.ext_ref(m->m_ext.ext_arg);
1642 n->m_ext = m->m_ext;
1643 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1644 } else {
1645 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1646 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1649 m = m->m_next;
1650 while (m) {
1651 o = m_get(how, m->m_type);
1652 if (!o)
1653 goto nospace;
1655 n->m_next = o;
1656 n = n->m_next;
1658 n->m_len = m->m_len;
1659 if (m->m_flags & M_EXT) {
1660 KKASSERT((n->m_flags & M_EXT) == 0);
1661 n->m_data = m->m_data;
1662 m->m_ext.ext_ref(m->m_ext.ext_arg);
1663 n->m_ext = m->m_ext;
1664 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1665 } else {
1666 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1669 m = m->m_next;
1671 return top;
1672 nospace:
1673 m_freem(top);
1674 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1675 return (NULL);
1679 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1680 * continuing for "len" bytes, into the indicated buffer.
1682 void
1683 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1685 unsigned count;
1687 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1688 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1689 while (off > 0) {
1690 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1691 if (off < m->m_len)
1692 break;
1693 off -= m->m_len;
1694 m = m->m_next;
1696 while (len > 0) {
1697 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1698 count = min(m->m_len - off, len);
1699 bcopy(mtod(m, caddr_t) + off, cp, count);
1700 len -= count;
1701 cp += count;
1702 off = 0;
1703 m = m->m_next;
1708 * Copy a packet header mbuf chain into a completely new chain, including
1709 * copying any mbuf clusters. Use this instead of m_copypacket() when
1710 * you need a writable copy of an mbuf chain.
1712 struct mbuf *
1713 m_dup(struct mbuf *m, int how)
1715 struct mbuf **p, *top = NULL;
1716 int remain, moff, nsize;
1718 /* Sanity check */
1719 if (m == NULL)
1720 return (NULL);
1721 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1723 /* While there's more data, get a new mbuf, tack it on, and fill it */
1724 remain = m->m_pkthdr.len;
1725 moff = 0;
1726 p = &top;
1727 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1728 struct mbuf *n;
1730 /* Get the next new mbuf */
1731 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1732 &nsize);
1733 if (n == NULL)
1734 goto nospace;
1735 if (top == NULL)
1736 if (!m_dup_pkthdr(n, m, how))
1737 goto nospace0;
1739 /* Link it into the new chain */
1740 *p = n;
1741 p = &n->m_next;
1743 /* Copy data from original mbuf(s) into new mbuf */
1744 n->m_len = 0;
1745 while (n->m_len < nsize && m != NULL) {
1746 int chunk = min(nsize - n->m_len, m->m_len - moff);
1748 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1749 moff += chunk;
1750 n->m_len += chunk;
1751 remain -= chunk;
1752 if (moff == m->m_len) {
1753 m = m->m_next;
1754 moff = 0;
1758 /* Check correct total mbuf length */
1759 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1760 ("%s: bogus m_pkthdr.len", __func__));
1762 return (top);
1764 nospace:
1765 m_freem(top);
1766 nospace0:
1767 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1768 return (NULL);
1772 * Copy the non-packet mbuf data chain into a new set of mbufs, including
1773 * copying any mbuf clusters. This is typically used to realign a data
1774 * chain by nfs_realign().
1776 * The original chain is left intact. how should be M_WAITOK or M_NOWAIT
1777 * and NULL can be returned if M_NOWAIT is passed.
1779 * Be careful to use cluster mbufs, a large mbuf chain converted to non
1780 * cluster mbufs can exhaust our supply of mbufs.
1782 struct mbuf *
1783 m_dup_data(struct mbuf *m, int how)
1785 struct mbuf **p, *n, *top = NULL;
1786 int mlen, moff, chunk, gsize, nsize;
1789 * Degenerate case
1791 if (m == NULL)
1792 return (NULL);
1795 * Optimize the mbuf allocation but do not get too carried away.
1797 if (m->m_next || m->m_len > MLEN)
1798 if (m->m_flags & M_EXT && m->m_ext.ext_size == MCLBYTES)
1799 gsize = MCLBYTES;
1800 else
1801 gsize = MJUMPAGESIZE;
1802 else
1803 gsize = MLEN;
1805 /* Chain control */
1806 p = &top;
1807 n = NULL;
1808 nsize = 0;
1811 * Scan the mbuf chain until nothing is left, the new mbuf chain
1812 * will be allocated on the fly as needed.
1814 while (m) {
1815 mlen = m->m_len;
1816 moff = 0;
1818 while (mlen) {
1819 KKASSERT(m->m_type == MT_DATA);
1820 if (n == NULL) {
1821 n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1822 n->m_len = 0;
1823 if (n == NULL)
1824 goto nospace;
1825 *p = n;
1826 p = &n->m_next;
1828 chunk = imin(mlen, nsize);
1829 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1830 mlen -= chunk;
1831 moff += chunk;
1832 n->m_len += chunk;
1833 nsize -= chunk;
1834 if (nsize == 0)
1835 n = NULL;
1837 m = m->m_next;
1839 *p = NULL;
1840 return(top);
1841 nospace:
1842 *p = NULL;
1843 m_freem(top);
1844 ++mbstat[mycpu->gd_cpuid].m_mcfail;
1845 return (NULL);
1849 * Concatenate mbuf chain n to m.
1850 * Both chains must be of the same type (e.g. MT_DATA).
1851 * Any m_pkthdr is not updated.
1853 void
1854 m_cat(struct mbuf *m, struct mbuf *n)
1856 m = m_last(m);
1857 while (n) {
1858 if (m->m_flags & M_EXT ||
1859 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1860 /* just join the two chains */
1861 m->m_next = n;
1862 return;
1864 /* splat the data from one into the other */
1865 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1866 (u_int)n->m_len);
1867 m->m_len += n->m_len;
1868 n = m_free(n);
1872 void
1873 m_adj(struct mbuf *mp, int req_len)
1875 int len = req_len;
1876 struct mbuf *m;
1877 int count;
1879 if ((m = mp) == NULL)
1880 return;
1881 if (len >= 0) {
1883 * Trim from head.
1885 while (m != NULL && len > 0) {
1886 if (m->m_len <= len) {
1887 len -= m->m_len;
1888 m->m_len = 0;
1889 m = m->m_next;
1890 } else {
1891 m->m_len -= len;
1892 m->m_data += len;
1893 len = 0;
1896 m = mp;
1897 if (mp->m_flags & M_PKTHDR)
1898 m->m_pkthdr.len -= (req_len - len);
1899 } else {
1901 * Trim from tail. Scan the mbuf chain,
1902 * calculating its length and finding the last mbuf.
1903 * If the adjustment only affects this mbuf, then just
1904 * adjust and return. Otherwise, rescan and truncate
1905 * after the remaining size.
1907 len = -len;
1908 count = 0;
1909 for (;;) {
1910 count += m->m_len;
1911 if (m->m_next == NULL)
1912 break;
1913 m = m->m_next;
1915 if (m->m_len >= len) {
1916 m->m_len -= len;
1917 if (mp->m_flags & M_PKTHDR)
1918 mp->m_pkthdr.len -= len;
1919 return;
1921 count -= len;
1922 if (count < 0)
1923 count = 0;
1925 * Correct length for chain is "count".
1926 * Find the mbuf with last data, adjust its length,
1927 * and toss data from remaining mbufs on chain.
1929 m = mp;
1930 if (m->m_flags & M_PKTHDR)
1931 m->m_pkthdr.len = count;
1932 for (; m; m = m->m_next) {
1933 if (m->m_len >= count) {
1934 m->m_len = count;
1935 break;
1937 count -= m->m_len;
1939 while (m->m_next)
1940 (m = m->m_next) ->m_len = 0;
1945 * Set the m_data pointer of a newly-allocated mbuf
1946 * to place an object of the specified size at the
1947 * end of the mbuf, longword aligned.
1949 void
1950 m_align(struct mbuf *m, int len)
1952 int adjust;
1954 if (m->m_flags & M_EXT)
1955 adjust = m->m_ext.ext_size - len;
1956 else if (m->m_flags & M_PKTHDR)
1957 adjust = MHLEN - len;
1958 else
1959 adjust = MLEN - len;
1960 m->m_data += rounddown2(adjust, sizeof(long));
1964 * Create a writable copy of the mbuf chain. While doing this
1965 * we compact the chain with a goal of producing a chain with
1966 * at most two mbufs. The second mbuf in this chain is likely
1967 * to be a cluster. The primary purpose of this work is to create
1968 * a writable packet for encryption, compression, etc. The
1969 * secondary goal is to linearize the data so the data can be
1970 * passed to crypto hardware in the most efficient manner possible.
1972 struct mbuf *
1973 m_unshare(struct mbuf *m0, int how)
1975 struct mbuf *m, *mprev;
1976 struct mbuf *n, *mfirst, *mlast;
1977 int len, off;
1979 mprev = NULL;
1980 for (m = m0; m != NULL; m = mprev->m_next) {
1982 * Regular mbufs are ignored unless there's a cluster
1983 * in front of it that we can use to coalesce. We do
1984 * the latter mainly so later clusters can be coalesced
1985 * also w/o having to handle them specially (i.e. convert
1986 * mbuf+cluster -> cluster). This optimization is heavily
1987 * influenced by the assumption that we're running over
1988 * Ethernet where MCLBYTES is large enough that the max
1989 * packet size will permit lots of coalescing into a
1990 * single cluster. This in turn permits efficient
1991 * crypto operations, especially when using hardware.
1993 if ((m->m_flags & M_EXT) == 0) {
1994 if (mprev && (mprev->m_flags & M_EXT) &&
1995 m->m_len <= M_TRAILINGSPACE(mprev)) {
1996 /* XXX: this ignores mbuf types */
1997 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1998 mtod(m, caddr_t), m->m_len);
1999 mprev->m_len += m->m_len;
2000 mprev->m_next = m->m_next; /* unlink from chain */
2001 m_free(m); /* reclaim mbuf */
2002 } else {
2003 mprev = m;
2005 continue;
2008 * Writable mbufs are left alone (for now).
2010 if (M_WRITABLE(m)) {
2011 mprev = m;
2012 continue;
2016 * Not writable, replace with a copy or coalesce with
2017 * the previous mbuf if possible (since we have to copy
2018 * it anyway, we try to reduce the number of mbufs and
2019 * clusters so that future work is easier).
2021 KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
2022 /* NB: we only coalesce into a cluster or larger */
2023 if (mprev != NULL && (mprev->m_flags & M_EXT) &&
2024 m->m_len <= M_TRAILINGSPACE(mprev)) {
2025 /* XXX: this ignores mbuf types */
2026 memcpy(mtod(mprev, caddr_t) + mprev->m_len,
2027 mtod(m, caddr_t), m->m_len);
2028 mprev->m_len += m->m_len;
2029 mprev->m_next = m->m_next; /* unlink from chain */
2030 m_free(m); /* reclaim mbuf */
2031 continue;
2035 * Allocate new space to hold the copy...
2037 /* XXX why can M_PKTHDR be set past the first mbuf? */
2038 if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
2040 * NB: if a packet header is present we must
2041 * allocate the mbuf separately from any cluster
2042 * because M_MOVE_PKTHDR will smash the data
2043 * pointer and drop the M_EXT marker.
2045 MGETHDR(n, how, m->m_type);
2046 if (n == NULL) {
2047 m_freem(m0);
2048 return (NULL);
2050 M_MOVE_PKTHDR(n, m);
2051 MCLGET(n, how);
2052 if ((n->m_flags & M_EXT) == 0) {
2053 m_free(n);
2054 m_freem(m0);
2055 return (NULL);
2057 } else {
2058 n = m_getcl(how, m->m_type, m->m_flags);
2059 if (n == NULL) {
2060 m_freem(m0);
2061 return (NULL);
2065 * ... and copy the data. We deal with jumbo mbufs
2066 * (i.e. m_len > MCLBYTES) by splitting them into
2067 * clusters. We could just malloc a buffer and make
2068 * it external but too many device drivers don't know
2069 * how to break up the non-contiguous memory when
2070 * doing DMA.
2072 len = m->m_len;
2073 off = 0;
2074 mfirst = n;
2075 mlast = NULL;
2076 for (;;) {
2077 int cc = min(len, MCLBYTES);
2078 memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
2079 n->m_len = cc;
2080 if (mlast != NULL)
2081 mlast->m_next = n;
2082 mlast = n;
2084 len -= cc;
2085 if (len <= 0)
2086 break;
2087 off += cc;
2089 n = m_getcl(how, m->m_type, m->m_flags);
2090 if (n == NULL) {
2091 m_freem(mfirst);
2092 m_freem(m0);
2093 return (NULL);
2096 n->m_next = m->m_next;
2097 if (mprev == NULL)
2098 m0 = mfirst; /* new head of chain */
2099 else
2100 mprev->m_next = mfirst; /* replace old mbuf */
2101 m_free(m); /* release old mbuf */
2102 mprev = mfirst;
2104 return (m0);
2108 * Rearrange an mbuf chain so that len bytes are contiguous
2109 * and in the data area of an mbuf (so that mtod will work for a structure
2110 * of size len). Returns the resulting mbuf chain on success, frees it and
2111 * returns null on failure. If there is room, it will add up to
2112 * max_protohdr-len extra bytes to the contiguous region in an attempt to
2113 * avoid being called next time.
2115 struct mbuf *
2116 m_pullup(struct mbuf *n, int len)
2118 struct mbuf *m;
2119 int count;
2120 int space;
2123 * If first mbuf has no cluster, and has room for len bytes
2124 * without shifting current data, pullup into it,
2125 * otherwise allocate a new mbuf to prepend to the chain.
2127 if (!(n->m_flags & M_EXT) &&
2128 n->m_data + len < &n->m_dat[MLEN] &&
2129 n->m_next) {
2130 if (n->m_len >= len)
2131 return (n);
2132 m = n;
2133 n = n->m_next;
2134 len -= m->m_len;
2135 } else {
2136 if (len > MHLEN)
2137 goto bad;
2138 if (n->m_flags & M_PKTHDR)
2139 m = m_gethdr(M_NOWAIT, n->m_type);
2140 else
2141 m = m_get(M_NOWAIT, n->m_type);
2142 if (m == NULL)
2143 goto bad;
2144 m->m_len = 0;
2145 if (n->m_flags & M_PKTHDR)
2146 M_MOVE_PKTHDR(m, n);
2148 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
2149 do {
2150 count = min(min(max(len, max_protohdr), space), n->m_len);
2151 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
2152 (unsigned)count);
2153 len -= count;
2154 m->m_len += count;
2155 n->m_len -= count;
2156 space -= count;
2157 if (n->m_len)
2158 n->m_data += count;
2159 else
2160 n = m_free(n);
2161 } while (len > 0 && n);
2162 if (len > 0) {
2163 m_free(m);
2164 goto bad;
2166 m->m_next = n;
2167 return (m);
2168 bad:
2169 m_freem(n);
2170 ++mbstat[mycpu->gd_cpuid].m_mcfail;
2171 return (NULL);
2175 * Partition an mbuf chain in two pieces, returning the tail --
2176 * all but the first len0 bytes. In case of failure, it returns NULL and
2177 * attempts to restore the chain to its original state.
2179 * Note that the resulting mbufs might be read-only, because the new
2180 * mbuf can end up sharing an mbuf cluster with the original mbuf if
2181 * the "breaking point" happens to lie within a cluster mbuf. Use the
2182 * M_WRITABLE() macro to check for this case.
2184 struct mbuf *
2185 m_split(struct mbuf *m0, int len0, int wait)
2187 struct mbuf *m, *n;
2188 unsigned len = len0, remain;
2190 for (m = m0; m && len > m->m_len; m = m->m_next)
2191 len -= m->m_len;
2192 if (m == NULL)
2193 return (NULL);
2194 remain = m->m_len - len;
2195 if (m0->m_flags & M_PKTHDR) {
2196 n = m_gethdr(wait, m0->m_type);
2197 if (n == NULL)
2198 return (NULL);
2199 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
2200 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
2201 m0->m_pkthdr.len = len0;
2202 if (m->m_flags & M_EXT)
2203 goto extpacket;
2204 if (remain > MHLEN) {
2205 /* m can't be the lead packet */
2206 MH_ALIGN(n, 0);
2207 n->m_next = m_split(m, len, wait);
2208 if (n->m_next == NULL) {
2209 m_free(n);
2210 return (NULL);
2211 } else {
2212 n->m_len = 0;
2213 return (n);
2215 } else
2216 MH_ALIGN(n, remain);
2217 } else if (remain == 0) {
2218 n = m->m_next;
2219 m->m_next = NULL;
2220 return (n);
2221 } else {
2222 n = m_get(wait, m->m_type);
2223 if (n == NULL)
2224 return (NULL);
2225 M_ALIGN(n, remain);
2227 extpacket:
2228 if (m->m_flags & M_EXT) {
2229 KKASSERT((n->m_flags & M_EXT) == 0);
2230 n->m_data = m->m_data + len;
2231 m->m_ext.ext_ref(m->m_ext.ext_arg);
2232 n->m_ext = m->m_ext;
2233 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
2234 } else {
2235 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
2237 n->m_len = remain;
2238 m->m_len = len;
2239 n->m_next = m->m_next;
2240 m->m_next = NULL;
2241 return (n);
2245 * Routine to copy from device local memory into mbufs.
2246 * Note: "offset" is ill-defined and always called as 0, so ignore it.
2248 struct mbuf *
2249 m_devget(char *buf, int len, int offset, struct ifnet *ifp)
2251 struct mbuf *m, *mfirst = NULL, **mtail;
2252 int nsize, flags;
2254 mtail = &mfirst;
2255 flags = M_PKTHDR;
2257 while (len > 0) {
2258 m = m_getl(len, M_NOWAIT, MT_DATA, flags, &nsize);
2259 if (m == NULL) {
2260 m_freem(mfirst);
2261 return (NULL);
2263 m->m_len = min(len, nsize);
2265 if (flags & M_PKTHDR) {
2266 if (len + max_linkhdr <= nsize)
2267 m->m_data += max_linkhdr;
2268 m->m_pkthdr.rcvif = ifp;
2269 m->m_pkthdr.len = len;
2270 flags = 0;
2273 bcopy(buf, m->m_data, (unsigned)m->m_len);
2274 buf += m->m_len;
2275 len -= m->m_len;
2276 *mtail = m;
2277 mtail = &m->m_next;
2280 return (mfirst);
2284 * Routine to pad mbuf to the specified length 'padto'.
2287 m_devpad(struct mbuf *m, int padto)
2289 struct mbuf *last = NULL;
2290 int padlen;
2292 if (padto <= m->m_pkthdr.len)
2293 return 0;
2295 padlen = padto - m->m_pkthdr.len;
2297 /* if there's only the packet-header and we can pad there, use it. */
2298 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
2299 last = m;
2300 } else {
2302 * Walk packet chain to find last mbuf. We will either
2303 * pad there, or append a new mbuf and pad it
2305 for (last = m; last->m_next != NULL; last = last->m_next)
2306 ; /* EMPTY */
2308 /* `last' now points to last in chain. */
2309 if (M_TRAILINGSPACE(last) < padlen) {
2310 struct mbuf *n;
2312 /* Allocate new empty mbuf, pad it. Compact later. */
2313 MGET(n, M_NOWAIT, MT_DATA);
2314 if (n == NULL)
2315 return ENOBUFS;
2316 n->m_len = 0;
2317 last->m_next = n;
2318 last = n;
2321 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2322 KKASSERT(M_WRITABLE(last));
2324 /* Now zero the pad area */
2325 bzero(mtod(last, char *) + last->m_len, padlen);
2326 last->m_len += padlen;
2327 m->m_pkthdr.len += padlen;
2328 return 0;
2332 * Copy data from a buffer back into the indicated mbuf chain,
2333 * starting "off" bytes from the beginning, extending the mbuf
2334 * chain if necessary.
2336 void
2337 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
2339 int mlen;
2340 struct mbuf *m = m0, *n;
2341 int totlen = 0;
2343 if (m0 == NULL)
2344 return;
2345 while (off > (mlen = m->m_len)) {
2346 off -= mlen;
2347 totlen += mlen;
2348 if (m->m_next == NULL) {
2349 n = m_getclr(M_NOWAIT, m->m_type);
2350 if (n == NULL)
2351 goto out;
2352 n->m_len = min(MLEN, len + off);
2353 m->m_next = n;
2355 m = m->m_next;
2357 while (len > 0) {
2358 mlen = min (m->m_len - off, len);
2359 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
2360 cp += mlen;
2361 len -= mlen;
2362 mlen += off;
2363 off = 0;
2364 totlen += mlen;
2365 if (len == 0)
2366 break;
2367 if (m->m_next == NULL) {
2368 n = m_get(M_NOWAIT, m->m_type);
2369 if (n == NULL)
2370 break;
2371 n->m_len = min(MLEN, len);
2372 m->m_next = n;
2374 m = m->m_next;
2376 out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
2377 m->m_pkthdr.len = totlen;
2381 * Append the specified data to the indicated mbuf chain,
2382 * Extend the mbuf chain if the new data does not fit in
2383 * existing space.
2385 * Return 1 if able to complete the job; otherwise 0.
2388 m_append(struct mbuf *m0, int len, c_caddr_t cp)
2390 struct mbuf *m, *n;
2391 int remainder, space;
2393 for (m = m0; m->m_next != NULL; m = m->m_next)
2395 remainder = len;
2396 space = M_TRAILINGSPACE(m);
2397 if (space > 0) {
2399 * Copy into available space.
2401 if (space > remainder)
2402 space = remainder;
2403 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
2404 m->m_len += space;
2405 cp += space, remainder -= space;
2407 while (remainder > 0) {
2409 * Allocate a new mbuf; could check space
2410 * and allocate a cluster instead.
2412 n = m_get(M_NOWAIT, m->m_type);
2413 if (n == NULL)
2414 break;
2415 n->m_len = min(MLEN, remainder);
2416 bcopy(cp, mtod(n, caddr_t), n->m_len);
2417 cp += n->m_len, remainder -= n->m_len;
2418 m->m_next = n;
2419 m = n;
2421 if (m0->m_flags & M_PKTHDR)
2422 m0->m_pkthdr.len += len - remainder;
2423 return (remainder == 0);
2427 * Apply function f to the data in an mbuf chain starting "off" bytes from
2428 * the beginning, continuing for "len" bytes.
2431 m_apply(struct mbuf *m, int off, int len,
2432 int (*f)(void *, void *, u_int), void *arg)
2434 u_int count;
2435 int rval;
2437 KASSERT(off >= 0, ("m_apply, negative off %d", off));
2438 KASSERT(len >= 0, ("m_apply, negative len %d", len));
2439 while (off > 0) {
2440 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2441 if (off < m->m_len)
2442 break;
2443 off -= m->m_len;
2444 m = m->m_next;
2446 while (len > 0) {
2447 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2448 count = min(m->m_len - off, len);
2449 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
2450 if (rval)
2451 return (rval);
2452 len -= count;
2453 off = 0;
2454 m = m->m_next;
2456 return (0);
2460 * Return a pointer to mbuf/offset of location in mbuf chain.
2462 struct mbuf *
2463 m_getptr(struct mbuf *m, int loc, int *off)
2466 while (loc >= 0) {
2467 /* Normal end of search. */
2468 if (m->m_len > loc) {
2469 *off = loc;
2470 return (m);
2471 } else {
2472 loc -= m->m_len;
2473 if (m->m_next == NULL) {
2474 if (loc == 0) {
2475 /* Point at the end of valid data. */
2476 *off = m->m_len;
2477 return (m);
2479 return (NULL);
2481 m = m->m_next;
2484 return (NULL);
2487 void
2488 m_print(const struct mbuf *m)
2490 int len;
2491 const struct mbuf *m2;
2492 char *hexstr;
2494 len = m->m_pkthdr.len;
2495 m2 = m;
2496 hexstr = kmalloc(HEX_NCPYLEN(len), M_TEMP, M_ZERO | M_WAITOK);
2497 while (len) {
2498 kprintf("%p %s\n", m2, hexncpy(m2->m_data, m2->m_len, hexstr,
2499 HEX_NCPYLEN(m2->m_len), "-"));
2500 len -= m2->m_len;
2501 m2 = m2->m_next;
2503 kfree(hexstr, M_TEMP);
2504 return;
2508 * "Move" mbuf pkthdr from "from" to "to".
2509 * "from" must have M_PKTHDR set, and "to" must be empty.
2511 void
2512 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
2514 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
2516 to->m_flags |= from->m_flags & M_COPYFLAGS;
2517 to->m_pkthdr = from->m_pkthdr; /* especially tags */
2518 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
2522 * Duplicate "from"'s mbuf pkthdr in "to".
2523 * "from" must have M_PKTHDR set, and "to" must be empty.
2524 * In particular, this does a deep copy of the packet tags.
2527 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
2529 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
2531 to->m_flags = (from->m_flags & M_COPYFLAGS) |
2532 (to->m_flags & ~M_COPYFLAGS);
2533 to->m_pkthdr = from->m_pkthdr;
2534 SLIST_INIT(&to->m_pkthdr.tags);
2535 return (m_tag_copy_chain(to, from, how));
2539 * Defragment a mbuf chain, returning the shortest possible
2540 * chain of mbufs and clusters. If allocation fails and
2541 * this cannot be completed, NULL will be returned, but
2542 * the passed in chain will be unchanged. Upon success,
2543 * the original chain will be freed, and the new chain
2544 * will be returned.
2546 * If a non-packet header is passed in, the original
2547 * mbuf (chain?) will be returned unharmed.
2549 * m_defrag_nofree doesn't free the passed in mbuf.
2551 struct mbuf *
2552 m_defrag(struct mbuf *m0, int how)
2554 struct mbuf *m_new;
2556 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
2557 return (NULL);
2558 if (m_new != m0)
2559 m_freem(m0);
2560 return (m_new);
2563 struct mbuf *
2564 m_defrag_nofree(struct mbuf *m0, int how)
2566 struct mbuf *m_new = NULL, *m_final = NULL;
2567 int progress = 0, length, nsize;
2569 if (!(m0->m_flags & M_PKTHDR))
2570 return (m0);
2572 #ifdef MBUF_STRESS_TEST
2573 if (m_defragrandomfailures) {
2574 int temp = karc4random() & 0xff;
2575 if (temp == 0xba)
2576 goto nospace;
2578 #endif
2580 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
2581 if (m_final == NULL)
2582 goto nospace;
2583 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
2585 if (m_dup_pkthdr(m_final, m0, how) == 0)
2586 goto nospace;
2588 m_new = m_final;
2590 while (progress < m0->m_pkthdr.len) {
2591 length = m0->m_pkthdr.len - progress;
2592 if (length > MCLBYTES)
2593 length = MCLBYTES;
2595 if (m_new == NULL) {
2596 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
2597 if (m_new == NULL)
2598 goto nospace;
2601 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2602 progress += length;
2603 m_new->m_len = length;
2604 if (m_new != m_final)
2605 m_cat(m_final, m_new);
2606 m_new = NULL;
2608 if (m0->m_next == NULL)
2609 m_defraguseless++;
2610 m_defragpackets++;
2611 m_defragbytes += m_final->m_pkthdr.len;
2612 return (m_final);
2613 nospace:
2614 m_defragfailure++;
2615 if (m_new)
2616 m_free(m_new);
2617 m_freem(m_final);
2618 return (NULL);
2622 * Move data from uio into mbufs.
2624 struct mbuf *
2625 m_uiomove(struct uio *uio)
2627 struct mbuf *m; /* current working mbuf */
2628 struct mbuf *head = NULL; /* result mbuf chain */
2629 struct mbuf **mp = &head;
2630 int flags = M_PKTHDR;
2631 int nsize;
2632 int error;
2633 int resid;
2635 do {
2636 if (uio->uio_resid > INT_MAX)
2637 resid = INT_MAX;
2638 else
2639 resid = (int)uio->uio_resid;
2640 m = m_getl(resid, M_WAITOK, MT_DATA, flags, &nsize);
2641 if (flags) {
2642 m->m_pkthdr.len = 0;
2643 /* Leave room for protocol headers. */
2644 if (resid < MHLEN)
2645 MH_ALIGN(m, resid);
2646 flags = 0;
2648 m->m_len = imin(nsize, resid);
2649 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
2650 if (error) {
2651 m_free(m);
2652 goto failed;
2654 *mp = m;
2655 mp = &m->m_next;
2656 head->m_pkthdr.len += m->m_len;
2657 } while (uio->uio_resid > 0);
2659 return (head);
2661 failed:
2662 m_freem(head);
2663 return (NULL);
2666 struct mbuf *
2667 m_last(struct mbuf *m)
2669 while (m->m_next)
2670 m = m->m_next;
2671 return (m);
2675 * Return the number of bytes in an mbuf chain.
2676 * If lastm is not NULL, also return the last mbuf.
2678 u_int
2679 m_lengthm(struct mbuf *m, struct mbuf **lastm)
2681 u_int len = 0;
2682 struct mbuf *prev = m;
2684 while (m) {
2685 len += m->m_len;
2686 prev = m;
2687 m = m->m_next;
2689 if (lastm != NULL)
2690 *lastm = prev;
2691 return (len);
2695 * Like m_lengthm(), except also keep track of mbuf usage.
2697 u_int
2698 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2700 u_int len = 0, mbcnt = 0;
2701 struct mbuf *prev = m;
2703 while (m) {
2704 len += m->m_len;
2705 mbcnt += MSIZE;
2706 if (m->m_flags & M_EXT)
2707 mbcnt += m->m_ext.ext_size;
2708 prev = m;
2709 m = m->m_next;
2711 if (lastm != NULL)
2712 *lastm = prev;
2713 *pmbcnt = mbcnt;
2714 return (len);