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