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