xref: /netbsd-src/sys/kern/uipc_mbuf.c (revision a24efa7dea9f1f56c3bdb15a927d3516792ace1c)
1 /*	$NetBSD: uipc_mbuf.c,v 1.165 2016/05/12 02:24:16 ozaki-r Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2001 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1988, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)uipc_mbuf.c	8.4 (Berkeley) 2/14/95
62  */
63 
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: uipc_mbuf.c,v 1.165 2016/05/12 02:24:16 ozaki-r Exp $");
66 
67 #ifdef _KERNEL_OPT
68 #include "opt_mbuftrace.h"
69 #include "opt_nmbclusters.h"
70 #include "opt_ddb.h"
71 #endif
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/atomic.h>
76 #include <sys/cpu.h>
77 #include <sys/proc.h>
78 #include <sys/mbuf.h>
79 #include <sys/kernel.h>
80 #include <sys/syslog.h>
81 #include <sys/domain.h>
82 #include <sys/protosw.h>
83 #include <sys/percpu.h>
84 #include <sys/pool.h>
85 #include <sys/socket.h>
86 #include <sys/sysctl.h>
87 
88 #include <net/if.h>
89 
90 pool_cache_t mb_cache;	/* mbuf cache */
91 pool_cache_t mcl_cache;	/* mbuf cluster cache */
92 
93 struct mbstat mbstat;
94 int	max_linkhdr;
95 int	max_protohdr;
96 int	max_hdr;
97 int	max_datalen;
98 
99 static int mb_ctor(void *, void *, int);
100 
101 static void	sysctl_kern_mbuf_setup(void);
102 
103 static struct sysctllog *mbuf_sysctllog;
104 
105 static struct mbuf *m_copym0(struct mbuf *, int, int, int, int);
106 static struct mbuf *m_split0(struct mbuf *, int, int, int);
107 static int m_copyback0(struct mbuf **, int, int, const void *, int, int);
108 
109 /* flags for m_copyback0 */
110 #define	M_COPYBACK0_COPYBACK	0x0001	/* copyback from cp */
111 #define	M_COPYBACK0_PRESERVE	0x0002	/* preserve original data */
112 #define	M_COPYBACK0_COW		0x0004	/* do copy-on-write */
113 #define	M_COPYBACK0_EXTEND	0x0008	/* extend chain */
114 
115 static const char mclpool_warnmsg[] =
116     "WARNING: mclpool limit reached; increase kern.mbuf.nmbclusters";
117 
118 MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
119 
120 static percpu_t *mbstat_percpu;
121 
122 #ifdef MBUFTRACE
123 struct mownerhead mowners = LIST_HEAD_INITIALIZER(mowners);
124 struct mowner unknown_mowners[] = {
125 	MOWNER_INIT("unknown", "free"),
126 	MOWNER_INIT("unknown", "data"),
127 	MOWNER_INIT("unknown", "header"),
128 	MOWNER_INIT("unknown", "soname"),
129 	MOWNER_INIT("unknown", "soopts"),
130 	MOWNER_INIT("unknown", "ftable"),
131 	MOWNER_INIT("unknown", "control"),
132 	MOWNER_INIT("unknown", "oobdata"),
133 };
134 struct mowner revoked_mowner = MOWNER_INIT("revoked", "");
135 #endif
136 
137 #define	MEXT_ISEMBEDDED(m) ((m)->m_ext_ref == (m))
138 
139 #define	MCLADDREFERENCE(o, n)						\
140 do {									\
141 	KASSERT(((o)->m_flags & M_EXT) != 0);				\
142 	KASSERT(((n)->m_flags & M_EXT) == 0);				\
143 	KASSERT((o)->m_ext.ext_refcnt >= 1);				\
144 	(n)->m_flags |= ((o)->m_flags & M_EXTCOPYFLAGS);		\
145 	atomic_inc_uint(&(o)->m_ext.ext_refcnt);			\
146 	(n)->m_ext_ref = (o)->m_ext_ref;				\
147 	mowner_ref((n), (n)->m_flags);					\
148 	MCLREFDEBUGN((n), __FILE__, __LINE__);				\
149 } while (/* CONSTCOND */ 0)
150 
151 static int
152 nmbclusters_limit(void)
153 {
154 #if defined(PMAP_MAP_POOLPAGE)
155 	/* direct mapping, doesn't use space in kmem_arena */
156 	vsize_t max_size = physmem / 4;
157 #else
158 	vsize_t max_size = MIN(physmem / 4, nkmempages / 4);
159 #endif
160 
161 	max_size = max_size * PAGE_SIZE / MCLBYTES;
162 #ifdef NMBCLUSTERS_MAX
163 	max_size = MIN(max_size, NMBCLUSTERS_MAX);
164 #endif
165 
166 #ifdef NMBCLUSTERS
167 	return MIN(max_size, NMBCLUSTERS);
168 #else
169 	return max_size;
170 #endif
171 }
172 
173 /*
174  * Initialize the mbuf allocator.
175  */
176 void
177 mbinit(void)
178 {
179 
180 	CTASSERT(sizeof(struct _m_ext) <= MHLEN);
181 	CTASSERT(sizeof(struct mbuf) == MSIZE);
182 
183 	sysctl_kern_mbuf_setup();
184 
185 	mb_cache = pool_cache_init(msize, 0, 0, 0, "mbpl",
186 	    NULL, IPL_VM, mb_ctor, NULL, NULL);
187 	KASSERT(mb_cache != NULL);
188 
189 	mcl_cache = pool_cache_init(mclbytes, 0, 0, 0, "mclpl", NULL,
190 	    IPL_VM, NULL, NULL, NULL);
191 	KASSERT(mcl_cache != NULL);
192 
193 	pool_cache_set_drain_hook(mb_cache, m_reclaim, NULL);
194 	pool_cache_set_drain_hook(mcl_cache, m_reclaim, NULL);
195 
196 	/*
197 	 * Set an arbitrary default limit on the number of mbuf clusters.
198 	 */
199 #ifdef NMBCLUSTERS
200 	nmbclusters = nmbclusters_limit();
201 #else
202 	nmbclusters = MAX(1024,
203 	    (vsize_t)physmem * PAGE_SIZE / MCLBYTES / 16);
204 	nmbclusters = MIN(nmbclusters, nmbclusters_limit());
205 #endif
206 
207 	/*
208 	 * Set the hard limit on the mclpool to the number of
209 	 * mbuf clusters the kernel is to support.  Log the limit
210 	 * reached message max once a minute.
211 	 */
212 	pool_cache_sethardlimit(mcl_cache, nmbclusters, mclpool_warnmsg, 60);
213 
214 	mbstat_percpu = percpu_alloc(sizeof(struct mbstat_cpu));
215 
216 	/*
217 	 * Set a low water mark for both mbufs and clusters.  This should
218 	 * help ensure that they can be allocated in a memory starvation
219 	 * situation.  This is important for e.g. diskless systems which
220 	 * must allocate mbufs in order for the pagedaemon to clean pages.
221 	 */
222 	pool_cache_setlowat(mb_cache, mblowat);
223 	pool_cache_setlowat(mcl_cache, mcllowat);
224 
225 #ifdef MBUFTRACE
226 	{
227 		/*
228 		 * Attach the unknown mowners.
229 		 */
230 		int i;
231 		MOWNER_ATTACH(&revoked_mowner);
232 		for (i = sizeof(unknown_mowners)/sizeof(unknown_mowners[0]);
233 		     i-- > 0; )
234 			MOWNER_ATTACH(&unknown_mowners[i]);
235 	}
236 #endif
237 }
238 
239 /*
240  * sysctl helper routine for the kern.mbuf subtree.
241  * nmbclusters, mblowat and mcllowat need range
242  * checking and pool tweaking after being reset.
243  */
244 static int
245 sysctl_kern_mbuf(SYSCTLFN_ARGS)
246 {
247 	int error, newval;
248 	struct sysctlnode node;
249 
250 	node = *rnode;
251 	node.sysctl_data = &newval;
252 	switch (rnode->sysctl_num) {
253 	case MBUF_NMBCLUSTERS:
254 	case MBUF_MBLOWAT:
255 	case MBUF_MCLLOWAT:
256 		newval = *(int*)rnode->sysctl_data;
257 		break;
258 	default:
259 		return (EOPNOTSUPP);
260 	}
261 
262 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
263 	if (error || newp == NULL)
264 		return (error);
265 	if (newval < 0)
266 		return (EINVAL);
267 
268 	switch (node.sysctl_num) {
269 	case MBUF_NMBCLUSTERS:
270 		if (newval < nmbclusters)
271 			return (EINVAL);
272 		if (newval > nmbclusters_limit())
273 			return (EINVAL);
274 		nmbclusters = newval;
275 		pool_cache_sethardlimit(mcl_cache, nmbclusters,
276 		    mclpool_warnmsg, 60);
277 		break;
278 	case MBUF_MBLOWAT:
279 		mblowat = newval;
280 		pool_cache_setlowat(mb_cache, mblowat);
281 		break;
282 	case MBUF_MCLLOWAT:
283 		mcllowat = newval;
284 		pool_cache_setlowat(mcl_cache, mcllowat);
285 		break;
286 	}
287 
288 	return (0);
289 }
290 
291 #ifdef MBUFTRACE
292 static void
293 mowner_conver_to_user_cb(void *v1, void *v2, struct cpu_info *ci)
294 {
295 	struct mowner_counter *mc = v1;
296 	struct mowner_user *mo_user = v2;
297 	int i;
298 
299 	for (i = 0; i < MOWNER_COUNTER_NCOUNTERS; i++) {
300 		mo_user->mo_counter[i] += mc->mc_counter[i];
301 	}
302 }
303 
304 static void
305 mowner_convert_to_user(struct mowner *mo, struct mowner_user *mo_user)
306 {
307 
308 	memset(mo_user, 0, sizeof(*mo_user));
309 	CTASSERT(sizeof(mo_user->mo_name) == sizeof(mo->mo_name));
310 	CTASSERT(sizeof(mo_user->mo_descr) == sizeof(mo->mo_descr));
311 	memcpy(mo_user->mo_name, mo->mo_name, sizeof(mo->mo_name));
312 	memcpy(mo_user->mo_descr, mo->mo_descr, sizeof(mo->mo_descr));
313 	percpu_foreach(mo->mo_counters, mowner_conver_to_user_cb, mo_user);
314 }
315 
316 static int
317 sysctl_kern_mbuf_mowners(SYSCTLFN_ARGS)
318 {
319 	struct mowner *mo;
320 	size_t len = 0;
321 	int error = 0;
322 
323 	if (namelen != 0)
324 		return (EINVAL);
325 	if (newp != NULL)
326 		return (EPERM);
327 
328 	LIST_FOREACH(mo, &mowners, mo_link) {
329 		struct mowner_user mo_user;
330 
331 		mowner_convert_to_user(mo, &mo_user);
332 
333 		if (oldp != NULL) {
334 			if (*oldlenp - len < sizeof(mo_user)) {
335 				error = ENOMEM;
336 				break;
337 			}
338 			error = copyout(&mo_user, (char *)oldp + len,
339 			    sizeof(mo_user));
340 			if (error)
341 				break;
342 		}
343 		len += sizeof(mo_user);
344 	}
345 
346 	if (error == 0)
347 		*oldlenp = len;
348 
349 	return (error);
350 }
351 #endif /* MBUFTRACE */
352 
353 static void
354 mbstat_conver_to_user_cb(void *v1, void *v2, struct cpu_info *ci)
355 {
356 	struct mbstat_cpu *mbsc = v1;
357 	struct mbstat *mbs = v2;
358 	int i;
359 
360 	for (i = 0; i < __arraycount(mbs->m_mtypes); i++) {
361 		mbs->m_mtypes[i] += mbsc->m_mtypes[i];
362 	}
363 }
364 
365 static void
366 mbstat_convert_to_user(struct mbstat *mbs)
367 {
368 
369 	memset(mbs, 0, sizeof(*mbs));
370 	mbs->m_drain = mbstat.m_drain;
371 	percpu_foreach(mbstat_percpu, mbstat_conver_to_user_cb, mbs);
372 }
373 
374 static int
375 sysctl_kern_mbuf_stats(SYSCTLFN_ARGS)
376 {
377 	struct sysctlnode node;
378 	struct mbstat mbs;
379 
380 	mbstat_convert_to_user(&mbs);
381 	node = *rnode;
382 	node.sysctl_data = &mbs;
383 	node.sysctl_size = sizeof(mbs);
384 	return sysctl_lookup(SYSCTLFN_CALL(&node));
385 }
386 
387 static void
388 sysctl_kern_mbuf_setup(void)
389 {
390 
391 	KASSERT(mbuf_sysctllog == NULL);
392 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
393 		       CTLFLAG_PERMANENT,
394 		       CTLTYPE_NODE, "mbuf",
395 		       SYSCTL_DESCR("mbuf control variables"),
396 		       NULL, 0, NULL, 0,
397 		       CTL_KERN, KERN_MBUF, CTL_EOL);
398 
399 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
400 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
401 		       CTLTYPE_INT, "msize",
402 		       SYSCTL_DESCR("mbuf base size"),
403 		       NULL, msize, NULL, 0,
404 		       CTL_KERN, KERN_MBUF, MBUF_MSIZE, CTL_EOL);
405 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
406 		       CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
407 		       CTLTYPE_INT, "mclbytes",
408 		       SYSCTL_DESCR("mbuf cluster size"),
409 		       NULL, mclbytes, NULL, 0,
410 		       CTL_KERN, KERN_MBUF, MBUF_MCLBYTES, CTL_EOL);
411 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
412 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
413 		       CTLTYPE_INT, "nmbclusters",
414 		       SYSCTL_DESCR("Limit on the number of mbuf clusters"),
415 		       sysctl_kern_mbuf, 0, &nmbclusters, 0,
416 		       CTL_KERN, KERN_MBUF, MBUF_NMBCLUSTERS, CTL_EOL);
417 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
418 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
419 		       CTLTYPE_INT, "mblowat",
420 		       SYSCTL_DESCR("mbuf low water mark"),
421 		       sysctl_kern_mbuf, 0, &mblowat, 0,
422 		       CTL_KERN, KERN_MBUF, MBUF_MBLOWAT, CTL_EOL);
423 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
424 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
425 		       CTLTYPE_INT, "mcllowat",
426 		       SYSCTL_DESCR("mbuf cluster low water mark"),
427 		       sysctl_kern_mbuf, 0, &mcllowat, 0,
428 		       CTL_KERN, KERN_MBUF, MBUF_MCLLOWAT, CTL_EOL);
429 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
430 		       CTLFLAG_PERMANENT,
431 		       CTLTYPE_STRUCT, "stats",
432 		       SYSCTL_DESCR("mbuf allocation statistics"),
433 		       sysctl_kern_mbuf_stats, 0, NULL, 0,
434 		       CTL_KERN, KERN_MBUF, MBUF_STATS, CTL_EOL);
435 #ifdef MBUFTRACE
436 	sysctl_createv(&mbuf_sysctllog, 0, NULL, NULL,
437 		       CTLFLAG_PERMANENT,
438 		       CTLTYPE_STRUCT, "mowners",
439 		       SYSCTL_DESCR("Information about mbuf owners"),
440 		       sysctl_kern_mbuf_mowners, 0, NULL, 0,
441 		       CTL_KERN, KERN_MBUF, MBUF_MOWNERS, CTL_EOL);
442 #endif /* MBUFTRACE */
443 }
444 
445 static int
446 mb_ctor(void *arg, void *object, int flags)
447 {
448 	struct mbuf *m = object;
449 
450 #ifdef POOL_VTOPHYS
451 	m->m_paddr = POOL_VTOPHYS(m);
452 #else
453 	m->m_paddr = M_PADDR_INVALID;
454 #endif
455 	return (0);
456 }
457 
458 /*
459  * Add mbuf to the end of a chain
460  */
461 struct mbuf *
462 m_add(struct mbuf *c, struct mbuf *m) {
463 	struct mbuf *n;
464 
465 	if (c == NULL)
466 		return m;
467 
468 	for (n = c; n->m_next != NULL; n = n->m_next)
469 		continue;
470 	n->m_next = m;
471 	return c;
472 }
473 
474 /*
475  * Set the m_data pointer of a newly-allocated mbuf
476  * to place an object of the specified size at the
477  * end of the mbuf, longword aligned.
478  */
479 void
480 m_align(struct mbuf *m, int len)
481 {
482 	int adjust;
483 
484 	KASSERT(len != M_COPYALL);
485 
486 	if (m->m_flags & M_EXT)
487 		adjust = m->m_ext.ext_size - len;
488 	else if (m->m_flags & M_PKTHDR)
489 		adjust = MHLEN - len;
490 	else
491 		adjust = MLEN - len;
492 	m->m_data += adjust &~ (sizeof(long)-1);
493 }
494 
495 /*
496  * Append the specified data to the indicated mbuf chain,
497  * Extend the mbuf chain if the new data does not fit in
498  * existing space.
499  *
500  * Return 1 if able to complete the job; otherwise 0.
501  */
502 int
503 m_append(struct mbuf *m0, int len, const void *cpv)
504 {
505 	struct mbuf *m, *n;
506 	int remainder, space;
507 	const char *cp = cpv;
508 
509 	KASSERT(len != M_COPYALL);
510 	for (m = m0; m->m_next != NULL; m = m->m_next)
511 		continue;
512 	remainder = len;
513 	space = M_TRAILINGSPACE(m);
514 	if (space > 0) {
515 		/*
516 		 * Copy into available space.
517 		 */
518 		if (space > remainder)
519 			space = remainder;
520 		memmove(mtod(m, char *) + m->m_len, cp, space);
521 		m->m_len += space;
522 		cp = cp + space, remainder -= space;
523 	}
524 	while (remainder > 0) {
525 		/*
526 		 * Allocate a new mbuf; could check space
527 		 * and allocate a cluster instead.
528 		 */
529 		n = m_get(M_DONTWAIT, m->m_type);
530 		if (n == NULL)
531 			break;
532 		n->m_len = min(MLEN, remainder);
533 		memmove(mtod(n, void *), cp, n->m_len);
534 		cp += n->m_len, remainder -= n->m_len;
535 		m->m_next = n;
536 		m = n;
537 	}
538 	if (m0->m_flags & M_PKTHDR)
539 		m0->m_pkthdr.len += len - remainder;
540 	return (remainder == 0);
541 }
542 
543 void
544 m_reclaim(void *arg, int flags)
545 {
546 	struct domain *dp;
547 	const struct protosw *pr;
548 	struct ifnet *ifp;
549 	int s;
550 
551 	KERNEL_LOCK(1, NULL);
552 	s = splvm();
553 	DOMAIN_FOREACH(dp) {
554 		for (pr = dp->dom_protosw;
555 		     pr < dp->dom_protoswNPROTOSW; pr++)
556 			if (pr->pr_drain)
557 				(*pr->pr_drain)();
558 	}
559 	/* XXX we cannot use psref in H/W interrupt */
560 	if (!cpu_intr_p()) {
561 		int bound = curlwp->l_pflag & LP_BOUND;
562 		curlwp->l_pflag |= LP_BOUND;
563 		IFNET_READER_FOREACH(ifp) {
564 			struct psref psref;
565 
566 			psref_acquire(&psref, &ifp->if_psref,
567 			    ifnet_psref_class);
568 
569 			if (ifp->if_drain)
570 				(*ifp->if_drain)(ifp);
571 
572 			psref_release(&psref, &ifp->if_psref,
573 			    ifnet_psref_class);
574 		}
575 		curlwp->l_pflag ^= bound ^ LP_BOUND;
576 	}
577 	splx(s);
578 	mbstat.m_drain++;
579 	KERNEL_UNLOCK_ONE(NULL);
580 }
581 
582 /*
583  * Space allocation routines.
584  * These are also available as macros
585  * for critical paths.
586  */
587 struct mbuf *
588 m_get(int nowait, int type)
589 {
590 	struct mbuf *m;
591 
592 	KASSERT(type != MT_FREE);
593 
594 	m = pool_cache_get(mb_cache,
595 	    nowait == M_WAIT ? PR_WAITOK|PR_LIMITFAIL : 0);
596 	if (m == NULL)
597 		return NULL;
598 
599 	mbstat_type_add(type, 1);
600 
601 	m_hdr_init(m, type, NULL, m->m_dat, 0);
602 
603 	return m;
604 }
605 
606 struct mbuf *
607 m_gethdr(int nowait, int type)
608 {
609 	struct mbuf *m;
610 
611 	m = m_get(nowait, type);
612 	if (m == NULL)
613 		return NULL;
614 
615 	m_pkthdr_init(m);
616 
617 	return m;
618 }
619 
620 struct mbuf *
621 m_getclr(int nowait, int type)
622 {
623 	struct mbuf *m;
624 
625 	m = m_get(nowait, type);
626 	if (m == 0)
627 		return (NULL);
628 	memset(mtod(m, void *), 0, MLEN);
629 	return (m);
630 }
631 
632 void
633 m_clget(struct mbuf *m, int nowait)
634 {
635 
636 	MCLGET(m, nowait);
637 }
638 
639 struct mbuf *
640 m_free(struct mbuf *m)
641 {
642 	struct mbuf *n;
643 
644 	MFREE(m, n);
645 	return (n);
646 }
647 
648 void
649 m_freem(struct mbuf *m)
650 {
651 	struct mbuf *n;
652 
653 	if (m == NULL)
654 		return;
655 	do {
656 		MFREE(m, n);
657 		m = n;
658 	} while (m);
659 }
660 
661 #ifdef MBUFTRACE
662 /*
663  * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
664  */
665 void
666 m_claimm(struct mbuf *m, struct mowner *mo)
667 {
668 
669 	for (; m != NULL; m = m->m_next)
670 		MCLAIM(m, mo);
671 }
672 #endif
673 
674 /*
675  * Mbuffer utility routines.
676  */
677 
678 /*
679  * Lesser-used path for M_PREPEND:
680  * allocate new mbuf to prepend to chain,
681  * copy junk along.
682  */
683 struct mbuf *
684 m_prepend(struct mbuf *m, int len, int how)
685 {
686 	struct mbuf *mn;
687 
688 	KASSERT(len != M_COPYALL);
689 	mn = m_get(how, m->m_type);
690 	if (mn == NULL) {
691 		m_freem(m);
692 		return (NULL);
693 	}
694 	if (m->m_flags & M_PKTHDR) {
695 		M_MOVE_PKTHDR(mn, m);
696 	} else {
697 		MCLAIM(mn, m->m_owner);
698 	}
699 	mn->m_next = m;
700 	m = mn;
701 	if (len < MHLEN)
702 		MH_ALIGN(m, len);
703 	m->m_len = len;
704 	return (m);
705 }
706 
707 /*
708  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
709  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
710  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
711  */
712 int MCFail;
713 
714 struct mbuf *
715 m_copym(struct mbuf *m, int off0, int len, int wait)
716 {
717 
718 	return m_copym0(m, off0, len, wait, 0);	/* shallow copy on M_EXT */
719 }
720 
721 struct mbuf *
722 m_dup(struct mbuf *m, int off0, int len, int wait)
723 {
724 
725 	return m_copym0(m, off0, len, wait, 1);	/* deep copy */
726 }
727 
728 static inline int
729 m_copylen(int len, int copylen) {
730     return len == M_COPYALL ? copylen : min(len, copylen);
731 }
732 
733 static struct mbuf *
734 m_copym0(struct mbuf *m, int off0, int len, int wait, int deep)
735 {
736 	struct mbuf *n, **np;
737 	int off = off0;
738 	struct mbuf *top;
739 	int copyhdr = 0;
740 
741 	if (off < 0 || (len != M_COPYALL && len < 0))
742 		panic("m_copym: off %d, len %d", off, len);
743 	if (off == 0 && m->m_flags & M_PKTHDR)
744 		copyhdr = 1;
745 	while (off > 0) {
746 		if (m == 0)
747 			panic("m_copym: m == 0, off %d", off);
748 		if (off < m->m_len)
749 			break;
750 		off -= m->m_len;
751 		m = m->m_next;
752 	}
753 	np = &top;
754 	top = 0;
755 	while (len == M_COPYALL || len > 0) {
756 		if (m == 0) {
757 			if (len != M_COPYALL)
758 				panic("m_copym: m == 0, len %d [!COPYALL]",
759 				    len);
760 			break;
761 		}
762 		n = m_get(wait, m->m_type);
763 		*np = n;
764 		if (n == 0)
765 			goto nospace;
766 		MCLAIM(n, m->m_owner);
767 		if (copyhdr) {
768 			M_COPY_PKTHDR(n, m);
769 			if (len == M_COPYALL)
770 				n->m_pkthdr.len -= off0;
771 			else
772 				n->m_pkthdr.len = len;
773 			copyhdr = 0;
774 		}
775 		n->m_len = m_copylen(len, m->m_len - off);
776 		if (m->m_flags & M_EXT) {
777 			if (!deep) {
778 				n->m_data = m->m_data + off;
779 				MCLADDREFERENCE(m, n);
780 			} else {
781 				/*
782 				 * we are unsure about the way m was allocated.
783 				 * copy into multiple MCLBYTES cluster mbufs.
784 				 *
785 				 * recompute m_len, it is no longer valid if MCLGET()
786 				 * fails to allocate a cluster. Then we try to split
787 				 * the source into normal sized mbufs.
788 				 */
789 				MCLGET(n, wait);
790 				n->m_len = 0;
791 				n->m_len = M_TRAILINGSPACE(n);
792 				n->m_len = m_copylen(len, n->m_len);
793 				n->m_len = min(n->m_len, m->m_len - off);
794 				memcpy(mtod(n, void *), mtod(m, char *) + off,
795 				    (unsigned)n->m_len);
796 			}
797 		} else
798 			memcpy(mtod(n, void *), mtod(m, char *) + off,
799 			    (unsigned)n->m_len);
800 		if (len != M_COPYALL)
801 			len -= n->m_len;
802 		off += n->m_len;
803 #ifdef DIAGNOSTIC
804 		if (off > m->m_len)
805 			panic("m_copym0 overrun %d %d", off, m->m_len);
806 #endif
807 		if (off == m->m_len) {
808 			m = m->m_next;
809 			off = 0;
810 		}
811 		np = &n->m_next;
812 	}
813 	if (top == 0)
814 		MCFail++;
815 	return (top);
816 nospace:
817 	m_freem(top);
818 	MCFail++;
819 	return (NULL);
820 }
821 
822 /*
823  * Copy an entire packet, including header (which must be present).
824  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
825  */
826 struct mbuf *
827 m_copypacket(struct mbuf *m, int how)
828 {
829 	struct mbuf *top, *n, *o;
830 
831 	n = m_get(how, m->m_type);
832 	top = n;
833 	if (!n)
834 		goto nospace;
835 
836 	MCLAIM(n, m->m_owner);
837 	M_COPY_PKTHDR(n, m);
838 	n->m_len = m->m_len;
839 	if (m->m_flags & M_EXT) {
840 		n->m_data = m->m_data;
841 		MCLADDREFERENCE(m, n);
842 	} else {
843 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
844 	}
845 
846 	m = m->m_next;
847 	while (m) {
848 		o = m_get(how, m->m_type);
849 		if (!o)
850 			goto nospace;
851 
852 		MCLAIM(o, m->m_owner);
853 		n->m_next = o;
854 		n = n->m_next;
855 
856 		n->m_len = m->m_len;
857 		if (m->m_flags & M_EXT) {
858 			n->m_data = m->m_data;
859 			MCLADDREFERENCE(m, n);
860 		} else {
861 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
862 		}
863 
864 		m = m->m_next;
865 	}
866 	return top;
867 nospace:
868 	m_freem(top);
869 	MCFail++;
870 	return NULL;
871 }
872 
873 /*
874  * Copy data from an mbuf chain starting "off" bytes from the beginning,
875  * continuing for "len" bytes, into the indicated buffer.
876  */
877 void
878 m_copydata(struct mbuf *m, int off, int len, void *vp)
879 {
880 	unsigned	count;
881 	void *		cp = vp;
882 	struct mbuf	*m0 = m;
883 	int		len0 = len;
884 	int		off0 = off;
885 	void		*vp0 = vp;
886 
887 	KASSERT(len != M_COPYALL);
888 	if (off < 0 || len < 0)
889 		panic("m_copydata: off %d, len %d", off, len);
890 	while (off > 0) {
891 		if (m == NULL)
892 			panic("m_copydata(%p,%d,%d,%p): m=NULL, off=%d (%d)",
893 			    m0, len0, off0, vp0, off, off0 - off);
894 		if (off < m->m_len)
895 			break;
896 		off -= m->m_len;
897 		m = m->m_next;
898 	}
899 	while (len > 0) {
900 		if (m == NULL)
901 			panic("m_copydata(%p,%d,%d,%p): "
902 			    "m=NULL, off=%d (%d), len=%d (%d)",
903 			    m0, len0, off0, vp0,
904 			    off, off0 - off, len, len0 - len);
905 		count = min(m->m_len - off, len);
906 		memcpy(cp, mtod(m, char *) + off, count);
907 		len -= count;
908 		cp = (char *)cp + count;
909 		off = 0;
910 		m = m->m_next;
911 	}
912 }
913 
914 /*
915  * Concatenate mbuf chain n to m.
916  * n might be copied into m (when n->m_len is small), therefore data portion of
917  * n could be copied into an mbuf of different mbuf type.
918  * Any m_pkthdr is not updated.
919  */
920 void
921 m_cat(struct mbuf *m, struct mbuf *n)
922 {
923 
924 	while (m->m_next)
925 		m = m->m_next;
926 	while (n) {
927 		if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
928 			/* just join the two chains */
929 			m->m_next = n;
930 			return;
931 		}
932 		/* splat the data from one into the other */
933 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
934 		    (u_int)n->m_len);
935 		m->m_len += n->m_len;
936 		n = m_free(n);
937 	}
938 }
939 
940 void
941 m_adj(struct mbuf *mp, int req_len)
942 {
943 	int len = req_len;
944 	struct mbuf *m;
945 	int count;
946 
947 	if ((m = mp) == NULL)
948 		return;
949 	if (len >= 0) {
950 		/*
951 		 * Trim from head.
952 		 */
953 		while (m != NULL && len > 0) {
954 			if (m->m_len <= len) {
955 				len -= m->m_len;
956 				m->m_len = 0;
957 				m = m->m_next;
958 			} else {
959 				m->m_len -= len;
960 				m->m_data += len;
961 				len = 0;
962 			}
963 		}
964 		m = mp;
965 		if (mp->m_flags & M_PKTHDR)
966 			m->m_pkthdr.len -= (req_len - len);
967 	} else {
968 		/*
969 		 * Trim from tail.  Scan the mbuf chain,
970 		 * calculating its length and finding the last mbuf.
971 		 * If the adjustment only affects this mbuf, then just
972 		 * adjust and return.  Otherwise, rescan and truncate
973 		 * after the remaining size.
974 		 */
975 		len = -len;
976 		count = 0;
977 		for (;;) {
978 			count += m->m_len;
979 			if (m->m_next == (struct mbuf *)0)
980 				break;
981 			m = m->m_next;
982 		}
983 		if (m->m_len >= len) {
984 			m->m_len -= len;
985 			if (mp->m_flags & M_PKTHDR)
986 				mp->m_pkthdr.len -= len;
987 			return;
988 		}
989 		count -= len;
990 		if (count < 0)
991 			count = 0;
992 		/*
993 		 * Correct length for chain is "count".
994 		 * Find the mbuf with last data, adjust its length,
995 		 * and toss data from remaining mbufs on chain.
996 		 */
997 		m = mp;
998 		if (m->m_flags & M_PKTHDR)
999 			m->m_pkthdr.len = count;
1000 		for (; m; m = m->m_next) {
1001 			if (m->m_len >= count) {
1002 				m->m_len = count;
1003 				break;
1004 			}
1005 			count -= m->m_len;
1006 		}
1007 		if (m)
1008 			while (m->m_next)
1009 				(m = m->m_next)->m_len = 0;
1010 	}
1011 }
1012 
1013 /*
1014  * m_ensure_contig: rearrange an mbuf chain that given length of bytes
1015  * would be contiguous and in the data area of an mbuf (therefore, mtod()
1016  * would work for a structure of given length).
1017  *
1018  * => On success, returns true and the resulting mbuf chain; false otherwise.
1019  * => The mbuf chain may change, but is always preserved valid.
1020  */
1021 bool
1022 m_ensure_contig(struct mbuf **m0, int len)
1023 {
1024 	struct mbuf *n = *m0, *m;
1025 	size_t count, space;
1026 
1027 	KASSERT(len != M_COPYALL);
1028 	/*
1029 	 * If first mbuf has no cluster, and has room for len bytes
1030 	 * without shifting current data, pullup into it,
1031 	 * otherwise allocate a new mbuf to prepend to the chain.
1032 	 */
1033 	if ((n->m_flags & M_EXT) == 0 &&
1034 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1035 		if (n->m_len >= len) {
1036 			return true;
1037 		}
1038 		m = n;
1039 		n = n->m_next;
1040 		len -= m->m_len;
1041 	} else {
1042 		if (len > MHLEN) {
1043 			return false;
1044 		}
1045 		m = m_get(M_DONTWAIT, n->m_type);
1046 		if (m == NULL) {
1047 			return false;
1048 		}
1049 		MCLAIM(m, n->m_owner);
1050 		if (n->m_flags & M_PKTHDR) {
1051 			M_MOVE_PKTHDR(m, n);
1052 		}
1053 	}
1054 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1055 	do {
1056 		count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
1057 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1058 		  (unsigned)count);
1059 		len -= count;
1060 		m->m_len += count;
1061 		n->m_len -= count;
1062 		space -= count;
1063 		if (n->m_len)
1064 			n->m_data += count;
1065 		else
1066 			n = m_free(n);
1067 	} while (len > 0 && n);
1068 
1069 	m->m_next = n;
1070 	*m0 = m;
1071 
1072 	return len <= 0;
1073 }
1074 
1075 /*
1076  * m_pullup: same as m_ensure_contig(), but destroys mbuf chain on error.
1077  */
1078 int MPFail;
1079 
1080 struct mbuf *
1081 m_pullup(struct mbuf *n, int len)
1082 {
1083 	struct mbuf *m = n;
1084 
1085 	KASSERT(len != M_COPYALL);
1086 	if (!m_ensure_contig(&m, len)) {
1087 		KASSERT(m != NULL);
1088 		m_freem(m);
1089 		MPFail++;
1090 		m = NULL;
1091 	}
1092 	return m;
1093 }
1094 
1095 /*
1096  * Like m_pullup(), except a new mbuf is always allocated, and we allow
1097  * the amount of empty space before the data in the new mbuf to be specified
1098  * (in the event that the caller expects to prepend later).
1099  */
1100 int MSFail;
1101 
1102 struct mbuf *
1103 m_copyup(struct mbuf *n, int len, int dstoff)
1104 {
1105 	struct mbuf *m;
1106 	int count, space;
1107 
1108 	KASSERT(len != M_COPYALL);
1109 	if (len > (MHLEN - dstoff))
1110 		goto bad;
1111 	m = m_get(M_DONTWAIT, n->m_type);
1112 	if (m == NULL)
1113 		goto bad;
1114 	MCLAIM(m, n->m_owner);
1115 	if (n->m_flags & M_PKTHDR) {
1116 		M_MOVE_PKTHDR(m, n);
1117 	}
1118 	m->m_data += dstoff;
1119 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1120 	do {
1121 		count = min(min(max(len, max_protohdr), space), n->m_len);
1122 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1123 		    (unsigned)count);
1124 		len -= count;
1125 		m->m_len += count;
1126 		n->m_len -= count;
1127 		space -= count;
1128 		if (n->m_len)
1129 			n->m_data += count;
1130 		else
1131 			n = m_free(n);
1132 	} while (len > 0 && n);
1133 	if (len > 0) {
1134 		(void) m_free(m);
1135 		goto bad;
1136 	}
1137 	m->m_next = n;
1138 	return (m);
1139  bad:
1140 	m_freem(n);
1141 	MSFail++;
1142 	return (NULL);
1143 }
1144 
1145 /*
1146  * Partition an mbuf chain in two pieces, returning the tail --
1147  * all but the first len0 bytes.  In case of failure, it returns NULL and
1148  * attempts to restore the chain to its original state.
1149  */
1150 struct mbuf *
1151 m_split(struct mbuf *m0, int len0, int wait)
1152 {
1153 
1154 	return m_split0(m0, len0, wait, 1);
1155 }
1156 
1157 static struct mbuf *
1158 m_split0(struct mbuf *m0, int len0, int wait, int copyhdr)
1159 {
1160 	struct mbuf *m, *n;
1161 	unsigned len = len0, remain, len_save;
1162 
1163 	KASSERT(len0 != M_COPYALL);
1164 	for (m = m0; m && len > m->m_len; m = m->m_next)
1165 		len -= m->m_len;
1166 	if (m == 0)
1167 		return (NULL);
1168 	remain = m->m_len - len;
1169 	if (copyhdr && (m0->m_flags & M_PKTHDR)) {
1170 		n = m_gethdr(wait, m0->m_type);
1171 		if (n == NULL)
1172 			return NULL;
1173 		MCLAIM(n, m0->m_owner);
1174 		n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1175 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1176 		len_save = m0->m_pkthdr.len;
1177 		m0->m_pkthdr.len = len0;
1178 		if (m->m_flags & M_EXT)
1179 			goto extpacket;
1180 		if (remain > MHLEN) {
1181 			/* m can't be the lead packet */
1182 			MH_ALIGN(n, 0);
1183 			n->m_len = 0;
1184 			n->m_next = m_split(m, len, wait);
1185 			if (n->m_next == 0) {
1186 				(void) m_free(n);
1187 				m0->m_pkthdr.len = len_save;
1188 				return (NULL);
1189 			} else
1190 				return (n);
1191 		} else
1192 			MH_ALIGN(n, remain);
1193 	} else if (remain == 0) {
1194 		n = m->m_next;
1195 		m->m_next = 0;
1196 		return (n);
1197 	} else {
1198 		n = m_get(wait, m->m_type);
1199 		if (n == 0)
1200 			return (NULL);
1201 		MCLAIM(n, m->m_owner);
1202 		M_ALIGN(n, remain);
1203 	}
1204 extpacket:
1205 	if (m->m_flags & M_EXT) {
1206 		n->m_data = m->m_data + len;
1207 		MCLADDREFERENCE(m, n);
1208 	} else {
1209 		memcpy(mtod(n, void *), mtod(m, char *) + len, remain);
1210 	}
1211 	n->m_len = remain;
1212 	m->m_len = len;
1213 	n->m_next = m->m_next;
1214 	m->m_next = 0;
1215 	return (n);
1216 }
1217 /*
1218  * Routine to copy from device local memory into mbufs.
1219  */
1220 struct mbuf *
1221 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
1222     void (*copy)(const void *from, void *to, size_t len))
1223 {
1224 	struct mbuf *m;
1225 	struct mbuf *top = 0, **mp = &top;
1226 	int off = off0, len;
1227 	char *cp;
1228 	char *epkt;
1229 
1230 	cp = buf;
1231 	epkt = cp + totlen;
1232 	if (off) {
1233 		/*
1234 		 * If 'off' is non-zero, packet is trailer-encapsulated,
1235 		 * so we have to skip the type and length fields.
1236 		 */
1237 		cp += off + 2 * sizeof(uint16_t);
1238 		totlen -= 2 * sizeof(uint16_t);
1239 	}
1240 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1241 	if (m == NULL)
1242 		return NULL;
1243 	m->m_pkthdr.rcvif = ifp;
1244 	m->m_pkthdr.len = totlen;
1245 	m->m_len = MHLEN;
1246 
1247 	while (totlen > 0) {
1248 		if (top) {
1249 			m = m_get(M_DONTWAIT, MT_DATA);
1250 			if (m == 0) {
1251 				m_freem(top);
1252 				return (NULL);
1253 			}
1254 			m->m_len = MLEN;
1255 		}
1256 		len = min(totlen, epkt - cp);
1257 		if (len >= MINCLSIZE) {
1258 			MCLGET(m, M_DONTWAIT);
1259 			if ((m->m_flags & M_EXT) == 0) {
1260 				m_free(m);
1261 				m_freem(top);
1262 				return (NULL);
1263 			}
1264 			m->m_len = len = min(len, MCLBYTES);
1265 		} else {
1266 			/*
1267 			 * Place initial small packet/header at end of mbuf.
1268 			 */
1269 			if (len < m->m_len) {
1270 				if (top == 0 && len + max_linkhdr <= m->m_len)
1271 					m->m_data += max_linkhdr;
1272 				m->m_len = len;
1273 			} else
1274 				len = m->m_len;
1275 		}
1276 		if (copy)
1277 			copy(cp, mtod(m, void *), (size_t)len);
1278 		else
1279 			memcpy(mtod(m, void *), cp, (size_t)len);
1280 		cp += len;
1281 		*mp = m;
1282 		mp = &m->m_next;
1283 		totlen -= len;
1284 		if (cp == epkt)
1285 			cp = buf;
1286 	}
1287 	return (top);
1288 }
1289 
1290 /*
1291  * Copy data from a buffer back into the indicated mbuf chain,
1292  * starting "off" bytes from the beginning, extending the mbuf
1293  * chain if necessary.
1294  */
1295 void
1296 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
1297 {
1298 #if defined(DEBUG)
1299 	struct mbuf *origm = m0;
1300 	int error;
1301 #endif /* defined(DEBUG) */
1302 
1303 	if (m0 == NULL)
1304 		return;
1305 
1306 #if defined(DEBUG)
1307 	error =
1308 #endif /* defined(DEBUG) */
1309 	m_copyback0(&m0, off, len, cp,
1310 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
1311 
1312 #if defined(DEBUG)
1313 	if (error != 0 || (m0 != NULL && origm != m0))
1314 		panic("m_copyback");
1315 #endif /* defined(DEBUG) */
1316 }
1317 
1318 struct mbuf *
1319 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
1320 {
1321 	int error;
1322 
1323 	/* don't support chain expansion */
1324 	KASSERT(len != M_COPYALL);
1325 	KDASSERT(off + len <= m_length(m0));
1326 
1327 	error = m_copyback0(&m0, off, len, cp,
1328 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
1329 	if (error) {
1330 		/*
1331 		 * no way to recover from partial success.
1332 		 * just free the chain.
1333 		 */
1334 		m_freem(m0);
1335 		return NULL;
1336 	}
1337 	return m0;
1338 }
1339 
1340 /*
1341  * m_makewritable: ensure the specified range writable.
1342  */
1343 int
1344 m_makewritable(struct mbuf **mp, int off, int len, int how)
1345 {
1346 	int error;
1347 #if defined(DEBUG)
1348 	int origlen = m_length(*mp);
1349 #endif /* defined(DEBUG) */
1350 
1351 	error = m_copyback0(mp, off, len, NULL,
1352 	    M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
1353 
1354 #if defined(DEBUG)
1355 	int reslen = 0;
1356 	for (struct mbuf *n = *mp; n; n = n->m_next)
1357 		reslen += n->m_len;
1358 	if (origlen != reslen)
1359 		panic("m_makewritable: length changed");
1360 	if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
1361 		panic("m_makewritable: inconsist");
1362 #endif /* defined(DEBUG) */
1363 
1364 	return error;
1365 }
1366 
1367 /*
1368  * Copy the mbuf chain to a new mbuf chain that is as short as possible.
1369  * Return the new mbuf chain on success, NULL on failure.  On success,
1370  * free the old mbuf chain.
1371  */
1372 struct mbuf *
1373 m_defrag(struct mbuf *mold, int flags)
1374 {
1375 	struct mbuf *m0, *mn, *n;
1376 	size_t sz = mold->m_pkthdr.len;
1377 
1378 #ifdef DIAGNOSTIC
1379 	if ((mold->m_flags & M_PKTHDR) == 0)
1380 		panic("m_defrag: not a mbuf chain header");
1381 #endif
1382 
1383 	m0 = m_gethdr(flags, MT_DATA);
1384 	if (m0 == NULL)
1385 		return NULL;
1386 	M_COPY_PKTHDR(m0, mold);
1387 	mn = m0;
1388 
1389 	do {
1390 		if (sz > MHLEN) {
1391 			MCLGET(mn, M_DONTWAIT);
1392 			if ((mn->m_flags & M_EXT) == 0) {
1393 				m_freem(m0);
1394 				return NULL;
1395 			}
1396 		}
1397 
1398 		mn->m_len = MIN(sz, MCLBYTES);
1399 
1400 		m_copydata(mold, mold->m_pkthdr.len - sz, mn->m_len,
1401 		     mtod(mn, void *));
1402 
1403 		sz -= mn->m_len;
1404 
1405 		if (sz > 0) {
1406 			/* need more mbufs */
1407 			n = m_get(M_NOWAIT, MT_DATA);
1408 			if (n == NULL) {
1409 				m_freem(m0);
1410 				return NULL;
1411 			}
1412 
1413 			mn->m_next = n;
1414 			mn = n;
1415 		}
1416 	} while (sz > 0);
1417 
1418 	m_freem(mold);
1419 
1420 	return m0;
1421 }
1422 
1423 int
1424 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
1425     int how)
1426 {
1427 	int mlen;
1428 	struct mbuf *m, *n;
1429 	struct mbuf **mp;
1430 	int totlen = 0;
1431 	const char *cp = vp;
1432 
1433 	KASSERT(mp0 != NULL);
1434 	KASSERT(*mp0 != NULL);
1435 	KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
1436 	KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
1437 
1438 	if (len == M_COPYALL)
1439 		len = m_length(*mp0) - off;
1440 
1441 	/*
1442 	 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
1443 	 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
1444 	 */
1445 
1446 	KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
1447 
1448 	mp = mp0;
1449 	m = *mp;
1450 	while (off > (mlen = m->m_len)) {
1451 		off -= mlen;
1452 		totlen += mlen;
1453 		if (m->m_next == NULL) {
1454 			int tspace;
1455 extend:
1456 			if ((flags & M_COPYBACK0_EXTEND) == 0)
1457 				goto out;
1458 
1459 			/*
1460 			 * try to make some space at the end of "m".
1461 			 */
1462 
1463 			mlen = m->m_len;
1464 			if (off + len >= MINCLSIZE &&
1465 			    (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
1466 				MCLGET(m, how);
1467 			}
1468 			tspace = M_TRAILINGSPACE(m);
1469 			if (tspace > 0) {
1470 				tspace = min(tspace, off + len);
1471 				KASSERT(tspace > 0);
1472 				memset(mtod(m, char *) + m->m_len, 0,
1473 				    min(off, tspace));
1474 				m->m_len += tspace;
1475 				off += mlen;
1476 				totlen -= mlen;
1477 				continue;
1478 			}
1479 
1480 			/*
1481 			 * need to allocate an mbuf.
1482 			 */
1483 
1484 			if (off + len >= MINCLSIZE) {
1485 				n = m_getcl(how, m->m_type, 0);
1486 			} else {
1487 				n = m_get(how, m->m_type);
1488 			}
1489 			if (n == NULL) {
1490 				goto out;
1491 			}
1492 			n->m_len = min(M_TRAILINGSPACE(n), off + len);
1493 			memset(mtod(n, char *), 0, min(n->m_len, off));
1494 			m->m_next = n;
1495 		}
1496 		mp = &m->m_next;
1497 		m = m->m_next;
1498 	}
1499 	while (len > 0) {
1500 		mlen = m->m_len - off;
1501 		if (mlen != 0 && M_READONLY(m)) {
1502 			char *datap;
1503 			int eatlen;
1504 
1505 			/*
1506 			 * this mbuf is read-only.
1507 			 * allocate a new writable mbuf and try again.
1508 			 */
1509 
1510 #if defined(DIAGNOSTIC)
1511 			if ((flags & M_COPYBACK0_COW) == 0)
1512 				panic("m_copyback0: read-only");
1513 #endif /* defined(DIAGNOSTIC) */
1514 
1515 			/*
1516 			 * if we're going to write into the middle of
1517 			 * a mbuf, split it first.
1518 			 */
1519 			if (off > 0) {
1520 				n = m_split0(m, off, how, 0);
1521 				if (n == NULL)
1522 					goto enobufs;
1523 				m->m_next = n;
1524 				mp = &m->m_next;
1525 				m = n;
1526 				off = 0;
1527 				continue;
1528 			}
1529 
1530 			/*
1531 			 * XXX TODO coalesce into the trailingspace of
1532 			 * the previous mbuf when possible.
1533 			 */
1534 
1535 			/*
1536 			 * allocate a new mbuf.  copy packet header if needed.
1537 			 */
1538 			n = m_get(how, m->m_type);
1539 			if (n == NULL)
1540 				goto enobufs;
1541 			MCLAIM(n, m->m_owner);
1542 			if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
1543 				M_MOVE_PKTHDR(n, m);
1544 				n->m_len = MHLEN;
1545 			} else {
1546 				if (len >= MINCLSIZE)
1547 					MCLGET(n, M_DONTWAIT);
1548 				n->m_len =
1549 				    (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
1550 			}
1551 			if (n->m_len > len)
1552 				n->m_len = len;
1553 
1554 			/*
1555 			 * free the region which has been overwritten.
1556 			 * copying data from old mbufs if requested.
1557 			 */
1558 			if (flags & M_COPYBACK0_PRESERVE)
1559 				datap = mtod(n, char *);
1560 			else
1561 				datap = NULL;
1562 			eatlen = n->m_len;
1563 			while (m != NULL && M_READONLY(m) &&
1564 			    n->m_type == m->m_type && eatlen > 0) {
1565 				mlen = min(eatlen, m->m_len);
1566 				if (datap) {
1567 					m_copydata(m, 0, mlen, datap);
1568 					datap += mlen;
1569 				}
1570 				m->m_data += mlen;
1571 				m->m_len -= mlen;
1572 				eatlen -= mlen;
1573 				if (m->m_len == 0)
1574 					*mp = m = m_free(m);
1575 			}
1576 			if (eatlen > 0)
1577 				n->m_len -= eatlen;
1578 			n->m_next = m;
1579 			*mp = m = n;
1580 			continue;
1581 		}
1582 		mlen = min(mlen, len);
1583 		if (flags & M_COPYBACK0_COPYBACK) {
1584 			memcpy(mtod(m, char *) + off, cp, (unsigned)mlen);
1585 			cp += mlen;
1586 		}
1587 		len -= mlen;
1588 		mlen += off;
1589 		off = 0;
1590 		totlen += mlen;
1591 		if (len == 0)
1592 			break;
1593 		if (m->m_next == NULL) {
1594 			goto extend;
1595 		}
1596 		mp = &m->m_next;
1597 		m = m->m_next;
1598 	}
1599 out:	if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
1600 		KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
1601 		m->m_pkthdr.len = totlen;
1602 	}
1603 
1604 	return 0;
1605 
1606 enobufs:
1607 	return ENOBUFS;
1608 }
1609 
1610 void
1611 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1612 {
1613 
1614 	KASSERT((to->m_flags & M_EXT) == 0);
1615 	KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
1616 	KASSERT((from->m_flags & M_PKTHDR) != 0);
1617 
1618 	to->m_pkthdr = from->m_pkthdr;
1619 	to->m_flags = from->m_flags & M_COPYFLAGS;
1620 	to->m_data = to->m_pktdat;
1621 
1622 	from->m_flags &= ~M_PKTHDR;
1623 }
1624 
1625 /*
1626  * Apply function f to the data in an mbuf chain starting "off" bytes from the
1627  * beginning, continuing for "len" bytes.
1628  */
1629 int
1630 m_apply(struct mbuf *m, int off, int len,
1631     int (*f)(void *, void *, unsigned int), void *arg)
1632 {
1633 	unsigned int count;
1634 	int rval;
1635 
1636 	KASSERT(len != M_COPYALL);
1637 	KASSERT(len >= 0);
1638 	KASSERT(off >= 0);
1639 
1640 	while (off > 0) {
1641 		KASSERT(m != NULL);
1642 		if (off < m->m_len)
1643 			break;
1644 		off -= m->m_len;
1645 		m = m->m_next;
1646 	}
1647 	while (len > 0) {
1648 		KASSERT(m != NULL);
1649 		count = min(m->m_len - off, len);
1650 
1651 		rval = (*f)(arg, mtod(m, char *) + off, count);
1652 		if (rval)
1653 			return (rval);
1654 
1655 		len -= count;
1656 		off = 0;
1657 		m = m->m_next;
1658 	}
1659 
1660 	return (0);
1661 }
1662 
1663 /*
1664  * Return a pointer to mbuf/offset of location in mbuf chain.
1665  */
1666 struct mbuf *
1667 m_getptr(struct mbuf *m, int loc, int *off)
1668 {
1669 
1670 	while (loc >= 0) {
1671 		/* Normal end of search */
1672 		if (m->m_len > loc) {
1673 	    		*off = loc;
1674 	    		return (m);
1675 		} else {
1676 	    		loc -= m->m_len;
1677 
1678 	    		if (m->m_next == NULL) {
1679 				if (loc == 0) {
1680  					/* Point at the end of valid data */
1681 		    			*off = m->m_len;
1682 		    			return (m);
1683 				} else
1684 		  			return (NULL);
1685 	    		} else
1686 	      			m = m->m_next;
1687 		}
1688     	}
1689 
1690 	return (NULL);
1691 }
1692 
1693 /*
1694  * m_ext_free: release a reference to the mbuf external storage.
1695  *
1696  * => free the mbuf m itself as well.
1697  */
1698 
1699 void
1700 m_ext_free(struct mbuf *m)
1701 {
1702 	bool embedded = MEXT_ISEMBEDDED(m);
1703 	bool dofree = true;
1704 	u_int refcnt;
1705 
1706 	KASSERT((m->m_flags & M_EXT) != 0);
1707 	KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
1708 	KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
1709 	KASSERT((m->m_flags & M_EXT_CLUSTER) ==
1710 	    (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
1711 
1712 	if (__predict_true(m->m_ext.ext_refcnt == 1)) {
1713 		refcnt = m->m_ext.ext_refcnt = 0;
1714 	} else {
1715 		refcnt = atomic_dec_uint_nv(&m->m_ext.ext_refcnt);
1716 	}
1717 	if (refcnt > 0) {
1718 		if (embedded) {
1719 			/*
1720 			 * other mbuf's m_ext_ref still points to us.
1721 			 */
1722 			dofree = false;
1723 		} else {
1724 			m->m_ext_ref = m;
1725 		}
1726 	} else {
1727 		/*
1728 		 * dropping the last reference
1729 		 */
1730 		if (!embedded) {
1731 			m->m_ext.ext_refcnt++; /* XXX */
1732 			m_ext_free(m->m_ext_ref);
1733 			m->m_ext_ref = m;
1734 		} else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
1735 			pool_cache_put_paddr((struct pool_cache *)
1736 			    m->m_ext.ext_arg,
1737 			    m->m_ext.ext_buf, m->m_ext.ext_paddr);
1738 		} else if (m->m_ext.ext_free) {
1739 			(*m->m_ext.ext_free)(m,
1740 			    m->m_ext.ext_buf, m->m_ext.ext_size,
1741 			    m->m_ext.ext_arg);
1742 			/*
1743 			 * 'm' is already freed by the ext_free callback.
1744 			 */
1745 			dofree = false;
1746 		} else {
1747 			free(m->m_ext.ext_buf, m->m_ext.ext_type);
1748 		}
1749 	}
1750 	if (dofree) {
1751 		m->m_type = MT_FREE;
1752 		pool_cache_put(mb_cache, m);
1753 	}
1754 }
1755 
1756 #if defined(DDB)
1757 void
1758 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
1759 {
1760 	char ch;
1761 	bool opt_c = false;
1762 	char buf[512];
1763 
1764 	while ((ch = *(modif++)) != '\0') {
1765 		switch (ch) {
1766 		case 'c':
1767 			opt_c = true;
1768 			break;
1769 		}
1770 	}
1771 
1772 nextchain:
1773 	(*pr)("MBUF %p\n", m);
1774 	snprintb(buf, sizeof(buf), M_FLAGS_BITS, (u_int)m->m_flags);
1775 	(*pr)("  data=%p, len=%d, type=%d, flags=%s\n",
1776 	    m->m_data, m->m_len, m->m_type, buf);
1777 	(*pr)("  owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
1778 	    m->m_nextpkt);
1779 	(*pr)("  leadingspace=%u, trailingspace=%u, readonly=%u\n",
1780 	    (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
1781 	    (int)M_READONLY(m));
1782 	if ((m->m_flags & M_PKTHDR) != 0) {
1783 		snprintb(buf, sizeof(buf), M_CSUM_BITS, m->m_pkthdr.csum_flags);
1784 		(*pr)("  pktlen=%d, rcvif=%p, csum_flags=0x%s, csum_data=0x%"
1785 		    PRIx32 ", segsz=%u\n",
1786 		    m->m_pkthdr.len, m->m_pkthdr.rcvif,
1787 		    buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
1788 	}
1789 	if ((m->m_flags & M_EXT)) {
1790 		(*pr)("  ext_refcnt=%u, ext_buf=%p, ext_size=%zd, "
1791 		    "ext_free=%p, ext_arg=%p\n",
1792 		    m->m_ext.ext_refcnt,
1793 		    m->m_ext.ext_buf, m->m_ext.ext_size,
1794 		    m->m_ext.ext_free, m->m_ext.ext_arg);
1795 	}
1796 	if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
1797 		vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
1798 		vaddr_t eva = sva + m->m_ext.ext_size;
1799 		int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
1800 		int i;
1801 
1802 		(*pr)("  pages:");
1803 		for (i = 0; i < n; i ++) {
1804 			(*pr)(" %p", m->m_ext.ext_pgs[i]);
1805 		}
1806 		(*pr)("\n");
1807 	}
1808 
1809 	if (opt_c) {
1810 		m = m->m_next;
1811 		if (m != NULL) {
1812 			goto nextchain;
1813 		}
1814 	}
1815 }
1816 #endif /* defined(DDB) */
1817 
1818 void
1819 mbstat_type_add(int type, int diff)
1820 {
1821 	struct mbstat_cpu *mb;
1822 	int s;
1823 
1824 	s = splvm();
1825 	mb = percpu_getref(mbstat_percpu);
1826 	mb->m_mtypes[type] += diff;
1827 	percpu_putref(mbstat_percpu);
1828 	splx(s);
1829 }
1830 
1831 #if defined(MBUFTRACE)
1832 void
1833 mowner_attach(struct mowner *mo)
1834 {
1835 
1836 	KASSERT(mo->mo_counters == NULL);
1837 	mo->mo_counters = percpu_alloc(sizeof(struct mowner_counter));
1838 
1839 	/* XXX lock */
1840 	LIST_INSERT_HEAD(&mowners, mo, mo_link);
1841 }
1842 
1843 void
1844 mowner_detach(struct mowner *mo)
1845 {
1846 
1847 	KASSERT(mo->mo_counters != NULL);
1848 
1849 	/* XXX lock */
1850 	LIST_REMOVE(mo, mo_link);
1851 
1852 	percpu_free(mo->mo_counters, sizeof(struct mowner_counter));
1853 	mo->mo_counters = NULL;
1854 }
1855 
1856 void
1857 mowner_init(struct mbuf *m, int type)
1858 {
1859 	struct mowner_counter *mc;
1860 	struct mowner *mo;
1861 	int s;
1862 
1863 	m->m_owner = mo = &unknown_mowners[type];
1864 	s = splvm();
1865 	mc = percpu_getref(mo->mo_counters);
1866 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1867 	percpu_putref(mo->mo_counters);
1868 	splx(s);
1869 }
1870 
1871 void
1872 mowner_ref(struct mbuf *m, int flags)
1873 {
1874 	struct mowner *mo = m->m_owner;
1875 	struct mowner_counter *mc;
1876 	int s;
1877 
1878 	s = splvm();
1879 	mc = percpu_getref(mo->mo_counters);
1880 	if ((flags & M_EXT) != 0)
1881 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1882 	if ((flags & M_CLUSTER) != 0)
1883 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1884 	percpu_putref(mo->mo_counters);
1885 	splx(s);
1886 }
1887 
1888 void
1889 mowner_revoke(struct mbuf *m, bool all, int flags)
1890 {
1891 	struct mowner *mo = m->m_owner;
1892 	struct mowner_counter *mc;
1893 	int s;
1894 
1895 	s = splvm();
1896 	mc = percpu_getref(mo->mo_counters);
1897 	if ((flags & M_EXT) != 0)
1898 		mc->mc_counter[MOWNER_COUNTER_EXT_RELEASES]++;
1899 	if ((flags & M_CLUSTER) != 0)
1900 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_RELEASES]++;
1901 	if (all)
1902 		mc->mc_counter[MOWNER_COUNTER_RELEASES]++;
1903 	percpu_putref(mo->mo_counters);
1904 	splx(s);
1905 	if (all)
1906 		m->m_owner = &revoked_mowner;
1907 }
1908 
1909 static void
1910 mowner_claim(struct mbuf *m, struct mowner *mo)
1911 {
1912 	struct mowner_counter *mc;
1913 	int flags = m->m_flags;
1914 	int s;
1915 
1916 	s = splvm();
1917 	mc = percpu_getref(mo->mo_counters);
1918 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1919 	if ((flags & M_EXT) != 0)
1920 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1921 	if ((flags & M_CLUSTER) != 0)
1922 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1923 	percpu_putref(mo->mo_counters);
1924 	splx(s);
1925 	m->m_owner = mo;
1926 }
1927 
1928 void
1929 m_claim(struct mbuf *m, struct mowner *mo)
1930 {
1931 
1932 	if (m->m_owner == mo || mo == NULL)
1933 		return;
1934 
1935 	mowner_revoke(m, true, m->m_flags);
1936 	mowner_claim(m, mo);
1937 }
1938 #endif /* defined(MBUFTRACE) */
1939