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