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