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