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