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