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