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