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