uipc_mbuf.c revision 1.181.2.1 1 /* $NetBSD: uipc_mbuf.c,v 1.181.2.1 2018/03/15 09:12:06 pgoyette 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.181.2.1 2018/03/15 09:12:06 pgoyette 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 m_hdr_init(m, type, NULL, m->m_dat, 0);
610
611 return m;
612 }
613
614 struct mbuf *
615 m_gethdr(int nowait, int type)
616 {
617 struct mbuf *m;
618
619 m = m_get(nowait, type);
620 if (m == NULL)
621 return NULL;
622
623 m_pkthdr_init(m);
624
625 return m;
626 }
627
628 struct mbuf *
629 m_getclr(int nowait, int type)
630 {
631 struct mbuf *m;
632
633 m = m_get(nowait, type);
634 if (m == NULL)
635 return NULL;
636 memset(mtod(m, void *), 0, MLEN);
637 return m;
638 }
639
640 void
641 m_clget(struct mbuf *m, int nowait)
642 {
643
644 MCLGET(m, nowait);
645 }
646
647 #ifdef MBUFTRACE
648 /*
649 * Walk a chain of mbufs, claiming ownership of each mbuf in the chain.
650 */
651 void
652 m_claimm(struct mbuf *m, struct mowner *mo)
653 {
654
655 for (; m != NULL; m = m->m_next)
656 MCLAIM(m, mo);
657 }
658 #endif
659
660 /*
661 * Mbuffer utility routines.
662 */
663
664 /*
665 * Lesser-used path for M_PREPEND:
666 * allocate new mbuf to prepend to chain,
667 * copy junk along.
668 */
669 struct mbuf *
670 m_prepend(struct mbuf *m, int len, int how)
671 {
672 struct mbuf *mn;
673
674 if (__predict_false(len > MHLEN)) {
675 panic("%s: len > MHLEN", __func__);
676 }
677
678 KASSERT(len != M_COPYALL);
679 mn = m_get(how, m->m_type);
680 if (mn == NULL) {
681 m_freem(m);
682 return NULL;
683 }
684
685 if (m->m_flags & M_PKTHDR) {
686 M_MOVE_PKTHDR(mn, m);
687 } else {
688 MCLAIM(mn, m->m_owner);
689 }
690 mn->m_next = m;
691 m = mn;
692
693 if (m->m_flags & M_PKTHDR) {
694 if (len < MHLEN)
695 MH_ALIGN(m, len);
696 } else {
697 if (len < MLEN)
698 M_ALIGN(m, len);
699 }
700
701 m->m_len = len;
702 return m;
703 }
704
705 /*
706 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
707 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
708 * The wait parameter is a choice of M_WAIT/M_DONTWAIT from caller.
709 */
710 int MCFail;
711
712 struct mbuf *
713 m_copym(struct mbuf *m, int off0, int len, int wait)
714 {
715
716 return m_copym0(m, off0, len, wait, false); /* shallow copy on M_EXT */
717 }
718
719 struct mbuf *
720 m_dup(struct mbuf *m, int off0, int len, int wait)
721 {
722
723 return m_copym0(m, off0, len, wait, true); /* deep copy */
724 }
725
726 static inline int
727 m_copylen(int len, int copylen)
728 {
729 return (len == M_COPYALL) ? copylen : min(len, copylen);
730 }
731
732 static struct mbuf *
733 m_copym0(struct mbuf *m, int off0, int len, int wait, bool deep)
734 {
735 struct mbuf *n, **np;
736 int off = off0;
737 struct mbuf *top;
738 int copyhdr = 0;
739
740 if (off < 0 || (len != M_COPYALL && len < 0))
741 panic("m_copym: off %d, len %d", off, len);
742 if (off == 0 && m->m_flags & M_PKTHDR)
743 copyhdr = 1;
744 while (off > 0) {
745 if (m == NULL)
746 panic("m_copym: m == 0, off %d", off);
747 if (off < m->m_len)
748 break;
749 off -= m->m_len;
750 m = m->m_next;
751 }
752
753 np = ⊤
754 top = NULL;
755 while (len == M_COPYALL || len > 0) {
756 if (m == NULL) {
757 if (len != M_COPYALL)
758 panic("m_copym: m == 0, len %d [!COPYALL]",
759 len);
760 break;
761 }
762
763 n = m_get(wait, m->m_type);
764 *np = n;
765 if (n == NULL)
766 goto nospace;
767 MCLAIM(n, m->m_owner);
768
769 if (copyhdr) {
770 M_COPY_PKTHDR(n, m);
771 if (len == M_COPYALL)
772 n->m_pkthdr.len -= off0;
773 else
774 n->m_pkthdr.len = len;
775 copyhdr = 0;
776 }
777 n->m_len = m_copylen(len, m->m_len - off);
778
779 if (m->m_flags & M_EXT) {
780 if (!deep) {
781 n->m_data = m->m_data + off;
782 MCLADDREFERENCE(m, n);
783 } else {
784 /*
785 * We don't care if MCLGET fails. n->m_len is
786 * recomputed and handles that.
787 */
788 MCLGET(n, wait);
789 n->m_len = 0;
790 n->m_len = M_TRAILINGSPACE(n);
791 n->m_len = m_copylen(len, n->m_len);
792 n->m_len = min(n->m_len, m->m_len - off);
793 memcpy(mtod(n, void *), mtod(m, char *) + off,
794 (unsigned)n->m_len);
795 }
796 } else {
797 memcpy(mtod(n, void *), mtod(m, char *) + off,
798 (unsigned)n->m_len);
799 }
800
801 if (len != M_COPYALL)
802 len -= n->m_len;
803 off += n->m_len;
804 #ifdef DIAGNOSTIC
805 if (off > m->m_len)
806 panic("m_copym0 overrun %d %d", off, m->m_len);
807 #endif
808 if (off == m->m_len) {
809 m = m->m_next;
810 off = 0;
811 }
812 np = &n->m_next;
813 }
814
815 if (top == NULL)
816 MCFail++;
817
818 return top;
819
820 nospace:
821 m_freem(top);
822 MCFail++;
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 MCFail++;
875 return NULL;
876 }
877
878 /*
879 * Copy data from an mbuf chain starting "off" bytes from the beginning,
880 * continuing for "len" bytes, into the indicated buffer.
881 */
882 void
883 m_copydata(struct mbuf *m, int off, int len, void *vp)
884 {
885 unsigned count;
886 void *cp = vp;
887 struct mbuf *m0 = m;
888 int len0 = len;
889 int off0 = off;
890 void *vp0 = vp;
891
892 KASSERT(len != M_COPYALL);
893 if (off < 0 || len < 0)
894 panic("m_copydata: off %d, len %d", off, len);
895 while (off > 0) {
896 if (m == NULL)
897 panic("m_copydata(%p,%d,%d,%p): m=NULL, off=%d (%d)",
898 m0, len0, off0, vp0, off, off0 - off);
899 if (off < m->m_len)
900 break;
901 off -= m->m_len;
902 m = m->m_next;
903 }
904 while (len > 0) {
905 if (m == NULL)
906 panic("m_copydata(%p,%d,%d,%p): "
907 "m=NULL, off=%d (%d), len=%d (%d)",
908 m0, len0, off0, vp0,
909 off, off0 - off, len, len0 - len);
910 count = min(m->m_len - off, len);
911 memcpy(cp, mtod(m, char *) + off, count);
912 len -= count;
913 cp = (char *)cp + count;
914 off = 0;
915 m = m->m_next;
916 }
917 }
918
919 /*
920 * Concatenate mbuf chain n to m.
921 * n might be copied into m (when n->m_len is small), therefore data portion of
922 * n could be copied into an mbuf of different mbuf type.
923 * Any m_pkthdr is not updated.
924 */
925 void
926 m_cat(struct mbuf *m, struct mbuf *n)
927 {
928
929 while (m->m_next)
930 m = m->m_next;
931 while (n) {
932 if (M_READONLY(m) || n->m_len > M_TRAILINGSPACE(m)) {
933 /* just join the two chains */
934 m->m_next = n;
935 return;
936 }
937 /* splat the data from one into the other */
938 memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
939 (u_int)n->m_len);
940 m->m_len += n->m_len;
941 n = m_free(n);
942 }
943 }
944
945 void
946 m_adj(struct mbuf *mp, int req_len)
947 {
948 int len = req_len;
949 struct mbuf *m;
950 int count;
951
952 if ((m = mp) == NULL)
953 return;
954 if (len >= 0) {
955 /*
956 * Trim from head.
957 */
958 while (m != NULL && len > 0) {
959 if (m->m_len <= len) {
960 len -= m->m_len;
961 m->m_len = 0;
962 m = m->m_next;
963 } else {
964 m->m_len -= len;
965 m->m_data += len;
966 len = 0;
967 }
968 }
969 if (mp->m_flags & M_PKTHDR)
970 mp->m_pkthdr.len -= (req_len - len);
971 } else {
972 /*
973 * Trim from tail. Scan the mbuf chain,
974 * calculating its length and finding the last mbuf.
975 * If the adjustment only affects this mbuf, then just
976 * adjust and return. Otherwise, rescan and truncate
977 * after the remaining size.
978 */
979 len = -len;
980 count = 0;
981 for (;;) {
982 count += m->m_len;
983 if (m->m_next == NULL)
984 break;
985 m = m->m_next;
986 }
987 if (m->m_len >= len) {
988 m->m_len -= len;
989 if (mp->m_flags & M_PKTHDR)
990 mp->m_pkthdr.len -= len;
991 return;
992 }
993
994 count -= len;
995 if (count < 0)
996 count = 0;
997
998 /*
999 * Correct length for chain is "count".
1000 * Find the mbuf with last data, adjust its length,
1001 * and toss data from remaining mbufs on chain.
1002 */
1003 m = mp;
1004 if (m->m_flags & M_PKTHDR)
1005 m->m_pkthdr.len = count;
1006 for (; m; m = m->m_next) {
1007 if (m->m_len >= count) {
1008 m->m_len = count;
1009 break;
1010 }
1011 count -= m->m_len;
1012 }
1013 if (m) {
1014 while (m->m_next)
1015 (m = m->m_next)->m_len = 0;
1016 }
1017 }
1018 }
1019
1020 /*
1021 * m_ensure_contig: rearrange an mbuf chain that given length of bytes
1022 * would be contiguous and in the data area of an mbuf (therefore, mtod()
1023 * would work for a structure of given length).
1024 *
1025 * => On success, returns true and the resulting mbuf chain; false otherwise.
1026 * => The mbuf chain may change, but is always preserved valid.
1027 */
1028 bool
1029 m_ensure_contig(struct mbuf **m0, int len)
1030 {
1031 struct mbuf *n = *m0, *m;
1032 size_t count, space;
1033
1034 KASSERT(len != M_COPYALL);
1035 /*
1036 * If first mbuf has no cluster, and has room for len bytes
1037 * without shifting current data, pullup into it,
1038 * otherwise allocate a new mbuf to prepend to the chain.
1039 */
1040 if ((n->m_flags & M_EXT) == 0 &&
1041 n->m_data + len < &n->m_dat[MLEN] && n->m_next) {
1042 if (n->m_len >= len) {
1043 return true;
1044 }
1045 m = n;
1046 n = n->m_next;
1047 len -= m->m_len;
1048 } else {
1049 if (len > MHLEN) {
1050 return false;
1051 }
1052 m = m_get(M_DONTWAIT, n->m_type);
1053 if (m == NULL) {
1054 return false;
1055 }
1056 MCLAIM(m, n->m_owner);
1057 if (n->m_flags & M_PKTHDR) {
1058 M_MOVE_PKTHDR(m, n);
1059 }
1060 }
1061 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1062 do {
1063 count = MIN(MIN(MAX(len, max_protohdr), space), n->m_len);
1064 memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1065 (unsigned)count);
1066 len -= count;
1067 m->m_len += count;
1068 n->m_len -= count;
1069 space -= count;
1070 if (n->m_len)
1071 n->m_data += count;
1072 else
1073 n = m_free(n);
1074 } while (len > 0 && n);
1075
1076 m->m_next = n;
1077 *m0 = m;
1078
1079 return len <= 0;
1080 }
1081
1082 /*
1083 * m_pullup: same as m_ensure_contig(), but destroys mbuf chain on error.
1084 */
1085 int MPFail;
1086
1087 struct mbuf *
1088 m_pullup(struct mbuf *n, int len)
1089 {
1090 struct mbuf *m = n;
1091
1092 KASSERT(len != M_COPYALL);
1093 if (!m_ensure_contig(&m, len)) {
1094 KASSERT(m != NULL);
1095 m_freem(m);
1096 MPFail++;
1097 m = NULL;
1098 }
1099 return m;
1100 }
1101
1102 /*
1103 * Like m_pullup(), except a new mbuf is always allocated, and we allow
1104 * the amount of empty space before the data in the new mbuf to be specified
1105 * (in the event that the caller expects to prepend later).
1106 */
1107 int MSFail;
1108
1109 struct mbuf *
1110 m_copyup(struct mbuf *n, int len, int dstoff)
1111 {
1112 struct mbuf *m;
1113 int count, space;
1114
1115 KASSERT(len != M_COPYALL);
1116 if (len > (MHLEN - dstoff))
1117 goto bad;
1118 m = m_get(M_DONTWAIT, n->m_type);
1119 if (m == NULL)
1120 goto bad;
1121 MCLAIM(m, n->m_owner);
1122 if (n->m_flags & M_PKTHDR) {
1123 M_MOVE_PKTHDR(m, n);
1124 }
1125 m->m_data += dstoff;
1126 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1127 do {
1128 count = min(min(max(len, max_protohdr), space), n->m_len);
1129 memcpy(mtod(m, char *) + m->m_len, mtod(n, void *),
1130 (unsigned)count);
1131 len -= count;
1132 m->m_len += count;
1133 n->m_len -= count;
1134 space -= count;
1135 if (n->m_len)
1136 n->m_data += count;
1137 else
1138 n = m_free(n);
1139 } while (len > 0 && n);
1140 if (len > 0) {
1141 (void) m_free(m);
1142 goto bad;
1143 }
1144 m->m_next = n;
1145 return (m);
1146 bad:
1147 m_freem(n);
1148 MSFail++;
1149 return (NULL);
1150 }
1151
1152 /*
1153 * Partition an mbuf chain in two pieces, returning the tail --
1154 * all but the first len0 bytes. In case of failure, it returns NULL and
1155 * attempts to restore the chain to its original state.
1156 */
1157 struct mbuf *
1158 m_split(struct mbuf *m0, int len0, int wait)
1159 {
1160
1161 return m_split0(m0, len0, wait, true);
1162 }
1163
1164 static struct mbuf *
1165 m_split0(struct mbuf *m0, int len0, int wait, bool copyhdr)
1166 {
1167 struct mbuf *m, *n;
1168 unsigned len = len0, remain, len_save;
1169
1170 KASSERT(len0 != M_COPYALL);
1171 for (m = m0; m && len > m->m_len; m = m->m_next)
1172 len -= m->m_len;
1173 if (m == NULL)
1174 return NULL;
1175
1176 remain = m->m_len - len;
1177 if (copyhdr && (m0->m_flags & M_PKTHDR)) {
1178 n = m_gethdr(wait, m0->m_type);
1179 if (n == NULL)
1180 return NULL;
1181
1182 MCLAIM(n, m0->m_owner);
1183 m_copy_rcvif(n, m0);
1184 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1185 len_save = m0->m_pkthdr.len;
1186 m0->m_pkthdr.len = len0;
1187
1188 if (m->m_flags & M_EXT)
1189 goto extpacket;
1190
1191 if (remain > MHLEN) {
1192 /* m can't be the lead packet */
1193 MH_ALIGN(n, 0);
1194 n->m_len = 0;
1195 n->m_next = m_split(m, len, wait);
1196 if (n->m_next == NULL) {
1197 (void)m_free(n);
1198 m0->m_pkthdr.len = len_save;
1199 return NULL;
1200 }
1201 return n;
1202 } else {
1203 MH_ALIGN(n, remain);
1204 }
1205 } else if (remain == 0) {
1206 n = m->m_next;
1207 m->m_next = NULL;
1208 return n;
1209 } else {
1210 n = m_get(wait, m->m_type);
1211 if (n == NULL)
1212 return NULL;
1213 MCLAIM(n, m->m_owner);
1214 M_ALIGN(n, remain);
1215 }
1216
1217 extpacket:
1218 if (m->m_flags & M_EXT) {
1219 n->m_data = m->m_data + len;
1220 MCLADDREFERENCE(m, n);
1221 } else {
1222 memcpy(mtod(n, void *), mtod(m, char *) + len, remain);
1223 }
1224
1225 n->m_len = remain;
1226 m->m_len = len;
1227 n->m_next = m->m_next;
1228 m->m_next = NULL;
1229 return n;
1230 }
1231
1232 /*
1233 * Routine to copy from device local memory into mbufs.
1234 */
1235 struct mbuf *
1236 m_devget(char *buf, int totlen, int off0, struct ifnet *ifp,
1237 void (*copy)(const void *from, void *to, size_t len))
1238 {
1239 struct mbuf *m;
1240 struct mbuf *top = NULL, **mp = ⊤
1241 int off = off0, len;
1242 char *cp, *epkt;
1243
1244 cp = buf;
1245 epkt = cp + totlen;
1246 if (off) {
1247 /*
1248 * If 'off' is non-zero, packet is trailer-encapsulated,
1249 * so we have to skip the type and length fields.
1250 */
1251 cp += off + 2 * sizeof(uint16_t);
1252 totlen -= 2 * sizeof(uint16_t);
1253 }
1254
1255 m = m_gethdr(M_DONTWAIT, MT_DATA);
1256 if (m == NULL)
1257 return NULL;
1258 m_set_rcvif(m, ifp);
1259 m->m_pkthdr.len = totlen;
1260 m->m_len = MHLEN;
1261
1262 while (totlen > 0) {
1263 if (top) {
1264 m = m_get(M_DONTWAIT, MT_DATA);
1265 if (m == NULL) {
1266 m_freem(top);
1267 return NULL;
1268 }
1269 m->m_len = MLEN;
1270 }
1271
1272 len = min(totlen, epkt - cp);
1273
1274 if (len >= MINCLSIZE) {
1275 MCLGET(m, M_DONTWAIT);
1276 if ((m->m_flags & M_EXT) == 0) {
1277 m_free(m);
1278 m_freem(top);
1279 return NULL;
1280 }
1281 m->m_len = len = min(len, MCLBYTES);
1282 } else {
1283 /*
1284 * Place initial small packet/header at end of mbuf.
1285 */
1286 if (len < m->m_len) {
1287 if (top == 0 && len + max_linkhdr <= m->m_len)
1288 m->m_data += max_linkhdr;
1289 m->m_len = len;
1290 } else
1291 len = m->m_len;
1292 }
1293
1294 if (copy)
1295 copy(cp, mtod(m, void *), (size_t)len);
1296 else
1297 memcpy(mtod(m, void *), cp, (size_t)len);
1298
1299 cp += len;
1300 *mp = m;
1301 mp = &m->m_next;
1302 totlen -= len;
1303 if (cp == epkt)
1304 cp = buf;
1305 }
1306
1307 return top;
1308 }
1309
1310 /*
1311 * Copy data from a buffer back into the indicated mbuf chain,
1312 * starting "off" bytes from the beginning, extending the mbuf
1313 * chain if necessary.
1314 */
1315 void
1316 m_copyback(struct mbuf *m0, int off, int len, const void *cp)
1317 {
1318 #if defined(DEBUG)
1319 struct mbuf *origm = m0;
1320 int error;
1321 #endif
1322
1323 if (m0 == NULL)
1324 return;
1325
1326 #if defined(DEBUG)
1327 error =
1328 #endif
1329 m_copyback0(&m0, off, len, cp,
1330 M_COPYBACK0_COPYBACK|M_COPYBACK0_EXTEND, M_DONTWAIT);
1331
1332 #if defined(DEBUG)
1333 if (error != 0 || (m0 != NULL && origm != m0))
1334 panic("m_copyback");
1335 #endif
1336 }
1337
1338 struct mbuf *
1339 m_copyback_cow(struct mbuf *m0, int off, int len, const void *cp, int how)
1340 {
1341 int error;
1342
1343 /* don't support chain expansion */
1344 KASSERT(len != M_COPYALL);
1345 KDASSERT(off + len <= m_length(m0));
1346
1347 error = m_copyback0(&m0, off, len, cp,
1348 M_COPYBACK0_COPYBACK|M_COPYBACK0_COW, how);
1349 if (error) {
1350 /*
1351 * no way to recover from partial success.
1352 * just free the chain.
1353 */
1354 m_freem(m0);
1355 return NULL;
1356 }
1357 return m0;
1358 }
1359
1360 /*
1361 * m_makewritable: ensure the specified range writable.
1362 */
1363 int
1364 m_makewritable(struct mbuf **mp, int off, int len, int how)
1365 {
1366 int error;
1367 #if defined(DEBUG)
1368 int origlen = m_length(*mp);
1369 #endif
1370
1371 error = m_copyback0(mp, off, len, NULL,
1372 M_COPYBACK0_PRESERVE|M_COPYBACK0_COW, how);
1373
1374 if (error)
1375 return error;
1376
1377 #if defined(DEBUG)
1378 int reslen = 0;
1379 for (struct mbuf *n = *mp; n; n = n->m_next)
1380 reslen += n->m_len;
1381 if (origlen != reslen)
1382 panic("m_makewritable: length changed");
1383 if (((*mp)->m_flags & M_PKTHDR) != 0 && reslen != (*mp)->m_pkthdr.len)
1384 panic("m_makewritable: inconsist");
1385 #endif
1386
1387 return 0;
1388 }
1389
1390 /*
1391 * Copy the mbuf chain to a new mbuf chain that is as short as possible.
1392 * Return the new mbuf chain on success, NULL on failure. On success,
1393 * free the old mbuf chain.
1394 */
1395 struct mbuf *
1396 m_defrag(struct mbuf *mold, int flags)
1397 {
1398 struct mbuf *m0, *mn, *n;
1399 size_t sz = mold->m_pkthdr.len;
1400
1401 KASSERT((mold->m_flags & M_PKTHDR) != 0);
1402
1403 m0 = m_gethdr(flags, MT_DATA);
1404 if (m0 == NULL)
1405 return NULL;
1406 M_COPY_PKTHDR(m0, mold);
1407 mn = m0;
1408
1409 do {
1410 if (sz > MHLEN) {
1411 MCLGET(mn, M_DONTWAIT);
1412 if ((mn->m_flags & M_EXT) == 0) {
1413 m_freem(m0);
1414 return NULL;
1415 }
1416 }
1417
1418 mn->m_len = MIN(sz, MCLBYTES);
1419
1420 m_copydata(mold, mold->m_pkthdr.len - sz, mn->m_len,
1421 mtod(mn, void *));
1422
1423 sz -= mn->m_len;
1424
1425 if (sz > 0) {
1426 /* need more mbufs */
1427 n = m_get(M_NOWAIT, MT_DATA);
1428 if (n == NULL) {
1429 m_freem(m0);
1430 return NULL;
1431 }
1432
1433 mn->m_next = n;
1434 mn = n;
1435 }
1436 } while (sz > 0);
1437
1438 m_freem(mold);
1439
1440 return m0;
1441 }
1442
1443 int
1444 m_copyback0(struct mbuf **mp0, int off, int len, const void *vp, int flags,
1445 int how)
1446 {
1447 int mlen;
1448 struct mbuf *m, *n;
1449 struct mbuf **mp;
1450 int totlen = 0;
1451 const char *cp = vp;
1452
1453 KASSERT(mp0 != NULL);
1454 KASSERT(*mp0 != NULL);
1455 KASSERT((flags & M_COPYBACK0_PRESERVE) == 0 || cp == NULL);
1456 KASSERT((flags & M_COPYBACK0_COPYBACK) == 0 || cp != NULL);
1457
1458 if (len == M_COPYALL)
1459 len = m_length(*mp0) - off;
1460
1461 /*
1462 * we don't bother to update "totlen" in the case of M_COPYBACK0_COW,
1463 * assuming that M_COPYBACK0_EXTEND and M_COPYBACK0_COW are exclusive.
1464 */
1465
1466 KASSERT((~flags & (M_COPYBACK0_EXTEND|M_COPYBACK0_COW)) != 0);
1467
1468 mp = mp0;
1469 m = *mp;
1470 while (off > (mlen = m->m_len)) {
1471 off -= mlen;
1472 totlen += mlen;
1473 if (m->m_next == NULL) {
1474 int tspace;
1475 extend:
1476 if ((flags & M_COPYBACK0_EXTEND) == 0)
1477 goto out;
1478
1479 /*
1480 * try to make some space at the end of "m".
1481 */
1482
1483 mlen = m->m_len;
1484 if (off + len >= MINCLSIZE &&
1485 (m->m_flags & M_EXT) == 0 && m->m_len == 0) {
1486 MCLGET(m, how);
1487 }
1488 tspace = M_TRAILINGSPACE(m);
1489 if (tspace > 0) {
1490 tspace = min(tspace, off + len);
1491 KASSERT(tspace > 0);
1492 memset(mtod(m, char *) + m->m_len, 0,
1493 min(off, tspace));
1494 m->m_len += tspace;
1495 off += mlen;
1496 totlen -= mlen;
1497 continue;
1498 }
1499
1500 /*
1501 * need to allocate an mbuf.
1502 */
1503
1504 if (off + len >= MINCLSIZE) {
1505 n = m_getcl(how, m->m_type, 0);
1506 } else {
1507 n = m_get(how, m->m_type);
1508 }
1509 if (n == NULL) {
1510 goto out;
1511 }
1512 n->m_len = min(M_TRAILINGSPACE(n), off + len);
1513 memset(mtod(n, char *), 0, min(n->m_len, off));
1514 m->m_next = n;
1515 }
1516 mp = &m->m_next;
1517 m = m->m_next;
1518 }
1519 while (len > 0) {
1520 mlen = m->m_len - off;
1521 if (mlen != 0 && M_READONLY(m)) {
1522 char *datap;
1523 int eatlen;
1524
1525 /*
1526 * this mbuf is read-only.
1527 * allocate a new writable mbuf and try again.
1528 */
1529
1530 #if defined(DIAGNOSTIC)
1531 if ((flags & M_COPYBACK0_COW) == 0)
1532 panic("m_copyback0: read-only");
1533 #endif /* defined(DIAGNOSTIC) */
1534
1535 /*
1536 * if we're going to write into the middle of
1537 * a mbuf, split it first.
1538 */
1539 if (off > 0) {
1540 n = m_split0(m, off, how, false);
1541 if (n == NULL)
1542 goto enobufs;
1543 m->m_next = n;
1544 mp = &m->m_next;
1545 m = n;
1546 off = 0;
1547 continue;
1548 }
1549
1550 /*
1551 * XXX TODO coalesce into the trailingspace of
1552 * the previous mbuf when possible.
1553 */
1554
1555 /*
1556 * allocate a new mbuf. copy packet header if needed.
1557 */
1558 n = m_get(how, m->m_type);
1559 if (n == NULL)
1560 goto enobufs;
1561 MCLAIM(n, m->m_owner);
1562 if (off == 0 && (m->m_flags & M_PKTHDR) != 0) {
1563 M_MOVE_PKTHDR(n, m);
1564 n->m_len = MHLEN;
1565 } else {
1566 if (len >= MINCLSIZE)
1567 MCLGET(n, M_DONTWAIT);
1568 n->m_len =
1569 (n->m_flags & M_EXT) ? MCLBYTES : MLEN;
1570 }
1571 if (n->m_len > len)
1572 n->m_len = len;
1573
1574 /*
1575 * free the region which has been overwritten.
1576 * copying data from old mbufs if requested.
1577 */
1578 if (flags & M_COPYBACK0_PRESERVE)
1579 datap = mtod(n, char *);
1580 else
1581 datap = NULL;
1582 eatlen = n->m_len;
1583 while (m != NULL && M_READONLY(m) &&
1584 n->m_type == m->m_type && eatlen > 0) {
1585 mlen = min(eatlen, m->m_len);
1586 if (datap) {
1587 m_copydata(m, 0, mlen, datap);
1588 datap += mlen;
1589 }
1590 m->m_data += mlen;
1591 m->m_len -= mlen;
1592 eatlen -= mlen;
1593 if (m->m_len == 0)
1594 *mp = m = m_free(m);
1595 }
1596 if (eatlen > 0)
1597 n->m_len -= eatlen;
1598 n->m_next = m;
1599 *mp = m = n;
1600 continue;
1601 }
1602 mlen = min(mlen, len);
1603 if (flags & M_COPYBACK0_COPYBACK) {
1604 memcpy(mtod(m, char *) + off, cp, (unsigned)mlen);
1605 cp += mlen;
1606 }
1607 len -= mlen;
1608 mlen += off;
1609 off = 0;
1610 totlen += mlen;
1611 if (len == 0)
1612 break;
1613 if (m->m_next == NULL) {
1614 goto extend;
1615 }
1616 mp = &m->m_next;
1617 m = m->m_next;
1618 }
1619 out: if (((m = *mp0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen)) {
1620 KASSERT((flags & M_COPYBACK0_EXTEND) != 0);
1621 m->m_pkthdr.len = totlen;
1622 }
1623
1624 return 0;
1625
1626 enobufs:
1627 return ENOBUFS;
1628 }
1629
1630 void
1631 m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1632 {
1633
1634 KASSERT((to->m_flags & M_EXT) == 0);
1635 KASSERT((to->m_flags & M_PKTHDR) == 0 || m_tag_first(to) == NULL);
1636 KASSERT((from->m_flags & M_PKTHDR) != 0);
1637
1638 to->m_pkthdr = from->m_pkthdr;
1639 to->m_flags = from->m_flags & M_COPYFLAGS;
1640 to->m_data = to->m_pktdat;
1641
1642 from->m_flags &= ~M_PKTHDR;
1643 }
1644
1645 /*
1646 * Apply function f to the data in an mbuf chain starting "off" bytes from the
1647 * beginning, continuing for "len" bytes.
1648 */
1649 int
1650 m_apply(struct mbuf *m, int off, int len,
1651 int (*f)(void *, void *, unsigned int), void *arg)
1652 {
1653 unsigned int count;
1654 int rval;
1655
1656 KASSERT(len != M_COPYALL);
1657 KASSERT(len >= 0);
1658 KASSERT(off >= 0);
1659
1660 while (off > 0) {
1661 KASSERT(m != NULL);
1662 if (off < m->m_len)
1663 break;
1664 off -= m->m_len;
1665 m = m->m_next;
1666 }
1667 while (len > 0) {
1668 KASSERT(m != NULL);
1669 count = min(m->m_len - off, len);
1670
1671 rval = (*f)(arg, mtod(m, char *) + off, count);
1672 if (rval)
1673 return rval;
1674
1675 len -= count;
1676 off = 0;
1677 m = m->m_next;
1678 }
1679
1680 return 0;
1681 }
1682
1683 /*
1684 * Return a pointer to mbuf/offset of location in mbuf chain.
1685 */
1686 struct mbuf *
1687 m_getptr(struct mbuf *m, int loc, int *off)
1688 {
1689
1690 while (loc >= 0) {
1691 /* Normal end of search */
1692 if (m->m_len > loc) {
1693 *off = loc;
1694 return m;
1695 }
1696
1697 loc -= m->m_len;
1698
1699 if (m->m_next == NULL) {
1700 if (loc == 0) {
1701 /* Point at the end of valid data */
1702 *off = m->m_len;
1703 return m;
1704 }
1705 return NULL;
1706 } else {
1707 m = m->m_next;
1708 }
1709 }
1710
1711 return NULL;
1712 }
1713
1714 /*
1715 * m_ext_free: release a reference to the mbuf external storage.
1716 *
1717 * => free the mbuf m itself as well.
1718 */
1719
1720 void
1721 m_ext_free(struct mbuf *m)
1722 {
1723 const bool embedded = MEXT_ISEMBEDDED(m);
1724 bool dofree = true;
1725 u_int refcnt;
1726
1727 KASSERT((m->m_flags & M_EXT) != 0);
1728 KASSERT(MEXT_ISEMBEDDED(m->m_ext_ref));
1729 KASSERT((m->m_ext_ref->m_flags & M_EXT) != 0);
1730 KASSERT((m->m_flags & M_EXT_CLUSTER) ==
1731 (m->m_ext_ref->m_flags & M_EXT_CLUSTER));
1732
1733 if (__predict_false(m->m_type == MT_FREE)) {
1734 panic("mbuf %p already freed", m);
1735 }
1736
1737 if (__predict_true(m->m_ext.ext_refcnt == 1)) {
1738 refcnt = m->m_ext.ext_refcnt = 0;
1739 } else {
1740 refcnt = atomic_dec_uint_nv(&m->m_ext.ext_refcnt);
1741 }
1742
1743 if (refcnt > 0) {
1744 if (embedded) {
1745 /*
1746 * other mbuf's m_ext_ref still points to us.
1747 */
1748 dofree = false;
1749 } else {
1750 m->m_ext_ref = m;
1751 }
1752 } else {
1753 /*
1754 * dropping the last reference
1755 */
1756 if (!embedded) {
1757 m->m_ext.ext_refcnt++; /* XXX */
1758 m_ext_free(m->m_ext_ref);
1759 m->m_ext_ref = m;
1760 } else if ((m->m_flags & M_EXT_CLUSTER) != 0) {
1761 pool_cache_put_paddr((struct pool_cache *)
1762 m->m_ext.ext_arg,
1763 m->m_ext.ext_buf, m->m_ext.ext_paddr);
1764 } else if (m->m_ext.ext_free) {
1765 (*m->m_ext.ext_free)(m,
1766 m->m_ext.ext_buf, m->m_ext.ext_size,
1767 m->m_ext.ext_arg);
1768 /*
1769 * 'm' is already freed by the ext_free callback.
1770 */
1771 dofree = false;
1772 } else {
1773 free(m->m_ext.ext_buf, m->m_ext.ext_type);
1774 }
1775 }
1776
1777 if (dofree) {
1778 m->m_type = MT_FREE;
1779 m->m_data = NULL;
1780 pool_cache_put(mb_cache, m);
1781 }
1782 }
1783
1784 #if defined(DDB)
1785 void
1786 m_print(const struct mbuf *m, const char *modif, void (*pr)(const char *, ...))
1787 {
1788 char ch;
1789 bool opt_c = false;
1790 char buf[512];
1791
1792 while ((ch = *(modif++)) != '\0') {
1793 switch (ch) {
1794 case 'c':
1795 opt_c = true;
1796 break;
1797 }
1798 }
1799
1800 nextchain:
1801 (*pr)("MBUF %p\n", m);
1802 snprintb(buf, sizeof(buf), M_FLAGS_BITS, (u_int)m->m_flags);
1803 (*pr)(" data=%p, len=%d, type=%d, flags=%s\n",
1804 m->m_data, m->m_len, m->m_type, buf);
1805 (*pr)(" owner=%p, next=%p, nextpkt=%p\n", m->m_owner, m->m_next,
1806 m->m_nextpkt);
1807 (*pr)(" leadingspace=%u, trailingspace=%u, readonly=%u\n",
1808 (int)M_LEADINGSPACE(m), (int)M_TRAILINGSPACE(m),
1809 (int)M_READONLY(m));
1810 if ((m->m_flags & M_PKTHDR) != 0) {
1811 snprintb(buf, sizeof(buf), M_CSUM_BITS, m->m_pkthdr.csum_flags);
1812 (*pr)(" pktlen=%d, rcvif=%p, csum_flags=%s, csum_data=0x%"
1813 PRIx32 ", segsz=%u\n",
1814 m->m_pkthdr.len, m_get_rcvif_NOMPSAFE(m),
1815 buf, m->m_pkthdr.csum_data, m->m_pkthdr.segsz);
1816 }
1817 if ((m->m_flags & M_EXT)) {
1818 (*pr)(" ext_refcnt=%u, ext_buf=%p, ext_size=%zd, "
1819 "ext_free=%p, ext_arg=%p\n",
1820 m->m_ext.ext_refcnt,
1821 m->m_ext.ext_buf, m->m_ext.ext_size,
1822 m->m_ext.ext_free, m->m_ext.ext_arg);
1823 }
1824 if ((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0) {
1825 vaddr_t sva = (vaddr_t)m->m_ext.ext_buf;
1826 vaddr_t eva = sva + m->m_ext.ext_size;
1827 int n = (round_page(eva) - trunc_page(sva)) >> PAGE_SHIFT;
1828 int i;
1829
1830 (*pr)(" pages:");
1831 for (i = 0; i < n; i ++) {
1832 (*pr)(" %p", m->m_ext.ext_pgs[i]);
1833 }
1834 (*pr)("\n");
1835 }
1836
1837 if (opt_c) {
1838 m = m->m_next;
1839 if (m != NULL) {
1840 goto nextchain;
1841 }
1842 }
1843 }
1844 #endif /* defined(DDB) */
1845
1846 void
1847 mbstat_type_add(int type, int diff)
1848 {
1849 struct mbstat_cpu *mb;
1850 int s;
1851
1852 s = splvm();
1853 mb = percpu_getref(mbstat_percpu);
1854 mb->m_mtypes[type] += diff;
1855 percpu_putref(mbstat_percpu);
1856 splx(s);
1857 }
1858
1859 #if defined(MBUFTRACE)
1860 void
1861 mowner_attach(struct mowner *mo)
1862 {
1863
1864 KASSERT(mo->mo_counters == NULL);
1865 mo->mo_counters = percpu_alloc(sizeof(struct mowner_counter));
1866
1867 /* XXX lock */
1868 LIST_INSERT_HEAD(&mowners, mo, mo_link);
1869 }
1870
1871 void
1872 mowner_detach(struct mowner *mo)
1873 {
1874
1875 KASSERT(mo->mo_counters != NULL);
1876
1877 /* XXX lock */
1878 LIST_REMOVE(mo, mo_link);
1879
1880 percpu_free(mo->mo_counters, sizeof(struct mowner_counter));
1881 mo->mo_counters = NULL;
1882 }
1883
1884 void
1885 mowner_init(struct mbuf *m, int type)
1886 {
1887 struct mowner_counter *mc;
1888 struct mowner *mo;
1889 int s;
1890
1891 m->m_owner = mo = &unknown_mowners[type];
1892 s = splvm();
1893 mc = percpu_getref(mo->mo_counters);
1894 mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1895 percpu_putref(mo->mo_counters);
1896 splx(s);
1897 }
1898
1899 void
1900 mowner_ref(struct mbuf *m, int flags)
1901 {
1902 struct mowner *mo = m->m_owner;
1903 struct mowner_counter *mc;
1904 int s;
1905
1906 s = splvm();
1907 mc = percpu_getref(mo->mo_counters);
1908 if ((flags & M_EXT) != 0)
1909 mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1910 if ((flags & M_CLUSTER) != 0)
1911 mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1912 percpu_putref(mo->mo_counters);
1913 splx(s);
1914 }
1915
1916 void
1917 mowner_revoke(struct mbuf *m, bool all, int flags)
1918 {
1919 struct mowner *mo = m->m_owner;
1920 struct mowner_counter *mc;
1921 int s;
1922
1923 s = splvm();
1924 mc = percpu_getref(mo->mo_counters);
1925 if ((flags & M_EXT) != 0)
1926 mc->mc_counter[MOWNER_COUNTER_EXT_RELEASES]++;
1927 if ((flags & M_CLUSTER) != 0)
1928 mc->mc_counter[MOWNER_COUNTER_CLUSTER_RELEASES]++;
1929 if (all)
1930 mc->mc_counter[MOWNER_COUNTER_RELEASES]++;
1931 percpu_putref(mo->mo_counters);
1932 splx(s);
1933 if (all)
1934 m->m_owner = &revoked_mowner;
1935 }
1936
1937 static void
1938 mowner_claim(struct mbuf *m, struct mowner *mo)
1939 {
1940 struct mowner_counter *mc;
1941 int flags = m->m_flags;
1942 int s;
1943
1944 s = splvm();
1945 mc = percpu_getref(mo->mo_counters);
1946 mc->mc_counter[MOWNER_COUNTER_CLAIMS]++;
1947 if ((flags & M_EXT) != 0)
1948 mc->mc_counter[MOWNER_COUNTER_EXT_CLAIMS]++;
1949 if ((flags & M_CLUSTER) != 0)
1950 mc->mc_counter[MOWNER_COUNTER_CLUSTER_CLAIMS]++;
1951 percpu_putref(mo->mo_counters);
1952 splx(s);
1953 m->m_owner = mo;
1954 }
1955
1956 void
1957 m_claim(struct mbuf *m, struct mowner *mo)
1958 {
1959
1960 if (m->m_owner == mo || mo == NULL)
1961 return;
1962
1963 mowner_revoke(m, true, m->m_flags);
1964 mowner_claim(m, mo);
1965 }
1966 #endif /* defined(MBUFTRACE) */
1967
1968 /*
1969 * Free a single mbuf and associated external storage. Return the
1970 * successor, if any.
1971 */
1972 struct mbuf *
1973 m_free(struct mbuf *m)
1974 {
1975 struct mbuf *n;
1976
1977 mowner_revoke(m, 1, m->m_flags);
1978 mbstat_type_add(m->m_type, -1);
1979
1980 if (m->m_flags & M_PKTHDR)
1981 m_tag_delete_chain(m, NULL);
1982
1983 n = m->m_next;
1984
1985 if (m->m_flags & M_EXT) {
1986 m_ext_free(m);
1987 } else {
1988 if (__predict_false(m->m_type == MT_FREE)) {
1989 panic("mbuf %p already freed", m);
1990 }
1991 m->m_type = MT_FREE;
1992 m->m_data = NULL;
1993 pool_cache_put(mb_cache, m);
1994 }
1995
1996 return n;
1997 }
1998
1999 void
2000 m_freem(struct mbuf *m)
2001 {
2002 if (m == NULL)
2003 return;
2004 do {
2005 m = m_free(m);
2006 } while (m);
2007 }
2008