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