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