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