xref: /freebsd/sys/kern/uipc_mbuf.c (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_param.h"
36 #include "opt_mbuf_stress_test.h"
37 #include "opt_mbuf_profiling.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/limits.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/sysctl.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/uio.h>
50 
51 int	max_linkhdr;
52 int	max_protohdr;
53 int	max_hdr;
54 int	max_datalen;
55 #ifdef MBUF_STRESS_TEST
56 int	m_defragpackets;
57 int	m_defragbytes;
58 int	m_defraguseless;
59 int	m_defragfailure;
60 int	m_defragrandomfailures;
61 #endif
62 
63 /*
64  * sysctl(8) exported objects
65  */
66 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RD,
67 	   &max_linkhdr, 0, "Size of largest link layer header");
68 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RD,
69 	   &max_protohdr, 0, "Size of largest protocol layer header");
70 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RD,
71 	   &max_hdr, 0, "Size of largest link plus protocol header");
72 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RD,
73 	   &max_datalen, 0, "Minimum space left in mbuf after max_hdr");
74 #ifdef MBUF_STRESS_TEST
75 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
76 	   &m_defragpackets, 0, "");
77 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
78 	   &m_defragbytes, 0, "");
79 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
80 	   &m_defraguseless, 0, "");
81 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
82 	   &m_defragfailure, 0, "");
83 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
84 	   &m_defragrandomfailures, 0, "");
85 #endif
86 
87 /*
88  * Ensure the correct size of various mbuf parameters.  It could be off due
89  * to compiler-induced padding and alignment artifacts.
90  */
91 CTASSERT(MSIZE - offsetof(struct mbuf, m_dat) == MLEN);
92 CTASSERT(MSIZE - offsetof(struct mbuf, m_pktdat) == MHLEN);
93 
94 /*
95  * mbuf data storage should be 64-bit aligned regardless of architectural
96  * pointer size; check this is the case with and without a packet header.
97  */
98 CTASSERT(offsetof(struct mbuf, m_dat) % 8 == 0);
99 CTASSERT(offsetof(struct mbuf, m_pktdat) % 8 == 0);
100 
101 /*
102  * While the specific values here don't matter too much (i.e., +/- a few
103  * words), we do want to ensure that changes to these values are carefully
104  * reasoned about and properly documented.  This is especially the case as
105  * network-protocol and device-driver modules encode these layouts, and must
106  * be recompiled if the structures change.  Check these values at compile time
107  * against the ones documented in comments in mbuf.h.
108  *
109  * NB: Possibly they should be documented there via #define's and not just
110  * comments.
111  */
112 #if defined(__LP64__)
113 CTASSERT(offsetof(struct mbuf, m_dat) == 32);
114 CTASSERT(sizeof(struct pkthdr) == 56);
115 CTASSERT(sizeof(struct struct_m_ext) == 48);
116 #else
117 CTASSERT(offsetof(struct mbuf, m_dat) == 24);
118 CTASSERT(sizeof(struct pkthdr) == 48);
119 CTASSERT(sizeof(struct struct_m_ext) == 28);
120 #endif
121 
122 /*
123  * m_get2() allocates minimum mbuf that would fit "size" argument.
124  */
125 struct mbuf *
126 m_get2(int size, int how, short type, int flags)
127 {
128 	struct mb_args args;
129 	struct mbuf *m, *n;
130 
131 	args.flags = flags;
132 	args.type = type;
133 
134 	if (size <= MHLEN || (size <= MLEN && (flags & M_PKTHDR) == 0))
135 		return (uma_zalloc_arg(zone_mbuf, &args, how));
136 	if (size <= MCLBYTES)
137 		return (uma_zalloc_arg(zone_pack, &args, how));
138 
139 	if (size > MJUMPAGESIZE)
140 		return (NULL);
141 
142 	m = uma_zalloc_arg(zone_mbuf, &args, how);
143 	if (m == NULL)
144 		return (NULL);
145 
146 	n = uma_zalloc_arg(zone_jumbop, m, how);
147 	if (n == NULL) {
148 		uma_zfree(zone_mbuf, m);
149 		return (NULL);
150 	}
151 
152 	return (m);
153 }
154 
155 /*
156  * m_getjcl() returns an mbuf with a cluster of the specified size attached.
157  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
158  */
159 struct mbuf *
160 m_getjcl(int how, short type, int flags, int size)
161 {
162 	struct mb_args args;
163 	struct mbuf *m, *n;
164 	uma_zone_t zone;
165 
166 	if (size == MCLBYTES)
167 		return m_getcl(how, type, flags);
168 
169 	args.flags = flags;
170 	args.type = type;
171 
172 	m = uma_zalloc_arg(zone_mbuf, &args, how);
173 	if (m == NULL)
174 		return (NULL);
175 
176 	zone = m_getzone(size);
177 	n = uma_zalloc_arg(zone, m, how);
178 	if (n == NULL) {
179 		uma_zfree(zone_mbuf, m);
180 		return (NULL);
181 	}
182 	return (m);
183 }
184 
185 /*
186  * Allocate a given length worth of mbufs and/or clusters (whatever fits
187  * best) and return a pointer to the top of the allocated chain.  If an
188  * existing mbuf chain is provided, then we will append the new chain
189  * to the existing one but still return the top of the newly allocated
190  * chain.
191  */
192 struct mbuf *
193 m_getm2(struct mbuf *m, int len, int how, short type, int flags)
194 {
195 	struct mbuf *mb, *nm = NULL, *mtail = NULL;
196 
197 	KASSERT(len >= 0, ("%s: len is < 0", __func__));
198 
199 	/* Validate flags. */
200 	flags &= (M_PKTHDR | M_EOR);
201 
202 	/* Packet header mbuf must be first in chain. */
203 	if ((flags & M_PKTHDR) && m != NULL)
204 		flags &= ~M_PKTHDR;
205 
206 	/* Loop and append maximum sized mbufs to the chain tail. */
207 	while (len > 0) {
208 		if (len > MCLBYTES)
209 			mb = m_getjcl(how, type, (flags & M_PKTHDR),
210 			    MJUMPAGESIZE);
211 		else if (len >= MINCLSIZE)
212 			mb = m_getcl(how, type, (flags & M_PKTHDR));
213 		else if (flags & M_PKTHDR)
214 			mb = m_gethdr(how, type);
215 		else
216 			mb = m_get(how, type);
217 
218 		/* Fail the whole operation if one mbuf can't be allocated. */
219 		if (mb == NULL) {
220 			if (nm != NULL)
221 				m_freem(nm);
222 			return (NULL);
223 		}
224 
225 		/* Book keeping. */
226 		len -= M_SIZE(mb);
227 		if (mtail != NULL)
228 			mtail->m_next = mb;
229 		else
230 			nm = mb;
231 		mtail = mb;
232 		flags &= ~M_PKTHDR;	/* Only valid on the first mbuf. */
233 	}
234 	if (flags & M_EOR)
235 		mtail->m_flags |= M_EOR;  /* Only valid on the last mbuf. */
236 
237 	/* If mbuf was supplied, append new chain to the end of it. */
238 	if (m != NULL) {
239 		for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
240 			;
241 		mtail->m_next = nm;
242 		mtail->m_flags &= ~M_EOR;
243 	} else
244 		m = nm;
245 
246 	return (m);
247 }
248 
249 /*
250  * Free an entire chain of mbufs and associated external buffers, if
251  * applicable.
252  */
253 void
254 m_freem(struct mbuf *mb)
255 {
256 
257 	while (mb != NULL)
258 		mb = m_free(mb);
259 }
260 
261 /*-
262  * Configure a provided mbuf to refer to the provided external storage
263  * buffer and setup a reference count for said buffer.  If the setting
264  * up of the reference count fails, the M_EXT bit will not be set.  If
265  * successfull, the M_EXT bit is set in the mbuf's flags.
266  *
267  * Arguments:
268  *    mb     The existing mbuf to which to attach the provided buffer.
269  *    buf    The address of the provided external storage buffer.
270  *    size   The size of the provided buffer.
271  *    freef  A pointer to a routine that is responsible for freeing the
272  *           provided external storage buffer.
273  *    args   A pointer to an argument structure (of any type) to be passed
274  *           to the provided freef routine (may be NULL).
275  *    flags  Any other flags to be passed to the provided mbuf.
276  *    type   The type that the external storage buffer should be
277  *           labeled with.
278  *
279  * Returns:
280  *    Nothing.
281  */
282 int
283 m_extadd(struct mbuf *mb, caddr_t buf, u_int size,
284     void (*freef)(struct mbuf *, void *, void *), void *arg1, void *arg2,
285     int flags, int type, int wait)
286 {
287 	KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
288 
289 	if (type != EXT_EXTREF)
290 		mb->m_ext.ext_cnt = uma_zalloc(zone_ext_refcnt, wait);
291 
292 	if (mb->m_ext.ext_cnt == NULL)
293 		return (ENOMEM);
294 
295 	*(mb->m_ext.ext_cnt) = 1;
296 	mb->m_flags |= (M_EXT | flags);
297 	mb->m_ext.ext_buf = buf;
298 	mb->m_data = mb->m_ext.ext_buf;
299 	mb->m_ext.ext_size = size;
300 	mb->m_ext.ext_free = freef;
301 	mb->m_ext.ext_arg1 = arg1;
302 	mb->m_ext.ext_arg2 = arg2;
303 	mb->m_ext.ext_type = type;
304 	mb->m_ext.ext_flags = 0;
305 
306 	return (0);
307 }
308 
309 /*
310  * Non-directly-exported function to clean up after mbufs with M_EXT
311  * storage attached to them if the reference count hits 1.
312  */
313 void
314 mb_free_ext(struct mbuf *m)
315 {
316 	int freembuf;
317 
318 	KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
319 
320 	/*
321 	 * Check if the header is embedded in the cluster.
322 	 */
323 	freembuf = (m->m_flags & M_NOFREE) ? 0 : 1;
324 
325 	switch (m->m_ext.ext_type) {
326 	case EXT_SFBUF:
327 		sf_ext_free(m->m_ext.ext_arg1, m->m_ext.ext_arg2);
328 		break;
329 	default:
330 		KASSERT(m->m_ext.ext_cnt != NULL,
331 		    ("%s: no refcounting pointer on %p", __func__, m));
332 		/*
333 		 * Free attached storage if this mbuf is the only
334 		 * reference to it.
335 		 */
336 		if (*(m->m_ext.ext_cnt) != 1) {
337 			if (atomic_fetchadd_int(m->m_ext.ext_cnt, -1) != 1)
338 				break;
339 		}
340 
341 		switch (m->m_ext.ext_type) {
342 		case EXT_PACKET:	/* The packet zone is special. */
343 			if (*(m->m_ext.ext_cnt) == 0)
344 				*(m->m_ext.ext_cnt) = 1;
345 			uma_zfree(zone_pack, m);
346 			return;		/* Job done. */
347 		case EXT_CLUSTER:
348 			uma_zfree(zone_clust, m->m_ext.ext_buf);
349 			break;
350 		case EXT_JUMBOP:
351 			uma_zfree(zone_jumbop, m->m_ext.ext_buf);
352 			break;
353 		case EXT_JUMBO9:
354 			uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
355 			break;
356 		case EXT_JUMBO16:
357 			uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
358 			break;
359 		case EXT_NET_DRV:
360 		case EXT_MOD_TYPE:
361 		case EXT_DISPOSABLE:
362 			*(m->m_ext.ext_cnt) = 0;
363 			uma_zfree(zone_ext_refcnt, __DEVOLATILE(u_int *,
364 				m->m_ext.ext_cnt));
365 			/* FALLTHROUGH */
366 		case EXT_EXTREF:
367 			KASSERT(m->m_ext.ext_free != NULL,
368 				("%s: ext_free not set", __func__));
369 			(*(m->m_ext.ext_free))(m, m->m_ext.ext_arg1,
370 			    m->m_ext.ext_arg2);
371 			break;
372 		default:
373 			KASSERT(m->m_ext.ext_type == 0,
374 				("%s: unknown ext_type", __func__));
375 		}
376 	}
377 
378 	if (freembuf)
379 		uma_zfree(zone_mbuf, m);
380 }
381 
382 /*
383  * Attach the cluster from *m to *n, set up m_ext in *n
384  * and bump the refcount of the cluster.
385  */
386 static void
387 mb_dupcl(struct mbuf *n, struct mbuf *m)
388 {
389 
390 	KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
391 	KASSERT(!(n->m_flags & M_EXT), ("%s: M_EXT set on %p", __func__, n));
392 
393 	switch (m->m_ext.ext_type) {
394 	case EXT_SFBUF:
395 		sf_ext_ref(m->m_ext.ext_arg1, m->m_ext.ext_arg2);
396 		break;
397 	default:
398 		KASSERT(m->m_ext.ext_cnt != NULL,
399 		    ("%s: no refcounting pointer on %p", __func__, m));
400 		if (*(m->m_ext.ext_cnt) == 1)
401 			*(m->m_ext.ext_cnt) += 1;
402 		else
403 			atomic_add_int(m->m_ext.ext_cnt, 1);
404 	}
405 
406 	n->m_ext = m->m_ext;
407 	n->m_flags |= M_EXT;
408 	n->m_flags |= m->m_flags & M_RDONLY;
409 }
410 
411 /*
412  * Clean up mbuf (chain) from any tags and packet headers.
413  * If "all" is set then the first mbuf in the chain will be
414  * cleaned too.
415  */
416 void
417 m_demote(struct mbuf *m0, int all, int flags)
418 {
419 	struct mbuf *m;
420 
421 	for (m = all ? m0 : m0->m_next; m != NULL; m = m->m_next) {
422 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt in m %p, m0 %p",
423 		    __func__, m, m0));
424 		if (m->m_flags & M_PKTHDR) {
425 			m_tag_delete_chain(m, NULL);
426 			m->m_flags &= ~M_PKTHDR;
427 			bzero(&m->m_pkthdr, sizeof(struct pkthdr));
428 		}
429 		m->m_flags = m->m_flags & (M_EXT | M_RDONLY | M_NOFREE | flags);
430 	}
431 }
432 
433 /*
434  * Sanity checks on mbuf (chain) for use in KASSERT() and general
435  * debugging.
436  * Returns 0 or panics when bad and 1 on all tests passed.
437  * Sanitize, 0 to run M_SANITY_ACTION, 1 to garble things so they
438  * blow up later.
439  */
440 int
441 m_sanity(struct mbuf *m0, int sanitize)
442 {
443 	struct mbuf *m;
444 	caddr_t a, b;
445 	int pktlen = 0;
446 
447 #ifdef INVARIANTS
448 #define	M_SANITY_ACTION(s)	panic("mbuf %p: " s, m)
449 #else
450 #define	M_SANITY_ACTION(s)	printf("mbuf %p: " s, m)
451 #endif
452 
453 	for (m = m0; m != NULL; m = m->m_next) {
454 		/*
455 		 * Basic pointer checks.  If any of these fails then some
456 		 * unrelated kernel memory before or after us is trashed.
457 		 * No way to recover from that.
458 		 */
459 		a = M_START(m);
460 		b = a + M_SIZE(m);
461 		if ((caddr_t)m->m_data < a)
462 			M_SANITY_ACTION("m_data outside mbuf data range left");
463 		if ((caddr_t)m->m_data > b)
464 			M_SANITY_ACTION("m_data outside mbuf data range right");
465 		if ((caddr_t)m->m_data + m->m_len > b)
466 			M_SANITY_ACTION("m_data + m_len exeeds mbuf space");
467 
468 		/* m->m_nextpkt may only be set on first mbuf in chain. */
469 		if (m != m0 && m->m_nextpkt != NULL) {
470 			if (sanitize) {
471 				m_freem(m->m_nextpkt);
472 				m->m_nextpkt = (struct mbuf *)0xDEADC0DE;
473 			} else
474 				M_SANITY_ACTION("m->m_nextpkt on in-chain mbuf");
475 		}
476 
477 		/* packet length (not mbuf length!) calculation */
478 		if (m0->m_flags & M_PKTHDR)
479 			pktlen += m->m_len;
480 
481 		/* m_tags may only be attached to first mbuf in chain. */
482 		if (m != m0 && m->m_flags & M_PKTHDR &&
483 		    !SLIST_EMPTY(&m->m_pkthdr.tags)) {
484 			if (sanitize) {
485 				m_tag_delete_chain(m, NULL);
486 				/* put in 0xDEADC0DE perhaps? */
487 			} else
488 				M_SANITY_ACTION("m_tags on in-chain mbuf");
489 		}
490 
491 		/* M_PKTHDR may only be set on first mbuf in chain */
492 		if (m != m0 && m->m_flags & M_PKTHDR) {
493 			if (sanitize) {
494 				bzero(&m->m_pkthdr, sizeof(m->m_pkthdr));
495 				m->m_flags &= ~M_PKTHDR;
496 				/* put in 0xDEADCODE and leave hdr flag in */
497 			} else
498 				M_SANITY_ACTION("M_PKTHDR on in-chain mbuf");
499 		}
500 	}
501 	m = m0;
502 	if (pktlen && pktlen != m->m_pkthdr.len) {
503 		if (sanitize)
504 			m->m_pkthdr.len = 0;
505 		else
506 			M_SANITY_ACTION("m_pkthdr.len != mbuf chain length");
507 	}
508 	return 1;
509 
510 #undef	M_SANITY_ACTION
511 }
512 
513 
514 /*
515  * "Move" mbuf pkthdr from "from" to "to".
516  * "from" must have M_PKTHDR set, and "to" must be empty.
517  */
518 void
519 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
520 {
521 
522 #if 0
523 	/* see below for why these are not enabled */
524 	M_ASSERTPKTHDR(to);
525 	/* Note: with MAC, this may not be a good assertion. */
526 	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
527 	    ("m_move_pkthdr: to has tags"));
528 #endif
529 #ifdef MAC
530 	/*
531 	 * XXXMAC: It could be this should also occur for non-MAC?
532 	 */
533 	if (to->m_flags & M_PKTHDR)
534 		m_tag_delete_chain(to, NULL);
535 #endif
536 	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
537 	if ((to->m_flags & M_EXT) == 0)
538 		to->m_data = to->m_pktdat;
539 	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
540 	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
541 	from->m_flags &= ~M_PKTHDR;
542 }
543 
544 /*
545  * Duplicate "from"'s mbuf pkthdr in "to".
546  * "from" must have M_PKTHDR set, and "to" must be empty.
547  * In particular, this does a deep copy of the packet tags.
548  */
549 int
550 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
551 {
552 
553 #if 0
554 	/*
555 	 * The mbuf allocator only initializes the pkthdr
556 	 * when the mbuf is allocated with m_gethdr(). Many users
557 	 * (e.g. m_copy*, m_prepend) use m_get() and then
558 	 * smash the pkthdr as needed causing these
559 	 * assertions to trip.  For now just disable them.
560 	 */
561 	M_ASSERTPKTHDR(to);
562 	/* Note: with MAC, this may not be a good assertion. */
563 	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
564 #endif
565 	MBUF_CHECKSLEEP(how);
566 #ifdef MAC
567 	if (to->m_flags & M_PKTHDR)
568 		m_tag_delete_chain(to, NULL);
569 #endif
570 	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
571 	if ((to->m_flags & M_EXT) == 0)
572 		to->m_data = to->m_pktdat;
573 	to->m_pkthdr = from->m_pkthdr;
574 	SLIST_INIT(&to->m_pkthdr.tags);
575 	return (m_tag_copy_chain(to, from, how));
576 }
577 
578 /*
579  * Lesser-used path for M_PREPEND:
580  * allocate new mbuf to prepend to chain,
581  * copy junk along.
582  */
583 struct mbuf *
584 m_prepend(struct mbuf *m, int len, int how)
585 {
586 	struct mbuf *mn;
587 
588 	if (m->m_flags & M_PKTHDR)
589 		mn = m_gethdr(how, m->m_type);
590 	else
591 		mn = m_get(how, m->m_type);
592 	if (mn == NULL) {
593 		m_freem(m);
594 		return (NULL);
595 	}
596 	if (m->m_flags & M_PKTHDR)
597 		m_move_pkthdr(mn, m);
598 	mn->m_next = m;
599 	m = mn;
600 	if (len < M_SIZE(m))
601 		M_ALIGN(m, len);
602 	m->m_len = len;
603 	return (m);
604 }
605 
606 /*
607  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
608  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
609  * The wait parameter is a choice of M_WAITOK/M_NOWAIT from caller.
610  * Note that the copy is read-only, because clusters are not copied,
611  * only their reference counts are incremented.
612  */
613 struct mbuf *
614 m_copym(struct mbuf *m, int off0, int len, int wait)
615 {
616 	struct mbuf *n, **np;
617 	int off = off0;
618 	struct mbuf *top;
619 	int copyhdr = 0;
620 
621 	KASSERT(off >= 0, ("m_copym, negative off %d", off));
622 	KASSERT(len >= 0, ("m_copym, negative len %d", len));
623 	MBUF_CHECKSLEEP(wait);
624 	if (off == 0 && m->m_flags & M_PKTHDR)
625 		copyhdr = 1;
626 	while (off > 0) {
627 		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
628 		if (off < m->m_len)
629 			break;
630 		off -= m->m_len;
631 		m = m->m_next;
632 	}
633 	np = &top;
634 	top = 0;
635 	while (len > 0) {
636 		if (m == NULL) {
637 			KASSERT(len == M_COPYALL,
638 			    ("m_copym, length > size of mbuf chain"));
639 			break;
640 		}
641 		if (copyhdr)
642 			n = m_gethdr(wait, m->m_type);
643 		else
644 			n = m_get(wait, m->m_type);
645 		*np = n;
646 		if (n == NULL)
647 			goto nospace;
648 		if (copyhdr) {
649 			if (!m_dup_pkthdr(n, m, wait))
650 				goto nospace;
651 			if (len == M_COPYALL)
652 				n->m_pkthdr.len -= off0;
653 			else
654 				n->m_pkthdr.len = len;
655 			copyhdr = 0;
656 		}
657 		n->m_len = min(len, m->m_len - off);
658 		if (m->m_flags & M_EXT) {
659 			n->m_data = m->m_data + off;
660 			mb_dupcl(n, m);
661 		} else
662 			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
663 			    (u_int)n->m_len);
664 		if (len != M_COPYALL)
665 			len -= n->m_len;
666 		off = 0;
667 		m = m->m_next;
668 		np = &n->m_next;
669 	}
670 
671 	return (top);
672 nospace:
673 	m_freem(top);
674 	return (NULL);
675 }
676 
677 /*
678  * Copy an entire packet, including header (which must be present).
679  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
680  * Note that the copy is read-only, because clusters are not copied,
681  * only their reference counts are incremented.
682  * Preserve alignment of the first mbuf so if the creator has left
683  * some room at the beginning (e.g. for inserting protocol headers)
684  * the copies still have the room available.
685  */
686 struct mbuf *
687 m_copypacket(struct mbuf *m, int how)
688 {
689 	struct mbuf *top, *n, *o;
690 
691 	MBUF_CHECKSLEEP(how);
692 	n = m_get(how, m->m_type);
693 	top = n;
694 	if (n == NULL)
695 		goto nospace;
696 
697 	if (!m_dup_pkthdr(n, m, how))
698 		goto nospace;
699 	n->m_len = m->m_len;
700 	if (m->m_flags & M_EXT) {
701 		n->m_data = m->m_data;
702 		mb_dupcl(n, m);
703 	} else {
704 		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
705 		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
706 	}
707 
708 	m = m->m_next;
709 	while (m) {
710 		o = m_get(how, m->m_type);
711 		if (o == NULL)
712 			goto nospace;
713 
714 		n->m_next = o;
715 		n = n->m_next;
716 
717 		n->m_len = m->m_len;
718 		if (m->m_flags & M_EXT) {
719 			n->m_data = m->m_data;
720 			mb_dupcl(n, m);
721 		} else {
722 			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
723 		}
724 
725 		m = m->m_next;
726 	}
727 	return top;
728 nospace:
729 	m_freem(top);
730 	return (NULL);
731 }
732 
733 /*
734  * Copy data from an mbuf chain starting "off" bytes from the beginning,
735  * continuing for "len" bytes, into the indicated buffer.
736  */
737 void
738 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
739 {
740 	u_int count;
741 
742 	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
743 	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
744 	while (off > 0) {
745 		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
746 		if (off < m->m_len)
747 			break;
748 		off -= m->m_len;
749 		m = m->m_next;
750 	}
751 	while (len > 0) {
752 		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
753 		count = min(m->m_len - off, len);
754 		bcopy(mtod(m, caddr_t) + off, cp, count);
755 		len -= count;
756 		cp += count;
757 		off = 0;
758 		m = m->m_next;
759 	}
760 }
761 
762 /*
763  * Copy a packet header mbuf chain into a completely new chain, including
764  * copying any mbuf clusters.  Use this instead of m_copypacket() when
765  * you need a writable copy of an mbuf chain.
766  */
767 struct mbuf *
768 m_dup(struct mbuf *m, int how)
769 {
770 	struct mbuf **p, *top = NULL;
771 	int remain, moff, nsize;
772 
773 	MBUF_CHECKSLEEP(how);
774 	/* Sanity check */
775 	if (m == NULL)
776 		return (NULL);
777 	M_ASSERTPKTHDR(m);
778 
779 	/* While there's more data, get a new mbuf, tack it on, and fill it */
780 	remain = m->m_pkthdr.len;
781 	moff = 0;
782 	p = &top;
783 	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
784 		struct mbuf *n;
785 
786 		/* Get the next new mbuf */
787 		if (remain >= MINCLSIZE) {
788 			n = m_getcl(how, m->m_type, 0);
789 			nsize = MCLBYTES;
790 		} else {
791 			n = m_get(how, m->m_type);
792 			nsize = MLEN;
793 		}
794 		if (n == NULL)
795 			goto nospace;
796 
797 		if (top == NULL) {		/* First one, must be PKTHDR */
798 			if (!m_dup_pkthdr(n, m, how)) {
799 				m_free(n);
800 				goto nospace;
801 			}
802 			if ((n->m_flags & M_EXT) == 0)
803 				nsize = MHLEN;
804 		}
805 		n->m_len = 0;
806 
807 		/* Link it into the new chain */
808 		*p = n;
809 		p = &n->m_next;
810 
811 		/* Copy data from original mbuf(s) into new mbuf */
812 		while (n->m_len < nsize && m != NULL) {
813 			int chunk = min(nsize - n->m_len, m->m_len - moff);
814 
815 			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
816 			moff += chunk;
817 			n->m_len += chunk;
818 			remain -= chunk;
819 			if (moff == m->m_len) {
820 				m = m->m_next;
821 				moff = 0;
822 			}
823 		}
824 
825 		/* Check correct total mbuf length */
826 		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
827 		    	("%s: bogus m_pkthdr.len", __func__));
828 	}
829 	return (top);
830 
831 nospace:
832 	m_freem(top);
833 	return (NULL);
834 }
835 
836 /*
837  * Concatenate mbuf chain n to m.
838  * Both chains must be of the same type (e.g. MT_DATA).
839  * Any m_pkthdr is not updated.
840  */
841 void
842 m_cat(struct mbuf *m, struct mbuf *n)
843 {
844 	while (m->m_next)
845 		m = m->m_next;
846 	while (n) {
847 		if (!M_WRITABLE(m) ||
848 		    M_TRAILINGSPACE(m) < n->m_len) {
849 			/* just join the two chains */
850 			m->m_next = n;
851 			return;
852 		}
853 		/* splat the data from one into the other */
854 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
855 		    (u_int)n->m_len);
856 		m->m_len += n->m_len;
857 		n = m_free(n);
858 	}
859 }
860 
861 /*
862  * Concatenate two pkthdr mbuf chains.
863  */
864 void
865 m_catpkt(struct mbuf *m, struct mbuf *n)
866 {
867 
868 	M_ASSERTPKTHDR(m);
869 	M_ASSERTPKTHDR(n);
870 
871 	m->m_pkthdr.len += n->m_pkthdr.len;
872 	m_demote(n, 1, 0);
873 
874 	m_cat(m, n);
875 }
876 
877 void
878 m_adj(struct mbuf *mp, int req_len)
879 {
880 	int len = req_len;
881 	struct mbuf *m;
882 	int count;
883 
884 	if ((m = mp) == NULL)
885 		return;
886 	if (len >= 0) {
887 		/*
888 		 * Trim from head.
889 		 */
890 		while (m != NULL && len > 0) {
891 			if (m->m_len <= len) {
892 				len -= m->m_len;
893 				m->m_len = 0;
894 				m = m->m_next;
895 			} else {
896 				m->m_len -= len;
897 				m->m_data += len;
898 				len = 0;
899 			}
900 		}
901 		if (mp->m_flags & M_PKTHDR)
902 			mp->m_pkthdr.len -= (req_len - len);
903 	} else {
904 		/*
905 		 * Trim from tail.  Scan the mbuf chain,
906 		 * calculating its length and finding the last mbuf.
907 		 * If the adjustment only affects this mbuf, then just
908 		 * adjust and return.  Otherwise, rescan and truncate
909 		 * after the remaining size.
910 		 */
911 		len = -len;
912 		count = 0;
913 		for (;;) {
914 			count += m->m_len;
915 			if (m->m_next == (struct mbuf *)0)
916 				break;
917 			m = m->m_next;
918 		}
919 		if (m->m_len >= len) {
920 			m->m_len -= len;
921 			if (mp->m_flags & M_PKTHDR)
922 				mp->m_pkthdr.len -= len;
923 			return;
924 		}
925 		count -= len;
926 		if (count < 0)
927 			count = 0;
928 		/*
929 		 * Correct length for chain is "count".
930 		 * Find the mbuf with last data, adjust its length,
931 		 * and toss data from remaining mbufs on chain.
932 		 */
933 		m = mp;
934 		if (m->m_flags & M_PKTHDR)
935 			m->m_pkthdr.len = count;
936 		for (; m; m = m->m_next) {
937 			if (m->m_len >= count) {
938 				m->m_len = count;
939 				if (m->m_next != NULL) {
940 					m_freem(m->m_next);
941 					m->m_next = NULL;
942 				}
943 				break;
944 			}
945 			count -= m->m_len;
946 		}
947 	}
948 }
949 
950 /*
951  * Rearange an mbuf chain so that len bytes are contiguous
952  * and in the data area of an mbuf (so that mtod will work
953  * for a structure of size len).  Returns the resulting
954  * mbuf chain on success, frees it and returns null on failure.
955  * If there is room, it will add up to max_protohdr-len extra bytes to the
956  * contiguous region in an attempt to avoid being called next time.
957  */
958 struct mbuf *
959 m_pullup(struct mbuf *n, int len)
960 {
961 	struct mbuf *m;
962 	int count;
963 	int space;
964 
965 	/*
966 	 * If first mbuf has no cluster, and has room for len bytes
967 	 * without shifting current data, pullup into it,
968 	 * otherwise allocate a new mbuf to prepend to the chain.
969 	 */
970 	if ((n->m_flags & M_EXT) == 0 &&
971 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
972 		if (n->m_len >= len)
973 			return (n);
974 		m = n;
975 		n = n->m_next;
976 		len -= m->m_len;
977 	} else {
978 		if (len > MHLEN)
979 			goto bad;
980 		m = m_get(M_NOWAIT, n->m_type);
981 		if (m == NULL)
982 			goto bad;
983 		if (n->m_flags & M_PKTHDR)
984 			m_move_pkthdr(m, n);
985 	}
986 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
987 	do {
988 		count = min(min(max(len, max_protohdr), space), n->m_len);
989 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
990 		  (u_int)count);
991 		len -= count;
992 		m->m_len += count;
993 		n->m_len -= count;
994 		space -= count;
995 		if (n->m_len)
996 			n->m_data += count;
997 		else
998 			n = m_free(n);
999 	} while (len > 0 && n);
1000 	if (len > 0) {
1001 		(void) m_free(m);
1002 		goto bad;
1003 	}
1004 	m->m_next = n;
1005 	return (m);
1006 bad:
1007 	m_freem(n);
1008 	return (NULL);
1009 }
1010 
1011 /*
1012  * Like m_pullup(), except a new mbuf is always allocated, and we allow
1013  * the amount of empty space before the data in the new mbuf to be specified
1014  * (in the event that the caller expects to prepend later).
1015  */
1016 int MSFail;
1017 
1018 struct mbuf *
1019 m_copyup(struct mbuf *n, int len, int dstoff)
1020 {
1021 	struct mbuf *m;
1022 	int count, space;
1023 
1024 	if (len > (MHLEN - dstoff))
1025 		goto bad;
1026 	m = m_get(M_NOWAIT, n->m_type);
1027 	if (m == NULL)
1028 		goto bad;
1029 	if (n->m_flags & M_PKTHDR)
1030 		m_move_pkthdr(m, n);
1031 	m->m_data += dstoff;
1032 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1033 	do {
1034 		count = min(min(max(len, max_protohdr), space), n->m_len);
1035 		memcpy(mtod(m, caddr_t) + m->m_len, mtod(n, caddr_t),
1036 		    (unsigned)count);
1037 		len -= count;
1038 		m->m_len += count;
1039 		n->m_len -= count;
1040 		space -= count;
1041 		if (n->m_len)
1042 			n->m_data += count;
1043 		else
1044 			n = m_free(n);
1045 	} while (len > 0 && n);
1046 	if (len > 0) {
1047 		(void) m_free(m);
1048 		goto bad;
1049 	}
1050 	m->m_next = n;
1051 	return (m);
1052  bad:
1053 	m_freem(n);
1054 	MSFail++;
1055 	return (NULL);
1056 }
1057 
1058 /*
1059  * Partition an mbuf chain in two pieces, returning the tail --
1060  * all but the first len0 bytes.  In case of failure, it returns NULL and
1061  * attempts to restore the chain to its original state.
1062  *
1063  * Note that the resulting mbufs might be read-only, because the new
1064  * mbuf can end up sharing an mbuf cluster with the original mbuf if
1065  * the "breaking point" happens to lie within a cluster mbuf. Use the
1066  * M_WRITABLE() macro to check for this case.
1067  */
1068 struct mbuf *
1069 m_split(struct mbuf *m0, int len0, int wait)
1070 {
1071 	struct mbuf *m, *n;
1072 	u_int len = len0, remain;
1073 
1074 	MBUF_CHECKSLEEP(wait);
1075 	for (m = m0; m && len > m->m_len; m = m->m_next)
1076 		len -= m->m_len;
1077 	if (m == NULL)
1078 		return (NULL);
1079 	remain = m->m_len - len;
1080 	if (m0->m_flags & M_PKTHDR && remain == 0) {
1081 		n = m_gethdr(wait, m0->m_type);
1082 		if (n == NULL)
1083 			return (NULL);
1084 		n->m_next = m->m_next;
1085 		m->m_next = NULL;
1086 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1087 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1088 		m0->m_pkthdr.len = len0;
1089 		return (n);
1090 	} else if (m0->m_flags & M_PKTHDR) {
1091 		n = m_gethdr(wait, m0->m_type);
1092 		if (n == NULL)
1093 			return (NULL);
1094 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1095 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1096 		m0->m_pkthdr.len = len0;
1097 		if (m->m_flags & M_EXT)
1098 			goto extpacket;
1099 		if (remain > MHLEN) {
1100 			/* m can't be the lead packet */
1101 			M_ALIGN(n, 0);
1102 			n->m_next = m_split(m, len, wait);
1103 			if (n->m_next == NULL) {
1104 				(void) m_free(n);
1105 				return (NULL);
1106 			} else {
1107 				n->m_len = 0;
1108 				return (n);
1109 			}
1110 		} else
1111 			M_ALIGN(n, remain);
1112 	} else if (remain == 0) {
1113 		n = m->m_next;
1114 		m->m_next = NULL;
1115 		return (n);
1116 	} else {
1117 		n = m_get(wait, m->m_type);
1118 		if (n == NULL)
1119 			return (NULL);
1120 		M_ALIGN(n, remain);
1121 	}
1122 extpacket:
1123 	if (m->m_flags & M_EXT) {
1124 		n->m_data = m->m_data + len;
1125 		mb_dupcl(n, m);
1126 	} else {
1127 		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1128 	}
1129 	n->m_len = remain;
1130 	m->m_len = len;
1131 	n->m_next = m->m_next;
1132 	m->m_next = NULL;
1133 	return (n);
1134 }
1135 /*
1136  * Routine to copy from device local memory into mbufs.
1137  * Note that `off' argument is offset into first mbuf of target chain from
1138  * which to begin copying the data to.
1139  */
1140 struct mbuf *
1141 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
1142     void (*copy)(char *from, caddr_t to, u_int len))
1143 {
1144 	struct mbuf *m;
1145 	struct mbuf *top = NULL, **mp = &top;
1146 	int len;
1147 
1148 	if (off < 0 || off > MHLEN)
1149 		return (NULL);
1150 
1151 	while (totlen > 0) {
1152 		if (top == NULL) {	/* First one, must be PKTHDR */
1153 			if (totlen + off >= MINCLSIZE) {
1154 				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1155 				len = MCLBYTES;
1156 			} else {
1157 				m = m_gethdr(M_NOWAIT, MT_DATA);
1158 				len = MHLEN;
1159 
1160 				/* Place initial small packet/header at end of mbuf */
1161 				if (m && totlen + off + max_linkhdr <= MLEN) {
1162 					m->m_data += max_linkhdr;
1163 					len -= max_linkhdr;
1164 				}
1165 			}
1166 			if (m == NULL)
1167 				return NULL;
1168 			m->m_pkthdr.rcvif = ifp;
1169 			m->m_pkthdr.len = totlen;
1170 		} else {
1171 			if (totlen + off >= MINCLSIZE) {
1172 				m = m_getcl(M_NOWAIT, MT_DATA, 0);
1173 				len = MCLBYTES;
1174 			} else {
1175 				m = m_get(M_NOWAIT, MT_DATA);
1176 				len = MLEN;
1177 			}
1178 			if (m == NULL) {
1179 				m_freem(top);
1180 				return NULL;
1181 			}
1182 		}
1183 		if (off) {
1184 			m->m_data += off;
1185 			len -= off;
1186 			off = 0;
1187 		}
1188 		m->m_len = len = min(totlen, len);
1189 		if (copy)
1190 			copy(buf, mtod(m, caddr_t), (u_int)len);
1191 		else
1192 			bcopy(buf, mtod(m, caddr_t), (u_int)len);
1193 		buf += len;
1194 		*mp = m;
1195 		mp = &m->m_next;
1196 		totlen -= len;
1197 	}
1198 	return (top);
1199 }
1200 
1201 /*
1202  * Copy data from a buffer back into the indicated mbuf chain,
1203  * starting "off" bytes from the beginning, extending the mbuf
1204  * chain if necessary.
1205  */
1206 void
1207 m_copyback(struct mbuf *m0, int off, int len, c_caddr_t cp)
1208 {
1209 	int mlen;
1210 	struct mbuf *m = m0, *n;
1211 	int totlen = 0;
1212 
1213 	if (m0 == NULL)
1214 		return;
1215 	while (off > (mlen = m->m_len)) {
1216 		off -= mlen;
1217 		totlen += mlen;
1218 		if (m->m_next == NULL) {
1219 			n = m_get(M_NOWAIT, m->m_type);
1220 			if (n == NULL)
1221 				goto out;
1222 			bzero(mtod(n, caddr_t), MLEN);
1223 			n->m_len = min(MLEN, len + off);
1224 			m->m_next = n;
1225 		}
1226 		m = m->m_next;
1227 	}
1228 	while (len > 0) {
1229 		if (m->m_next == NULL && (len > m->m_len - off)) {
1230 			m->m_len += min(len - (m->m_len - off),
1231 			    M_TRAILINGSPACE(m));
1232 		}
1233 		mlen = min (m->m_len - off, len);
1234 		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
1235 		cp += mlen;
1236 		len -= mlen;
1237 		mlen += off;
1238 		off = 0;
1239 		totlen += mlen;
1240 		if (len == 0)
1241 			break;
1242 		if (m->m_next == NULL) {
1243 			n = m_get(M_NOWAIT, m->m_type);
1244 			if (n == NULL)
1245 				break;
1246 			n->m_len = min(MLEN, len);
1247 			m->m_next = n;
1248 		}
1249 		m = m->m_next;
1250 	}
1251 out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1252 		m->m_pkthdr.len = totlen;
1253 }
1254 
1255 /*
1256  * Append the specified data to the indicated mbuf chain,
1257  * Extend the mbuf chain if the new data does not fit in
1258  * existing space.
1259  *
1260  * Return 1 if able to complete the job; otherwise 0.
1261  */
1262 int
1263 m_append(struct mbuf *m0, int len, c_caddr_t cp)
1264 {
1265 	struct mbuf *m, *n;
1266 	int remainder, space;
1267 
1268 	for (m = m0; m->m_next != NULL; m = m->m_next)
1269 		;
1270 	remainder = len;
1271 	space = M_TRAILINGSPACE(m);
1272 	if (space > 0) {
1273 		/*
1274 		 * Copy into available space.
1275 		 */
1276 		if (space > remainder)
1277 			space = remainder;
1278 		bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1279 		m->m_len += space;
1280 		cp += space, remainder -= space;
1281 	}
1282 	while (remainder > 0) {
1283 		/*
1284 		 * Allocate a new mbuf; could check space
1285 		 * and allocate a cluster instead.
1286 		 */
1287 		n = m_get(M_NOWAIT, m->m_type);
1288 		if (n == NULL)
1289 			break;
1290 		n->m_len = min(MLEN, remainder);
1291 		bcopy(cp, mtod(n, caddr_t), n->m_len);
1292 		cp += n->m_len, remainder -= n->m_len;
1293 		m->m_next = n;
1294 		m = n;
1295 	}
1296 	if (m0->m_flags & M_PKTHDR)
1297 		m0->m_pkthdr.len += len - remainder;
1298 	return (remainder == 0);
1299 }
1300 
1301 /*
1302  * Apply function f to the data in an mbuf chain starting "off" bytes from
1303  * the beginning, continuing for "len" bytes.
1304  */
1305 int
1306 m_apply(struct mbuf *m, int off, int len,
1307     int (*f)(void *, void *, u_int), void *arg)
1308 {
1309 	u_int count;
1310 	int rval;
1311 
1312 	KASSERT(off >= 0, ("m_apply, negative off %d", off));
1313 	KASSERT(len >= 0, ("m_apply, negative len %d", len));
1314 	while (off > 0) {
1315 		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1316 		if (off < m->m_len)
1317 			break;
1318 		off -= m->m_len;
1319 		m = m->m_next;
1320 	}
1321 	while (len > 0) {
1322 		KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1323 		count = min(m->m_len - off, len);
1324 		rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1325 		if (rval)
1326 			return (rval);
1327 		len -= count;
1328 		off = 0;
1329 		m = m->m_next;
1330 	}
1331 	return (0);
1332 }
1333 
1334 /*
1335  * Return a pointer to mbuf/offset of location in mbuf chain.
1336  */
1337 struct mbuf *
1338 m_getptr(struct mbuf *m, int loc, int *off)
1339 {
1340 
1341 	while (loc >= 0) {
1342 		/* Normal end of search. */
1343 		if (m->m_len > loc) {
1344 			*off = loc;
1345 			return (m);
1346 		} else {
1347 			loc -= m->m_len;
1348 			if (m->m_next == NULL) {
1349 				if (loc == 0) {
1350 					/* Point at the end of valid data. */
1351 					*off = m->m_len;
1352 					return (m);
1353 				}
1354 				return (NULL);
1355 			}
1356 			m = m->m_next;
1357 		}
1358 	}
1359 	return (NULL);
1360 }
1361 
1362 void
1363 m_print(const struct mbuf *m, int maxlen)
1364 {
1365 	int len;
1366 	int pdata;
1367 	const struct mbuf *m2;
1368 
1369 	if (m == NULL) {
1370 		printf("mbuf: %p\n", m);
1371 		return;
1372 	}
1373 
1374 	if (m->m_flags & M_PKTHDR)
1375 		len = m->m_pkthdr.len;
1376 	else
1377 		len = -1;
1378 	m2 = m;
1379 	while (m2 != NULL && (len == -1 || len)) {
1380 		pdata = m2->m_len;
1381 		if (maxlen != -1 && pdata > maxlen)
1382 			pdata = maxlen;
1383 		printf("mbuf: %p len: %d, next: %p, %b%s", m2, m2->m_len,
1384 		    m2->m_next, m2->m_flags, "\20\20freelist\17skipfw"
1385 		    "\11proto5\10proto4\7proto3\6proto2\5proto1\4rdonly"
1386 		    "\3eor\2pkthdr\1ext", pdata ? "" : "\n");
1387 		if (pdata)
1388 			printf(", %*D\n", pdata, (u_char *)m2->m_data, "-");
1389 		if (len != -1)
1390 			len -= m2->m_len;
1391 		m2 = m2->m_next;
1392 	}
1393 	if (len > 0)
1394 		printf("%d bytes unaccounted for.\n", len);
1395 	return;
1396 }
1397 
1398 u_int
1399 m_fixhdr(struct mbuf *m0)
1400 {
1401 	u_int len;
1402 
1403 	len = m_length(m0, NULL);
1404 	m0->m_pkthdr.len = len;
1405 	return (len);
1406 }
1407 
1408 u_int
1409 m_length(struct mbuf *m0, struct mbuf **last)
1410 {
1411 	struct mbuf *m;
1412 	u_int len;
1413 
1414 	len = 0;
1415 	for (m = m0; m != NULL; m = m->m_next) {
1416 		len += m->m_len;
1417 		if (m->m_next == NULL)
1418 			break;
1419 	}
1420 	if (last != NULL)
1421 		*last = m;
1422 	return (len);
1423 }
1424 
1425 /*
1426  * Defragment a mbuf chain, returning the shortest possible
1427  * chain of mbufs and clusters.  If allocation fails and
1428  * this cannot be completed, NULL will be returned, but
1429  * the passed in chain will be unchanged.  Upon success,
1430  * the original chain will be freed, and the new chain
1431  * will be returned.
1432  *
1433  * If a non-packet header is passed in, the original
1434  * mbuf (chain?) will be returned unharmed.
1435  */
1436 struct mbuf *
1437 m_defrag(struct mbuf *m0, int how)
1438 {
1439 	struct mbuf *m_new = NULL, *m_final = NULL;
1440 	int progress = 0, length;
1441 
1442 	MBUF_CHECKSLEEP(how);
1443 	if (!(m0->m_flags & M_PKTHDR))
1444 		return (m0);
1445 
1446 	m_fixhdr(m0); /* Needed sanity check */
1447 
1448 #ifdef MBUF_STRESS_TEST
1449 	if (m_defragrandomfailures) {
1450 		int temp = arc4random() & 0xff;
1451 		if (temp == 0xba)
1452 			goto nospace;
1453 	}
1454 #endif
1455 
1456 	if (m0->m_pkthdr.len > MHLEN)
1457 		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1458 	else
1459 		m_final = m_gethdr(how, MT_DATA);
1460 
1461 	if (m_final == NULL)
1462 		goto nospace;
1463 
1464 	if (m_dup_pkthdr(m_final, m0, how) == 0)
1465 		goto nospace;
1466 
1467 	m_new = m_final;
1468 
1469 	while (progress < m0->m_pkthdr.len) {
1470 		length = m0->m_pkthdr.len - progress;
1471 		if (length > MCLBYTES)
1472 			length = MCLBYTES;
1473 
1474 		if (m_new == NULL) {
1475 			if (length > MLEN)
1476 				m_new = m_getcl(how, MT_DATA, 0);
1477 			else
1478 				m_new = m_get(how, MT_DATA);
1479 			if (m_new == NULL)
1480 				goto nospace;
1481 		}
1482 
1483 		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1484 		progress += length;
1485 		m_new->m_len = length;
1486 		if (m_new != m_final)
1487 			m_cat(m_final, m_new);
1488 		m_new = NULL;
1489 	}
1490 #ifdef MBUF_STRESS_TEST
1491 	if (m0->m_next == NULL)
1492 		m_defraguseless++;
1493 #endif
1494 	m_freem(m0);
1495 	m0 = m_final;
1496 #ifdef MBUF_STRESS_TEST
1497 	m_defragpackets++;
1498 	m_defragbytes += m0->m_pkthdr.len;
1499 #endif
1500 	return (m0);
1501 nospace:
1502 #ifdef MBUF_STRESS_TEST
1503 	m_defragfailure++;
1504 #endif
1505 	if (m_final)
1506 		m_freem(m_final);
1507 	return (NULL);
1508 }
1509 
1510 /*
1511  * Defragment an mbuf chain, returning at most maxfrags separate
1512  * mbufs+clusters.  If this is not possible NULL is returned and
1513  * the original mbuf chain is left in it's present (potentially
1514  * modified) state.  We use two techniques: collapsing consecutive
1515  * mbufs and replacing consecutive mbufs by a cluster.
1516  *
1517  * NB: this should really be named m_defrag but that name is taken
1518  */
1519 struct mbuf *
1520 m_collapse(struct mbuf *m0, int how, int maxfrags)
1521 {
1522 	struct mbuf *m, *n, *n2, **prev;
1523 	u_int curfrags;
1524 
1525 	/*
1526 	 * Calculate the current number of frags.
1527 	 */
1528 	curfrags = 0;
1529 	for (m = m0; m != NULL; m = m->m_next)
1530 		curfrags++;
1531 	/*
1532 	 * First, try to collapse mbufs.  Note that we always collapse
1533 	 * towards the front so we don't need to deal with moving the
1534 	 * pkthdr.  This may be suboptimal if the first mbuf has much
1535 	 * less data than the following.
1536 	 */
1537 	m = m0;
1538 again:
1539 	for (;;) {
1540 		n = m->m_next;
1541 		if (n == NULL)
1542 			break;
1543 		if (M_WRITABLE(m) &&
1544 		    n->m_len < M_TRAILINGSPACE(m)) {
1545 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
1546 				n->m_len);
1547 			m->m_len += n->m_len;
1548 			m->m_next = n->m_next;
1549 			m_free(n);
1550 			if (--curfrags <= maxfrags)
1551 				return m0;
1552 		} else
1553 			m = n;
1554 	}
1555 	KASSERT(maxfrags > 1,
1556 		("maxfrags %u, but normal collapse failed", maxfrags));
1557 	/*
1558 	 * Collapse consecutive mbufs to a cluster.
1559 	 */
1560 	prev = &m0->m_next;		/* NB: not the first mbuf */
1561 	while ((n = *prev) != NULL) {
1562 		if ((n2 = n->m_next) != NULL &&
1563 		    n->m_len + n2->m_len < MCLBYTES) {
1564 			m = m_getcl(how, MT_DATA, 0);
1565 			if (m == NULL)
1566 				goto bad;
1567 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
1568 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
1569 				n2->m_len);
1570 			m->m_len = n->m_len + n2->m_len;
1571 			m->m_next = n2->m_next;
1572 			*prev = m;
1573 			m_free(n);
1574 			m_free(n2);
1575 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
1576 				return m0;
1577 			/*
1578 			 * Still not there, try the normal collapse
1579 			 * again before we allocate another cluster.
1580 			 */
1581 			goto again;
1582 		}
1583 		prev = &n->m_next;
1584 	}
1585 	/*
1586 	 * No place where we can collapse to a cluster; punt.
1587 	 * This can occur if, for example, you request 2 frags
1588 	 * but the packet requires that both be clusters (we
1589 	 * never reallocate the first mbuf to avoid moving the
1590 	 * packet header).
1591 	 */
1592 bad:
1593 	return NULL;
1594 }
1595 
1596 #ifdef MBUF_STRESS_TEST
1597 
1598 /*
1599  * Fragment an mbuf chain.  There's no reason you'd ever want to do
1600  * this in normal usage, but it's great for stress testing various
1601  * mbuf consumers.
1602  *
1603  * If fragmentation is not possible, the original chain will be
1604  * returned.
1605  *
1606  * Possible length values:
1607  * 0	 no fragmentation will occur
1608  * > 0	each fragment will be of the specified length
1609  * -1	each fragment will be the same random value in length
1610  * -2	each fragment's length will be entirely random
1611  * (Random values range from 1 to 256)
1612  */
1613 struct mbuf *
1614 m_fragment(struct mbuf *m0, int how, int length)
1615 {
1616 	struct mbuf *m_new = NULL, *m_final = NULL;
1617 	int progress = 0;
1618 
1619 	if (!(m0->m_flags & M_PKTHDR))
1620 		return (m0);
1621 
1622 	if ((length == 0) || (length < -2))
1623 		return (m0);
1624 
1625 	m_fixhdr(m0); /* Needed sanity check */
1626 
1627 	m_final = m_getcl(how, MT_DATA, M_PKTHDR);
1628 
1629 	if (m_final == NULL)
1630 		goto nospace;
1631 
1632 	if (m_dup_pkthdr(m_final, m0, how) == 0)
1633 		goto nospace;
1634 
1635 	m_new = m_final;
1636 
1637 	if (length == -1)
1638 		length = 1 + (arc4random() & 255);
1639 
1640 	while (progress < m0->m_pkthdr.len) {
1641 		int fraglen;
1642 
1643 		if (length > 0)
1644 			fraglen = length;
1645 		else
1646 			fraglen = 1 + (arc4random() & 255);
1647 		if (fraglen > m0->m_pkthdr.len - progress)
1648 			fraglen = m0->m_pkthdr.len - progress;
1649 
1650 		if (fraglen > MCLBYTES)
1651 			fraglen = MCLBYTES;
1652 
1653 		if (m_new == NULL) {
1654 			m_new = m_getcl(how, MT_DATA, 0);
1655 			if (m_new == NULL)
1656 				goto nospace;
1657 		}
1658 
1659 		m_copydata(m0, progress, fraglen, mtod(m_new, caddr_t));
1660 		progress += fraglen;
1661 		m_new->m_len = fraglen;
1662 		if (m_new != m_final)
1663 			m_cat(m_final, m_new);
1664 		m_new = NULL;
1665 	}
1666 	m_freem(m0);
1667 	m0 = m_final;
1668 	return (m0);
1669 nospace:
1670 	if (m_final)
1671 		m_freem(m_final);
1672 	/* Return the original chain on failure */
1673 	return (m0);
1674 }
1675 
1676 #endif
1677 
1678 /*
1679  * Copy the contents of uio into a properly sized mbuf chain.
1680  */
1681 struct mbuf *
1682 m_uiotombuf(struct uio *uio, int how, int len, int align, int flags)
1683 {
1684 	struct mbuf *m, *mb;
1685 	int error, length;
1686 	ssize_t total;
1687 	int progress = 0;
1688 
1689 	/*
1690 	 * len can be zero or an arbitrary large value bound by
1691 	 * the total data supplied by the uio.
1692 	 */
1693 	if (len > 0)
1694 		total = min(uio->uio_resid, len);
1695 	else
1696 		total = uio->uio_resid;
1697 
1698 	/*
1699 	 * The smallest unit returned by m_getm2() is a single mbuf
1700 	 * with pkthdr.  We can't align past it.
1701 	 */
1702 	if (align >= MHLEN)
1703 		return (NULL);
1704 
1705 	/*
1706 	 * Give us the full allocation or nothing.
1707 	 * If len is zero return the smallest empty mbuf.
1708 	 */
1709 	m = m_getm2(NULL, max(total + align, 1), how, MT_DATA, flags);
1710 	if (m == NULL)
1711 		return (NULL);
1712 	m->m_data += align;
1713 
1714 	/* Fill all mbufs with uio data and update header information. */
1715 	for (mb = m; mb != NULL; mb = mb->m_next) {
1716 		length = min(M_TRAILINGSPACE(mb), total - progress);
1717 
1718 		error = uiomove(mtod(mb, void *), length, uio);
1719 		if (error) {
1720 			m_freem(m);
1721 			return (NULL);
1722 		}
1723 
1724 		mb->m_len = length;
1725 		progress += length;
1726 		if (flags & M_PKTHDR)
1727 			m->m_pkthdr.len += length;
1728 	}
1729 	KASSERT(progress == total, ("%s: progress != total", __func__));
1730 
1731 	return (m);
1732 }
1733 
1734 /*
1735  * Copy an mbuf chain into a uio limited by len if set.
1736  */
1737 int
1738 m_mbuftouio(struct uio *uio, struct mbuf *m, int len)
1739 {
1740 	int error, length, total;
1741 	int progress = 0;
1742 
1743 	if (len > 0)
1744 		total = min(uio->uio_resid, len);
1745 	else
1746 		total = uio->uio_resid;
1747 
1748 	/* Fill the uio with data from the mbufs. */
1749 	for (; m != NULL; m = m->m_next) {
1750 		length = min(m->m_len, total - progress);
1751 
1752 		error = uiomove(mtod(m, void *), length, uio);
1753 		if (error)
1754 			return (error);
1755 
1756 		progress += length;
1757 	}
1758 
1759 	return (0);
1760 }
1761 
1762 /*
1763  * Create a writable copy of the mbuf chain.  While doing this
1764  * we compact the chain with a goal of producing a chain with
1765  * at most two mbufs.  The second mbuf in this chain is likely
1766  * to be a cluster.  The primary purpose of this work is to create
1767  * a writable packet for encryption, compression, etc.  The
1768  * secondary goal is to linearize the data so the data can be
1769  * passed to crypto hardware in the most efficient manner possible.
1770  */
1771 struct mbuf *
1772 m_unshare(struct mbuf *m0, int how)
1773 {
1774 	struct mbuf *m, *mprev;
1775 	struct mbuf *n, *mfirst, *mlast;
1776 	int len, off;
1777 
1778 	mprev = NULL;
1779 	for (m = m0; m != NULL; m = mprev->m_next) {
1780 		/*
1781 		 * Regular mbufs are ignored unless there's a cluster
1782 		 * in front of it that we can use to coalesce.  We do
1783 		 * the latter mainly so later clusters can be coalesced
1784 		 * also w/o having to handle them specially (i.e. convert
1785 		 * mbuf+cluster -> cluster).  This optimization is heavily
1786 		 * influenced by the assumption that we're running over
1787 		 * Ethernet where MCLBYTES is large enough that the max
1788 		 * packet size will permit lots of coalescing into a
1789 		 * single cluster.  This in turn permits efficient
1790 		 * crypto operations, especially when using hardware.
1791 		 */
1792 		if ((m->m_flags & M_EXT) == 0) {
1793 			if (mprev && (mprev->m_flags & M_EXT) &&
1794 			    m->m_len <= M_TRAILINGSPACE(mprev)) {
1795 				/* XXX: this ignores mbuf types */
1796 				memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1797 				    mtod(m, caddr_t), m->m_len);
1798 				mprev->m_len += m->m_len;
1799 				mprev->m_next = m->m_next;	/* unlink from chain */
1800 				m_free(m);			/* reclaim mbuf */
1801 #if 0
1802 				newipsecstat.ips_mbcoalesced++;
1803 #endif
1804 			} else {
1805 				mprev = m;
1806 			}
1807 			continue;
1808 		}
1809 		/*
1810 		 * Writable mbufs are left alone (for now).
1811 		 */
1812 		if (M_WRITABLE(m)) {
1813 			mprev = m;
1814 			continue;
1815 		}
1816 
1817 		/*
1818 		 * Not writable, replace with a copy or coalesce with
1819 		 * the previous mbuf if possible (since we have to copy
1820 		 * it anyway, we try to reduce the number of mbufs and
1821 		 * clusters so that future work is easier).
1822 		 */
1823 		KASSERT(m->m_flags & M_EXT, ("m_flags 0x%x", m->m_flags));
1824 		/* NB: we only coalesce into a cluster or larger */
1825 		if (mprev != NULL && (mprev->m_flags & M_EXT) &&
1826 		    m->m_len <= M_TRAILINGSPACE(mprev)) {
1827 			/* XXX: this ignores mbuf types */
1828 			memcpy(mtod(mprev, caddr_t) + mprev->m_len,
1829 			    mtod(m, caddr_t), m->m_len);
1830 			mprev->m_len += m->m_len;
1831 			mprev->m_next = m->m_next;	/* unlink from chain */
1832 			m_free(m);			/* reclaim mbuf */
1833 #if 0
1834 			newipsecstat.ips_clcoalesced++;
1835 #endif
1836 			continue;
1837 		}
1838 
1839 		/*
1840 		 * Allocate new space to hold the copy and copy the data.
1841 		 * We deal with jumbo mbufs (i.e. m_len > MCLBYTES) by
1842 		 * splitting them into clusters.  We could just malloc a
1843 		 * buffer and make it external but too many device drivers
1844 		 * don't know how to break up the non-contiguous memory when
1845 		 * doing DMA.
1846 		 */
1847 		n = m_getcl(how, m->m_type, m->m_flags);
1848 		if (n == NULL) {
1849 			m_freem(m0);
1850 			return (NULL);
1851 		}
1852 		len = m->m_len;
1853 		off = 0;
1854 		mfirst = n;
1855 		mlast = NULL;
1856 		for (;;) {
1857 			int cc = min(len, MCLBYTES);
1858 			memcpy(mtod(n, caddr_t), mtod(m, caddr_t) + off, cc);
1859 			n->m_len = cc;
1860 			if (mlast != NULL)
1861 				mlast->m_next = n;
1862 			mlast = n;
1863 #if 0
1864 			newipsecstat.ips_clcopied++;
1865 #endif
1866 
1867 			len -= cc;
1868 			if (len <= 0)
1869 				break;
1870 			off += cc;
1871 
1872 			n = m_getcl(how, m->m_type, m->m_flags);
1873 			if (n == NULL) {
1874 				m_freem(mfirst);
1875 				m_freem(m0);
1876 				return (NULL);
1877 			}
1878 		}
1879 		n->m_next = m->m_next;
1880 		if (mprev == NULL)
1881 			m0 = mfirst;		/* new head of chain */
1882 		else
1883 			mprev->m_next = mfirst;	/* replace old mbuf */
1884 		m_free(m);			/* release old mbuf */
1885 		mprev = mfirst;
1886 	}
1887 	return (m0);
1888 }
1889 
1890 #ifdef MBUF_PROFILING
1891 
1892 #define MP_BUCKETS 32 /* don't just change this as things may overflow.*/
1893 struct mbufprofile {
1894 	uintmax_t wasted[MP_BUCKETS];
1895 	uintmax_t used[MP_BUCKETS];
1896 	uintmax_t segments[MP_BUCKETS];
1897 } mbprof;
1898 
1899 #define MP_MAXDIGITS 21	/* strlen("16,000,000,000,000,000,000") == 21 */
1900 #define MP_NUMLINES 6
1901 #define MP_NUMSPERLINE 16
1902 #define MP_EXTRABYTES 64	/* > strlen("used:\nwasted:\nsegments:\n") */
1903 /* work out max space needed and add a bit of spare space too */
1904 #define MP_MAXLINE ((MP_MAXDIGITS+1) * MP_NUMSPERLINE)
1905 #define MP_BUFSIZE ((MP_MAXLINE * MP_NUMLINES) + 1 + MP_EXTRABYTES)
1906 
1907 char mbprofbuf[MP_BUFSIZE];
1908 
1909 void
1910 m_profile(struct mbuf *m)
1911 {
1912 	int segments = 0;
1913 	int used = 0;
1914 	int wasted = 0;
1915 
1916 	while (m) {
1917 		segments++;
1918 		used += m->m_len;
1919 		if (m->m_flags & M_EXT) {
1920 			wasted += MHLEN - sizeof(m->m_ext) +
1921 			    m->m_ext.ext_size - m->m_len;
1922 		} else {
1923 			if (m->m_flags & M_PKTHDR)
1924 				wasted += MHLEN - m->m_len;
1925 			else
1926 				wasted += MLEN - m->m_len;
1927 		}
1928 		m = m->m_next;
1929 	}
1930 	/* be paranoid.. it helps */
1931 	if (segments > MP_BUCKETS - 1)
1932 		segments = MP_BUCKETS - 1;
1933 	if (used > 100000)
1934 		used = 100000;
1935 	if (wasted > 100000)
1936 		wasted = 100000;
1937 	/* store in the appropriate bucket */
1938 	/* don't bother locking. if it's slightly off, so what? */
1939 	mbprof.segments[segments]++;
1940 	mbprof.used[fls(used)]++;
1941 	mbprof.wasted[fls(wasted)]++;
1942 }
1943 
1944 static void
1945 mbprof_textify(void)
1946 {
1947 	int offset;
1948 	char *c;
1949 	uint64_t *p;
1950 
1951 	p = &mbprof.wasted[0];
1952 	c = mbprofbuf;
1953 	offset = snprintf(c, MP_MAXLINE + 10,
1954 	    "wasted:\n"
1955 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1956 	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1957 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1958 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1959 #ifdef BIG_ARRAY
1960 	p = &mbprof.wasted[16];
1961 	c += offset;
1962 	offset = snprintf(c, MP_MAXLINE,
1963 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1964 	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1965 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1966 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1967 #endif
1968 	p = &mbprof.used[0];
1969 	c += offset;
1970 	offset = snprintf(c, MP_MAXLINE + 10,
1971 	    "used:\n"
1972 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1973 	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1974 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1975 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1976 #ifdef BIG_ARRAY
1977 	p = &mbprof.used[16];
1978 	c += offset;
1979 	offset = snprintf(c, MP_MAXLINE,
1980 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1981 	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1982 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1983 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1984 #endif
1985 	p = &mbprof.segments[0];
1986 	c += offset;
1987 	offset = snprintf(c, MP_MAXLINE + 10,
1988 	    "segments:\n"
1989 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1990 	    "%ju %ju %ju %ju %ju %ju %ju %ju\n",
1991 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
1992 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
1993 #ifdef BIG_ARRAY
1994 	p = &mbprof.segments[16];
1995 	c += offset;
1996 	offset = snprintf(c, MP_MAXLINE,
1997 	    "%ju %ju %ju %ju %ju %ju %ju %ju "
1998 	    "%ju %ju %ju %ju %ju %ju %ju %jju",
1999 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
2000 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
2001 #endif
2002 }
2003 
2004 static int
2005 mbprof_handler(SYSCTL_HANDLER_ARGS)
2006 {
2007 	int error;
2008 
2009 	mbprof_textify();
2010 	error = SYSCTL_OUT(req, mbprofbuf, strlen(mbprofbuf) + 1);
2011 	return (error);
2012 }
2013 
2014 static int
2015 mbprof_clr_handler(SYSCTL_HANDLER_ARGS)
2016 {
2017 	int clear, error;
2018 
2019 	clear = 0;
2020 	error = sysctl_handle_int(oidp, &clear, 0, req);
2021 	if (error || !req->newptr)
2022 		return (error);
2023 
2024 	if (clear) {
2025 		bzero(&mbprof, sizeof(mbprof));
2026 	}
2027 
2028 	return (error);
2029 }
2030 
2031 
2032 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofile, CTLTYPE_STRING|CTLFLAG_RD,
2033 	    NULL, 0, mbprof_handler, "A", "mbuf profiling statistics");
2034 
2035 SYSCTL_PROC(_kern_ipc, OID_AUTO, mbufprofileclr, CTLTYPE_INT|CTLFLAG_RW,
2036 	    NULL, 0, mbprof_clr_handler, "I", "clear mbuf profiling statistics");
2037 #endif
2038 
2039