xref: /freebsd/sys/kern/uipc_mbuf.c (revision d086ded32300bc0f33fb1574d0bcfccfbc60881d)
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)uipc_mbuf.c	8.2 (Berkeley) 1/4/94
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include "opt_mac.h"
40 #include "opt_param.h"
41 #include "opt_mbuf_stress_test.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/mac.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/sysctl.h>
51 #include <sys/domain.h>
52 #include <sys/protosw.h>
53 
54 int	max_linkhdr;
55 int	max_protohdr;
56 int	max_hdr;
57 int	max_datalen;
58 #ifdef MBUF_STRESS_TEST
59 int	m_defragpackets;
60 int	m_defragbytes;
61 int	m_defraguseless;
62 int	m_defragfailure;
63 int	m_defragrandomfailures;
64 #endif
65 
66 /*
67  * sysctl(8) exported objects
68  */
69 SYSCTL_DECL(_kern_ipc);
70 SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
71 	   &max_linkhdr, 0, "");
72 SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
73 	   &max_protohdr, 0, "");
74 SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
75 SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
76 	   &max_datalen, 0, "");
77 #ifdef MBUF_STRESS_TEST
78 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
79 	   &m_defragpackets, 0, "");
80 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
81 	   &m_defragbytes, 0, "");
82 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
83 	   &m_defraguseless, 0, "");
84 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
85 	   &m_defragfailure, 0, "");
86 SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
87 	   &m_defragrandomfailures, 0, "");
88 #endif
89 
90 /*
91  * "Move" mbuf pkthdr from "from" to "to".
92  * "from" must have M_PKTHDR set, and "to" must be empty.
93  */
94 void
95 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
96 {
97 
98 #if 0
99 	/* see below for why these are not enabled */
100 	M_ASSERTPKTHDR(to);
101 	/* Note: with MAC, this may not be a good assertion. */
102 	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags),
103 	    ("m_move_pkthdr: to has tags"));
104 #endif
105 	KASSERT((to->m_flags & M_EXT) == 0, ("m_move_pkthdr: to has cluster"));
106 #ifdef MAC
107 	/*
108 	 * XXXMAC: It could be this should also occur for non-MAC?
109 	 */
110 	if (to->m_flags & M_PKTHDR)
111 		m_tag_delete_chain(to, NULL);
112 #endif
113 	to->m_flags = from->m_flags & M_COPYFLAGS;
114 	to->m_data = to->m_pktdat;
115 	to->m_pkthdr = from->m_pkthdr;		/* especially tags */
116 	SLIST_INIT(&from->m_pkthdr.tags);	/* purge tags from src */
117 	from->m_flags &= ~M_PKTHDR;
118 }
119 
120 /*
121  * Duplicate "from"'s mbuf pkthdr in "to".
122  * "from" must have M_PKTHDR set, and "to" must be empty.
123  * In particular, this does a deep copy of the packet tags.
124  */
125 int
126 m_dup_pkthdr(struct mbuf *to, struct mbuf *from, int how)
127 {
128 
129 #if 0
130 	/*
131 	 * The mbuf allocator only initializes the pkthdr
132 	 * when the mbuf is allocated with MGETHDR. Many users
133 	 * (e.g. m_copy*, m_prepend) use MGET and then
134 	 * smash the pkthdr as needed causing these
135 	 * assertions to trip.  For now just disable them.
136 	 */
137 	M_ASSERTPKTHDR(to);
138 	/* Note: with MAC, this may not be a good assertion. */
139 	KASSERT(SLIST_EMPTY(&to->m_pkthdr.tags), ("m_dup_pkthdr: to has tags"));
140 #endif
141 #ifdef MAC
142 	if (to->m_flags & M_PKTHDR)
143 		m_tag_delete_chain(to, NULL);
144 #endif
145 	to->m_flags = (from->m_flags & M_COPYFLAGS) | (to->m_flags & M_EXT);
146 	if ((to->m_flags & M_EXT) == 0)
147 		to->m_data = to->m_pktdat;
148 	to->m_pkthdr = from->m_pkthdr;
149 	SLIST_INIT(&to->m_pkthdr.tags);
150 	return (m_tag_copy_chain(to, from, MBTOM(how)));
151 }
152 
153 /*
154  * Lesser-used path for M_PREPEND:
155  * allocate new mbuf to prepend to chain,
156  * copy junk along.
157  */
158 struct mbuf *
159 m_prepend(struct mbuf *m, int len, int how)
160 {
161 	struct mbuf *mn;
162 
163 	MGET(mn, how, m->m_type);
164 	if (mn == NULL) {
165 		m_freem(m);
166 		return (NULL);
167 	}
168 	if (m->m_flags & M_PKTHDR)
169 		M_MOVE_PKTHDR(mn, m);
170 	mn->m_next = m;
171 	m = mn;
172 	if (len < MHLEN)
173 		MH_ALIGN(m, len);
174 	m->m_len = len;
175 	return (m);
176 }
177 
178 /*
179  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
180  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
181  * The wait parameter is a choice of M_TRYWAIT/M_DONTWAIT from caller.
182  * Note that the copy is read-only, because clusters are not copied,
183  * only their reference counts are incremented.
184  */
185 struct mbuf *
186 m_copym(struct mbuf *m, int off0, int len, int wait)
187 {
188 	struct mbuf *n, **np;
189 	int off = off0;
190 	struct mbuf *top;
191 	int copyhdr = 0;
192 
193 	KASSERT(off >= 0, ("m_copym, negative off %d", off));
194 	KASSERT(len >= 0, ("m_copym, negative len %d", len));
195 	if (off == 0 && m->m_flags & M_PKTHDR)
196 		copyhdr = 1;
197 	while (off > 0) {
198 		KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
199 		if (off < m->m_len)
200 			break;
201 		off -= m->m_len;
202 		m = m->m_next;
203 	}
204 	np = &top;
205 	top = 0;
206 	while (len > 0) {
207 		if (m == NULL) {
208 			KASSERT(len == M_COPYALL,
209 			    ("m_copym, length > size of mbuf chain"));
210 			break;
211 		}
212 		MGET(n, wait, m->m_type);
213 		*np = n;
214 		if (n == NULL)
215 			goto nospace;
216 		if (copyhdr) {
217 			if (!m_dup_pkthdr(n, m, wait))
218 				goto nospace;
219 			if (len == M_COPYALL)
220 				n->m_pkthdr.len -= off0;
221 			else
222 				n->m_pkthdr.len = len;
223 			copyhdr = 0;
224 		}
225 		n->m_len = min(len, m->m_len - off);
226 		if (m->m_flags & M_EXT) {
227 			n->m_data = m->m_data + off;
228 			n->m_ext = m->m_ext;
229 			n->m_flags |= M_EXT;
230 			MEXT_ADD_REF(m);
231 		} else
232 			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
233 			    (u_int)n->m_len);
234 		if (len != M_COPYALL)
235 			len -= n->m_len;
236 		off = 0;
237 		m = m->m_next;
238 		np = &n->m_next;
239 	}
240 	if (top == NULL)
241 		mbstat.m_mcfail++;	/* XXX: No consistency. */
242 
243 	return (top);
244 nospace:
245 	m_freem(top);
246 	mbstat.m_mcfail++;	/* XXX: No consistency. */
247 	return (NULL);
248 }
249 
250 /*
251  * Copy an entire packet, including header (which must be present).
252  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
253  * Note that the copy is read-only, because clusters are not copied,
254  * only their reference counts are incremented.
255  * Preserve alignment of the first mbuf so if the creator has left
256  * some room at the beginning (e.g. for inserting protocol headers)
257  * the copies still have the room available.
258  */
259 struct mbuf *
260 m_copypacket(struct mbuf *m, int how)
261 {
262 	struct mbuf *top, *n, *o;
263 
264 	MGET(n, how, m->m_type);
265 	top = n;
266 	if (n == NULL)
267 		goto nospace;
268 
269 	if (!m_dup_pkthdr(n, m, how))
270 		goto nospace;
271 	n->m_len = m->m_len;
272 	if (m->m_flags & M_EXT) {
273 		n->m_data = m->m_data;
274 		n->m_ext = m->m_ext;
275 		n->m_flags |= M_EXT;
276 		MEXT_ADD_REF(m);
277 	} else {
278 		n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
279 		bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
280 	}
281 
282 	m = m->m_next;
283 	while (m) {
284 		MGET(o, how, m->m_type);
285 		if (o == NULL)
286 			goto nospace;
287 
288 		n->m_next = o;
289 		n = n->m_next;
290 
291 		n->m_len = m->m_len;
292 		if (m->m_flags & M_EXT) {
293 			n->m_data = m->m_data;
294 			n->m_ext = m->m_ext;
295 			n->m_flags |= M_EXT;
296 			MEXT_ADD_REF(m);
297 		} else {
298 			bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
299 		}
300 
301 		m = m->m_next;
302 	}
303 	return top;
304 nospace:
305 	m_freem(top);
306 	mbstat.m_mcfail++;	/* XXX: No consistency. */
307 	return (NULL);
308 }
309 
310 /*
311  * Copy data from an mbuf chain starting "off" bytes from the beginning,
312  * continuing for "len" bytes, into the indicated buffer.
313  */
314 void
315 m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
316 {
317 	u_int count;
318 
319 	KASSERT(off >= 0, ("m_copydata, negative off %d", off));
320 	KASSERT(len >= 0, ("m_copydata, negative len %d", len));
321 	while (off > 0) {
322 		KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
323 		if (off < m->m_len)
324 			break;
325 		off -= m->m_len;
326 		m = m->m_next;
327 	}
328 	while (len > 0) {
329 		KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
330 		count = min(m->m_len - off, len);
331 		bcopy(mtod(m, caddr_t) + off, cp, count);
332 		len -= count;
333 		cp += count;
334 		off = 0;
335 		m = m->m_next;
336 	}
337 }
338 
339 /*
340  * Copy a packet header mbuf chain into a completely new chain, including
341  * copying any mbuf clusters.  Use this instead of m_copypacket() when
342  * you need a writable copy of an mbuf chain.
343  */
344 struct mbuf *
345 m_dup(struct mbuf *m, int how)
346 {
347 	struct mbuf **p, *top = NULL;
348 	int remain, moff, nsize;
349 
350 	/* Sanity check */
351 	if (m == NULL)
352 		return (NULL);
353 	M_ASSERTPKTHDR(m);
354 
355 	/* While there's more data, get a new mbuf, tack it on, and fill it */
356 	remain = m->m_pkthdr.len;
357 	moff = 0;
358 	p = &top;
359 	while (remain > 0 || top == NULL) {	/* allow m->m_pkthdr.len == 0 */
360 		struct mbuf *n;
361 
362 		/* Get the next new mbuf */
363 		MGET(n, how, m->m_type);
364 		if (n == NULL)
365 			goto nospace;
366 		if (top == NULL) {		/* first one, must be PKTHDR */
367 			if (!m_dup_pkthdr(n, m, how))
368 				goto nospace;
369 			nsize = MHLEN;
370 		} else				/* not the first one */
371 			nsize = MLEN;
372 		if (remain >= MINCLSIZE) {
373 			MCLGET(n, how);
374 			if ((n->m_flags & M_EXT) == 0) {
375 				(void)m_free(n);
376 				goto nospace;
377 			}
378 			nsize = MCLBYTES;
379 		}
380 		n->m_len = 0;
381 
382 		/* Link it into the new chain */
383 		*p = n;
384 		p = &n->m_next;
385 
386 		/* Copy data from original mbuf(s) into new mbuf */
387 		while (n->m_len < nsize && m != NULL) {
388 			int chunk = min(nsize - n->m_len, m->m_len - moff);
389 
390 			bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
391 			moff += chunk;
392 			n->m_len += chunk;
393 			remain -= chunk;
394 			if (moff == m->m_len) {
395 				m = m->m_next;
396 				moff = 0;
397 			}
398 		}
399 
400 		/* Check correct total mbuf length */
401 		KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
402 		    	("%s: bogus m_pkthdr.len", __func__));
403 	}
404 	return (top);
405 
406 nospace:
407 	m_freem(top);
408 	mbstat.m_mcfail++;	/* XXX: No consistency. */
409 	return (NULL);
410 }
411 
412 /*
413  * Concatenate mbuf chain n to m.
414  * Both chains must be of the same type (e.g. MT_DATA).
415  * Any m_pkthdr is not updated.
416  */
417 void
418 m_cat(struct mbuf *m, struct mbuf *n)
419 {
420 	while (m->m_next)
421 		m = m->m_next;
422 	while (n) {
423 		if (m->m_flags & M_EXT ||
424 		    m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
425 			/* just join the two chains */
426 			m->m_next = n;
427 			return;
428 		}
429 		/* splat the data from one into the other */
430 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
431 		    (u_int)n->m_len);
432 		m->m_len += n->m_len;
433 		n = m_free(n);
434 	}
435 }
436 
437 void
438 m_adj(struct mbuf *mp, int req_len)
439 {
440 	int len = req_len;
441 	struct mbuf *m;
442 	int count;
443 
444 	if ((m = mp) == NULL)
445 		return;
446 	if (len >= 0) {
447 		/*
448 		 * Trim from head.
449 		 */
450 		while (m != NULL && len > 0) {
451 			if (m->m_len <= len) {
452 				len -= m->m_len;
453 				m->m_len = 0;
454 				m = m->m_next;
455 			} else {
456 				m->m_len -= len;
457 				m->m_data += len;
458 				len = 0;
459 			}
460 		}
461 		m = mp;
462 		if (mp->m_flags & M_PKTHDR)
463 			m->m_pkthdr.len -= (req_len - len);
464 	} else {
465 		/*
466 		 * Trim from tail.  Scan the mbuf chain,
467 		 * calculating its length and finding the last mbuf.
468 		 * If the adjustment only affects this mbuf, then just
469 		 * adjust and return.  Otherwise, rescan and truncate
470 		 * after the remaining size.
471 		 */
472 		len = -len;
473 		count = 0;
474 		for (;;) {
475 			count += m->m_len;
476 			if (m->m_next == (struct mbuf *)0)
477 				break;
478 			m = m->m_next;
479 		}
480 		if (m->m_len >= len) {
481 			m->m_len -= len;
482 			if (mp->m_flags & M_PKTHDR)
483 				mp->m_pkthdr.len -= len;
484 			return;
485 		}
486 		count -= len;
487 		if (count < 0)
488 			count = 0;
489 		/*
490 		 * Correct length for chain is "count".
491 		 * Find the mbuf with last data, adjust its length,
492 		 * and toss data from remaining mbufs on chain.
493 		 */
494 		m = mp;
495 		if (m->m_flags & M_PKTHDR)
496 			m->m_pkthdr.len = count;
497 		for (; m; m = m->m_next) {
498 			if (m->m_len >= count) {
499 				m->m_len = count;
500 				break;
501 			}
502 			count -= m->m_len;
503 		}
504 		while (m->m_next)
505 			(m = m->m_next) ->m_len = 0;
506 	}
507 }
508 
509 /*
510  * Rearange an mbuf chain so that len bytes are contiguous
511  * and in the data area of an mbuf (so that mtod and dtom
512  * will work for a structure of size len).  Returns the resulting
513  * mbuf chain on success, frees it and returns null on failure.
514  * If there is room, it will add up to max_protohdr-len extra bytes to the
515  * contiguous region in an attempt to avoid being called next time.
516  */
517 struct mbuf *
518 m_pullup(struct mbuf *n, int len)
519 {
520 	struct mbuf *m;
521 	int count;
522 	int space;
523 
524 	/*
525 	 * If first mbuf has no cluster, and has room for len bytes
526 	 * without shifting current data, pullup into it,
527 	 * otherwise allocate a new mbuf to prepend to the chain.
528 	 */
529 	if ((n->m_flags & M_EXT) == 0 &&
530 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
531 		if (n->m_len >= len)
532 			return (n);
533 		m = n;
534 		n = n->m_next;
535 		len -= m->m_len;
536 	} else {
537 		if (len > MHLEN)
538 			goto bad;
539 		MGET(m, M_DONTWAIT, n->m_type);
540 		if (m == NULL)
541 			goto bad;
542 		m->m_len = 0;
543 		if (n->m_flags & M_PKTHDR)
544 			M_MOVE_PKTHDR(m, n);
545 	}
546 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
547 	do {
548 		count = min(min(max(len, max_protohdr), space), n->m_len);
549 		bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
550 		  (u_int)count);
551 		len -= count;
552 		m->m_len += count;
553 		n->m_len -= count;
554 		space -= count;
555 		if (n->m_len)
556 			n->m_data += count;
557 		else
558 			n = m_free(n);
559 	} while (len > 0 && n);
560 	if (len > 0) {
561 		(void) m_free(m);
562 		goto bad;
563 	}
564 	m->m_next = n;
565 	return (m);
566 bad:
567 	m_freem(n);
568 	mbstat.m_mpfail++;	/* XXX: No consistency. */
569 	return (NULL);
570 }
571 
572 /*
573  * Partition an mbuf chain in two pieces, returning the tail --
574  * all but the first len0 bytes.  In case of failure, it returns NULL and
575  * attempts to restore the chain to its original state.
576  *
577  * Note that the resulting mbufs might be read-only, because the new
578  * mbuf can end up sharing an mbuf cluster with the original mbuf if
579  * the "breaking point" happens to lie within a cluster mbuf. Use the
580  * M_WRITABLE() macro to check for this case.
581  */
582 struct mbuf *
583 m_split(struct mbuf *m0, int len0, int wait)
584 {
585 	struct mbuf *m, *n;
586 	u_int len = len0, remain;
587 
588 	for (m = m0; m && len > m->m_len; m = m->m_next)
589 		len -= m->m_len;
590 	if (m == NULL)
591 		return (NULL);
592 	remain = m->m_len - len;
593 	if (m0->m_flags & M_PKTHDR) {
594 		MGETHDR(n, wait, m0->m_type);
595 		if (n == NULL)
596 			return (NULL);
597 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
598 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
599 		m0->m_pkthdr.len = len0;
600 		if (m->m_flags & M_EXT)
601 			goto extpacket;
602 		if (remain > MHLEN) {
603 			/* m can't be the lead packet */
604 			MH_ALIGN(n, 0);
605 			n->m_next = m_split(m, len, wait);
606 			if (n->m_next == NULL) {
607 				(void) m_free(n);
608 				return (NULL);
609 			} else {
610 				n->m_len = 0;
611 				return (n);
612 			}
613 		} else
614 			MH_ALIGN(n, remain);
615 	} else if (remain == 0) {
616 		n = m->m_next;
617 		m->m_next = NULL;
618 		return (n);
619 	} else {
620 		MGET(n, wait, m->m_type);
621 		if (n == NULL)
622 			return (NULL);
623 		M_ALIGN(n, remain);
624 	}
625 extpacket:
626 	if (m->m_flags & M_EXT) {
627 		n->m_flags |= M_EXT;
628 		n->m_ext = m->m_ext;
629 		MEXT_ADD_REF(m);
630 		n->m_data = m->m_data + len;
631 	} else {
632 		bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
633 	}
634 	n->m_len = remain;
635 	m->m_len = len;
636 	n->m_next = m->m_next;
637 	m->m_next = NULL;
638 	return (n);
639 }
640 /*
641  * Routine to copy from device local memory into mbufs.
642  * Note that `off' argument is offset into first mbuf of target chain from
643  * which to begin copying the data to.
644  */
645 struct mbuf *
646 m_devget(char *buf, int totlen, int off, struct ifnet *ifp,
647 	 void (*copy)(char *from, caddr_t to, u_int len))
648 {
649 	struct mbuf *m;
650 	struct mbuf *top = 0, **mp = &top;
651 	int len;
652 
653 	if (off < 0 || off > MHLEN)
654 		return (NULL);
655 
656 	MGETHDR(m, M_DONTWAIT, MT_DATA);
657 	if (m == NULL)
658 		return (NULL);
659 	m->m_pkthdr.rcvif = ifp;
660 	m->m_pkthdr.len = totlen;
661 	len = MHLEN;
662 
663 	while (totlen > 0) {
664 		if (top) {
665 			MGET(m, M_DONTWAIT, MT_DATA);
666 			if (m == NULL) {
667 				m_freem(top);
668 				return (NULL);
669 			}
670 			len = MLEN;
671 		}
672 		if (totlen + off >= MINCLSIZE) {
673 			MCLGET(m, M_DONTWAIT);
674 			if (m->m_flags & M_EXT)
675 				len = MCLBYTES;
676 		} else {
677 			/*
678 			 * Place initial small packet/header at end of mbuf.
679 			 */
680 			if (top == NULL && totlen + off + max_linkhdr <= len) {
681 				m->m_data += max_linkhdr;
682 				len -= max_linkhdr;
683 			}
684 		}
685 		if (off) {
686 			m->m_data += off;
687 			len -= off;
688 			off = 0;
689 		}
690 		m->m_len = len = min(totlen, len);
691 		if (copy)
692 			copy(buf, mtod(m, caddr_t), (u_int)len);
693 		else
694 			bcopy(buf, mtod(m, caddr_t), (u_int)len);
695 		buf += len;
696 		*mp = m;
697 		mp = &m->m_next;
698 		totlen -= len;
699 	}
700 	return (top);
701 }
702 
703 /*
704  * Copy data from a buffer back into the indicated mbuf chain,
705  * starting "off" bytes from the beginning, extending the mbuf
706  * chain if necessary.
707  */
708 void
709 m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
710 {
711 	int mlen;
712 	struct mbuf *m = m0, *n;
713 	int totlen = 0;
714 
715 	if (m0 == NULL)
716 		return;
717 	while (off > (mlen = m->m_len)) {
718 		off -= mlen;
719 		totlen += mlen;
720 		if (m->m_next == NULL) {
721 			n = m_get_clrd(M_DONTWAIT, m->m_type);
722 			if (n == NULL)
723 				goto out;
724 			n->m_len = min(MLEN, len + off);
725 			m->m_next = n;
726 		}
727 		m = m->m_next;
728 	}
729 	while (len > 0) {
730 		mlen = min (m->m_len - off, len);
731 		bcopy(cp, off + mtod(m, caddr_t), (u_int)mlen);
732 		cp += mlen;
733 		len -= mlen;
734 		mlen += off;
735 		off = 0;
736 		totlen += mlen;
737 		if (len == 0)
738 			break;
739 		if (m->m_next == NULL) {
740 			n = m_get(M_DONTWAIT, m->m_type);
741 			if (n == NULL)
742 				break;
743 			n->m_len = min(MLEN, len);
744 			m->m_next = n;
745 		}
746 		m = m->m_next;
747 	}
748 out:	if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
749 		m->m_pkthdr.len = totlen;
750 }
751 
752 void
753 m_print(const struct mbuf *m)
754 {
755 	int len;
756 	const struct mbuf *m2;
757 
758 	len = m->m_pkthdr.len;
759 	m2 = m;
760 	while (len) {
761 		printf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
762 		len -= m2->m_len;
763 		m2 = m2->m_next;
764 	}
765 	return;
766 }
767 
768 u_int
769 m_fixhdr(struct mbuf *m0)
770 {
771 	u_int len;
772 
773 	len = m_length(m0, NULL);
774 	m0->m_pkthdr.len = len;
775 	return (len);
776 }
777 
778 u_int
779 m_length(struct mbuf *m0, struct mbuf **last)
780 {
781 	struct mbuf *m;
782 	u_int len;
783 
784 	len = 0;
785 	for (m = m0; m != NULL; m = m->m_next) {
786 		len += m->m_len;
787 		if (m->m_next == NULL)
788 			break;
789 	}
790 	if (last != NULL)
791 		*last = m;
792 	return (len);
793 }
794 
795 /*
796  * Defragment a mbuf chain, returning the shortest possible
797  * chain of mbufs and clusters.  If allocation fails and
798  * this cannot be completed, NULL will be returned, but
799  * the passed in chain will be unchanged.  Upon success,
800  * the original chain will be freed, and the new chain
801  * will be returned.
802  *
803  * If a non-packet header is passed in, the original
804  * mbuf (chain?) will be returned unharmed.
805  */
806 struct mbuf *
807 m_defrag(struct mbuf *m0, int how)
808 {
809 	struct mbuf	*m_new = NULL, *m_final = NULL;
810 	int		progress = 0, length;
811 
812 	if (!(m0->m_flags & M_PKTHDR))
813 		return (m0);
814 
815 #ifdef MBUF_STRESS_TEST
816 	if (m_defragrandomfailures) {
817 		int temp = arc4random() & 0xff;
818 		if (temp == 0xba)
819 			goto nospace;
820 	}
821 #endif
822 
823 	if (m0->m_pkthdr.len > MHLEN)
824 		m_final = m_getcl(how, MT_DATA, M_PKTHDR);
825 	else
826 		m_final = m_gethdr(how, MT_DATA);
827 
828 	if (m_final == NULL)
829 		goto nospace;
830 
831 	if (m_dup_pkthdr(m_final, m0, how) == NULL)
832 		goto nospace;
833 
834 	m_new = m_final;
835 
836 	while (progress < m0->m_pkthdr.len) {
837 		length = m0->m_pkthdr.len - progress;
838 		if (length > MCLBYTES)
839 			length = MCLBYTES;
840 
841 		if (m_new == NULL) {
842 			if (length > MLEN)
843 				m_new = m_getcl(how, MT_DATA, 0);
844 			else
845 				m_new = m_get(how, MT_DATA);
846 			if (m_new == NULL)
847 				goto nospace;
848 		}
849 
850 		m_copydata(m0, progress, length, mtod(m_new, caddr_t));
851 		progress += length;
852 		m_new->m_len = length;
853 		if (m_new != m_final)
854 			m_cat(m_final, m_new);
855 		m_new = NULL;
856 	}
857 #ifdef MBUF_STRESS_TEST
858 	if (m0->m_next == NULL)
859 		m_defraguseless++;
860 #endif
861 	m_freem(m0);
862 	m0 = m_final;
863 #ifdef MBUF_STRESS_TEST
864 	m_defragpackets++;
865 	m_defragbytes += m0->m_pkthdr.len;
866 #endif
867 	return (m0);
868 nospace:
869 #ifdef MBUF_STRESS_TEST
870 	m_defragfailure++;
871 #endif
872 	if (m_new)
873 		m_free(m_new);
874 	if (m_final)
875 		m_freem(m_final);
876 	return (NULL);
877 }
878