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