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