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