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