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