xref: /dflybsd-src/sys/kern/uipc_mbuf.c (revision 2d0700913d3c55b6181d2b703dd69aae2179ce8c)
1 /*
2  * (MPSAFE)
3  *
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.
21  *
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.
34  */
35 
36 /*
37  * Copyright (c) 1982, 1986, 1988, 1991, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  *
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.
51  *
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.
63  *
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 $
66  */
67 
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/globaldata.h>
84 
85 #include <sys/thread2.h>
86 #include <sys/spinlock2.h>
87 
88 #include <machine/atomic.h>
89 #include <machine/limits.h>
90 
91 #include <vm/vm.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
94 
95 #ifdef INVARIANTS
96 #include <machine/cpu.h>
97 #endif
98 
99 /*
100  * mbuf cluster meta-data
101  */
102 struct mbcluster {
103 	int32_t	mcl_refs;
104 	void	*mcl_data;
105 };
106 
107 /*
108  * mbuf tracking for debugging purposes
109  */
110 #ifdef MBUF_DEBUG
111 
112 static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
113 
114 struct mbctrack;
115 RB_HEAD(mbuf_rb_tree, mbtrack);
116 RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
117 
118 struct mbtrack {
119 	RB_ENTRY(mbtrack) rb_node;
120 	int trackid;
121 	struct mbuf *m;
122 };
123 
124 static int
125 mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
126 {
127 	if (mb1->m < mb2->m)
128 		return(-1);
129 	if (mb1->m > mb2->m)
130 		return(1);
131 	return(0);
132 }
133 
134 RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
135 
136 struct mbuf_rb_tree	mbuf_track_root;
137 static struct spinlock	mbuf_track_spin = SPINLOCK_INITIALIZER(mbuf_track_spin);
138 
139 static void
140 mbuftrack(struct mbuf *m)
141 {
142 	struct mbtrack *mbt;
143 
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);
150 	}
151 	spin_unlock(&mbuf_track_spin);
152 }
153 
154 static void
155 mbufuntrack(struct mbuf *m)
156 {
157 	struct mbtrack *mbt;
158 
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);
168 	}
169 }
170 
171 void
172 mbuftrackid(struct mbuf *m, int trackid)
173 {
174 	struct mbtrack *mbt;
175 	struct mbuf *n;
176 
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);
185 			}
186 			mbt->trackid = trackid;
187 			m = m->m_next;
188 		}
189 		m = n;
190 	}
191 	spin_unlock(&mbuf_track_spin);
192 }
193 
194 static int
195 mbuftrack_callback(struct mbtrack *mbt, void *arg)
196 {
197 	struct sysctl_req *req = arg;
198 	char buf[64];
199 	int error;
200 
201 	ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
202 
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);
209 }
210 
211 static int
212 mbuftrack_show(SYSCTL_HANDLER_ARGS)
213 {
214 	int error;
215 
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);
221 }
222 SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
223 	    0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
224 
225 #else
226 
227 #define mbuftrack(m)
228 #define mbufuntrack(m)
229 
230 #endif
231 
232 static void mbinit(void *);
233 SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
234 
235 static u_long	mbtypes[SMP_MAXCPU][MT_NTYPES];
236 
237 static struct mbstat mbstat[SMP_MAXCPU];
238 int	max_linkhdr;
239 int	max_protohdr;
240 int	max_hdr;
241 int	max_datalen;
242 int	m_defragpackets;
243 int	m_defragbytes;
244 int	m_defraguseless;
245 int	m_defragfailure;
246 #ifdef MBUF_STRESS_TEST
247 int	m_defragrandomfailures;
248 #endif
249 
250 struct objcache *mbuf_cache, *mbufphdr_cache;
251 struct objcache *mclmeta_cache, *mjclmeta_cache;
252 struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
253 struct objcache *mbufjcluster_cache, *mbufphdrjcluster_cache;
254 
255 int		nmbclusters;
256 static int	nmbjclusters;
257 int		nmbufs;
258 
259 static int	mclph_cachefrac;
260 static int	mcl_cachefrac;
261 
262 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
263 	&max_linkhdr, 0, "Max size of a link-level header");
264 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
265 	&max_protohdr, 0, "Max size of a protocol header");
266 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0,
267 	"Max size of link+protocol headers");
268 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
269 	&max_datalen, 0, "Max data payload size without headers");
270 SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
271 	&mbuf_wait, 0, "Time in ticks to sleep after failed mbuf allocations");
272 static int do_mbstat(SYSCTL_HANDLER_ARGS);
273 
274 SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
275 	0, 0, do_mbstat, "S,mbstat", "mbuf usage statistics");
276 
277 static int do_mbtypes(SYSCTL_HANDLER_ARGS);
278 
279 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
280 	0, 0, do_mbtypes, "LU", "");
281 
282 static int
283 do_mbstat(SYSCTL_HANDLER_ARGS)
284 {
285 	struct mbstat mbstat_total;
286 	struct mbstat *mbstat_totalp;
287 	int i;
288 
289 	bzero(&mbstat_total, sizeof(mbstat_total));
290 	mbstat_totalp = &mbstat_total;
291 
292 	for (i = 0; i < ncpus; i++)
293 	{
294 		mbstat_total.m_mbufs += mbstat[i].m_mbufs;
295 		mbstat_total.m_clusters += mbstat[i].m_clusters;
296 		mbstat_total.m_spare += mbstat[i].m_spare;
297 		mbstat_total.m_clfree += mbstat[i].m_clfree;
298 		mbstat_total.m_drops += mbstat[i].m_drops;
299 		mbstat_total.m_wait += mbstat[i].m_wait;
300 		mbstat_total.m_drain += mbstat[i].m_drain;
301 		mbstat_total.m_mcfail += mbstat[i].m_mcfail;
302 		mbstat_total.m_mpfail += mbstat[i].m_mpfail;
303 
304 	}
305 	/*
306 	 * The following fields are not cumulative fields so just
307 	 * get their values once.
308 	 */
309 	mbstat_total.m_msize = mbstat[0].m_msize;
310 	mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
311 	mbstat_total.m_minclsize = mbstat[0].m_minclsize;
312 	mbstat_total.m_mlen = mbstat[0].m_mlen;
313 	mbstat_total.m_mhlen = mbstat[0].m_mhlen;
314 
315 	return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
316 }
317 
318 static int
319 do_mbtypes(SYSCTL_HANDLER_ARGS)
320 {
321 	u_long totals[MT_NTYPES];
322 	int i, j;
323 
324 	for (i = 0; i < MT_NTYPES; i++)
325 		totals[i] = 0;
326 
327 	for (i = 0; i < ncpus; i++)
328 	{
329 		for (j = 0; j < MT_NTYPES; j++)
330 			totals[j] += mbtypes[i][j];
331 	}
332 
333 	return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
334 }
335 
336 /*
337  * These are read-only because we do not currently have any code
338  * to adjust the objcache limits after the fact.  The variables
339  * may only be set as boot-time tunables.
340  */
341 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
342 	   &nmbclusters, 0, "Maximum number of mbuf clusters available");
343 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
344 	   "Maximum number of mbufs available");
345 SYSCTL_INT(_kern_ipc, OID_AUTO, nmbjclusters, CTLFLAG_RD, &nmbjclusters, 0,
346 	   "Maximum number of mbuf jclusters available");
347 SYSCTL_INT(_kern_ipc, OID_AUTO, mclph_cachefrac, CTLFLAG_RD,
348     	   &mclph_cachefrac, 0,
349 	   "Fraction of cacheable mbuf clusters w/ pkthdr");
350 SYSCTL_INT(_kern_ipc, OID_AUTO, mcl_cachefrac, CTLFLAG_RD,
351     	   &mcl_cachefrac, 0, "Fraction of cacheable mbuf clusters");
352 
353 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
354 	   &m_defragpackets, 0, "Number of defragment packets");
355 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
356 	   &m_defragbytes, 0, "Number of defragment bytes");
357 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
358 	   &m_defraguseless, 0, "Number of useless defragment mbuf chain operations");
359 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
360 	   &m_defragfailure, 0, "Number of failed defragment mbuf chain operations");
361 #ifdef MBUF_STRESS_TEST
362 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
363 	   &m_defragrandomfailures, 0, "");
364 #endif
365 
366 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
367 static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
368 static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
369 
370 static void m_reclaim (void);
371 static void m_mclref(void *arg);
372 static void m_mclfree(void *arg);
373 
374 /*
375  * NOTE: Default NMBUFS must take into account a possible DOS attack
376  *	 using fd passing on unix domain sockets.
377  */
378 #ifndef NMBCLUSTERS
379 #define NMBCLUSTERS	(512 + maxusers * 16)
380 #endif
381 #ifndef MCLPH_CACHEFRAC
382 #define MCLPH_CACHEFRAC	16
383 #endif
384 #ifndef MCL_CACHEFRAC
385 #define MCL_CACHEFRAC	4
386 #endif
387 #ifndef NMBJCLUSTERS
388 #define NMBJCLUSTERS	2048
389 #endif
390 #ifndef NMBUFS
391 #define NMBUFS		(nmbclusters * 2 + maxfiles)
392 #endif
393 
394 /*
395  * Perform sanity checks of tunables declared above.
396  */
397 static void
398 tunable_mbinit(void *dummy)
399 {
400 	/*
401 	 * This has to be done before VM init.
402 	 */
403 	nmbclusters = NMBCLUSTERS;
404 	TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
405 	mclph_cachefrac = MCLPH_CACHEFRAC;
406 	TUNABLE_INT_FETCH("kern.ipc.mclph_cachefrac", &mclph_cachefrac);
407 	mcl_cachefrac = MCL_CACHEFRAC;
408 	TUNABLE_INT_FETCH("kern.ipc.mcl_cachefrac", &mcl_cachefrac);
409 
410 	nmbjclusters = NMBJCLUSTERS;
411 	TUNABLE_INT_FETCH("kern.ipc.nmbjclusters", &nmbjclusters);
412 
413 	nmbufs = NMBUFS;
414 	TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
415 
416 	/* Sanity checks */
417 	if (nmbufs < nmbclusters * 2)
418 		nmbufs = nmbclusters * 2;
419 }
420 SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
421 	tunable_mbinit, NULL);
422 
423 /* "number of clusters of pages" */
424 #define NCL_INIT	1
425 
426 #define NMB_INIT	16
427 
428 /*
429  * The mbuf object cache only guarantees that m_next and m_nextpkt are
430  * NULL and that m_data points to the beginning of the data area.  In
431  * particular, m_len and m_pkthdr.len are uninitialized.  It is the
432  * responsibility of the caller to initialize those fields before use.
433  */
434 
435 static __inline boolean_t
436 mbuf_ctor(void *obj, void *private, int ocflags)
437 {
438 	struct mbuf *m = obj;
439 
440 	m->m_next = NULL;
441 	m->m_nextpkt = NULL;
442 	m->m_data = m->m_dat;
443 	m->m_flags = 0;
444 
445 	return (TRUE);
446 }
447 
448 /*
449  * Initialize the mbuf and the packet header fields.
450  */
451 static boolean_t
452 mbufphdr_ctor(void *obj, void *private, int ocflags)
453 {
454 	struct mbuf *m = obj;
455 
456 	m->m_next = NULL;
457 	m->m_nextpkt = NULL;
458 	m->m_data = m->m_pktdat;
459 	m->m_flags = M_PKTHDR | M_PHCACHE;
460 
461 	m->m_pkthdr.rcvif = NULL;	/* eliminate XXX JH */
462 	SLIST_INIT(&m->m_pkthdr.tags);
463 	m->m_pkthdr.csum_flags = 0;	/* eliminate XXX JH */
464 	m->m_pkthdr.fw_flags = 0;	/* eliminate XXX JH */
465 
466 	return (TRUE);
467 }
468 
469 /*
470  * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
471  */
472 static boolean_t
473 mclmeta_ctor(void *obj, void *private, int ocflags)
474 {
475 	struct mbcluster *cl = obj;
476 	void *buf;
477 
478 	if (ocflags & M_NOWAIT)
479 		buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
480 	else
481 		buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
482 	if (buf == NULL)
483 		return (FALSE);
484 	cl->mcl_refs = 0;
485 	cl->mcl_data = buf;
486 	return (TRUE);
487 }
488 
489 static boolean_t
490 mjclmeta_ctor(void *obj, void *private, int ocflags)
491 {
492 	struct mbcluster *cl = obj;
493 	void *buf;
494 
495 	if (ocflags & M_NOWAIT)
496 		buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_NOWAIT | M_ZERO);
497 	else
498 		buf = kmalloc(MJUMPAGESIZE, M_MBUFCL, M_INTWAIT | M_ZERO);
499 	if (buf == NULL)
500 		return (FALSE);
501 	cl->mcl_refs = 0;
502 	cl->mcl_data = buf;
503 	return (TRUE);
504 }
505 
506 static void
507 mclmeta_dtor(void *obj, void *private)
508 {
509 	struct mbcluster *mcl = obj;
510 
511 	KKASSERT(mcl->mcl_refs == 0);
512 	kfree(mcl->mcl_data, M_MBUFCL);
513 }
514 
515 static void
516 linkjcluster(struct mbuf *m, struct mbcluster *cl, uint size)
517 {
518 	/*
519 	 * Add the cluster to the mbuf.  The caller will detect that the
520 	 * mbuf now has an attached cluster.
521 	 */
522 	m->m_ext.ext_arg = cl;
523 	m->m_ext.ext_buf = cl->mcl_data;
524 	m->m_ext.ext_ref = m_mclref;
525 	m->m_ext.ext_free = m_mclfree;
526 	m->m_ext.ext_size = size;
527 	atomic_add_int(&cl->mcl_refs, 1);
528 
529 	m->m_data = m->m_ext.ext_buf;
530 	m->m_flags |= M_EXT | M_EXT_CLUSTER;
531 }
532 
533 static void
534 linkcluster(struct mbuf *m, struct mbcluster *cl)
535 {
536 	linkjcluster(m, cl, MCLBYTES);
537 }
538 
539 static boolean_t
540 mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
541 {
542 	struct mbuf *m = obj;
543 	struct mbcluster *cl;
544 
545 	mbufphdr_ctor(obj, private, ocflags);
546 	cl = objcache_get(mclmeta_cache, ocflags);
547 	if (cl == NULL) {
548 		++mbstat[mycpu->gd_cpuid].m_drops;
549 		return (FALSE);
550 	}
551 	m->m_flags |= M_CLCACHE;
552 	linkcluster(m, cl);
553 	return (TRUE);
554 }
555 
556 static boolean_t
557 mbufphdrjcluster_ctor(void *obj, void *private, int ocflags)
558 {
559 	struct mbuf *m = obj;
560 	struct mbcluster *cl;
561 
562 	mbufphdr_ctor(obj, private, ocflags);
563 	cl = objcache_get(mjclmeta_cache, ocflags);
564 	if (cl == NULL) {
565 		++mbstat[mycpu->gd_cpuid].m_drops;
566 		return (FALSE);
567 	}
568 	m->m_flags |= M_CLCACHE;
569 	linkjcluster(m, cl, MJUMPAGESIZE);
570 	return (TRUE);
571 }
572 
573 static boolean_t
574 mbufcluster_ctor(void *obj, void *private, int ocflags)
575 {
576 	struct mbuf *m = obj;
577 	struct mbcluster *cl;
578 
579 	mbuf_ctor(obj, private, ocflags);
580 	cl = objcache_get(mclmeta_cache, ocflags);
581 	if (cl == NULL) {
582 		++mbstat[mycpu->gd_cpuid].m_drops;
583 		return (FALSE);
584 	}
585 	m->m_flags |= M_CLCACHE;
586 	linkcluster(m, cl);
587 	return (TRUE);
588 }
589 
590 static boolean_t
591 mbufjcluster_ctor(void *obj, void *private, int ocflags)
592 {
593 	struct mbuf *m = obj;
594 	struct mbcluster *cl;
595 
596 	mbuf_ctor(obj, private, ocflags);
597 	cl = objcache_get(mjclmeta_cache, ocflags);
598 	if (cl == NULL) {
599 		++mbstat[mycpu->gd_cpuid].m_drops;
600 		return (FALSE);
601 	}
602 	m->m_flags |= M_CLCACHE;
603 	linkjcluster(m, cl, MJUMPAGESIZE);
604 	return (TRUE);
605 }
606 
607 /*
608  * Used for both the cluster and cluster PHDR caches.
609  *
610  * The mbuf may have lost its cluster due to sharing, deal
611  * with the situation by checking M_EXT.
612  */
613 static void
614 mbufcluster_dtor(void *obj, void *private)
615 {
616 	struct mbuf *m = obj;
617 	struct mbcluster *mcl;
618 
619 	if (m->m_flags & M_EXT) {
620 		KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
621 		mcl = m->m_ext.ext_arg;
622 		KKASSERT(mcl->mcl_refs == 1);
623 		mcl->mcl_refs = 0;
624 		if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES)
625 			objcache_put(mjclmeta_cache, mcl);
626 		else
627 			objcache_put(mclmeta_cache, mcl);
628 	}
629 }
630 
631 struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
632 struct objcache_malloc_args mclmeta_malloc_args =
633 	{ sizeof(struct mbcluster), M_MCLMETA };
634 
635 /* ARGSUSED*/
636 static void
637 mbinit(void *dummy)
638 {
639 	int mb_limit, cl_limit, ncl_limit, jcl_limit;
640 	int limit;
641 	int i;
642 
643 	/*
644 	 * Initialize statistics
645 	 */
646 	for (i = 0; i < ncpus; i++) {
647 		mbstat[i].m_msize = MSIZE;
648 		mbstat[i].m_mclbytes = MCLBYTES;
649 		mbstat[i].m_mjumpagesize = MJUMPAGESIZE;
650 		mbstat[i].m_minclsize = MINCLSIZE;
651 		mbstat[i].m_mlen = MLEN;
652 		mbstat[i].m_mhlen = MHLEN;
653 	}
654 
655 	/*
656 	 * Create objtect caches and save cluster limits, which will
657 	 * be used to adjust backing kmalloc pools' limit later.
658 	 */
659 
660 	mb_limit = cl_limit = 0;
661 
662 	limit = nmbufs;
663 	mbuf_cache = objcache_create("mbuf",
664 	    limit, 0,
665 	    mbuf_ctor, NULL, NULL,
666 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
667 	mb_limit += limit;
668 
669 	limit = nmbufs;
670 	mbufphdr_cache = objcache_create("mbuf pkt hdr",
671 	    limit, nmbufs / 4,
672 	    mbufphdr_ctor, NULL, NULL,
673 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
674 	mb_limit += limit;
675 
676 	ncl_limit = nmbclusters;
677 	mclmeta_cache = objcache_create("cluster mbuf",
678 	    ncl_limit, 0,
679 	    mclmeta_ctor, mclmeta_dtor, NULL,
680 	    objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
681 	cl_limit += ncl_limit;
682 
683 	jcl_limit = nmbjclusters;
684 	mjclmeta_cache = objcache_create("jcluster mbuf",
685 	    jcl_limit, 0,
686 	    mjclmeta_ctor, mclmeta_dtor, NULL,
687 	    objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
688 	cl_limit += jcl_limit;
689 
690 	limit = nmbclusters;
691 	mbufcluster_cache = objcache_create("mbuf + cluster",
692 	    limit, nmbclusters / mcl_cachefrac,
693 	    mbufcluster_ctor, mbufcluster_dtor, NULL,
694 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
695 	mb_limit += limit;
696 
697 	limit = nmbclusters;
698 	mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
699 	    limit, nmbclusters / mclph_cachefrac,
700 	    mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
701 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
702 	mb_limit += limit;
703 
704 	limit = nmbjclusters / 4; /* XXX really rarely used */
705 	mbufjcluster_cache = objcache_create("mbuf + jcluster",
706 	    limit, 0,
707 	    mbufjcluster_ctor, mbufcluster_dtor, NULL,
708 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
709 	mb_limit += limit;
710 
711 	limit = nmbjclusters;
712 	mbufphdrjcluster_cache = objcache_create("mbuf pkt hdr + jcluster",
713 	    limit, nmbjclusters / 16,
714 	    mbufphdrjcluster_ctor, mbufcluster_dtor, NULL,
715 	    objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
716 	mb_limit += limit;
717 
718 	/*
719 	 * Adjust backing kmalloc pools' limit
720 	 *
721 	 * NOTE: We raise the limit by another 1/8 to take the effect
722 	 * of loosememuse into account.
723 	 */
724 	cl_limit += cl_limit / 8;
725 	kmalloc_raise_limit(mclmeta_malloc_args.mtype,
726 	    mclmeta_malloc_args.objsize * (size_t)cl_limit);
727 	kmalloc_raise_limit(M_MBUFCL,
728 	    (MCLBYTES * (size_t)ncl_limit) +
729 	    (MJUMPAGESIZE * (size_t)jcl_limit));
730 
731 	mb_limit += mb_limit / 8;
732 	kmalloc_raise_limit(mbuf_malloc_args.mtype,
733 	    mbuf_malloc_args.objsize * (size_t)mb_limit);
734 }
735 
736 /*
737  * Return the number of references to this mbuf's data.  0 is returned
738  * if the mbuf is not M_EXT, a reference count is returned if it is
739  * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
740  */
741 int
742 m_sharecount(struct mbuf *m)
743 {
744 	switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
745 	case 0:
746 		return (0);
747 	case M_EXT:
748 		return (99);
749 	case M_EXT | M_EXT_CLUSTER:
750 		return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
751 	}
752 	/* NOTREACHED */
753 	return (0);		/* to shut up compiler */
754 }
755 
756 /*
757  * change mbuf to new type
758  */
759 void
760 m_chtype(struct mbuf *m, int type)
761 {
762 	struct globaldata *gd = mycpu;
763 
764 	++mbtypes[gd->gd_cpuid][type];
765 	--mbtypes[gd->gd_cpuid][m->m_type];
766 	m->m_type = type;
767 }
768 
769 static void
770 m_reclaim(void)
771 {
772 	struct domain *dp;
773 	struct protosw *pr;
774 
775 	kprintf("Debug: m_reclaim() called\n");
776 
777 	SLIST_FOREACH(dp, &domains, dom_next) {
778 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
779 			if (pr->pr_drain)
780 				(*pr->pr_drain)();
781 		}
782 	}
783 	++mbstat[mycpu->gd_cpuid].m_drain;
784 }
785 
786 static __inline void
787 updatestats(struct mbuf *m, int type)
788 {
789 	struct globaldata *gd = mycpu;
790 
791 	m->m_type = type;
792 	mbuftrack(m);
793 #ifdef MBUF_DEBUG
794 	KASSERT(m->m_next == NULL, ("mbuf %p: bad m_next in get", m));
795 	KASSERT(m->m_nextpkt == NULL, ("mbuf %p: bad m_nextpkt in get", m));
796 #endif
797 
798 	++mbtypes[gd->gd_cpuid][type];
799 	++mbstat[gd->gd_cpuid].m_mbufs;
800 
801 }
802 
803 /*
804  * Allocate an mbuf.
805  */
806 struct mbuf *
807 m_get(int how, int type)
808 {
809 	struct mbuf *m;
810 	int ntries = 0;
811 	int ocf = MBTOM(how);
812 
813 retryonce:
814 
815 	m = objcache_get(mbuf_cache, ocf);
816 
817 	if (m == NULL) {
818 		if ((how & MB_TRYWAIT) && ntries++ == 0) {
819 			struct objcache *reclaimlist[] = {
820 				mbufphdr_cache,
821 				mbufcluster_cache,
822 				mbufphdrcluster_cache,
823 				mbufjcluster_cache,
824 				mbufphdrjcluster_cache
825 			};
826 			const int nreclaims = NELEM(reclaimlist);
827 
828 			if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
829 				m_reclaim();
830 			goto retryonce;
831 		}
832 		++mbstat[mycpu->gd_cpuid].m_drops;
833 		return (NULL);
834 	}
835 #ifdef MBUF_DEBUG
836 	KASSERT(m->m_data == m->m_dat, ("mbuf %p: bad m_data in get", m));
837 #endif
838 	m->m_len = 0;
839 
840 	updatestats(m, type);
841 	return (m);
842 }
843 
844 struct mbuf *
845 m_gethdr(int how, int type)
846 {
847 	struct mbuf *m;
848 	int ocf = MBTOM(how);
849 	int ntries = 0;
850 
851 retryonce:
852 
853 	m = objcache_get(mbufphdr_cache, ocf);
854 
855 	if (m == NULL) {
856 		if ((how & MB_TRYWAIT) && ntries++ == 0) {
857 			struct objcache *reclaimlist[] = {
858 				mbuf_cache,
859 				mbufcluster_cache, mbufphdrcluster_cache,
860 				mbufjcluster_cache, mbufphdrjcluster_cache
861 			};
862 			const int nreclaims = NELEM(reclaimlist);
863 
864 			if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
865 				m_reclaim();
866 			goto retryonce;
867 		}
868 		++mbstat[mycpu->gd_cpuid].m_drops;
869 		return (NULL);
870 	}
871 #ifdef MBUF_DEBUG
872 	KASSERT(m->m_data == m->m_pktdat, ("mbuf %p: bad m_data in get", m));
873 #endif
874 	m->m_len = 0;
875 	m->m_pkthdr.len = 0;
876 
877 	updatestats(m, type);
878 	return (m);
879 }
880 
881 /*
882  * Get a mbuf (not a mbuf cluster!) and zero it.
883  * Deprecated.
884  */
885 struct mbuf *
886 m_getclr(int how, int type)
887 {
888 	struct mbuf *m;
889 
890 	m = m_get(how, type);
891 	if (m != NULL)
892 		bzero(m->m_data, MLEN);
893 	return (m);
894 }
895 
896 static struct mbuf *
897 m_getcl_cache(int how, short type, int flags, struct objcache *mbclc,
898     struct objcache *mbphclc)
899 {
900 	struct mbuf *m = NULL;
901 	int ocflags = MBTOM(how);
902 	int ntries = 0;
903 
904 retryonce:
905 
906 	if (flags & M_PKTHDR)
907 		m = objcache_get(mbphclc, ocflags);
908 	else
909 		m = objcache_get(mbclc, ocflags);
910 
911 	if (m == NULL) {
912 		if ((how & MB_TRYWAIT) && ntries++ == 0) {
913 			struct objcache *reclaimlist[1];
914 
915 			if (flags & M_PKTHDR)
916 				reclaimlist[0] = mbclc;
917 			else
918 				reclaimlist[0] = mbphclc;
919 			if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
920 				m_reclaim();
921 			goto retryonce;
922 		}
923 		++mbstat[mycpu->gd_cpuid].m_drops;
924 		return (NULL);
925 	}
926 
927 #ifdef MBUF_DEBUG
928 	KASSERT(m->m_data == m->m_ext.ext_buf,
929 		("mbuf %p: bad m_data in get", m));
930 #endif
931 	m->m_type = type;
932 	m->m_len = 0;
933 	m->m_pkthdr.len = 0;	/* just do it unconditonally */
934 
935 	mbuftrack(m);
936 
937 	++mbtypes[mycpu->gd_cpuid][type];
938 	++mbstat[mycpu->gd_cpuid].m_clusters;
939 	return (m);
940 }
941 
942 struct mbuf *
943 m_getjcl(int how, short type, int flags, size_t size)
944 {
945 	struct objcache *mbclc, *mbphclc;
946 
947 	switch (size) {
948 	case MCLBYTES:
949 		mbclc = mbufcluster_cache;
950 		mbphclc = mbufphdrcluster_cache;
951 		break;
952 
953 	default:
954 		mbclc = mbufjcluster_cache;
955 		mbphclc = mbufphdrjcluster_cache;
956 		break;
957 	}
958 	return m_getcl_cache(how, type, flags, mbclc, mbphclc);
959 }
960 
961 /*
962  * Returns an mbuf with an attached cluster.
963  * Because many network drivers use this kind of buffers a lot, it is
964  * convenient to keep a small pool of free buffers of this kind.
965  * Even a small size such as 10 gives about 10% improvement in the
966  * forwarding rate in a bridge or router.
967  */
968 struct mbuf *
969 m_getcl(int how, short type, int flags)
970 {
971 	return m_getcl_cache(how, type, flags,
972 	    mbufcluster_cache, mbufphdrcluster_cache);
973 }
974 
975 /*
976  * Allocate chain of requested length.
977  */
978 struct mbuf *
979 m_getc(int len, int how, int type)
980 {
981 	struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
982 	int nsize;
983 
984 	while (len > 0) {
985 		n = m_getl(len, how, type, 0, &nsize);
986 		if (n == NULL)
987 			goto failed;
988 		n->m_len = 0;
989 		*ntail = n;
990 		ntail = &n->m_next;
991 		len -= nsize;
992 	}
993 	return (nfirst);
994 
995 failed:
996 	m_freem(nfirst);
997 	return (NULL);
998 }
999 
1000 /*
1001  * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
1002  * and return a pointer to the head of the allocated chain. If m0 is
1003  * non-null, then we assume that it is a single mbuf or an mbuf chain to
1004  * which we want len bytes worth of mbufs and/or clusters attached, and so
1005  * if we succeed in allocating it, we will just return a pointer to m0.
1006  *
1007  * If we happen to fail at any point during the allocation, we will free
1008  * up everything we have already allocated and return NULL.
1009  *
1010  * Deprecated.  Use m_getc() and m_cat() instead.
1011  */
1012 struct mbuf *
1013 m_getm(struct mbuf *m0, int len, int type, int how)
1014 {
1015 	struct mbuf *nfirst;
1016 
1017 	nfirst = m_getc(len, how, type);
1018 
1019 	if (m0 != NULL) {
1020 		m_last(m0)->m_next = nfirst;
1021 		return (m0);
1022 	}
1023 
1024 	return (nfirst);
1025 }
1026 
1027 /*
1028  * Adds a cluster to a normal mbuf, M_EXT is set on success.
1029  * Deprecated.  Use m_getcl() instead.
1030  */
1031 void
1032 m_mclget(struct mbuf *m, int how)
1033 {
1034 	struct mbcluster *mcl;
1035 
1036 	KKASSERT((m->m_flags & M_EXT) == 0);
1037 	mcl = objcache_get(mclmeta_cache, MBTOM(how));
1038 	if (mcl != NULL) {
1039 		linkcluster(m, mcl);
1040 		++mbstat[mycpu->gd_cpuid].m_clusters;
1041 	} else {
1042 		++mbstat[mycpu->gd_cpuid].m_drops;
1043 	}
1044 }
1045 
1046 /*
1047  * Updates to mbcluster must be MPSAFE.  Only an entity which already has
1048  * a reference to the cluster can ref it, so we are in no danger of
1049  * racing an add with a subtract.  But the operation must still be atomic
1050  * since multiple entities may have a reference on the cluster.
1051  *
1052  * m_mclfree() is almost the same but it must contend with two entities
1053  * freeing the cluster at the same time.
1054  */
1055 static void
1056 m_mclref(void *arg)
1057 {
1058 	struct mbcluster *mcl = arg;
1059 
1060 	atomic_add_int(&mcl->mcl_refs, 1);
1061 }
1062 
1063 /*
1064  * When dereferencing a cluster we have to deal with a N->0 race, where
1065  * N entities free their references simultaniously.  To do this we use
1066  * atomic_fetchadd_int().
1067  */
1068 static void
1069 m_mclfree(void *arg)
1070 {
1071 	struct mbcluster *mcl = arg;
1072 
1073 	if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1) {
1074 		--mbstat[mycpu->gd_cpuid].m_clusters;
1075 		objcache_put(mclmeta_cache, mcl);
1076 	}
1077 }
1078 
1079 /*
1080  * Free a single mbuf and any associated external storage.  The successor,
1081  * if any, is returned.
1082  *
1083  * We do need to check non-first mbuf for m_aux, since some of existing
1084  * code does not call M_PREPEND properly.
1085  * (example: call to bpf_mtap from drivers)
1086  */
1087 
1088 #ifdef MBUF_DEBUG
1089 
1090 struct mbuf  *
1091 _m_free(struct mbuf *m, const char *func)
1092 
1093 #else
1094 
1095 struct mbuf *
1096 m_free(struct mbuf *m)
1097 
1098 #endif
1099 {
1100 	struct mbuf *n;
1101 	struct globaldata *gd = mycpu;
1102 
1103 	KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
1104 	KASSERT(M_TRAILINGSPACE(m) >= 0, ("overflowed mbuf %p", m));
1105 	--mbtypes[gd->gd_cpuid][m->m_type];
1106 
1107 	n = m->m_next;
1108 
1109 	/*
1110 	 * Make sure the mbuf is in constructed state before returning it
1111 	 * to the objcache.
1112 	 */
1113 	m->m_next = NULL;
1114 	mbufuntrack(m);
1115 #ifdef MBUF_DEBUG
1116 	m->m_hdr.mh_lastfunc = func;
1117 #endif
1118 #ifdef notyet
1119 	KKASSERT(m->m_nextpkt == NULL);
1120 #else
1121 	if (m->m_nextpkt != NULL) {
1122 		static int afewtimes = 10;
1123 
1124 		if (afewtimes-- > 0) {
1125 			kprintf("mfree: m->m_nextpkt != NULL\n");
1126 			print_backtrace(-1);
1127 		}
1128 		m->m_nextpkt = NULL;
1129 	}
1130 #endif
1131 	if (m->m_flags & M_PKTHDR) {
1132 		m_tag_delete_chain(m);		/* eliminate XXX JH */
1133 	}
1134 
1135 	m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
1136 
1137 	/*
1138 	 * Clean the M_PKTHDR state so we can return the mbuf to its original
1139 	 * cache.  This is based on the PHCACHE flag which tells us whether
1140 	 * the mbuf was originally allocated out of a packet-header cache
1141 	 * or a non-packet-header cache.
1142 	 */
1143 	if (m->m_flags & M_PHCACHE) {
1144 		m->m_flags |= M_PKTHDR;
1145 		m->m_pkthdr.rcvif = NULL;	/* eliminate XXX JH */
1146 		m->m_pkthdr.csum_flags = 0;	/* eliminate XXX JH */
1147 		m->m_pkthdr.fw_flags = 0;	/* eliminate XXX JH */
1148 		SLIST_INIT(&m->m_pkthdr.tags);
1149 	}
1150 
1151 	/*
1152 	 * Handle remaining flags combinations.  M_CLCACHE tells us whether
1153 	 * the mbuf was originally allocated from a cluster cache or not,
1154 	 * and is totally separate from whether the mbuf is currently
1155 	 * associated with a cluster.
1156 	 */
1157 	switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
1158 	case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
1159 		/*
1160 		 * mbuf+cluster cache case.  The mbuf was allocated from the
1161 		 * combined mbuf_cluster cache and can be returned to the
1162 		 * cache if the cluster hasn't been shared.
1163 		 */
1164 		if (m_sharecount(m) == 1) {
1165 			/*
1166 			 * The cluster has not been shared, we can just
1167 			 * reset the data pointer and return the mbuf
1168 			 * to the cluster cache.  Note that the reference
1169 			 * count is left intact (it is still associated with
1170 			 * an mbuf).
1171 			 */
1172 			m->m_data = m->m_ext.ext_buf;
1173 			if (m->m_flags & M_EXT && m->m_ext.ext_size != MCLBYTES) {
1174 				if (m->m_flags & M_PHCACHE)
1175 					objcache_put(mbufphdrjcluster_cache, m);
1176 				else
1177 					objcache_put(mbufjcluster_cache, m);
1178 			} else {
1179 				if (m->m_flags & M_PHCACHE)
1180 					objcache_put(mbufphdrcluster_cache, m);
1181 				else
1182 					objcache_put(mbufcluster_cache, m);
1183 			}
1184 			--mbstat[mycpu->gd_cpuid].m_clusters;
1185 		} else {
1186 			/*
1187 			 * Hell.  Someone else has a ref on this cluster,
1188 			 * we have to disconnect it which means we can't
1189 			 * put it back into the mbufcluster_cache, we
1190 			 * have to destroy the mbuf.
1191 			 *
1192 			 * Other mbuf references to the cluster will typically
1193 			 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
1194 			 *
1195 			 * XXX we could try to connect another cluster to
1196 			 * it.
1197 			 */
1198 			m->m_ext.ext_free(m->m_ext.ext_arg);
1199 			m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1200 			if (m->m_ext.ext_size == MCLBYTES) {
1201 				if (m->m_flags & M_PHCACHE)
1202 					objcache_dtor(mbufphdrcluster_cache, m);
1203 				else
1204 					objcache_dtor(mbufcluster_cache, m);
1205 			} else {
1206 				if (m->m_flags & M_PHCACHE)
1207 					objcache_dtor(mbufphdrjcluster_cache, m);
1208 				else
1209 					objcache_dtor(mbufjcluster_cache, m);
1210 			}
1211 		}
1212 		break;
1213 	case M_EXT | M_EXT_CLUSTER:
1214 	case M_EXT:
1215 		/*
1216 		 * Normal cluster association case, disconnect the cluster from
1217 		 * the mbuf.  The cluster may or may not be custom.
1218 		 */
1219 		m->m_ext.ext_free(m->m_ext.ext_arg);
1220 		m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1221 		/* fall through */
1222 	case 0:
1223 		/*
1224 		 * return the mbuf to the mbuf cache.
1225 		 */
1226 		if (m->m_flags & M_PHCACHE) {
1227 			m->m_data = m->m_pktdat;
1228 			objcache_put(mbufphdr_cache, m);
1229 		} else {
1230 			m->m_data = m->m_dat;
1231 			objcache_put(mbuf_cache, m);
1232 		}
1233 		--mbstat[mycpu->gd_cpuid].m_mbufs;
1234 		break;
1235 	default:
1236 		if (!panicstr)
1237 			panic("bad mbuf flags %p %08x", m, m->m_flags);
1238 		break;
1239 	}
1240 	return (n);
1241 }
1242 
1243 #ifdef MBUF_DEBUG
1244 
1245 void
1246 _m_freem(struct mbuf *m, const char *func)
1247 {
1248 	while (m)
1249 		m = _m_free(m, func);
1250 }
1251 
1252 #else
1253 
1254 void
1255 m_freem(struct mbuf *m)
1256 {
1257 	while (m)
1258 		m = m_free(m);
1259 }
1260 
1261 #endif
1262 
1263 void
1264 m_extadd(struct mbuf *m, caddr_t buf, u_int size,  void (*reff)(void *),
1265     void (*freef)(void *), void *arg)
1266 {
1267 	m->m_ext.ext_arg = arg;
1268 	m->m_ext.ext_buf = buf;
1269 	m->m_ext.ext_ref = reff;
1270 	m->m_ext.ext_free = freef;
1271 	m->m_ext.ext_size = size;
1272 	reff(arg);
1273 	m->m_data = buf;
1274 	m->m_flags |= M_EXT;
1275 }
1276 
1277 /*
1278  * mbuf utility routines
1279  */
1280 
1281 /*
1282  * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
1283  * copy junk along.
1284  */
1285 struct mbuf *
1286 m_prepend(struct mbuf *m, int len, int how)
1287 {
1288 	struct mbuf *mn;
1289 
1290 	if (m->m_flags & M_PKTHDR)
1291 	    mn = m_gethdr(how, m->m_type);
1292 	else
1293 	    mn = m_get(how, m->m_type);
1294 	if (mn == NULL) {
1295 		m_freem(m);
1296 		return (NULL);
1297 	}
1298 	if (m->m_flags & M_PKTHDR)
1299 		M_MOVE_PKTHDR(mn, m);
1300 	mn->m_next = m;
1301 	m = mn;
1302 	if (len < MHLEN)
1303 		MH_ALIGN(m, len);
1304 	m->m_len = len;
1305 	return (m);
1306 }
1307 
1308 /*
1309  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1310  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
1311  * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
1312  * Note that the copy is read-only, because clusters are not copied,
1313  * only their reference counts are incremented.
1314  */
1315 struct mbuf *
1316 m_copym(const struct mbuf *m, int off0, int len, int wait)
1317 {
1318 	struct mbuf *n, **np;
1319 	int off = off0;
1320 	struct mbuf *top;
1321 	int copyhdr = 0;
1322 
1323 	KASSERT(off >= 0, ("m_copym, negative off %d", off));
1324 	KASSERT(len >= 0, ("m_copym, negative len %d", len));
1325 	if (off == 0 && (m->m_flags & M_PKTHDR))
1326 		copyhdr = 1;
1327 	while (off > 0) {
1328 		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1329 		if (off < m->m_len)
1330 			break;
1331 		off -= m->m_len;
1332 		m = m->m_next;
1333 	}
1334 	np = &top;
1335 	top = NULL;
1336 	while (len > 0) {
1337 		if (m == NULL) {
1338 			KASSERT(len == M_COPYALL,
1339 			    ("m_copym, length > size of mbuf chain"));
1340 			break;
1341 		}
1342 		/*
1343 		 * Because we are sharing any cluster attachment below,
1344 		 * be sure to get an mbuf that does not have a cluster
1345 		 * associated with it.
1346 		 */
1347 		if (copyhdr)
1348 			n = m_gethdr(wait, m->m_type);
1349 		else
1350 			n = m_get(wait, m->m_type);
1351 		*np = n;
1352 		if (n == NULL)
1353 			goto nospace;
1354 		if (copyhdr) {
1355 			if (!m_dup_pkthdr(n, m, wait))
1356 				goto nospace;
1357 			if (len == M_COPYALL)
1358 				n->m_pkthdr.len -= off0;
1359 			else
1360 				n->m_pkthdr.len = len;
1361 			copyhdr = 0;
1362 		}
1363 		n->m_len = min(len, m->m_len - off);
1364 		if (m->m_flags & M_EXT) {
1365 			KKASSERT((n->m_flags & M_EXT) == 0);
1366 			n->m_data = m->m_data + off;
1367 			m->m_ext.ext_ref(m->m_ext.ext_arg);
1368 			n->m_ext = m->m_ext;
1369 			n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1370 		} else {
1371 			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1372 			    (unsigned)n->m_len);
1373 		}
1374 		if (len != M_COPYALL)
1375 			len -= n->m_len;
1376 		off = 0;
1377 		m = m->m_next;
1378 		np = &n->m_next;
1379 	}
1380 	if (top == NULL)
1381 		++mbstat[mycpu->gd_cpuid].m_mcfail;
1382 	return (top);
1383 nospace:
1384 	m_freem(top);
1385 	++mbstat[mycpu->gd_cpuid].m_mcfail;
1386 	return (NULL);
1387 }
1388 
1389 /*
1390  * Copy an entire packet, including header (which must be present).
1391  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1392  * Note that the copy is read-only, because clusters are not copied,
1393  * only their reference counts are incremented.
1394  * Preserve alignment of the first mbuf so if the creator has left
1395  * some room at the beginning (e.g. for inserting protocol headers)
1396  * the copies also have the room available.
1397  */
1398 struct mbuf *
1399 m_copypacket(struct mbuf *m, int how)
1400 {
1401 	struct mbuf *top, *n, *o;
1402 
1403 	n = m_gethdr(how, m->m_type);
1404 	top = n;
1405 	if (!n)
1406 		goto nospace;
1407 
1408 	if (!m_dup_pkthdr(n, m, how))
1409 		goto nospace;
1410 	n->m_len = m->m_len;
1411 	if (m->m_flags & M_EXT) {
1412 		KKASSERT((n->m_flags & M_EXT) == 0);
1413 		n->m_data = m->m_data;
1414 		m->m_ext.ext_ref(m->m_ext.ext_arg);
1415 		n->m_ext = m->m_ext;
1416 		n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1417 	} else {
1418 		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1419 		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1420 	}
1421 
1422 	m = m->m_next;
1423 	while (m) {
1424 		o = m_get(how, m->m_type);
1425 		if (!o)
1426 			goto nospace;
1427 
1428 		n->m_next = o;
1429 		n = n->m_next;
1430 
1431 		n->m_len = m->m_len;
1432 		if (m->m_flags & M_EXT) {
1433 			KKASSERT((n->m_flags & M_EXT) == 0);
1434 			n->m_data = m->m_data;
1435 			m->m_ext.ext_ref(m->m_ext.ext_arg);
1436 			n->m_ext = m->m_ext;
1437 			n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
1438 		} else {
1439 			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1440 		}
1441 
1442 		m = m->m_next;
1443 	}
1444 	return top;
1445 nospace:
1446 	m_freem(top);
1447 	++mbstat[mycpu->gd_cpuid].m_mcfail;
1448 	return (NULL);
1449 }
1450 
1451 /*
1452  * Copy data from an mbuf chain starting "off" bytes from the beginning,
1453  * continuing for "len" bytes, into the indicated buffer.
1454  */
1455 void
1456 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
1457 {
1458 	unsigned count;
1459 
1460 	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1461 	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1462 	while (off > 0) {
1463 		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1464 		if (off < m->m_len)
1465 			break;
1466 		off -= m->m_len;
1467 		m = m->m_next;
1468 	}
1469 	while (len > 0) {
1470 		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1471 		count = min(m->m_len - off, len);
1472 		bcopy(mtod(m, caddr_t) + off, cp, count);
1473 		len -= count;
1474 		cp += count;
1475 		off = 0;
1476 		m = m->m_next;
1477 	}
1478 }
1479 
1480 /*
1481  * Copy a packet header mbuf chain into a completely new chain, including
1482  * copying any mbuf clusters.  Use this instead of m_copypacket() when
1483  * you need a writable copy of an mbuf chain.
1484  */
1485 struct mbuf *
1486 m_dup(struct mbuf *m, int how)
1487 {
1488 	struct mbuf **p, *top = NULL;
1489 	int remain, moff, nsize;
1490 
1491 	/* Sanity check */
1492 	if (m == NULL)
1493 		return (NULL);
1494 	KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
1495 
1496 	/* While there's more data, get a new mbuf, tack it on, and fill it */
1497 	remain = m->m_pkthdr.len;
1498 	moff = 0;
1499 	p = &top;
1500 	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
1501 		struct mbuf *n;
1502 
1503 		/* Get the next new mbuf */
1504 		n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1505 			   &nsize);
1506 		if (n == NULL)
1507 			goto nospace;
1508 		if (top == NULL)
1509 			if (!m_dup_pkthdr(n, m, how))
1510 				goto nospace0;
1511 
1512 		/* Link it into the new chain */
1513 		*p = n;
1514 		p = &n->m_next;
1515 
1516 		/* Copy data from original mbuf(s) into new mbuf */
1517 		n->m_len = 0;
1518 		while (n->m_len < nsize && m != NULL) {
1519 			int chunk = min(nsize - n->m_len, m->m_len - moff);
1520 
1521 			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1522 			moff += chunk;
1523 			n->m_len += chunk;
1524 			remain -= chunk;
1525 			if (moff == m->m_len) {
1526 				m = m->m_next;
1527 				moff = 0;
1528 			}
1529 		}
1530 
1531 		/* Check correct total mbuf length */
1532 		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
1533 			("%s: bogus m_pkthdr.len", __func__));
1534 	}
1535 	return (top);
1536 
1537 nospace:
1538 	m_freem(top);
1539 nospace0:
1540 	++mbstat[mycpu->gd_cpuid].m_mcfail;
1541 	return (NULL);
1542 }
1543 
1544 /*
1545  * Copy the non-packet mbuf data chain into a new set of mbufs, including
1546  * copying any mbuf clusters.  This is typically used to realign a data
1547  * chain by nfs_realign().
1548  *
1549  * The original chain is left intact.  how should be MB_WAIT or MB_DONTWAIT
1550  * and NULL can be returned if MB_DONTWAIT is passed.
1551  *
1552  * Be careful to use cluster mbufs, a large mbuf chain converted to non
1553  * cluster mbufs can exhaust our supply of mbufs.
1554  */
1555 struct mbuf *
1556 m_dup_data(struct mbuf *m, int how)
1557 {
1558 	struct mbuf **p, *n, *top = NULL;
1559 	int mlen, moff, chunk, gsize, nsize;
1560 
1561 	/*
1562 	 * Degenerate case
1563 	 */
1564 	if (m == NULL)
1565 		return (NULL);
1566 
1567 	/*
1568 	 * Optimize the mbuf allocation but do not get too carried away.
1569 	 */
1570 	if (m->m_next || m->m_len > MLEN)
1571 		if (m->m_flags & M_EXT && m->m_ext.ext_size == MCLBYTES)
1572 			gsize = MCLBYTES;
1573 		else
1574 			gsize = MJUMPAGESIZE;
1575 	else
1576 		gsize = MLEN;
1577 
1578 	/* Chain control */
1579 	p = &top;
1580 	n = NULL;
1581 	nsize = 0;
1582 
1583 	/*
1584 	 * Scan the mbuf chain until nothing is left, the new mbuf chain
1585 	 * will be allocated on the fly as needed.
1586 	 */
1587 	while (m) {
1588 		mlen = m->m_len;
1589 		moff = 0;
1590 
1591 		while (mlen) {
1592 			KKASSERT(m->m_type == MT_DATA);
1593 			if (n == NULL) {
1594 				n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1595 				n->m_len = 0;
1596 				if (n == NULL)
1597 					goto nospace;
1598 				*p = n;
1599 				p = &n->m_next;
1600 			}
1601 			chunk = imin(mlen, nsize);
1602 			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1603 			mlen -= chunk;
1604 			moff += chunk;
1605 			n->m_len += chunk;
1606 			nsize -= chunk;
1607 			if (nsize == 0)
1608 				n = NULL;
1609 		}
1610 		m = m->m_next;
1611 	}
1612 	*p = NULL;
1613 	return(top);
1614 nospace:
1615 	*p = NULL;
1616 	m_freem(top);
1617 	++mbstat[mycpu->gd_cpuid].m_mcfail;
1618 	return (NULL);
1619 }
1620 
1621 /*
1622  * Concatenate mbuf chain n to m.
1623  * Both chains must be of the same type (e.g. MT_DATA).
1624  * Any m_pkthdr is not updated.
1625  */
1626 void
1627 m_cat(struct mbuf *m, struct mbuf *n)
1628 {
1629 	m = m_last(m);
1630 	while (n) {
1631 		if (m->m_flags & M_EXT ||
1632 		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1633 			/* just join the two chains */
1634 			m->m_next = n;
1635 			return;
1636 		}
1637 		/* splat the data from one into the other */
1638 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1639 		    (u_int)n->m_len);
1640 		m->m_len += n->m_len;
1641 		n = m_free(n);
1642 	}
1643 }
1644 
1645 void
1646 m_adj(struct mbuf *mp, int req_len)
1647 {
1648 	int len = req_len;
1649 	struct mbuf *m;
1650 	int count;
1651 
1652 	if ((m = mp) == NULL)
1653 		return;
1654 	if (len >= 0) {
1655 		/*
1656 		 * Trim from head.
1657 		 */
1658 		while (m != NULL && len > 0) {
1659 			if (m->m_len <= len) {
1660 				len -= m->m_len;
1661 				m->m_len = 0;
1662 				m = m->m_next;
1663 			} else {
1664 				m->m_len -= len;
1665 				m->m_data += len;
1666 				len = 0;
1667 			}
1668 		}
1669 		m = mp;
1670 		if (mp->m_flags & M_PKTHDR)
1671 			m->m_pkthdr.len -= (req_len - len);
1672 	} else {
1673 		/*
1674 		 * Trim from tail.  Scan the mbuf chain,
1675 		 * calculating its length and finding the last mbuf.
1676 		 * If the adjustment only affects this mbuf, then just
1677 		 * adjust and return.  Otherwise, rescan and truncate
1678 		 * after the remaining size.
1679 		 */
1680 		len = -len;
1681 		count = 0;
1682 		for (;;) {
1683 			count += m->m_len;
1684 			if (m->m_next == NULL)
1685 				break;
1686 			m = m->m_next;
1687 		}
1688 		if (m->m_len >= len) {
1689 			m->m_len -= len;
1690 			if (mp->m_flags & M_PKTHDR)
1691 				mp->m_pkthdr.len -= len;
1692 			return;
1693 		}
1694 		count -= len;
1695 		if (count < 0)
1696 			count = 0;
1697 		/*
1698 		 * Correct length for chain is "count".
1699 		 * Find the mbuf with last data, adjust its length,
1700 		 * and toss data from remaining mbufs on chain.
1701 		 */
1702 		m = mp;
1703 		if (m->m_flags & M_PKTHDR)
1704 			m->m_pkthdr.len = count;
1705 		for (; m; m = m->m_next) {
1706 			if (m->m_len >= count) {
1707 				m->m_len = count;
1708 				break;
1709 			}
1710 			count -= m->m_len;
1711 		}
1712 		while (m->m_next)
1713 			(m = m->m_next) ->m_len = 0;
1714 	}
1715 }
1716 
1717 /*
1718  * Set the m_data pointer of a newly-allocated mbuf
1719  * to place an object of the specified size at the
1720  * end of the mbuf, longword aligned.
1721  */
1722 void
1723 m_align(struct mbuf *m, int len)
1724 {
1725 	int adjust;
1726 
1727 	if (m->m_flags & M_EXT)
1728 		adjust = m->m_ext.ext_size - len;
1729 	else if (m->m_flags & M_PKTHDR)
1730 		adjust = MHLEN - len;
1731 	else
1732 		adjust = MLEN - len;
1733 	m->m_data += adjust &~ (sizeof(long)-1);
1734 }
1735 
1736 /*
1737  * Create a writable copy of the mbuf chain.  While doing this
1738  * we compact the chain with a goal of producing a chain with
1739  * at most two mbufs.  The second mbuf in this chain is likely
1740  * to be a cluster.  The primary purpose of this work is to create
1741  * a writable packet for encryption, compression, etc.  The
1742  * secondary goal is to linearize the data so the data can be
1743  * passed to crypto hardware in the most efficient manner possible.
1744  */
1745 struct mbuf *
1746 m_unshare(struct mbuf *m0, int how)
1747 {
1748 	struct mbuf *m, *mprev;
1749 	struct mbuf *n, *mfirst, *mlast;
1750 	int len, off;
1751 
1752 	mprev = NULL;
1753 	for (m = m0; m != NULL; m = mprev->m_next) {
1754 		/*
1755 		 * Regular mbufs are ignored unless there's a cluster
1756 		 * in front of it that we can use to coalesce.  We do
1757 		 * the latter mainly so later clusters can be coalesced
1758 		 * also w/o having to handle them specially (i.e. convert
1759 		 * mbuf+cluster -> cluster).  This optimization is heavily
1760 		 * influenced by the assumption that we're running over
1761 		 * Ethernet where MCLBYTES is large enough that the max
1762 		 * packet size will permit lots of coalescing into a
1763 		 * single cluster.  This in turn permits efficient
1764 		 * crypto operations, especially when using hardware.
1765 		 */
1766 		if ((m->m_flags & M_EXT) == 0) {
1767 			if (mprev && (mprev->m_flags & M_EXT) &&
1768 			    m->m_len <= M_TRAILINGSPACE(mprev)) {
1769 				/* XXX: this ignores mbuf types */
1770 				memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1771 				       mtod(m, caddr_t), m->m_len);
1772 				mprev->m_len += m->m_len;
1773 				mprev->m_next = m->m_next;	/* unlink from chain */
1774 				m_free(m);			/* reclaim mbuf */
1775 			} else {
1776 				mprev = m;
1777 			}
1778 			continue;
1779 		}
1780 		/*
1781 		 * Writable mbufs are left alone (for now).
1782 		 */
1783 		if (M_WRITABLE(m)) {
1784 			mprev = m;
1785 			continue;
1786 		}
1787 
1788 		/*
1789 		 * Not writable, replace with a copy or coalesce with
1790 		 * the previous mbuf if possible (since we have to copy
1791 		 * it anyway, we try to reduce the number of mbufs and
1792 		 * clusters so that future work is easier).
1793 		 */
1794 		KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1795 		/* NB: we only coalesce into a cluster or larger */
1796 		if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1797 		    m->m_len <= M_TRAILINGSPACE(mprev)) {
1798 			/* XXX: this ignores mbuf types */
1799 			memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1800 			       mtod(m, caddr_t), m->m_len);
1801 			mprev->m_len += m->m_len;
1802 			mprev->m_next = m->m_next;	/* unlink from chain */
1803 			m_free(m);			/* reclaim mbuf */
1804 			continue;
1805 		}
1806 
1807 		/*
1808 		 * Allocate new space to hold the copy...
1809 		 */
1810 		/* XXX why can M_PKTHDR be set past the first mbuf? */
1811 		if (mprev == NULL && (m->m_flags & M_PKTHDR)) {
1812 			/*
1813 			 * NB: if a packet header is present we must
1814 			 * allocate the mbuf separately from any cluster
1815 			 * because M_MOVE_PKTHDR will smash the data
1816 			 * pointer and drop the M_EXT marker.
1817 			 */
1818 			MGETHDR(n, how, m->m_type);
1819 			if (n == NULL) {
1820 				m_freem(m0);
1821 				return (NULL);
1822 			}
1823 			M_MOVE_PKTHDR(n, m);
1824 			MCLGET(n, how);
1825 			if ((n->m_flags & M_EXT) == 0) {
1826 				m_free(n);
1827 				m_freem(m0);
1828 				return (NULL);
1829 			}
1830 		} else {
1831 			n = m_getcl(how, m->m_type, m->m_flags);
1832 			if (n == NULL) {
1833 				m_freem(m0);
1834 				return (NULL);
1835 			}
1836 		}
1837 		/*
1838 		 * ... and copy the data.  We deal with jumbo mbufs
1839 		 * (i.e. m_len > MCLBYTES) by splitting them into
1840 		 * clusters.  We could just malloc a buffer and make
1841 		 * it external but too many device drivers don't know
1842 		 * how to break up the non-contiguous memory when
1843 		 * doing DMA.
1844 		 */
1845 		len = m->m_len;
1846 		off = 0;
1847 		mfirst = n;
1848 		mlast = NULL;
1849 		for (;;) {
1850 			int cc = min(len, MCLBYTES);
1851 			memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1852 			n->m_len = cc;
1853 			if (mlast != NULL)
1854 				mlast->m_next = n;
1855 			mlast = n;
1856 
1857 			len -= cc;
1858 			if (len <= 0)
1859 				break;
1860 			off += cc;
1861 
1862 			n = m_getcl(how, m->m_type, m->m_flags);
1863 			if (n == NULL) {
1864 				m_freem(mfirst);
1865 				m_freem(m0);
1866 				return (NULL);
1867 			}
1868 		}
1869 		n->m_next = m->m_next;
1870 		if (mprev == NULL)
1871 			m0 = mfirst;		/* new head of chain */
1872 		else
1873 			mprev->m_next = mfirst;	/* replace old mbuf */
1874 		m_free(m);			/* release old mbuf */
1875 		mprev = mfirst;
1876 	}
1877 	return (m0);
1878 }
1879 
1880 /*
1881  * Rearrange an mbuf chain so that len bytes are contiguous
1882  * and in the data area of an mbuf (so that mtod will work for a structure
1883  * of size len).  Returns the resulting mbuf chain on success, frees it and
1884  * returns null on failure.  If there is room, it will add up to
1885  * max_protohdr-len extra bytes to the contiguous region in an attempt to
1886  * avoid being called next time.
1887  */
1888 struct mbuf *
1889 m_pullup(struct mbuf *n, int len)
1890 {
1891 	struct mbuf *m;
1892 	int count;
1893 	int space;
1894 
1895 	/*
1896 	 * If first mbuf has no cluster, and has room for len bytes
1897 	 * without shifting current data, pullup into it,
1898 	 * otherwise allocate a new mbuf to prepend to the chain.
1899 	 */
1900 	if (!(n->m_flags & M_EXT) &&
1901 	    n->m_data + len < &n->m_dat[MLEN] &&
1902 	    n->m_next) {
1903 		if (n->m_len >= len)
1904 			return (n);
1905 		m = n;
1906 		n = n->m_next;
1907 		len -= m->m_len;
1908 	} else {
1909 		if (len > MHLEN)
1910 			goto bad;
1911 		if (n->m_flags & M_PKTHDR)
1912 			m = m_gethdr(MB_DONTWAIT, n->m_type);
1913 		else
1914 			m = m_get(MB_DONTWAIT, n->m_type);
1915 		if (m == NULL)
1916 			goto bad;
1917 		m->m_len = 0;
1918 		if (n->m_flags & M_PKTHDR)
1919 			M_MOVE_PKTHDR(m, n);
1920 	}
1921 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1922 	do {
1923 		count = min(min(max(len, max_protohdr), space), n->m_len);
1924 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1925 		  (unsigned)count);
1926 		len -= count;
1927 		m->m_len += count;
1928 		n->m_len -= count;
1929 		space -= count;
1930 		if (n->m_len)
1931 			n->m_data += count;
1932 		else
1933 			n = m_free(n);
1934 	} while (len > 0 && n);
1935 	if (len > 0) {
1936 		m_free(m);
1937 		goto bad;
1938 	}
1939 	m->m_next = n;
1940 	return (m);
1941 bad:
1942 	m_freem(n);
1943 	++mbstat[mycpu->gd_cpuid].m_mcfail;
1944 	return (NULL);
1945 }
1946 
1947 /*
1948  * Partition an mbuf chain in two pieces, returning the tail --
1949  * all but the first len0 bytes.  In case of failure, it returns NULL and
1950  * attempts to restore the chain to its original state.
1951  *
1952  * Note that the resulting mbufs might be read-only, because the new
1953  * mbuf can end up sharing an mbuf cluster with the original mbuf if
1954  * the "breaking point" happens to lie within a cluster mbuf. Use the
1955  * M_WRITABLE() macro to check for this case.
1956  */
1957 struct mbuf *
1958 m_split(struct mbuf *m0, int len0, int wait)
1959 {
1960 	struct mbuf *m, *n;
1961 	unsigned len = len0, remain;
1962 
1963 	for (m = m0; m && len > m->m_len; m = m->m_next)
1964 		len -= m->m_len;
1965 	if (m == NULL)
1966 		return (NULL);
1967 	remain = m->m_len - len;
1968 	if (m0->m_flags & M_PKTHDR) {
1969 		n = m_gethdr(wait, m0->m_type);
1970 		if (n == NULL)
1971 			return (NULL);
1972 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1973 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1974 		m0->m_pkthdr.len = len0;
1975 		if (m->m_flags & M_EXT)
1976 			goto extpacket;
1977 		if (remain > MHLEN) {
1978 			/* m can't be the lead packet */
1979 			MH_ALIGN(n, 0);
1980 			n->m_next = m_split(m, len, wait);
1981 			if (n->m_next == NULL) {
1982 				m_free(n);
1983 				return (NULL);
1984 			} else {
1985 				n->m_len = 0;
1986 				return (n);
1987 			}
1988 		} else
1989 			MH_ALIGN(n, remain);
1990 	} else if (remain == 0) {
1991 		n = m->m_next;
1992 		m->m_next = NULL;
1993 		return (n);
1994 	} else {
1995 		n = m_get(wait, m->m_type);
1996 		if (n == NULL)
1997 			return (NULL);
1998 		M_ALIGN(n, remain);
1999 	}
2000 extpacket:
2001 	if (m->m_flags & M_EXT) {
2002 		KKASSERT((n->m_flags & M_EXT) == 0);
2003 		n->m_data = m->m_data + len;
2004 		m->m_ext.ext_ref(m->m_ext.ext_arg);
2005 		n->m_ext = m->m_ext;
2006 		n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
2007 	} else {
2008 		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
2009 	}
2010 	n->m_len = remain;
2011 	m->m_len = len;
2012 	n->m_next = m->m_next;
2013 	m->m_next = NULL;
2014 	return (n);
2015 }
2016 
2017 /*
2018  * Routine to copy from device local memory into mbufs.
2019  * Note: "offset" is ill-defined and always called as 0, so ignore it.
2020  */
2021 struct mbuf *
2022 m_devget(char *buf, int len, int offset, struct ifnet *ifp,
2023     void (*copy)(volatile const void *from, volatile void *to, size_t length))
2024 {
2025 	struct mbuf *m, *mfirst = NULL, **mtail;
2026 	int nsize, flags;
2027 
2028 	if (copy == NULL)
2029 		copy = bcopy;
2030 	mtail = &mfirst;
2031 	flags = M_PKTHDR;
2032 
2033 	while (len > 0) {
2034 		m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
2035 		if (m == NULL) {
2036 			m_freem(mfirst);
2037 			return (NULL);
2038 		}
2039 		m->m_len = min(len, nsize);
2040 
2041 		if (flags & M_PKTHDR) {
2042 			if (len + max_linkhdr <= nsize)
2043 				m->m_data += max_linkhdr;
2044 			m->m_pkthdr.rcvif = ifp;
2045 			m->m_pkthdr.len = len;
2046 			flags = 0;
2047 		}
2048 
2049 		copy(buf, m->m_data, (unsigned)m->m_len);
2050 		buf += m->m_len;
2051 		len -= m->m_len;
2052 		*mtail = m;
2053 		mtail = &m->m_next;
2054 	}
2055 
2056 	return (mfirst);
2057 }
2058 
2059 /*
2060  * Routine to pad mbuf to the specified length 'padto'.
2061  */
2062 int
2063 m_devpad(struct mbuf *m, int padto)
2064 {
2065 	struct mbuf *last = NULL;
2066 	int padlen;
2067 
2068 	if (padto <= m->m_pkthdr.len)
2069 		return 0;
2070 
2071 	padlen = padto - m->m_pkthdr.len;
2072 
2073 	/* if there's only the packet-header and we can pad there, use it. */
2074 	if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
2075 		last = m;
2076 	} else {
2077 		/*
2078 		 * Walk packet chain to find last mbuf. We will either
2079 		 * pad there, or append a new mbuf and pad it
2080 		 */
2081 		for (last = m; last->m_next != NULL; last = last->m_next)
2082 			; /* EMPTY */
2083 
2084 		/* `last' now points to last in chain. */
2085 		if (M_TRAILINGSPACE(last) < padlen) {
2086 			struct mbuf *n;
2087 
2088 			/* Allocate new empty mbuf, pad it.  Compact later. */
2089 			MGET(n, MB_DONTWAIT, MT_DATA);
2090 			if (n == NULL)
2091 				return ENOBUFS;
2092 			n->m_len = 0;
2093 			last->m_next = n;
2094 			last = n;
2095 		}
2096 	}
2097 	KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2098 	KKASSERT(M_WRITABLE(last));
2099 
2100 	/* Now zero the pad area */
2101 	bzero(mtod(last, char *) + last->m_len, padlen);
2102 	last->m_len += padlen;
2103 	m->m_pkthdr.len += padlen;
2104 	return 0;
2105 }
2106 
2107 /*
2108  * Copy data from a buffer back into the indicated mbuf chain,
2109  * starting "off" bytes from the beginning, extending the mbuf
2110  * chain if necessary.
2111  */
2112 void
2113 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
2114 {
2115 	int mlen;
2116 	struct mbuf *m = m0, *n;
2117 	int totlen = 0;
2118 
2119 	if (m0 == NULL)
2120 		return;
2121 	while (off > (mlen = m->m_len)) {
2122 		off -= mlen;
2123 		totlen += mlen;
2124 		if (m->m_next == NULL) {
2125 			n = m_getclr(MB_DONTWAIT, m->m_type);
2126 			if (n == NULL)
2127 				goto out;
2128 			n->m_len = min(MLEN, len + off);
2129 			m->m_next = n;
2130 		}
2131 		m = m->m_next;
2132 	}
2133 	while (len > 0) {
2134 		mlen = min (m->m_len - off, len);
2135 		bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
2136 		cp += mlen;
2137 		len -= mlen;
2138 		mlen += off;
2139 		off = 0;
2140 		totlen += mlen;
2141 		if (len == 0)
2142 			break;
2143 		if (m->m_next == NULL) {
2144 			n = m_get(MB_DONTWAIT, m->m_type);
2145 			if (n == NULL)
2146 				break;
2147 			n->m_len = min(MLEN, len);
2148 			m->m_next = n;
2149 		}
2150 		m = m->m_next;
2151 	}
2152 out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
2153 		m->m_pkthdr.len = totlen;
2154 }
2155 
2156 /*
2157  * Append the specified data to the indicated mbuf chain,
2158  * Extend the mbuf chain if the new data does not fit in
2159  * existing space.
2160  *
2161  * Return 1 if able to complete the job; otherwise 0.
2162  */
2163 int
2164 m_append(struct mbuf *m0, int len, c_caddr_t cp)
2165 {
2166 	struct mbuf *m, *n;
2167 	int remainder, space;
2168 
2169 	for (m = m0; m->m_next != NULL; m = m->m_next)
2170 		;
2171 	remainder = len;
2172 	space = M_TRAILINGSPACE(m);
2173 	if (space > 0) {
2174 		/*
2175 		 * Copy into available space.
2176 		 */
2177 		if (space > remainder)
2178 			space = remainder;
2179 		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
2180 		m->m_len += space;
2181 		cp += space, remainder -= space;
2182 	}
2183 	while (remainder > 0) {
2184 		/*
2185 		 * Allocate a new mbuf; could check space
2186 		 * and allocate a cluster instead.
2187 		 */
2188 		n = m_get(MB_DONTWAIT, m->m_type);
2189 		if (n == NULL)
2190 			break;
2191 		n->m_len = min(MLEN, remainder);
2192 		bcopy(cp, mtod(n, caddr_t), n->m_len);
2193 		cp += n->m_len, remainder -= n->m_len;
2194 		m->m_next = n;
2195 		m = n;
2196 	}
2197 	if (m0->m_flags & M_PKTHDR)
2198 		m0->m_pkthdr.len += len - remainder;
2199 	return (remainder == 0);
2200 }
2201 
2202 /*
2203  * Apply function f to the data in an mbuf chain starting "off" bytes from
2204  * the beginning, continuing for "len" bytes.
2205  */
2206 int
2207 m_apply(struct mbuf *m, int off, int len,
2208     int (*f)(void *, void *, u_int), void *arg)
2209 {
2210 	u_int count;
2211 	int rval;
2212 
2213 	KASSERT(off >= 0, ("m_apply, negative off %d", off));
2214 	KASSERT(len >= 0, ("m_apply, negative len %d", len));
2215 	while (off > 0) {
2216 		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2217 		if (off < m->m_len)
2218 			break;
2219 		off -= m->m_len;
2220 		m = m->m_next;
2221 	}
2222 	while (len > 0) {
2223 		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
2224 		count = min(m->m_len - off, len);
2225 		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
2226 		if (rval)
2227 			return (rval);
2228 		len -= count;
2229 		off = 0;
2230 		m = m->m_next;
2231 	}
2232 	return (0);
2233 }
2234 
2235 /*
2236  * Return a pointer to mbuf/offset of location in mbuf chain.
2237  */
2238 struct mbuf *
2239 m_getptr(struct mbuf *m, int loc, int *off)
2240 {
2241 
2242 	while (loc >= 0) {
2243 		/* Normal end of search. */
2244 		if (m->m_len > loc) {
2245 			*off = loc;
2246 			return (m);
2247 		} else {
2248 			loc -= m->m_len;
2249 			if (m->m_next == NULL) {
2250 				if (loc == 0) {
2251 					/* Point at the end of valid data. */
2252 					*off = m->m_len;
2253 					return (m);
2254 				}
2255 				return (NULL);
2256 			}
2257 			m = m->m_next;
2258 		}
2259 	}
2260 	return (NULL);
2261 }
2262 
2263 void
2264 m_print(const struct mbuf *m)
2265 {
2266 	int len;
2267 	const struct mbuf *m2;
2268 	char *hexstr;
2269 
2270 	len = m->m_pkthdr.len;
2271 	m2 = m;
2272 	hexstr = kmalloc(HEX_NCPYLEN(len), M_TEMP, M_ZERO | M_WAITOK);
2273 	while (len) {
2274 		kprintf("%p %s\n", m2, hexncpy(m2->m_data, m2->m_len, hexstr,
2275 			HEX_NCPYLEN(m2->m_len), "-"));
2276 		len -= m2->m_len;
2277 		m2 = m2->m_next;
2278 	}
2279 	kfree(hexstr, M_TEMP);
2280 	return;
2281 }
2282 
2283 /*
2284  * "Move" mbuf pkthdr from "from" to "to".
2285  * "from" must have M_PKTHDR set, and "to" must be empty.
2286  */
2287 void
2288 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
2289 {
2290 	KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
2291 
2292 	to->m_flags |= from->m_flags & M_COPYFLAGS;
2293 	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
2294 	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
2295 }
2296 
2297 /*
2298  * Duplicate "from"'s mbuf pkthdr in "to".
2299  * "from" must have M_PKTHDR set, and "to" must be empty.
2300  * In particular, this does a deep copy of the packet tags.
2301  */
2302 int
2303 m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
2304 {
2305 	KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
2306 
2307 	to->m_flags = (from->m_flags & M_COPYFLAGS) |
2308 		      (to->m_flags & ~M_COPYFLAGS);
2309 	to->m_pkthdr = from->m_pkthdr;
2310 	SLIST_INIT(&to->m_pkthdr.tags);
2311 	return (m_tag_copy_chain(to, from, how));
2312 }
2313 
2314 /*
2315  * Defragment a mbuf chain, returning the shortest possible
2316  * chain of mbufs and clusters.  If allocation fails and
2317  * this cannot be completed, NULL will be returned, but
2318  * the passed in chain will be unchanged.  Upon success,
2319  * the original chain will be freed, and the new chain
2320  * will be returned.
2321  *
2322  * If a non-packet header is passed in, the original
2323  * mbuf (chain?) will be returned unharmed.
2324  *
2325  * m_defrag_nofree doesn't free the passed in mbuf.
2326  */
2327 struct mbuf *
2328 m_defrag(struct mbuf *m0, int how)
2329 {
2330 	struct mbuf *m_new;
2331 
2332 	if ((m_new = m_defrag_nofree(m0, how)) == NULL)
2333 		return (NULL);
2334 	if (m_new != m0)
2335 		m_freem(m0);
2336 	return (m_new);
2337 }
2338 
2339 struct mbuf *
2340 m_defrag_nofree(struct mbuf *m0, int how)
2341 {
2342 	struct mbuf	*m_new = NULL, *m_final = NULL;
2343 	int		progress = 0, length, nsize;
2344 
2345 	if (!(m0->m_flags & M_PKTHDR))
2346 		return (m0);
2347 
2348 #ifdef MBUF_STRESS_TEST
2349 	if (m_defragrandomfailures) {
2350 		int temp = karc4random() & 0xff;
2351 		if (temp == 0xba)
2352 			goto nospace;
2353 	}
2354 #endif
2355 
2356 	m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
2357 	if (m_final == NULL)
2358 		goto nospace;
2359 	m_final->m_len = 0;	/* in case m0->m_pkthdr.len is zero */
2360 
2361 	if (m_dup_pkthdr(m_final, m0, how) == 0)
2362 		goto nospace;
2363 
2364 	m_new = m_final;
2365 
2366 	while (progress < m0->m_pkthdr.len) {
2367 		length = m0->m_pkthdr.len - progress;
2368 		if (length > MCLBYTES)
2369 			length = MCLBYTES;
2370 
2371 		if (m_new == NULL) {
2372 			m_new = m_getl(length, how, MT_DATA, 0, &nsize);
2373 			if (m_new == NULL)
2374 				goto nospace;
2375 		}
2376 
2377 		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2378 		progress += length;
2379 		m_new->m_len = length;
2380 		if (m_new != m_final)
2381 			m_cat(m_final, m_new);
2382 		m_new = NULL;
2383 	}
2384 	if (m0->m_next == NULL)
2385 		m_defraguseless++;
2386 	m_defragpackets++;
2387 	m_defragbytes += m_final->m_pkthdr.len;
2388 	return (m_final);
2389 nospace:
2390 	m_defragfailure++;
2391 	if (m_new)
2392 		m_free(m_new);
2393 	m_freem(m_final);
2394 	return (NULL);
2395 }
2396 
2397 /*
2398  * Move data from uio into mbufs.
2399  */
2400 struct mbuf *
2401 m_uiomove(struct uio *uio)
2402 {
2403 	struct mbuf *m;			/* current working mbuf */
2404 	struct mbuf *head = NULL;	/* result mbuf chain */
2405 	struct mbuf **mp = &head;
2406 	int flags = M_PKTHDR;
2407 	int nsize;
2408 	int error;
2409 	int resid;
2410 
2411 	do {
2412 		if (uio->uio_resid > INT_MAX)
2413 			resid = INT_MAX;
2414 		else
2415 			resid = (int)uio->uio_resid;
2416 		m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
2417 		if (flags) {
2418 			m->m_pkthdr.len = 0;
2419 			/* Leave room for protocol headers. */
2420 			if (resid < MHLEN)
2421 				MH_ALIGN(m, resid);
2422 			flags = 0;
2423 		}
2424 		m->m_len = imin(nsize, resid);
2425 		error = uiomove(mtod(m, caddr_t), m->m_len, uio);
2426 		if (error) {
2427 			m_free(m);
2428 			goto failed;
2429 		}
2430 		*mp = m;
2431 		mp = &m->m_next;
2432 		head->m_pkthdr.len += m->m_len;
2433 	} while (uio->uio_resid > 0);
2434 
2435 	return (head);
2436 
2437 failed:
2438 	m_freem(head);
2439 	return (NULL);
2440 }
2441 
2442 struct mbuf *
2443 m_last(struct mbuf *m)
2444 {
2445 	while (m->m_next)
2446 		m = m->m_next;
2447 	return (m);
2448 }
2449 
2450 /*
2451  * Return the number of bytes in an mbuf chain.
2452  * If lastm is not NULL, also return the last mbuf.
2453  */
2454 u_int
2455 m_lengthm(struct mbuf *m, struct mbuf **lastm)
2456 {
2457 	u_int len = 0;
2458 	struct mbuf *prev = m;
2459 
2460 	while (m) {
2461 		len += m->m_len;
2462 		prev = m;
2463 		m = m->m_next;
2464 	}
2465 	if (lastm != NULL)
2466 		*lastm = prev;
2467 	return (len);
2468 }
2469 
2470 /*
2471  * Like m_lengthm(), except also keep track of mbuf usage.
2472  */
2473 u_int
2474 m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2475 {
2476 	u_int len = 0, mbcnt = 0;
2477 	struct mbuf *prev = m;
2478 
2479 	while (m) {
2480 		len += m->m_len;
2481 		mbcnt += MSIZE;
2482 		if (m->m_flags & M_EXT)
2483 			mbcnt += m->m_ext.ext_size;
2484 		prev = m;
2485 		m = m->m_next;
2486 	}
2487 	if (lastm != NULL)
2488 		*lastm = prev;
2489 	*pmbcnt = mbcnt;
2490 	return (len);
2491 }
2492