xref: /netbsd-src/sys/kern/uipc_mbuf.c (revision f21b7d7f2cbdd5c14b3882c4e8a3d43580d460a6)
1 /*	$NetBSD: uipc_mbuf.c,v 1.169 2016/10/04 14:13:21 christos 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.169 2016/10/04 14:13:21 christos 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_bind();
562 		IFNET_READER_FOREACH(ifp) {
563 			struct psref psref;
564 
565 			psref_acquire(&psref, &ifp->if_psref,
566 			    ifnet_psref_class);
567 
568 			if (ifp->if_drain)
569 				(*ifp->if_drain)(ifp);
570 
571 			psref_release(&psref, &ifp->if_psref,
572 			    ifnet_psref_class);
573 		}
574 		curlwp_bindx(bound);
575 	}
576 	splx(s);
577 	mbstat.m_drain++;
578 	KERNEL_UNLOCK_ONE(NULL);
579 }
580 
581 /*
582  * Space allocation routines.
583  * These are also available as macros
584  * for critical paths.
585  */
586 struct mbuf *
587 m_get(int nowait, int type)
588 {
589 	struct mbuf *m;
590 
591 	KASSERT(type != MT_FREE);
592 
593 	m = pool_cache_get(mb_cache,
594 	    nowait == M_WAIT ? PR_WAITOK|PR_LIMITFAIL : 0);
595 	if (m == NULL)
596 		return NULL;
597 
598 	mbstat_type_add(type, 1);
599 
600 	m_hdr_init(m, type, NULL, m->m_dat, 0);
601 
602 	return m;
603 }
604 
605 struct mbuf *
606 m_gethdr(int nowait, int type)
607 {
608 	struct mbuf *m;
609 
610 	m = m_get(nowait, type);
611 	if (m == NULL)
612 		return NULL;
613 
614 	m_pkthdr_init(m);
615 
616 	return m;
617 }
618 
619 struct mbuf *
620 m_getclr(int nowait, int type)
621 {
622 	struct mbuf *m;
623 
624 	m = m_get(nowait, type);
625 	if (m == 0)
626 		return (NULL);
627 	memset(mtod(m, void *), 0, MLEN);
628 	return (m);
629 }
630 
631 void
632 m_clget(struct mbuf *m, int nowait)
633 {
634 
635 	MCLGET(m, nowait);
636 }
637 
638 #ifdef MBUFTRACE
639 /*
640  * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
641  */
642 void
643 m_claimm(struct mbuf *m, struct mowner *mo)
644 {
645 
646 	for (; m != NULL; m = m->m_next)
647 		MCLAIM(m, mo);
648 }
649 #endif
650 
651 /*
652  * Mbuffer utility routines.
653  */
654 
655 /*
656  * Lesser-used path for M_PREPEND:
657  * allocate new mbuf to prepend to chain,
658  * copy junk along.
659  */
660 struct mbuf *
661 m_prepend(struct mbuf *m, int len, int how)
662 {
663 	struct mbuf *mn;
664 
665 	KASSERT(len != M_COPYALL);
666 	mn = m_get(how, m->m_type);
667 	if (mn == NULL) {
668 		m_freem(m);
669 		return (NULL);
670 	}
671 	if (m->m_flags & M_PKTHDR) {
672 		M_MOVE_PKTHDR(mn, m);
673 	} else {
674 		MCLAIM(mn, m->m_owner);
675 	}
676 	mn->m_next = m;
677 	m = mn;
678 	if (len < MHLEN)
679 		MH_ALIGN(m, len);
680 	m->m_len = len;
681 	return (m);
682 }
683 
684 /*
685  * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
686  * continuing for "len" bytes.  If len is M_COPYALL, copy to end of mbuf.
687  * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
688  */
689 int MCFail;
690 
691 struct mbuf *
692 m_copym(struct mbuf *m, int off0, int len, int wait)
693 {
694 
695 	return m_copym0(m, off0, len, wait, 0);	/* shallow copy on M_EXT */
696 }
697 
698 struct mbuf *
699 m_dup(struct mbuf *m, int off0, int len, int wait)
700 {
701 
702 	return m_copym0(m, off0, len, wait, 1);	/* deep copy */
703 }
704 
705 static inline int
706 m_copylen(int len, int copylen) {
707     return len == M_COPYALL ? copylen : min(len, copylen);
708 }
709 
710 static struct mbuf *
711 m_copym0(struct mbuf *m, int off0, int len, int wait, int deep)
712 {
713 	struct mbuf *n, **np;
714 	int off = off0;
715 	struct mbuf *top;
716 	int copyhdr = 0;
717 
718 	if (off < 0 || (len != M_COPYALL && len < 0))
719 		panic("m_copym: off %d, len %d", off, len);
720 	if (off == 0 && m->m_flags & M_PKTHDR)
721 		copyhdr = 1;
722 	while (off > 0) {
723 		if (m == 0)
724 			panic("m_copym: m == 0, off %d", off);
725 		if (off < m->m_len)
726 			break;
727 		off -= m->m_len;
728 		m = m->m_next;
729 	}
730 	np = &top;
731 	top = 0;
732 	while (len == M_COPYALL || len > 0) {
733 		if (m == 0) {
734 			if (len != M_COPYALL)
735 				panic("m_copym: m == 0, len %d [!COPYALL]",
736 				    len);
737 			break;
738 		}
739 		n = m_get(wait, m->m_type);
740 		*np = n;
741 		if (n == 0)
742 			goto nospace;
743 		MCLAIM(n, m->m_owner);
744 		if (copyhdr) {
745 			M_COPY_PKTHDR(n, m);
746 			if (len == M_COPYALL)
747 				n->m_pkthdr.len -= off0;
748 			else
749 				n->m_pkthdr.len = len;
750 			copyhdr = 0;
751 		}
752 		n->m_len = m_copylen(len, m->m_len - off);
753 		if (m->m_flags & M_EXT) {
754 			if (!deep) {
755 				n->m_data = m->m_data + off;
756 				MCLADDREFERENCE(m, n);
757 			} else {
758 				/*
759 				 * we are unsure about the way m was allocated.
760 				 * copy into multiple MCLBYTES cluster mbufs.
761 				 *
762 				 * recompute m_len, it is no longer valid if MCLGET()
763 				 * fails to allocate a cluster. Then we try to split
764 				 * the source into normal sized mbufs.
765 				 */
766 				MCLGET(n, wait);
767 				n->m_len = 0;
768 				n->m_len = M_TRAILINGSPACE(n);
769 				n->m_len = m_copylen(len, n->m_len);
770 				n->m_len = min(n->m_len, m->m_len - off);
771 				memcpy(mtod(n, void *), mtod(m, char *) + off,
772 				    (unsigned)n->m_len);
773 			}
774 		} else
775 			memcpy(mtod(n, void *), mtod(m, char *) + off,
776 			    (unsigned)n->m_len);
777 		if (len != M_COPYALL)
778 			len -= n->m_len;
779 		off += n->m_len;
780 #ifdef DIAGNOSTIC
781 		if (off > m->m_len)
782 			panic("m_copym0 overrun %d %d", off, m->m_len);
783 #endif
784 		if (off == m->m_len) {
785 			m = m->m_next;
786 			off = 0;
787 		}
788 		np = &n->m_next;
789 	}
790 	if (top == 0)
791 		MCFail++;
792 	return (top);
793 nospace:
794 	m_freem(top);
795 	MCFail++;
796 	return (NULL);
797 }
798 
799 /*
800  * Copy an entire packet, including header (which must be present).
801  * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
802  */
803 struct mbuf *
804 m_copypacket(struct mbuf *m, int how)
805 {
806 	struct mbuf *top, *n, *o;
807 
808 	n = m_get(how, m->m_type);
809 	top = n;
810 	if (!n)
811 		goto nospace;
812 
813 	MCLAIM(n, m->m_owner);
814 	M_COPY_PKTHDR(n, m);
815 	n->m_len = m->m_len;
816 	if (m->m_flags & M_EXT) {
817 		n->m_data = m->m_data;
818 		MCLADDREFERENCE(m, n);
819 	} else {
820 		memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
821 	}
822 
823 	m = m->m_next;
824 	while (m) {
825 		o = m_get(how, m->m_type);
826 		if (!o)
827 			goto nospace;
828 
829 		MCLAIM(o, m->m_owner);
830 		n->m_next = o;
831 		n = n->m_next;
832 
833 		n->m_len = m->m_len;
834 		if (m->m_flags & M_EXT) {
835 			n->m_data = m->m_data;
836 			MCLADDREFERENCE(m, n);
837 		} else {
838 			memcpy(mtod(n, char *), mtod(m, char *), n->m_len);
839 		}
840 
841 		m = m->m_next;
842 	}
843 	return top;
844 nospace:
845 	m_freem(top);
846 	MCFail++;
847 	return NULL;
848 }
849 
850 /*
851  * Copy data from an mbuf chain starting "off" bytes from the beginning,
852  * continuing for "len" bytes, into the indicated buffer.
853  */
854 void
855 m_copydata(struct mbuf *m, int off, int len, void *vp)
856 {
857 	unsigned	count;
858 	void *		cp = vp;
859 	struct mbuf	*m0 = m;
860 	int		len0 = len;
861 	int		off0 = off;
862 	void		*vp0 = vp;
863 
864 	KASSERT(len != M_COPYALL);
865 	if (off < 0 || len < 0)
866 		panic("m_copydata: off %d, len %d", off, len);
867 	while (off > 0) {
868 		if (m == NULL)
869 			panic("m_copydata(%p,%d,%d,%p): m=NULL, off=%d (%d)",
870 			    m0, len0, off0, vp0, off, off0 - off);
871 		if (off < m->m_len)
872 			break;
873 		off -= m->m_len;
874 		m = m->m_next;
875 	}
876 	while (len > 0) {
877 		if (m == NULL)
878 			panic("m_copydata(%p,%d,%d,%p): "
879 			    "m=NULL, off=%d (%d), len=%d (%d)",
880 			    m0, len0, off0, vp0,
881 			    off, off0 - off, len, len0 - len);
882 		count = min(m->m_len - off, len);
883 		memcpy(cp, mtod(m, char *) + off, count);
884 		len -= count;
885 		cp = (char *)cp + count;
886 		off = 0;
887 		m = m->m_next;
888 	}
889 }
890 
891 /*
892  * Concatenate mbuf chain n to m.
893  * n might be copied into m (when n->m_len is small), therefore data portion of
894  * n could be copied into an mbuf of different mbuf type.
895  * Any m_pkthdr is not updated.
896  */
897 void
898 m_cat(struct mbuf *m, struct mbuf *n)
899 {
900 
901 	while (m->m_next)
902 		m = m->m_next;
903 	while (n) {
904 		if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
905 			/* just join the two chains */
906 			m->m_next = n;
907 			return;
908 		}
909 		/* splat the data from one into the other */
910 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
911 		    (u_int)n->m_len);
912 		m->m_len += n->m_len;
913 		n = m_free(n);
914 	}
915 }
916 
917 void
918 m_adj(struct mbuf *mp, int req_len)
919 {
920 	int len = req_len;
921 	struct mbuf *m;
922 	int count;
923 
924 	if ((m = mp) == NULL)
925 		return;
926 	if (len >= 0) {
927 		/*
928 		 * Trim from head.
929 		 */
930 		while (m != NULL && len > 0) {
931 			if (m->m_len <= len) {
932 				len -= m->m_len;
933 				m->m_len = 0;
934 				m = m->m_next;
935 			} else {
936 				m->m_len -= len;
937 				m->m_data += len;
938 				len = 0;
939 			}
940 		}
941 		m = mp;
942 		if (mp->m_flags & M_PKTHDR)
943 			m->m_pkthdr.len -= (req_len - len);
944 	} else {
945 		/*
946 		 * Trim from tail.  Scan the mbuf chain,
947 		 * calculating its length and finding the last mbuf.
948 		 * If the adjustment only affects this mbuf, then just
949 		 * adjust and return.  Otherwise, rescan and truncate
950 		 * after the remaining size.
951 		 */
952 		len = -len;
953 		count = 0;
954 		for (;;) {
955 			count += m->m_len;
956 			if (m->m_next == (struct mbuf *)0)
957 				break;
958 			m = m->m_next;
959 		}
960 		if (m->m_len >= len) {
961 			m->m_len -= len;
962 			if (mp->m_flags & M_PKTHDR)
963 				mp->m_pkthdr.len -= len;
964 			return;
965 		}
966 		count -= len;
967 		if (count < 0)
968 			count = 0;
969 		/*
970 		 * Correct length for chain is "count".
971 		 * Find the mbuf with last data, adjust its length,
972 		 * and toss data from remaining mbufs on chain.
973 		 */
974 		m = mp;
975 		if (m->m_flags & M_PKTHDR)
976 			m->m_pkthdr.len = count;
977 		for (; m; m = m->m_next) {
978 			if (m->m_len >= count) {
979 				m->m_len = count;
980 				break;
981 			}
982 			count -= m->m_len;
983 		}
984 		if (m)
985 			while (m->m_next)
986 				(m = m->m_next)->m_len = 0;
987 	}
988 }
989 
990 /*
991  * m_ensure_contig: rearrange an mbuf chain that given length of bytes
992  * would be contiguous and in the data area of an mbuf (therefore, mtod()
993  * would work for a structure of given length).
994  *
995  * => On success, returns true and the resulting mbuf chain; false otherwise.
996  * => The mbuf chain may change, but is always preserved valid.
997  */
998 bool
999 m_ensure_contig(struct mbuf **m0, int len)
1000 {
1001 	struct mbuf *n = *m0, *m;
1002 	size_t count, space;
1003 
1004 	KASSERT(len != M_COPYALL);
1005 	/*
1006 	 * If first mbuf has no cluster, and has room for len bytes
1007 	 * without shifting current data, pullup into it,
1008 	 * otherwise allocate a new mbuf to prepend to the chain.
1009 	 */
1010 	if ((n->m_flags & M_EXT) == 0 &&
1011 	    n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1012 		if (n->m_len >= len) {
1013 			return true;
1014 		}
1015 		m = n;
1016 		n = n->m_next;
1017 		len -= m->m_len;
1018 	} else {
1019 		if (len > MHLEN) {
1020 			return false;
1021 		}
1022 		m = m_get(M_DONTWAIT, n->m_type);
1023 		if (m == NULL) {
1024 			return false;
1025 		}
1026 		MCLAIM(m, n->m_owner);
1027 		if (n->m_flags & M_PKTHDR) {
1028 			M_MOVE_PKTHDR(m, n);
1029 		}
1030 	}
1031 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1032 	do {
1033 		count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
1034 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1035 		  (unsigned)count);
1036 		len -= count;
1037 		m->m_len += count;
1038 		n->m_len -= count;
1039 		space -= count;
1040 		if (n->m_len)
1041 			n->m_data += count;
1042 		else
1043 			n = m_free(n);
1044 	} while (len > 0 && n);
1045 
1046 	m->m_next = n;
1047 	*m0 = m;
1048 
1049 	return len <= 0;
1050 }
1051 
1052 /*
1053  * m_pullup: same as m_ensure_contig(), but destroys mbuf chain on error.
1054  */
1055 int MPFail;
1056 
1057 struct mbuf *
1058 m_pullup(struct mbuf *n, int len)
1059 {
1060 	struct mbuf *m = n;
1061 
1062 	KASSERT(len != M_COPYALL);
1063 	if (!m_ensure_contig(&m, len)) {
1064 		KASSERT(m != NULL);
1065 		m_freem(m);
1066 		MPFail++;
1067 		m = NULL;
1068 	}
1069 	return m;
1070 }
1071 
1072 /*
1073  * Like m_pullup(), except a new mbuf is always allocated, and we allow
1074  * the amount of empty space before the data in the new mbuf to be specified
1075  * (in the event that the caller expects to prepend later).
1076  */
1077 int MSFail;
1078 
1079 struct mbuf *
1080 m_copyup(struct mbuf *n, int len, int dstoff)
1081 {
1082 	struct mbuf *m;
1083 	int count, space;
1084 
1085 	KASSERT(len != M_COPYALL);
1086 	if (len > (MHLEN - dstoff))
1087 		goto bad;
1088 	m = m_get(M_DONTWAIT, n->m_type);
1089 	if (m == NULL)
1090 		goto bad;
1091 	MCLAIM(m, n->m_owner);
1092 	if (n->m_flags & M_PKTHDR) {
1093 		M_MOVE_PKTHDR(m, n);
1094 	}
1095 	m->m_data += dstoff;
1096 	space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1097 	do {
1098 		count = min(min(max(len, max_protohdr), space), n->m_len);
1099 		memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1100 		    (unsigned)count);
1101 		len -= count;
1102 		m->m_len += count;
1103 		n->m_len -= count;
1104 		space -= count;
1105 		if (n->m_len)
1106 			n->m_data += count;
1107 		else
1108 			n = m_free(n);
1109 	} while (len > 0 && n);
1110 	if (len > 0) {
1111 		(void) m_free(m);
1112 		goto bad;
1113 	}
1114 	m->m_next = n;
1115 	return (m);
1116  bad:
1117 	m_freem(n);
1118 	MSFail++;
1119 	return (NULL);
1120 }
1121 
1122 /*
1123  * Partition an mbuf chain in two pieces, returning the tail --
1124  * all but the first len0 bytes.  In case of failure, it returns NULL and
1125  * attempts to restore the chain to its original state.
1126  */
1127 struct mbuf *
1128 m_split(struct mbuf *m0, int len0, int wait)
1129 {
1130 
1131 	return m_split0(m0, len0, wait, 1);
1132 }
1133 
1134 static struct mbuf *
1135 m_split0(struct mbuf *m0, int len0, int wait, int copyhdr)
1136 {
1137 	struct mbuf *m, *n;
1138 	unsigned len = len0, remain, len_save;
1139 
1140 	KASSERT(len0 != M_COPYALL);
1141 	for (m = m0; m && len > m->m_len; m = m->m_next)
1142 		len -= m->m_len;
1143 	if (m == 0)
1144 		return (NULL);
1145 	remain = m->m_len - len;
1146 	if (copyhdr && (m0->m_flags & M_PKTHDR)) {
1147 		n = m_gethdr(wait, m0->m_type);
1148 		if (n == NULL)
1149 			return NULL;
1150 		MCLAIM(n, m0->m_owner);
1151 		m_copy_rcvif(n, m0);
1152 		n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1153 		len_save = m0->m_pkthdr.len;
1154 		m0->m_pkthdr.len = len0;
1155 		if (m->m_flags & M_EXT)
1156 			goto extpacket;
1157 		if (remain > MHLEN) {
1158 			/* m can't be the lead packet */
1159 			MH_ALIGN(n, 0);
1160 			n->m_len = 0;
1161 			n->m_next = m_split(m, len, wait);
1162 			if (n->m_next == 0) {
1163 				(void) m_free(n);
1164 				m0->m_pkthdr.len = len_save;
1165 				return (NULL);
1166 			} else
1167 				return (n);
1168 		} else
1169 			MH_ALIGN(n, remain);
1170 	} else if (remain == 0) {
1171 		n = m->m_next;
1172 		m->m_next = 0;
1173 		return (n);
1174 	} else {
1175 		n = m_get(wait, m->m_type);
1176 		if (n == 0)
1177 			return (NULL);
1178 		MCLAIM(n, m->m_owner);
1179 		M_ALIGN(n, remain);
1180 	}
1181 extpacket:
1182 	if (m->m_flags & M_EXT) {
1183 		n->m_data = m->m_data + len;
1184 		MCLADDREFERENCE(m, n);
1185 	} else {
1186 		memcpy(mtod(n, void *), mtod(m, char *) + len, remain);
1187 	}
1188 	n->m_len = remain;
1189 	m->m_len = len;
1190 	n->m_next = m->m_next;
1191 	m->m_next = 0;
1192 	return (n);
1193 }
1194 /*
1195  * Routine to copy from device local memory into mbufs.
1196  */
1197 struct mbuf *
1198 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
1199     void (*copy)(const void *from, void *to, size_t len))
1200 {
1201 	struct mbuf *m;
1202 	struct mbuf *top = 0, **mp = &top;
1203 	int off = off0, len;
1204 	char *cp;
1205 	char *epkt;
1206 
1207 	cp = buf;
1208 	epkt = cp + totlen;
1209 	if (off) {
1210 		/*
1211 		 * If 'off' is non-zero, packet is trailer-encapsulated,
1212 		 * so we have to skip the type and length fields.
1213 		 */
1214 		cp += off + 2 * sizeof(uint16_t);
1215 		totlen -= 2 * sizeof(uint16_t);
1216 	}
1217 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1218 	if (m == NULL)
1219 		return NULL;
1220 	m_set_rcvif(m, ifp);
1221 	m->m_pkthdr.len = totlen;
1222 	m->m_len = MHLEN;
1223 
1224 	while (totlen > 0) {
1225 		if (top) {
1226 			m = m_get(M_DONTWAIT, MT_DATA);
1227 			if (m == 0) {
1228 				m_freem(top);
1229 				return (NULL);
1230 			}
1231 			m->m_len = MLEN;
1232 		}
1233 		len = min(totlen, epkt - cp);
1234 		if (len >= MINCLSIZE) {
1235 			MCLGET(m, M_DONTWAIT);
1236 			if ((m->m_flags & M_EXT) == 0) {
1237 				m_free(m);
1238 				m_freem(top);
1239 				return (NULL);
1240 			}
1241 			m->m_len = len = min(len, MCLBYTES);
1242 		} else {
1243 			/*
1244 			 * Place initial small packet/header at end of mbuf.
1245 			 */
1246 			if (len < m->m_len) {
1247 				if (top == 0 && len + max_linkhdr <= m->m_len)
1248 					m->m_data += max_linkhdr;
1249 				m->m_len = len;
1250 			} else
1251 				len = m->m_len;
1252 		}
1253 		if (copy)
1254 			copy(cp, mtod(m, void *), (size_t)len);
1255 		else
1256 			memcpy(mtod(m, void *), cp, (size_t)len);
1257 		cp += len;
1258 		*mp = m;
1259 		mp = &m->m_next;
1260 		totlen -= len;
1261 		if (cp == epkt)
1262 			cp = buf;
1263 	}
1264 	return (top);
1265 }
1266 
1267 /*
1268  * Copy data from a buffer back into the indicated mbuf chain,
1269  * starting "off" bytes from the beginning, extending the mbuf
1270  * chain if necessary.
1271  */
1272 void
1273 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
1274 {
1275 #if defined(DEBUG)
1276 	struct mbuf *origm = m0;
1277 	int error;
1278 #endif /* defined(DEBUG) */
1279 
1280 	if (m0 == NULL)
1281 		return;
1282 
1283 #if defined(DEBUG)
1284 	error =
1285 #endif /* defined(DEBUG) */
1286 	m_copyback0(&m0, off, len, cp,
1287 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
1288 
1289 #if defined(DEBUG)
1290 	if (error != 0 || (m0 != NULL && origm != m0))
1291 		panic("m_copyback");
1292 #endif /* defined(DEBUG) */
1293 }
1294 
1295 struct mbuf *
1296 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
1297 {
1298 	int error;
1299 
1300 	/* don't support chain expansion */
1301 	KASSERT(len != M_COPYALL);
1302 	KDASSERT(off + len <= m_length(m0));
1303 
1304 	error = m_copyback0(&m0, off, len, cp,
1305 	    M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
1306 	if (error) {
1307 		/*
1308 		 * no way to recover from partial success.
1309 		 * just free the chain.
1310 		 */
1311 		m_freem(m0);
1312 		return NULL;
1313 	}
1314 	return m0;
1315 }
1316 
1317 /*
1318  * m_makewritable: ensure the specified range writable.
1319  */
1320 int
1321 m_makewritable(struct mbuf **mp, int off, int len, int how)
1322 {
1323 	int error;
1324 #if defined(DEBUG)
1325 	int origlen = m_length(*mp);
1326 #endif /* defined(DEBUG) */
1327 
1328 	error = m_copyback0(mp, off, len, NULL,
1329 	    M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
1330 
1331 #if defined(DEBUG)
1332 	int reslen = 0;
1333 	for (struct mbuf *n = *mp; n; n = n->m_next)
1334 		reslen += n->m_len;
1335 	if (origlen != reslen)
1336 		panic("m_makewritable: length changed");
1337 	if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
1338 		panic("m_makewritable: inconsist");
1339 #endif /* defined(DEBUG) */
1340 
1341 	return error;
1342 }
1343 
1344 /*
1345  * Copy the mbuf chain to a new mbuf chain that is as short as possible.
1346  * Return the new mbuf chain on success, NULL on failure.  On success,
1347  * free the old mbuf chain.
1348  */
1349 struct mbuf *
1350 m_defrag(struct mbuf *mold, int flags)
1351 {
1352 	struct mbuf *m0, *mn, *n;
1353 	size_t sz = mold->m_pkthdr.len;
1354 
1355 #ifdef DIAGNOSTIC
1356 	if ((mold->m_flags & M_PKTHDR) == 0)
1357 		panic("m_defrag: not a mbuf chain header");
1358 #endif
1359 
1360 	m0 = m_gethdr(flags, MT_DATA);
1361 	if (m0 == NULL)
1362 		return NULL;
1363 	M_COPY_PKTHDR(m0, mold);
1364 	mn = m0;
1365 
1366 	do {
1367 		if (sz > MHLEN) {
1368 			MCLGET(mn, M_DONTWAIT);
1369 			if ((mn->m_flags & M_EXT) == 0) {
1370 				m_freem(m0);
1371 				return NULL;
1372 			}
1373 		}
1374 
1375 		mn->m_len = MIN(sz, MCLBYTES);
1376 
1377 		m_copydata(mold, mold->m_pkthdr.len - sz, mn->m_len,
1378 		     mtod(mn, void *));
1379 
1380 		sz -= mn->m_len;
1381 
1382 		if (sz > 0) {
1383 			/* need more mbufs */
1384 			n = m_get(M_NOWAIT, MT_DATA);
1385 			if (n == NULL) {
1386 				m_freem(m0);
1387 				return NULL;
1388 			}
1389 
1390 			mn->m_next = n;
1391 			mn = n;
1392 		}
1393 	} while (sz > 0);
1394 
1395 	m_freem(mold);
1396 
1397 	return m0;
1398 }
1399 
1400 int
1401 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
1402     int how)
1403 {
1404 	int mlen;
1405 	struct mbuf *m, *n;
1406 	struct mbuf **mp;
1407 	int totlen = 0;
1408 	const char *cp = vp;
1409 
1410 	KASSERT(mp0 != NULL);
1411 	KASSERT(*mp0 != NULL);
1412 	KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
1413 	KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
1414 
1415 	if (len == M_COPYALL)
1416 		len = m_length(*mp0) - off;
1417 
1418 	/*
1419 	 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
1420 	 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
1421 	 */
1422 
1423 	KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
1424 
1425 	mp = mp0;
1426 	m = *mp;
1427 	while (off > (mlen = m->m_len)) {
1428 		off -= mlen;
1429 		totlen += mlen;
1430 		if (m->m_next == NULL) {
1431 			int tspace;
1432 extend:
1433 			if ((flags & M_COPYBACK0_EXTEND) == 0)
1434 				goto out;
1435 
1436 			/*
1437 			 * try to make some space at the end of "m".
1438 			 */
1439 
1440 			mlen = m->m_len;
1441 			if (off + len >= MINCLSIZE &&
1442 			    (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
1443 				MCLGET(m, how);
1444 			}
1445 			tspace = M_TRAILINGSPACE(m);
1446 			if (tspace > 0) {
1447 				tspace = min(tspace, off + len);
1448 				KASSERT(tspace > 0);
1449 				memset(mtod(m, char *) + m->m_len, 0,
1450 				    min(off, tspace));
1451 				m->m_len += tspace;
1452 				off += mlen;
1453 				totlen -= mlen;
1454 				continue;
1455 			}
1456 
1457 			/*
1458 			 * need to allocate an mbuf.
1459 			 */
1460 
1461 			if (off + len >= MINCLSIZE) {
1462 				n = m_getcl(how, m->m_type, 0);
1463 			} else {
1464 				n = m_get(how, m->m_type);
1465 			}
1466 			if (n == NULL) {
1467 				goto out;
1468 			}
1469 			n->m_len = min(M_TRAILINGSPACE(n), off + len);
1470 			memset(mtod(n, char *), 0, min(n->m_len, off));
1471 			m->m_next = n;
1472 		}
1473 		mp = &m->m_next;
1474 		m = m->m_next;
1475 	}
1476 	while (len > 0) {
1477 		mlen = m->m_len - off;
1478 		if (mlen != 0 && M_READONLY(m)) {
1479 			char *datap;
1480 			int eatlen;
1481 
1482 			/*
1483 			 * this mbuf is read-only.
1484 			 * allocate a new writable mbuf and try again.
1485 			 */
1486 
1487 #if defined(DIAGNOSTIC)
1488 			if ((flags & M_COPYBACK0_COW) == 0)
1489 				panic("m_copyback0: read-only");
1490 #endif /* defined(DIAGNOSTIC) */
1491 
1492 			/*
1493 			 * if we're going to write into the middle of
1494 			 * a mbuf, split it first.
1495 			 */
1496 			if (off > 0) {
1497 				n = m_split0(m, off, how, 0);
1498 				if (n == NULL)
1499 					goto enobufs;
1500 				m->m_next = n;
1501 				mp = &m->m_next;
1502 				m = n;
1503 				off = 0;
1504 				continue;
1505 			}
1506 
1507 			/*
1508 			 * XXX TODO coalesce into the trailingspace of
1509 			 * the previous mbuf when possible.
1510 			 */
1511 
1512 			/*
1513 			 * allocate a new mbuf.  copy packet header if needed.
1514 			 */
1515 			n = m_get(how, m->m_type);
1516 			if (n == NULL)
1517 				goto enobufs;
1518 			MCLAIM(n, m->m_owner);
1519 			if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
1520 				M_MOVE_PKTHDR(n, m);
1521 				n->m_len = MHLEN;
1522 			} else {
1523 				if (len >= MINCLSIZE)
1524 					MCLGET(n, M_DONTWAIT);
1525 				n->m_len =
1526 				    (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
1527 			}
1528 			if (n->m_len > len)
1529 				n->m_len = len;
1530 
1531 			/*
1532 			 * free the region which has been overwritten.
1533 			 * copying data from old mbufs if requested.
1534 			 */
1535 			if (flags & M_COPYBACK0_PRESERVE)
1536 				datap = mtod(n, char *);
1537 			else
1538 				datap = NULL;
1539 			eatlen = n->m_len;
1540 			while (m != NULL && M_READONLY(m) &&
1541 			    n->m_type == m->m_type && eatlen > 0) {
1542 				mlen = min(eatlen, m->m_len);
1543 				if (datap) {
1544 					m_copydata(m, 0, mlen, datap);
1545 					datap += mlen;
1546 				}
1547 				m->m_data += mlen;
1548 				m->m_len -= mlen;
1549 				eatlen -= mlen;
1550 				if (m->m_len == 0)
1551 					*mp = m = m_free(m);
1552 			}
1553 			if (eatlen > 0)
1554 				n->m_len -= eatlen;
1555 			n->m_next = m;
1556 			*mp = m = n;
1557 			continue;
1558 		}
1559 		mlen = min(mlen, len);
1560 		if (flags & M_COPYBACK0_COPYBACK) {
1561 			memcpy(mtod(m, char *) + off, cp, (unsigned)mlen);
1562 			cp += mlen;
1563 		}
1564 		len -= mlen;
1565 		mlen += off;
1566 		off = 0;
1567 		totlen += mlen;
1568 		if (len == 0)
1569 			break;
1570 		if (m->m_next == NULL) {
1571 			goto extend;
1572 		}
1573 		mp = &m->m_next;
1574 		m = m->m_next;
1575 	}
1576 out:	if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
1577 		KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
1578 		m->m_pkthdr.len = totlen;
1579 	}
1580 
1581 	return 0;
1582 
1583 enobufs:
1584 	return ENOBUFS;
1585 }
1586 
1587 void
1588 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1589 {
1590 
1591 	KASSERT((to->m_flags & M_EXT) == 0);
1592 	KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
1593 	KASSERT((from->m_flags & M_PKTHDR) != 0);
1594 
1595 	to->m_pkthdr = from->m_pkthdr;
1596 	to->m_flags = from->m_flags & M_COPYFLAGS;
1597 	to->m_data = to->m_pktdat;
1598 
1599 	from->m_flags &= ~M_PKTHDR;
1600 }
1601 
1602 /*
1603  * Apply function f to the data in an mbuf chain starting "off" bytes from the
1604  * beginning, continuing for "len" bytes.
1605  */
1606 int
1607 m_apply(struct mbuf *m, int off, int len,
1608     int (*f)(void *, void *, unsigned int), void *arg)
1609 {
1610 	unsigned int count;
1611 	int rval;
1612 
1613 	KASSERT(len != M_COPYALL);
1614 	KASSERT(len >= 0);
1615 	KASSERT(off >= 0);
1616 
1617 	while (off > 0) {
1618 		KASSERT(m != NULL);
1619 		if (off < m->m_len)
1620 			break;
1621 		off -= m->m_len;
1622 		m = m->m_next;
1623 	}
1624 	while (len > 0) {
1625 		KASSERT(m != NULL);
1626 		count = min(m->m_len - off, len);
1627 
1628 		rval = (*f)(arg, mtod(m, char *) + off, count);
1629 		if (rval)
1630 			return (rval);
1631 
1632 		len -= count;
1633 		off = 0;
1634 		m = m->m_next;
1635 	}
1636 
1637 	return (0);
1638 }
1639 
1640 /*
1641  * Return a pointer to mbuf/offset of location in mbuf chain.
1642  */
1643 struct mbuf *
1644 m_getptr(struct mbuf *m, int loc, int *off)
1645 {
1646 
1647 	while (loc >= 0) {
1648 		/* Normal end of search */
1649 		if (m->m_len > loc) {
1650 	    		*off = loc;
1651 	    		return (m);
1652 		} else {
1653 	    		loc -= m->m_len;
1654 
1655 	    		if (m->m_next == NULL) {
1656 				if (loc == 0) {
1657  					/* Point at the end of valid data */
1658 		    			*off = m->m_len;
1659 		    			return (m);
1660 				} else
1661 		  			return (NULL);
1662 	    		} else
1663 	      			m = m->m_next;
1664 		}
1665     	}
1666 
1667 	return (NULL);
1668 }
1669 
1670 /*
1671  * m_ext_free: release a reference to the mbuf external storage.
1672  *
1673  * => free the mbuf m itself as well.
1674  */
1675 
1676 void
1677 m_ext_free(struct mbuf *m)
1678 {
1679 	bool embedded = MEXT_ISEMBEDDED(m);
1680 	bool dofree = true;
1681 	u_int refcnt;
1682 
1683 	KASSERT((m->m_flags & M_EXT) != 0);
1684 	KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
1685 	KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
1686 	KASSERT((m->m_flags & M_EXT_CLUSTER) ==
1687 	    (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
1688 
1689 	if (__predict_true(m->m_ext.ext_refcnt == 1)) {
1690 		refcnt = m->m_ext.ext_refcnt = 0;
1691 	} else {
1692 		refcnt = atomic_dec_uint_nv(&m->m_ext.ext_refcnt);
1693 	}
1694 	if (refcnt > 0) {
1695 		if (embedded) {
1696 			/*
1697 			 * other mbuf's m_ext_ref still points to us.
1698 			 */
1699 			dofree = false;
1700 		} else {
1701 			m->m_ext_ref = m;
1702 		}
1703 	} else {
1704 		/*
1705 		 * dropping the last reference
1706 		 */
1707 		if (!embedded) {
1708 			m->m_ext.ext_refcnt++; /* XXX */
1709 			m_ext_free(m->m_ext_ref);
1710 			m->m_ext_ref = m;
1711 		} else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
1712 			pool_cache_put_paddr((struct pool_cache *)
1713 			    m->m_ext.ext_arg,
1714 			    m->m_ext.ext_buf, m->m_ext.ext_paddr);
1715 		} else if (m->m_ext.ext_free) {
1716 			(*m->m_ext.ext_free)(m,
1717 			    m->m_ext.ext_buf, m->m_ext.ext_size,
1718 			    m->m_ext.ext_arg);
1719 			/*
1720 			 * 'm' is already freed by the ext_free callback.
1721 			 */
1722 			dofree = false;
1723 		} else {
1724 			free(m->m_ext.ext_buf, m->m_ext.ext_type);
1725 		}
1726 	}
1727 	if (dofree) {
1728 		m->m_type = MT_FREE;
1729 		pool_cache_put(mb_cache, m);
1730 	}
1731 }
1732 
1733 #if defined(DDB)
1734 void
1735 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
1736 {
1737 	char ch;
1738 	bool opt_c = false;
1739 	char buf[512];
1740 
1741 	while ((ch = *(modif++)) != '\0') {
1742 		switch (ch) {
1743 		case 'c':
1744 			opt_c = true;
1745 			break;
1746 		}
1747 	}
1748 
1749 nextchain:
1750 	(*pr)("MBUF %p\n", m);
1751 	snprintb(buf, sizeof(buf), M_FLAGS_BITS, (u_int)m->m_flags);
1752 	(*pr)("  data=%p, len=%d, type=%d, flags=%s\n",
1753 	    m->m_data, m->m_len, m->m_type, buf);
1754 	(*pr)("  owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
1755 	    m->m_nextpkt);
1756 	(*pr)("  leadingspace=%u, trailingspace=%u, readonly=%u\n",
1757 	    (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
1758 	    (int)M_READONLY(m));
1759 	if ((m->m_flags & M_PKTHDR) != 0) {
1760 		snprintb(buf, sizeof(buf), M_CSUM_BITS, m->m_pkthdr.csum_flags);
1761 		(*pr)("  pktlen=%d, rcvif=%p, csum_flags=0x%s, csum_data=0x%"
1762 		    PRIx32 ", segsz=%u\n",
1763 		    m->m_pkthdr.len, m_get_rcvif_NOMPSAFE(m),
1764 		    buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
1765 	}
1766 	if ((m->m_flags & M_EXT)) {
1767 		(*pr)("  ext_refcnt=%u, ext_buf=%p, ext_size=%zd, "
1768 		    "ext_free=%p, ext_arg=%p\n",
1769 		    m->m_ext.ext_refcnt,
1770 		    m->m_ext.ext_buf, m->m_ext.ext_size,
1771 		    m->m_ext.ext_free, m->m_ext.ext_arg);
1772 	}
1773 	if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
1774 		vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
1775 		vaddr_t eva = sva + m->m_ext.ext_size;
1776 		int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
1777 		int i;
1778 
1779 		(*pr)("  pages:");
1780 		for (i = 0; i < n; i ++) {
1781 			(*pr)(" %p", m->m_ext.ext_pgs[i]);
1782 		}
1783 		(*pr)("\n");
1784 	}
1785 
1786 	if (opt_c) {
1787 		m = m->m_next;
1788 		if (m != NULL) {
1789 			goto nextchain;
1790 		}
1791 	}
1792 }
1793 #endif /* defined(DDB) */
1794 
1795 void
1796 mbstat_type_add(int type, int diff)
1797 {
1798 	struct mbstat_cpu *mb;
1799 	int s;
1800 
1801 	s = splvm();
1802 	mb = percpu_getref(mbstat_percpu);
1803 	mb->m_mtypes[type] += diff;
1804 	percpu_putref(mbstat_percpu);
1805 	splx(s);
1806 }
1807 
1808 #if defined(MBUFTRACE)
1809 void
1810 mowner_attach(struct mowner *mo)
1811 {
1812 
1813 	KASSERT(mo->mo_counters == NULL);
1814 	mo->mo_counters = percpu_alloc(sizeof(struct mowner_counter));
1815 
1816 	/* XXX lock */
1817 	LIST_INSERT_HEAD(&mowners, mo, mo_link);
1818 }
1819 
1820 void
1821 mowner_detach(struct mowner *mo)
1822 {
1823 
1824 	KASSERT(mo->mo_counters != NULL);
1825 
1826 	/* XXX lock */
1827 	LIST_REMOVE(mo, mo_link);
1828 
1829 	percpu_free(mo->mo_counters, sizeof(struct mowner_counter));
1830 	mo->mo_counters = NULL;
1831 }
1832 
1833 void
1834 mowner_init(struct mbuf *m, int type)
1835 {
1836 	struct mowner_counter *mc;
1837 	struct mowner *mo;
1838 	int s;
1839 
1840 	m->m_owner = mo = &unknown_mowners[type];
1841 	s = splvm();
1842 	mc = percpu_getref(mo->mo_counters);
1843 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1844 	percpu_putref(mo->mo_counters);
1845 	splx(s);
1846 }
1847 
1848 void
1849 mowner_ref(struct mbuf *m, int flags)
1850 {
1851 	struct mowner *mo = m->m_owner;
1852 	struct mowner_counter *mc;
1853 	int s;
1854 
1855 	s = splvm();
1856 	mc = percpu_getref(mo->mo_counters);
1857 	if ((flags & M_EXT) != 0)
1858 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1859 	if ((flags & M_CLUSTER) != 0)
1860 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1861 	percpu_putref(mo->mo_counters);
1862 	splx(s);
1863 }
1864 
1865 void
1866 mowner_revoke(struct mbuf *m, bool all, int flags)
1867 {
1868 	struct mowner *mo = m->m_owner;
1869 	struct mowner_counter *mc;
1870 	int s;
1871 
1872 	s = splvm();
1873 	mc = percpu_getref(mo->mo_counters);
1874 	if ((flags & M_EXT) != 0)
1875 		mc->mc_counter[MOWNER_COUNTER_EXT_RELEASES]++;
1876 	if ((flags & M_CLUSTER) != 0)
1877 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_RELEASES]++;
1878 	if (all)
1879 		mc->mc_counter[MOWNER_COUNTER_RELEASES]++;
1880 	percpu_putref(mo->mo_counters);
1881 	splx(s);
1882 	if (all)
1883 		m->m_owner = &revoked_mowner;
1884 }
1885 
1886 static void
1887 mowner_claim(struct mbuf *m, struct mowner *mo)
1888 {
1889 	struct mowner_counter *mc;
1890 	int flags = m->m_flags;
1891 	int s;
1892 
1893 	s = splvm();
1894 	mc = percpu_getref(mo->mo_counters);
1895 	mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1896 	if ((flags & M_EXT) != 0)
1897 		mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1898 	if ((flags & M_CLUSTER) != 0)
1899 		mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1900 	percpu_putref(mo->mo_counters);
1901 	splx(s);
1902 	m->m_owner = mo;
1903 }
1904 
1905 void
1906 m_claim(struct mbuf *m, struct mowner *mo)
1907 {
1908 
1909 	if (m->m_owner == mo || mo == NULL)
1910 		return;
1911 
1912 	mowner_revoke(m, true, m->m_flags);
1913 	mowner_claim(m, mo);
1914 }
1915 #endif /* defined(MBUFTRACE) */
1916 
1917 /*
1918  * MFREE(struct mbuf *m, struct mbuf *n)
1919  * Free a single mbuf and associated external storage.
1920  * Place the successor, if any, in n.
1921  */
1922 #define	MFREE(f, l, m, n)						\
1923 	mowner_revoke((m), 1, (m)->m_flags);				\
1924 	mbstat_type_add((m)->m_type, -1);				\
1925 	if ((m)->m_flags & M_PKTHDR)					\
1926 		m_tag_delete_chain((m), NULL);				\
1927 	(n) = (m)->m_next;						\
1928 	if ((m)->m_flags & M_EXT) {					\
1929 		m_ext_free((m));					\
1930 	} else {							\
1931 		MBUFFREE(f, l, m);					\
1932 	}								\
1933 
1934 #ifdef DEBUG
1935 #define MBUFFREE(f, l, m)						\
1936 	do {								\
1937 		if ((m)->m_type == MT_FREE)				\
1938 			panic("mbuf was already freed at %s,%d", 	\
1939 			    m->m_data, m->m_len);			\
1940 		(m)->m_type = MT_FREE;					\
1941 		(m)->m_data = __UNCONST(f);				\
1942 		(m)->m_len = l;						\
1943 		pool_cache_put(mb_cache, (m));				\
1944 	} while (/*CONSTCOND*/0)
1945 
1946 #else
1947 #define MBUFFREE(f, l, m)						\
1948 	do {								\
1949 		KASSERT((m)->m_type != MT_FREE);			\
1950 		(m)->m_type = MT_FREE;					\
1951 		pool_cache_put(mb_cache, (m));				\
1952 	} while (/*CONSTCOND*/0)
1953 #endif
1954 
1955 struct mbuf *
1956 m__free(const char *f, int l, struct mbuf *m)
1957 {
1958 	struct mbuf *n;
1959 
1960 	MFREE(f, l, m, n);
1961 	return (n);
1962 }
1963 
1964 void
1965 m__freem(const char *f, int l, struct mbuf *m)
1966 {
1967 	struct mbuf *n;
1968 
1969 	if (m == NULL)
1970 		return;
1971 	do {
1972 		MFREE(f, l, m, n);
1973 		m = n;
1974 	} while (m);
1975 }
1976 
1977 #undef m_free
1978 struct mbuf *m_free(struct mbuf *);
1979 struct mbuf *
1980 m_free(struct mbuf *m)
1981 {
1982 	return m__free(__func__, __LINE__, m);
1983 }
1984 
1985 #undef m_freem
1986 void m_freem(struct mbuf *);
1987 void
1988 m_freem(struct mbuf *m)
1989 {
1990 	m__freem(__func__, __LINE__, m);
1991 }
1992