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