Sync the vinum manpages with the recent disklabel work.
[dragonfly.git] / sys / kern / uipc_mbuf.c
CommitLineData
984263bc 1/*
0c33f36d 2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
66d6c637
JH
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
4 *
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
66d6c637 34/*
984263bc
MD
35 * Copyright (c) 1982, 1986, 1988, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
8a3125c6 66 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
984263bc 67 * $FreeBSD: src/sys/kern/uipc_mbuf.c,v 1.51.2.24 2003/04/15 06:59:29 silby Exp $
e9fa4b60 68 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.63 2007/08/09 01:10:04 dillon Exp $
984263bc
MD
69 */
70
71#include "opt_param.h"
7b6f875f 72#include "opt_ddb.h"
984263bc
MD
73#include "opt_mbuf_stress_test.h"
74#include <sys/param.h>
75#include <sys/systm.h>
76#include <sys/malloc.h>
77#include <sys/mbuf.h>
78#include <sys/kernel.h>
79#include <sys/sysctl.h>
80#include <sys/domain.h>
7b6f875f 81#include <sys/objcache.h>
e9fa4b60 82#include <sys/tree.h>
984263bc 83#include <sys/protosw.h>
0c33f36d 84#include <sys/uio.h>
ef0fdad1 85#include <sys/thread.h>
a2a5ad0d 86#include <sys/globaldata.h>
df8d1020 87#include <sys/serialize.h>
90775e29 88#include <sys/thread2.h>
984263bc
MD
89
90#include <vm/vm.h>
91#include <vm/vm_kern.h>
92#include <vm/vm_extern.h>
93
94#ifdef INVARIANTS
95#include <machine/cpu.h>
96#endif
97
90775e29
MD
98/*
99 * mbuf cluster meta-data
100 */
7b6f875f 101struct mbcluster {
90775e29
MD
102 int32_t mcl_refs;
103 void *mcl_data;
df8d1020 104 struct lwkt_serialize mcl_serializer;
7b6f875f 105};
90775e29 106
e9fa4b60
MD
107/*
108 * mbuf tracking for debugging purposes
109 */
110#ifdef MBUF_DEBUG
111
112static MALLOC_DEFINE(M_MTRACK, "mtrack", "mtrack");
113
114struct mbctrack;
115RB_HEAD(mbuf_rb_tree, mbtrack);
116RB_PROTOTYPE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *);
117
118struct mbtrack {
119 RB_ENTRY(mbtrack) rb_node;
120 int trackid;
121 struct mbuf *m;
122};
123
124static int
125mbtrack_cmp(struct mbtrack *mb1, struct mbtrack *mb2)
126{
127 if (mb1->m < mb2->m)
128 return(-1);
129 if (mb1->m > mb2->m)
130 return(1);
131 return(0);
132}
133
134RB_GENERATE2(mbuf_rb_tree, mbtrack, rb_node, mbtrack_cmp, struct mbuf *, m);
135
136struct mbuf_rb_tree mbuf_track_root;
137
138static void
139mbuftrack(struct mbuf *m)
140{
141 struct mbtrack *mbt;
142
143 crit_enter();
144 mbt = kmalloc(sizeof(*mbt), M_MTRACK, M_INTWAIT|M_ZERO);
145 mbt->m = m;
146 if (mbuf_rb_tree_RB_INSERT(&mbuf_track_root, mbt))
147 panic("mbuftrack: mbuf %p already being tracked\n", m);
148 crit_exit();
149}
150
151static void
152mbufuntrack(struct mbuf *m)
153{
154 struct mbtrack *mbt;
155
156 crit_enter();
157 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
158 if (mbt == NULL) {
159 kprintf("mbufuntrack: mbuf %p was not tracked\n", m);
160 } else {
161 mbuf_rb_tree_RB_REMOVE(&mbuf_track_root, mbt);
162 kfree(mbt, M_MTRACK);
163 }
164 crit_exit();
165}
166
167void
168mbuftrackid(struct mbuf *m, int trackid)
169{
170 struct mbtrack *mbt;
171 struct mbuf *n;
172
173 crit_enter();
174 while (m) {
175 n = m->m_nextpkt;
176 while (m) {
177 mbt = mbuf_rb_tree_RB_LOOKUP(&mbuf_track_root, m);
178 if (mbt)
179 mbt->trackid = trackid;
180 m = m->m_next;
181 }
182 m = n;
183 }
184 crit_exit();
185}
186
187static int
188mbuftrack_callback(struct mbtrack *mbt, void *arg)
189{
190 struct sysctl_req *req = arg;
191 char buf[64];
192 int error;
193
194 ksnprintf(buf, sizeof(buf), "mbuf %p track %d\n", mbt->m, mbt->trackid);
195
196 error = SYSCTL_OUT(req, buf, strlen(buf));
197 if (error)
198 return(-error);
199 return(0);
200}
201
202static int
203mbuftrack_show(SYSCTL_HANDLER_ARGS)
204{
205 int error;
206
207 crit_enter();
208 error = mbuf_rb_tree_RB_SCAN(&mbuf_track_root, NULL,
209 mbuftrack_callback, req);
210 crit_exit();
211 return (-error);
212}
213SYSCTL_PROC(_kern_ipc, OID_AUTO, showmbufs, CTLFLAG_RD|CTLTYPE_STRING,
214 0, 0, mbuftrack_show, "A", "Show all in-use mbufs");
215
216#else
217
218#define mbuftrack(m)
219#define mbufuntrack(m)
220
221#endif
222
7b6f875f 223static void mbinit(void *);
ba39e2e0 224SYSINIT(mbuf, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, mbinit, NULL)
984263bc 225
90775e29
MD
226static u_long mbtypes[MT_NTYPES];
227
984263bc 228struct mbstat mbstat;
984263bc
MD
229int max_linkhdr;
230int max_protohdr;
231int max_hdr;
232int max_datalen;
233int m_defragpackets;
234int m_defragbytes;
235int m_defraguseless;
236int m_defragfailure;
237#ifdef MBUF_STRESS_TEST
238int m_defragrandomfailures;
239#endif
240
7b6f875f
JH
241struct objcache *mbuf_cache, *mbufphdr_cache;
242struct objcache *mclmeta_cache;
243struct objcache *mbufcluster_cache, *mbufphdrcluster_cache;
244
984263bc
MD
245int nmbclusters;
246int nmbufs;
984263bc 247
984263bc
MD
248SYSCTL_INT(_kern_ipc, KIPC_MAX_LINKHDR, max_linkhdr, CTLFLAG_RW,
249 &max_linkhdr, 0, "");
250SYSCTL_INT(_kern_ipc, KIPC_MAX_PROTOHDR, max_protohdr, CTLFLAG_RW,
251 &max_protohdr, 0, "");
252SYSCTL_INT(_kern_ipc, KIPC_MAX_HDR, max_hdr, CTLFLAG_RW, &max_hdr, 0, "");
253SYSCTL_INT(_kern_ipc, KIPC_MAX_DATALEN, max_datalen, CTLFLAG_RW,
254 &max_datalen, 0, "");
255SYSCTL_INT(_kern_ipc, OID_AUTO, mbuf_wait, CTLFLAG_RW,
256 &mbuf_wait, 0, "");
257SYSCTL_STRUCT(_kern_ipc, KIPC_MBSTAT, mbstat, CTLFLAG_RW, &mbstat, mbstat, "");
258SYSCTL_OPAQUE(_kern_ipc, OID_AUTO, mbtypes, CTLFLAG_RD, mbtypes,
259 sizeof(mbtypes), "LU", "");
18c48b9c
MD
260
261/*
262 * These are read-only because we do not currently have any code
263 * to adjust the objcache limits after the fact. The variables
264 * may only be set as boot-time tunables.
265 */
266SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
984263bc 267 &nmbclusters, 0, "Maximum number of mbuf clusters available");
18c48b9c 268SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
984263bc 269 "Maximum number of mbufs available");
7b6f875f 270
984263bc
MD
271SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
272 &m_defragpackets, 0, "");
273SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
274 &m_defragbytes, 0, "");
275SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
276 &m_defraguseless, 0, "");
277SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
278 &m_defragfailure, 0, "");
279#ifdef MBUF_STRESS_TEST
280SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
281 &m_defragrandomfailures, 0, "");
282#endif
283
90775e29
MD
284static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
285static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
7b6f875f 286static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
90775e29
MD
287
288static void m_reclaim (void);
90775e29
MD
289static void m_mclref(void *arg);
290static void m_mclfree(void *arg);
984263bc
MD
291
292#ifndef NMBCLUSTERS
293#define NMBCLUSTERS (512 + maxusers * 16)
294#endif
295#ifndef NMBUFS
7b6f875f 296#define NMBUFS (nmbclusters * 2)
984263bc
MD
297#endif
298
299/*
300 * Perform sanity checks of tunables declared above.
301 */
302static void
303tunable_mbinit(void *dummy)
304{
984263bc
MD
305 /*
306 * This has to be done before VM init.
307 */
308 nmbclusters = NMBCLUSTERS;
309 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
310 nmbufs = NMBUFS;
311 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
312 /* Sanity checks */
313 if (nmbufs < nmbclusters * 2)
314 nmbufs = nmbclusters * 2;
984263bc 315}
ba39e2e0
MD
316SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
317 tunable_mbinit, NULL);
984263bc
MD
318
319/* "number of clusters of pages" */
320#define NCL_INIT 1
321
322#define NMB_INIT 16
323
7b6f875f
JH
324/*
325 * The mbuf object cache only guarantees that m_next and m_nextpkt are
326 * NULL and that m_data points to the beginning of the data area. In
327 * particular, m_len and m_pkthdr.len are uninitialized. It is the
328 * responsibility of the caller to initialize those fields before use.
329 */
330
331static boolean_t __inline
332mbuf_ctor(void *obj, void *private, int ocflags)
984263bc 333{
7b6f875f 334 struct mbuf *m = obj;
984263bc 335
7b6f875f
JH
336 m->m_next = NULL;
337 m->m_nextpkt = NULL;
338 m->m_data = m->m_dat;
339 m->m_flags = 0;
340
341 return (TRUE);
984263bc
MD
342}
343
344/*
7b6f875f 345 * Initialize the mbuf and the packet header fields.
984263bc 346 */
7b6f875f
JH
347static boolean_t
348mbufphdr_ctor(void *obj, void *private, int ocflags)
984263bc 349{
7b6f875f 350 struct mbuf *m = obj;
984263bc 351
7b6f875f
JH
352 m->m_next = NULL;
353 m->m_nextpkt = NULL;
354 m->m_data = m->m_pktdat;
77e294a1 355 m->m_flags = M_PKTHDR | M_PHCACHE;
984263bc 356
7b6f875f
JH
357 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
358 SLIST_INIT(&m->m_pkthdr.tags);
359 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
360 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
361
362 return (TRUE);
984263bc
MD
363}
364
365/*
7b6f875f 366 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
984263bc 367 */
7b6f875f
JH
368static boolean_t
369mclmeta_ctor(void *obj, void *private, int ocflags)
984263bc 370{
7b6f875f
JH
371 struct mbcluster *cl = obj;
372 void *buf;
373
374 if (ocflags & M_NOWAIT)
efda3bd0 375 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
7b6f875f 376 else
efda3bd0 377 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
7b6f875f
JH
378 if (buf == NULL)
379 return (FALSE);
77e294a1 380 cl->mcl_refs = 0;
7b6f875f 381 cl->mcl_data = buf;
df8d1020 382 lwkt_serialize_init(&cl->mcl_serializer);
7b6f875f
JH
383 return (TRUE);
384}
984263bc 385
c3ef87ca
MD
386static void
387mclmeta_dtor(void *obj, void *private)
388{
389 struct mbcluster *mcl = obj;
390
391 KKASSERT(mcl->mcl_refs == 0);
efda3bd0 392 kfree(mcl->mcl_data, M_MBUFCL);
c3ef87ca
MD
393}
394
7b6f875f
JH
395static void
396linkcluster(struct mbuf *m, struct mbcluster *cl)
397{
984263bc 398 /*
7b6f875f
JH
399 * Add the cluster to the mbuf. The caller will detect that the
400 * mbuf now has an attached cluster.
984263bc 401 */
7b6f875f
JH
402 m->m_ext.ext_arg = cl;
403 m->m_ext.ext_buf = cl->mcl_data;
404 m->m_ext.ext_ref = m_mclref;
405 m->m_ext.ext_free = m_mclfree;
406 m->m_ext.ext_size = MCLBYTES;
df8d1020 407 atomic_add_int(&cl->mcl_refs, 1);
984263bc 408
7b6f875f
JH
409 m->m_data = m->m_ext.ext_buf;
410 m->m_flags |= M_EXT | M_EXT_CLUSTER;
984263bc
MD
411}
412
7b6f875f
JH
413static boolean_t
414mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
415{
416 struct mbuf *m = obj;
417 struct mbcluster *cl;
418
419 mbufphdr_ctor(obj, private, ocflags);
420 cl = objcache_get(mclmeta_cache, ocflags);
421 if (cl == NULL)
422 return (FALSE);
77e294a1 423 m->m_flags |= M_CLCACHE;
7b6f875f
JH
424 linkcluster(m, cl);
425 return (TRUE);
426}
984263bc 427
7b6f875f
JH
428static boolean_t
429mbufcluster_ctor(void *obj, void *private, int ocflags)
984263bc 430{
7b6f875f
JH
431 struct mbuf *m = obj;
432 struct mbcluster *cl;
433
434 mbuf_ctor(obj, private, ocflags);
435 cl = objcache_get(mclmeta_cache, ocflags);
436 if (cl == NULL)
437 return (FALSE);
77e294a1 438 m->m_flags |= M_CLCACHE;
7b6f875f
JH
439 linkcluster(m, cl);
440 return (TRUE);
441}
984263bc 442
77e294a1
MD
443/*
444 * Used for both the cluster and cluster PHDR caches.
445 *
446 * The mbuf may have lost its cluster due to sharing, deal
447 * with the situation by checking M_EXT.
448 */
7b6f875f
JH
449static void
450mbufcluster_dtor(void *obj, void *private)
984263bc 451{
7b6f875f 452 struct mbuf *m = obj;
77e294a1 453 struct mbcluster *mcl;
984263bc 454
77e294a1
MD
455 if (m->m_flags & M_EXT) {
456 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
457 mcl = m->m_ext.ext_arg;
458 KKASSERT(mcl->mcl_refs == 1);
459 mcl->mcl_refs = 0;
460 objcache_put(mclmeta_cache, mcl);
461 }
984263bc
MD
462}
463
7b6f875f
JH
464struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
465struct objcache_malloc_args mclmeta_malloc_args =
466 { sizeof(struct mbcluster), M_MCLMETA };
467
468/* ARGSUSED*/
90775e29 469static void
7b6f875f 470mbinit(void *dummy)
984263bc 471{
7b6f875f
JH
472 mbstat.m_msize = MSIZE;
473 mbstat.m_mclbytes = MCLBYTES;
474 mbstat.m_minclsize = MINCLSIZE;
475 mbstat.m_mlen = MLEN;
476 mbstat.m_mhlen = MHLEN;
984263bc 477
7b6f875f 478 mbuf_cache = objcache_create("mbuf", nmbufs, 0,
5b7da64a 479 mbuf_ctor, NULL, NULL,
7b6f875f
JH
480 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
481 mbufphdr_cache = objcache_create("mbuf pkt hdr", nmbufs, 64,
5b7da64a 482 mbufphdr_ctor, NULL, NULL,
7b6f875f
JH
483 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
484 mclmeta_cache = objcache_create("cluster mbuf", nmbclusters , 0,
485 mclmeta_ctor, mclmeta_dtor, NULL,
486 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
487 mbufcluster_cache = objcache_create("mbuf + cluster", nmbclusters, 0,
488 mbufcluster_ctor, mbufcluster_dtor, NULL,
489 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
490 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
77e294a1 491 nmbclusters, 64, mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
7b6f875f
JH
492 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
493 return;
90775e29 494}
984263bc 495
90775e29
MD
496/*
497 * Return the number of references to this mbuf's data. 0 is returned
498 * if the mbuf is not M_EXT, a reference count is returned if it is
7b6f875f 499 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
90775e29
MD
500 */
501int
502m_sharecount(struct mbuf *m)
503{
7b6f875f
JH
504 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
505 case 0:
506 return (0);
507 case M_EXT:
508 return (99);
509 case M_EXT | M_EXT_CLUSTER:
510 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
511 }
512 /* NOTREACHED */
513 return (0); /* to shut up compiler */
90775e29
MD
514}
515
516/*
517 * change mbuf to new type
518 */
519void
520m_chtype(struct mbuf *m, int type)
521{
c6339e39 522 crit_enter();
90775e29 523 ++mbtypes[type];
87b85c14
MD
524 --mbtypes[m->m_type];
525 m->m_type = type;
c6339e39 526 crit_exit();
984263bc
MD
527}
528
984263bc 529static void
8a3125c6 530m_reclaim(void)
984263bc 531{
1fd87d54
RG
532 struct domain *dp;
533 struct protosw *pr;
984263bc 534
c6339e39 535 crit_enter();
9c70fe43 536 SLIST_FOREACH(dp, &domains, dom_next) {
8a3125c6 537 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
984263bc
MD
538 if (pr->pr_drain)
539 (*pr->pr_drain)();
8a3125c6
MD
540 }
541 }
c6339e39 542 crit_exit();
984263bc
MD
543 mbstat.m_drain++;
544}
545
7b6f875f
JH
546static void __inline
547updatestats(struct mbuf *m, int type)
548{
549 m->m_type = type;
550
551 crit_enter();
e9fa4b60 552 mbuftrack(m);
7b6f875f
JH
553 ++mbtypes[type];
554 ++mbstat.m_mbufs;
555 crit_exit();
556}
557
984263bc 558/*
7b6f875f 559 * Allocate an mbuf.
984263bc
MD
560 */
561struct mbuf *
8a3125c6 562m_get(int how, int type)
984263bc 563{
12496bdf 564 struct mbuf *m;
7b6f875f
JH
565 int ntries = 0;
566 int ocf = MBTOM(how);
12496bdf 567
7b6f875f
JH
568retryonce:
569
570 m = objcache_get(mbuf_cache, ocf);
571
572 if (m == NULL) {
573 if ((how & MB_TRYWAIT) && ntries++ == 0) {
574 struct objcache *reclaimlist[] = {
575 mbufphdr_cache,
576 mbufcluster_cache, mbufphdrcluster_cache
577 };
578 const int nreclaims = __arysize(reclaimlist);
579
580 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
581 m_reclaim();
582 goto retryonce;
c6339e39 583 }
7b6f875f 584 return (NULL);
12496bdf 585 }
c6339e39 586
7b6f875f 587 updatestats(m, type);
984263bc
MD
588 return (m);
589}
590
591struct mbuf *
8a3125c6 592m_gethdr(int how, int type)
984263bc 593{
12496bdf 594 struct mbuf *m;
7b6f875f
JH
595 int ocf = MBTOM(how);
596 int ntries = 0;
12496bdf 597
7b6f875f
JH
598retryonce:
599
600 m = objcache_get(mbufphdr_cache, ocf);
601
602 if (m == NULL) {
603 if ((how & MB_TRYWAIT) && ntries++ == 0) {
604 struct objcache *reclaimlist[] = {
605 mbuf_cache,
606 mbufcluster_cache, mbufphdrcluster_cache
607 };
608 const int nreclaims = __arysize(reclaimlist);
609
610 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
611 m_reclaim();
612 goto retryonce;
c6339e39 613 }
7b6f875f 614 return (NULL);
12496bdf 615 }
c6339e39 616
7b6f875f 617 updatestats(m, type);
984263bc
MD
618 return (m);
619}
620
7b6f875f
JH
621/*
622 * Get a mbuf (not a mbuf cluster!) and zero it.
623 * Deprecated.
624 */
984263bc 625struct mbuf *
8a3125c6 626m_getclr(int how, int type)
984263bc 627{
1fd87d54 628 struct mbuf *m;
984263bc 629
7b6f875f
JH
630 m = m_get(how, type);
631 if (m != NULL)
632 bzero(m->m_data, MLEN);
984263bc
MD
633 return (m);
634}
635
636/*
7b6f875f 637 * Returns an mbuf with an attached cluster.
984263bc
MD
638 * Because many network drivers use this kind of buffers a lot, it is
639 * convenient to keep a small pool of free buffers of this kind.
640 * Even a small size such as 10 gives about 10% improvement in the
641 * forwarding rate in a bridge or router.
984263bc 642 */
984263bc
MD
643struct mbuf *
644m_getcl(int how, short type, int flags)
645{
7b6f875f
JH
646 struct mbuf *m;
647 int ocflags = MBTOM(how);
648 int ntries = 0;
984263bc 649
7b6f875f
JH
650retryonce:
651
652 if (flags & M_PKTHDR)
653 m = objcache_get(mbufphdrcluster_cache, ocflags);
654 else
655 m = objcache_get(mbufcluster_cache, ocflags);
656
657 if (m == NULL) {
658 if ((how & MB_TRYWAIT) && ntries++ == 0) {
659 struct objcache *reclaimlist[1];
660
661 if (flags & M_PKTHDR)
662 reclaimlist[0] = mbufcluster_cache;
663 else
664 reclaimlist[0] = mbufphdrcluster_cache;
665 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
666 m_reclaim();
667 goto retryonce;
984263bc 668 }
7b6f875f 669 return (NULL);
984263bc 670 }
7b6f875f
JH
671
672 m->m_type = type;
673
674 crit_enter();
e9fa4b60 675 mbuftrack(m);
7b6f875f
JH
676 ++mbtypes[type];
677 ++mbstat.m_clusters;
c6339e39 678 crit_exit();
7b6f875f 679 return (m);
984263bc
MD
680}
681
682/*
50503f0f
JH
683 * Allocate chain of requested length.
684 */
685struct mbuf *
686m_getc(int len, int how, int type)
687{
688 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
689 int nsize;
690
691 while (len > 0) {
692 n = m_getl(len, how, type, 0, &nsize);
693 if (n == NULL)
694 goto failed;
695 n->m_len = 0;
696 *ntail = n;
697 ntail = &n->m_next;
698 len -= nsize;
699 }
700 return (nfirst);
701
702failed:
703 m_freem(nfirst);
704 return (NULL);
705}
706
707/*
708 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
709 * and return a pointer to the head of the allocated chain. If m0 is
984263bc
MD
710 * non-null, then we assume that it is a single mbuf or an mbuf chain to
711 * which we want len bytes worth of mbufs and/or clusters attached, and so
50503f0f 712 * if we succeed in allocating it, we will just return a pointer to m0.
984263bc
MD
713 *
714 * If we happen to fail at any point during the allocation, we will free
715 * up everything we have already allocated and return NULL.
716 *
50503f0f 717 * Deprecated. Use m_getc() and m_cat() instead.
984263bc
MD
718 */
719struct mbuf *
dc14b0a9 720m_getm(struct mbuf *m0, int len, int type, int how)
984263bc 721{
50503f0f 722 struct mbuf *nfirst;
984263bc 723
50503f0f 724 nfirst = m_getc(len, how, type);
984263bc 725
50503f0f
JH
726 if (m0 != NULL) {
727 m_last(m0)->m_next = nfirst;
728 return (m0);
984263bc
MD
729 }
730
50503f0f 731 return (nfirst);
984263bc
MD
732}
733
734/*
7b6f875f
JH
735 * Adds a cluster to a normal mbuf, M_EXT is set on success.
736 * Deprecated. Use m_getcl() instead.
b6650ec0 737 */
90775e29
MD
738void
739m_mclget(struct mbuf *m, int how)
b6650ec0 740{
7b6f875f 741 struct mbcluster *mcl;
b6650ec0 742
77e294a1 743 KKASSERT((m->m_flags & M_EXT) == 0);
7b6f875f 744 mcl = objcache_get(mclmeta_cache, MBTOM(how));
c3ef87ca
MD
745 if (mcl != NULL) {
746 linkcluster(m, mcl);
747 crit_enter();
748 ++mbstat.m_clusters;
749 /* leave the m_mbufs count intact for original mbuf */
750 crit_exit();
751 }
b6650ec0
MD
752}
753
df8d1020
MD
754/*
755 * Updates to mbcluster must be MPSAFE. Only an entity which already has
756 * a reference to the cluster can ref it, so we are in no danger of
757 * racing an add with a subtract. But the operation must still be atomic
758 * since multiple entities may have a reference on the cluster.
759 *
760 * m_mclfree() is almost the same but it must contend with two entities
761 * freeing the cluster at the same time. If there is only one reference
762 * count we are the only entity referencing the cluster and no further
763 * locking is required. Otherwise we must protect against a race to 0
764 * with the serializer.
765 */
90775e29 766static void
7b6f875f 767m_mclref(void *arg)
b6650ec0 768{
7b6f875f 769 struct mbcluster *mcl = arg;
90775e29 770
7b6f875f 771 atomic_add_int(&mcl->mcl_refs, 1);
b6650ec0
MD
772}
773
90775e29 774static void
7b6f875f 775m_mclfree(void *arg)
b6650ec0 776{
7b6f875f 777 struct mbcluster *mcl = arg;
90775e29 778
df8d1020 779 if (mcl->mcl_refs == 1) {
77e294a1
MD
780 mcl->mcl_refs = 0;
781 objcache_put(mclmeta_cache, mcl);
df8d1020
MD
782 } else {
783 lwkt_serialize_enter(&mcl->mcl_serializer);
784 if (mcl->mcl_refs > 1) {
785 atomic_subtract_int(&mcl->mcl_refs, 1);
786 lwkt_serialize_exit(&mcl->mcl_serializer);
787 } else {
788 lwkt_serialize_exit(&mcl->mcl_serializer);
789 KKASSERT(mcl->mcl_refs == 1);
790 mcl->mcl_refs = 0;
791 objcache_put(mclmeta_cache, mcl);
792 }
77e294a1 793 }
b6650ec0
MD
794}
795
7b6f875f 796extern void db_print_backtrace(void);
7eccf245 797
b6650ec0 798/*
b6650ec0
MD
799 * Free a single mbuf and any associated external storage. The successor,
800 * if any, is returned.
984263bc 801 *
b6650ec0 802 * We do need to check non-first mbuf for m_aux, since some of existing
984263bc
MD
803 * code does not call M_PREPEND properly.
804 * (example: call to bpf_mtap from drivers)
805 */
984263bc 806struct mbuf *
b6650ec0 807m_free(struct mbuf *m)
984263bc 808{
b6650ec0
MD
809 struct mbuf *n;
810
361af367 811 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
7b6f875f 812 --mbtypes[m->m_type];
90775e29 813
7b6f875f 814 n = m->m_next;
90775e29
MD
815
816 /*
7b6f875f
JH
817 * Make sure the mbuf is in constructed state before returning it
818 * to the objcache.
90775e29 819 */
90775e29 820 m->m_next = NULL;
e9fa4b60 821 mbufuntrack(m);
7b6f875f
JH
822#ifdef notyet
823 KKASSERT(m->m_nextpkt == NULL);
824#else
825 if (m->m_nextpkt != NULL) {
826#ifdef DDB
827 static int afewtimes = 10;
828
829 if (afewtimes-- > 0) {
6ea70f76 830 kprintf("mfree: m->m_nextpkt != NULL\n");
7b6f875f 831 db_print_backtrace();
90775e29 832 }
7b6f875f
JH
833#endif
834 m->m_nextpkt = NULL;
835 }
836#endif
837 if (m->m_flags & M_PKTHDR) {
7b6f875f 838 m_tag_delete_chain(m); /* eliminate XXX JH */
77e294a1
MD
839 }
840
841 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
842
843 /*
844 * Clean the M_PKTHDR state so we can return the mbuf to its original
845 * cache. This is based on the PHCACHE flag which tells us whether
846 * the mbuf was originally allocated out of a packet-header cache
847 * or a non-packet-header cache.
848 */
849 if (m->m_flags & M_PHCACHE) {
850 m->m_flags |= M_PKTHDR;
851 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
7b6f875f
JH
852 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
853 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
6b1d6bed 854 SLIST_INIT(&m->m_pkthdr.tags);
90775e29 855 }
7b6f875f 856
77e294a1
MD
857 /*
858 * Handle remaining flags combinations. M_CLCACHE tells us whether
859 * the mbuf was originally allocated from a cluster cache or not,
860 * and is totally separate from whether the mbuf is currently
861 * associated with a cluster.
862 */
863 crit_enter();
864 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
865 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
866 /*
867 * mbuf+cluster cache case. The mbuf was allocated from the
868 * combined mbuf_cluster cache and can be returned to the
869 * cache if the cluster hasn't been shared.
870 */
871 if (m_sharecount(m) == 1) {
872 /*
873 * The cluster has not been shared, we can just
874 * reset the data pointer and return the mbuf
875 * to the cluster cache. Note that the reference
876 * count is left intact (it is still associated with
877 * an mbuf).
878 */
879 m->m_data = m->m_ext.ext_buf;
880 if (m->m_flags & M_PHCACHE)
881 objcache_put(mbufphdrcluster_cache, m);
882 else
883 objcache_put(mbufcluster_cache, m);
cb086467 884 --mbstat.m_clusters;
77e294a1
MD
885 } else {
886 /*
887 * Hell. Someone else has a ref on this cluster,
888 * we have to disconnect it which means we can't
889 * put it back into the mbufcluster_cache, we
890 * have to destroy the mbuf.
891 *
cb086467
MD
892 * Other mbuf references to the cluster will typically
893 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
894 *
77e294a1
MD
895 * XXX we could try to connect another cluster to
896 * it.
897 */
7b6f875f
JH
898 m->m_ext.ext_free(m->m_ext.ext_arg);
899 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
77e294a1
MD
900 if (m->m_flags & M_PHCACHE)
901 objcache_dtor(mbufphdrcluster_cache, m);
902 else
903 objcache_dtor(mbufcluster_cache, m);
7b6f875f 904 }
77e294a1
MD
905 break;
906 case M_EXT | M_EXT_CLUSTER:
907 /*
908 * Normal cluster associated with an mbuf that was allocated
909 * from the normal mbuf pool rather then the cluster pool.
910 * The cluster has to be independantly disassociated from the
911 * mbuf.
912 */
cb086467
MD
913 if (m_sharecount(m) == 1)
914 --mbstat.m_clusters;
77e294a1
MD
915 /* fall through */
916 case M_EXT:
917 /*
918 * Normal cluster association case, disconnect the cluster from
919 * the mbuf. The cluster may or may not be custom.
920 */
921 m->m_ext.ext_free(m->m_ext.ext_arg);
922 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
923 /* fall through */
924 case 0:
925 /*
926 * return the mbuf to the mbuf cache.
927 */
928 if (m->m_flags & M_PHCACHE) {
7b6f875f
JH
929 m->m_data = m->m_pktdat;
930 objcache_put(mbufphdr_cache, m);
90775e29 931 } else {
7b6f875f
JH
932 m->m_data = m->m_dat;
933 objcache_put(mbuf_cache, m);
90775e29 934 }
7b6f875f 935 --mbstat.m_mbufs;
77e294a1
MD
936 break;
937 default:
938 if (!panicstr)
939 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
940 break;
b6650ec0 941 }
77e294a1 942 crit_exit();
984263bc
MD
943 return (n);
944}
945
946void
b6650ec0 947m_freem(struct mbuf *m)
984263bc 948{
c6339e39 949 crit_enter();
90775e29
MD
950 while (m)
951 m = m_free(m);
c6339e39 952 crit_exit();
984263bc
MD
953}
954
955/*
df80f2ea 956 * mbuf utility routines
984263bc
MD
957 */
958
959/*
7b6f875f 960 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
984263bc
MD
961 * copy junk along.
962 */
963struct mbuf *
8a3125c6 964m_prepend(struct mbuf *m, int len, int how)
984263bc
MD
965{
966 struct mbuf *mn;
967
c3ef87ca
MD
968 if (m->m_flags & M_PKTHDR)
969 mn = m_gethdr(how, m->m_type);
970 else
971 mn = m_get(how, m->m_type);
7b6f875f 972 if (mn == NULL) {
984263bc 973 m_freem(m);
7b6f875f 974 return (NULL);
984263bc
MD
975 }
976 if (m->m_flags & M_PKTHDR)
977 M_MOVE_PKTHDR(mn, m);
978 mn->m_next = m;
979 m = mn;
980 if (len < MHLEN)
981 MH_ALIGN(m, len);
982 m->m_len = len;
983 return (m);
984}
985
986/*
987 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
988 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
74f1caca 989 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
984263bc
MD
990 * Note that the copy is read-only, because clusters are not copied,
991 * only their reference counts are incremented.
992 */
984263bc 993struct mbuf *
8a3125c6 994m_copym(const struct mbuf *m, int off0, int len, int wait)
984263bc 995{
1fd87d54
RG
996 struct mbuf *n, **np;
997 int off = off0;
984263bc
MD
998 struct mbuf *top;
999 int copyhdr = 0;
1000
1001 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1002 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1003 if (off == 0 && m->m_flags & M_PKTHDR)
1004 copyhdr = 1;
1005 while (off > 0) {
1006 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1007 if (off < m->m_len)
1008 break;
1009 off -= m->m_len;
1010 m = m->m_next;
1011 }
1012 np = &top;
1013 top = 0;
1014 while (len > 0) {
7b6f875f 1015 if (m == NULL) {
984263bc
MD
1016 KASSERT(len == M_COPYALL,
1017 ("m_copym, length > size of mbuf chain"));
1018 break;
1019 }
c3ef87ca
MD
1020 /*
1021 * Because we are sharing any cluster attachment below,
1022 * be sure to get an mbuf that does not have a cluster
1023 * associated with it.
1024 */
1025 if (copyhdr)
1026 n = m_gethdr(wait, m->m_type);
1027 else
1028 n = m_get(wait, m->m_type);
984263bc 1029 *np = n;
7b6f875f 1030 if (n == NULL)
984263bc
MD
1031 goto nospace;
1032 if (copyhdr) {
1033 if (!m_dup_pkthdr(n, m, wait))
1034 goto nospace;
1035 if (len == M_COPYALL)
1036 n->m_pkthdr.len -= off0;
1037 else
1038 n->m_pkthdr.len = len;
1039 copyhdr = 0;
1040 }
1041 n->m_len = min(len, m->m_len - off);
1042 if (m->m_flags & M_EXT) {
c3ef87ca 1043 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1044 n->m_data = m->m_data + off;
7b6f875f 1045 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1046 n->m_ext = m->m_ext;
b542cd49 1047 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
7eccf245 1048 } else {
984263bc
MD
1049 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1050 (unsigned)n->m_len);
7eccf245 1051 }
984263bc
MD
1052 if (len != M_COPYALL)
1053 len -= n->m_len;
1054 off = 0;
1055 m = m->m_next;
1056 np = &n->m_next;
1057 }
7b6f875f
JH
1058 if (top == NULL)
1059 mbstat.m_mcfail++;
984263bc
MD
1060 return (top);
1061nospace:
1062 m_freem(top);
7b6f875f
JH
1063 mbstat.m_mcfail++;
1064 return (NULL);
984263bc
MD
1065}
1066
1067/*
1068 * Copy an entire packet, including header (which must be present).
1069 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1070 * Note that the copy is read-only, because clusters are not copied,
1071 * only their reference counts are incremented.
1072 * Preserve alignment of the first mbuf so if the creator has left
1073 * some room at the beginning (e.g. for inserting protocol headers)
1074 * the copies also have the room available.
1075 */
1076struct mbuf *
8a3125c6 1077m_copypacket(struct mbuf *m, int how)
984263bc
MD
1078{
1079 struct mbuf *top, *n, *o;
1080
7f3602fe 1081 n = m_gethdr(how, m->m_type);
984263bc
MD
1082 top = n;
1083 if (!n)
1084 goto nospace;
1085
1086 if (!m_dup_pkthdr(n, m, how))
1087 goto nospace;
1088 n->m_len = m->m_len;
1089 if (m->m_flags & M_EXT) {
c3ef87ca 1090 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1091 n->m_data = m->m_data;
7b6f875f 1092 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1093 n->m_ext = m->m_ext;
b542cd49 1094 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1095 } else {
1096 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1097 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1098 }
1099
1100 m = m->m_next;
1101 while (m) {
7b6f875f 1102 o = m_get(how, m->m_type);
984263bc
MD
1103 if (!o)
1104 goto nospace;
1105
1106 n->m_next = o;
1107 n = n->m_next;
1108
1109 n->m_len = m->m_len;
1110 if (m->m_flags & M_EXT) {
c3ef87ca 1111 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1112 n->m_data = m->m_data;
7b6f875f 1113 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1114 n->m_ext = m->m_ext;
b542cd49 1115 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1116 } else {
1117 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1118 }
1119
1120 m = m->m_next;
1121 }
1122 return top;
1123nospace:
1124 m_freem(top);
7b6f875f
JH
1125 mbstat.m_mcfail++;
1126 return (NULL);
984263bc
MD
1127}
1128
1129/*
1130 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1131 * continuing for "len" bytes, into the indicated buffer.
1132 */
1133void
8a3125c6 1134m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
984263bc 1135{
1fd87d54 1136 unsigned count;
984263bc
MD
1137
1138 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1139 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1140 while (off > 0) {
1141 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1142 if (off < m->m_len)
1143 break;
1144 off -= m->m_len;
1145 m = m->m_next;
1146 }
1147 while (len > 0) {
1148 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1149 count = min(m->m_len - off, len);
1150 bcopy(mtod(m, caddr_t) + off, cp, count);
1151 len -= count;
1152 cp += count;
1153 off = 0;
1154 m = m->m_next;
1155 }
1156}
1157
1158/*
1159 * Copy a packet header mbuf chain into a completely new chain, including
1160 * copying any mbuf clusters. Use this instead of m_copypacket() when
1161 * you need a writable copy of an mbuf chain.
1162 */
1163struct mbuf *
8a3125c6 1164m_dup(struct mbuf *m, int how)
984263bc
MD
1165{
1166 struct mbuf **p, *top = NULL;
1167 int remain, moff, nsize;
1168
1169 /* Sanity check */
1170 if (m == NULL)
50503f0f 1171 return (NULL);
5e2195bf 1172 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
984263bc
MD
1173
1174 /* While there's more data, get a new mbuf, tack it on, and fill it */
1175 remain = m->m_pkthdr.len;
1176 moff = 0;
1177 p = &top;
1178 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1179 struct mbuf *n;
1180
1181 /* Get the next new mbuf */
50503f0f
JH
1182 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1183 &nsize);
984263bc
MD
1184 if (n == NULL)
1185 goto nospace;
50503f0f 1186 if (top == NULL)
984263bc 1187 if (!m_dup_pkthdr(n, m, how))
50503f0f 1188 goto nospace0;
984263bc
MD
1189
1190 /* Link it into the new chain */
1191 *p = n;
1192 p = &n->m_next;
1193
1194 /* Copy data from original mbuf(s) into new mbuf */
50503f0f 1195 n->m_len = 0;
984263bc
MD
1196 while (n->m_len < nsize && m != NULL) {
1197 int chunk = min(nsize - n->m_len, m->m_len - moff);
1198
1199 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1200 moff += chunk;
1201 n->m_len += chunk;
1202 remain -= chunk;
1203 if (moff == m->m_len) {
1204 m = m->m_next;
1205 moff = 0;
1206 }
1207 }
1208
1209 /* Check correct total mbuf length */
1210 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
50503f0f 1211 ("%s: bogus m_pkthdr.len", __func__));
984263bc
MD
1212 }
1213 return (top);
1214
1215nospace:
1216 m_freem(top);
50503f0f
JH
1217nospace0:
1218 mbstat.m_mcfail++;
1219 return (NULL);
984263bc
MD
1220}
1221
1222/*
1223 * Concatenate mbuf chain n to m.
1224 * Both chains must be of the same type (e.g. MT_DATA).
1225 * Any m_pkthdr is not updated.
1226 */
1227void
8a3125c6 1228m_cat(struct mbuf *m, struct mbuf *n)
984263bc 1229{
50503f0f 1230 m = m_last(m);
984263bc
MD
1231 while (n) {
1232 if (m->m_flags & M_EXT ||
1233 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1234 /* just join the two chains */
1235 m->m_next = n;
1236 return;
1237 }
1238 /* splat the data from one into the other */
1239 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1240 (u_int)n->m_len);
1241 m->m_len += n->m_len;
1242 n = m_free(n);
1243 }
1244}
1245
1246void
8a3125c6 1247m_adj(struct mbuf *mp, int req_len)
984263bc 1248{
1fd87d54
RG
1249 int len = req_len;
1250 struct mbuf *m;
1251 int count;
984263bc
MD
1252
1253 if ((m = mp) == NULL)
1254 return;
1255 if (len >= 0) {
1256 /*
1257 * Trim from head.
1258 */
1259 while (m != NULL && len > 0) {
1260 if (m->m_len <= len) {
1261 len -= m->m_len;
1262 m->m_len = 0;
1263 m = m->m_next;
1264 } else {
1265 m->m_len -= len;
1266 m->m_data += len;
1267 len = 0;
1268 }
1269 }
1270 m = mp;
1271 if (mp->m_flags & M_PKTHDR)
1272 m->m_pkthdr.len -= (req_len - len);
1273 } else {
1274 /*
1275 * Trim from tail. Scan the mbuf chain,
1276 * calculating its length and finding the last mbuf.
1277 * If the adjustment only affects this mbuf, then just
1278 * adjust and return. Otherwise, rescan and truncate
1279 * after the remaining size.
1280 */
1281 len = -len;
1282 count = 0;
1283 for (;;) {
1284 count += m->m_len;
1285 if (m->m_next == (struct mbuf *)0)
1286 break;
1287 m = m->m_next;
1288 }
1289 if (m->m_len >= len) {
1290 m->m_len -= len;
1291 if (mp->m_flags & M_PKTHDR)
1292 mp->m_pkthdr.len -= len;
1293 return;
1294 }
1295 count -= len;
1296 if (count < 0)
1297 count = 0;
1298 /*
1299 * Correct length for chain is "count".
1300 * Find the mbuf with last data, adjust its length,
1301 * and toss data from remaining mbufs on chain.
1302 */
1303 m = mp;
1304 if (m->m_flags & M_PKTHDR)
1305 m->m_pkthdr.len = count;
1306 for (; m; m = m->m_next) {
1307 if (m->m_len >= count) {
1308 m->m_len = count;
1309 break;
1310 }
1311 count -= m->m_len;
1312 }
1313 while (m->m_next)
1314 (m = m->m_next) ->m_len = 0;
1315 }
1316}
1317
1318/*
7b6f875f 1319 * Rearrange an mbuf chain so that len bytes are contiguous
9e4465af
MD
1320 * and in the data area of an mbuf (so that mtod will work for a structure
1321 * of size len). Returns the resulting mbuf chain on success, frees it and
1322 * returns null on failure. If there is room, it will add up to
1323 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1324 * avoid being called next time.
984263bc 1325 */
984263bc 1326struct mbuf *
8a3125c6 1327m_pullup(struct mbuf *n, int len)
984263bc 1328{
1fd87d54
RG
1329 struct mbuf *m;
1330 int count;
984263bc
MD
1331 int space;
1332
1333 /*
1334 * If first mbuf has no cluster, and has room for len bytes
1335 * without shifting current data, pullup into it,
1336 * otherwise allocate a new mbuf to prepend to the chain.
1337 */
7b6f875f
JH
1338 if (!(n->m_flags & M_EXT) &&
1339 n->m_data + len < &n->m_dat[MLEN] &&
1340 n->m_next) {
984263bc
MD
1341 if (n->m_len >= len)
1342 return (n);
1343 m = n;
1344 n = n->m_next;
1345 len -= m->m_len;
1346 } else {
1347 if (len > MHLEN)
1348 goto bad;
c3ef87ca
MD
1349 if (n->m_flags & M_PKTHDR)
1350 m = m_gethdr(MB_DONTWAIT, n->m_type);
1351 else
1352 m = m_get(MB_DONTWAIT, n->m_type);
7b6f875f 1353 if (m == NULL)
984263bc
MD
1354 goto bad;
1355 m->m_len = 0;
1356 if (n->m_flags & M_PKTHDR)
1357 M_MOVE_PKTHDR(m, n);
1358 }
1359 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1360 do {
1361 count = min(min(max(len, max_protohdr), space), n->m_len);
1362 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1363 (unsigned)count);
1364 len -= count;
1365 m->m_len += count;
1366 n->m_len -= count;
1367 space -= count;
1368 if (n->m_len)
1369 n->m_data += count;
1370 else
1371 n = m_free(n);
1372 } while (len > 0 && n);
1373 if (len > 0) {
7b6f875f 1374 m_free(m);
984263bc
MD
1375 goto bad;
1376 }
1377 m->m_next = n;
1378 return (m);
1379bad:
1380 m_freem(n);
7b6f875f
JH
1381 mbstat.m_mpfail++;
1382 return (NULL);
984263bc
MD
1383}
1384
1385/*
1386 * Partition an mbuf chain in two pieces, returning the tail --
1387 * all but the first len0 bytes. In case of failure, it returns NULL and
1388 * attempts to restore the chain to its original state.
1389 *
1390 * Note that the resulting mbufs might be read-only, because the new
1391 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1392 * the "breaking point" happens to lie within a cluster mbuf. Use the
1393 * M_WRITABLE() macro to check for this case.
1394 */
1395struct mbuf *
8a3125c6 1396m_split(struct mbuf *m0, int len0, int wait)
984263bc 1397{
1fd87d54 1398 struct mbuf *m, *n;
984263bc
MD
1399 unsigned len = len0, remain;
1400
1401 for (m = m0; m && len > m->m_len; m = m->m_next)
1402 len -= m->m_len;
7b6f875f
JH
1403 if (m == NULL)
1404 return (NULL);
984263bc
MD
1405 remain = m->m_len - len;
1406 if (m0->m_flags & M_PKTHDR) {
7b6f875f
JH
1407 n = m_gethdr(wait, m0->m_type);
1408 if (n == NULL)
1409 return (NULL);
984263bc
MD
1410 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1411 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1412 m0->m_pkthdr.len = len0;
1413 if (m->m_flags & M_EXT)
1414 goto extpacket;
1415 if (remain > MHLEN) {
1416 /* m can't be the lead packet */
1417 MH_ALIGN(n, 0);
1418 n->m_next = m_split(m, len, wait);
7b6f875f
JH
1419 if (n->m_next == NULL) {
1420 m_free(n);
1421 return (NULL);
984263bc
MD
1422 } else {
1423 n->m_len = 0;
1424 return (n);
1425 }
1426 } else
1427 MH_ALIGN(n, remain);
1428 } else if (remain == 0) {
1429 n = m->m_next;
1430 m->m_next = 0;
1431 return (n);
1432 } else {
7b6f875f
JH
1433 n = m_get(wait, m->m_type);
1434 if (n == NULL)
1435 return (NULL);
984263bc
MD
1436 M_ALIGN(n, remain);
1437 }
1438extpacket:
1439 if (m->m_flags & M_EXT) {
c3ef87ca 1440 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1441 n->m_data = m->m_data + len;
7b6f875f 1442 m->m_ext.ext_ref(m->m_ext.ext_arg);
7eccf245 1443 n->m_ext = m->m_ext;
b542cd49 1444 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1445 } else {
1446 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1447 }
1448 n->m_len = remain;
1449 m->m_len = len;
1450 n->m_next = m->m_next;
1451 m->m_next = 0;
1452 return (n);
1453}
50503f0f 1454
984263bc
MD
1455/*
1456 * Routine to copy from device local memory into mbufs.
50503f0f 1457 * Note: "offset" is ill-defined and always called as 0, so ignore it.
984263bc
MD
1458 */
1459struct mbuf *
50503f0f
JH
1460m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1461 void (*copy)(volatile const void *from, volatile void *to, size_t length))
984263bc 1462{
50503f0f
JH
1463 struct mbuf *m, *mfirst = NULL, **mtail;
1464 int nsize, flags;
1465
1466 if (copy == NULL)
1467 copy = bcopy;
1468 mtail = &mfirst;
1469 flags = M_PKTHDR;
1470
1471 while (len > 0) {
1472 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1473 if (m == NULL) {
1474 m_freem(mfirst);
1475 return (NULL);
984263bc 1476 }
50503f0f
JH
1477 m->m_len = min(len, nsize);
1478
1479 if (flags & M_PKTHDR) {
1480 if (len + max_linkhdr <= nsize)
1481 m->m_data += max_linkhdr;
1482 m->m_pkthdr.rcvif = ifp;
1483 m->m_pkthdr.len = len;
1484 flags = 0;
984263bc 1485 }
50503f0f
JH
1486
1487 copy(buf, m->m_data, (unsigned)m->m_len);
1488 buf += m->m_len;
1489 len -= m->m_len;
1490 *mtail = m;
1491 mtail = &m->m_next;
984263bc 1492 }
50503f0f
JH
1493
1494 return (mfirst);
984263bc
MD
1495}
1496
1497/*
1498 * Copy data from a buffer back into the indicated mbuf chain,
1499 * starting "off" bytes from the beginning, extending the mbuf
1500 * chain if necessary.
1501 */
1502void
8a3125c6 1503m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
984263bc 1504{
1fd87d54
RG
1505 int mlen;
1506 struct mbuf *m = m0, *n;
984263bc
MD
1507 int totlen = 0;
1508
7b6f875f 1509 if (m0 == NULL)
984263bc
MD
1510 return;
1511 while (off > (mlen = m->m_len)) {
1512 off -= mlen;
1513 totlen += mlen;
7b6f875f 1514 if (m->m_next == NULL) {
74f1caca 1515 n = m_getclr(MB_DONTWAIT, m->m_type);
7b6f875f 1516 if (n == NULL)
984263bc
MD
1517 goto out;
1518 n->m_len = min(MLEN, len + off);
1519 m->m_next = n;
1520 }
1521 m = m->m_next;
1522 }
1523 while (len > 0) {
1524 mlen = min (m->m_len - off, len);
1525 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1526 cp += mlen;
1527 len -= mlen;
1528 mlen += off;
1529 off = 0;
1530 totlen += mlen;
1531 if (len == 0)
1532 break;
7b6f875f 1533 if (m->m_next == NULL) {
74f1caca 1534 n = m_get(MB_DONTWAIT, m->m_type);
7b6f875f 1535 if (n == NULL)
984263bc
MD
1536 break;
1537 n->m_len = min(MLEN, len);
1538 m->m_next = n;
1539 }
1540 m = m->m_next;
1541 }
1542out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1543 m->m_pkthdr.len = totlen;
1544}
1545
1546void
1547m_print(const struct mbuf *m)
1548{
1549 int len;
1550 const struct mbuf *m2;
1551
1552 len = m->m_pkthdr.len;
1553 m2 = m;
1554 while (len) {
6ea70f76 1555 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
984263bc
MD
1556 len -= m2->m_len;
1557 m2 = m2->m_next;
1558 }
1559 return;
1560}
1561
1562/*
1563 * "Move" mbuf pkthdr from "from" to "to".
1564 * "from" must have M_PKTHDR set, and "to" must be empty.
1565 */
1566void
1567m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1568{
e0d05288 1569 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
984263bc 1570
77e294a1 1571 to->m_flags |= from->m_flags & M_COPYFLAGS;
984263bc
MD
1572 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1573 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
984263bc
MD
1574}
1575
1576/*
1577 * Duplicate "from"'s mbuf pkthdr in "to".
1578 * "from" must have M_PKTHDR set, and "to" must be empty.
1579 * In particular, this does a deep copy of the packet tags.
1580 */
1581int
f15db79e 1582m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
984263bc 1583{
7f3602fe
JH
1584 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
1585
4bac35fc 1586 to->m_flags = (from->m_flags & M_COPYFLAGS) |
c4da22e4 1587 (to->m_flags & ~M_COPYFLAGS);
984263bc
MD
1588 to->m_pkthdr = from->m_pkthdr;
1589 SLIST_INIT(&to->m_pkthdr.tags);
1590 return (m_tag_copy_chain(to, from, how));
1591}
1592
1593/*
1594 * Defragment a mbuf chain, returning the shortest possible
1595 * chain of mbufs and clusters. If allocation fails and
1596 * this cannot be completed, NULL will be returned, but
1597 * the passed in chain will be unchanged. Upon success,
1598 * the original chain will be freed, and the new chain
1599 * will be returned.
1600 *
1601 * If a non-packet header is passed in, the original
1602 * mbuf (chain?) will be returned unharmed.
c8f5127a
JS
1603 *
1604 * m_defrag_nofree doesn't free the passed in mbuf.
984263bc
MD
1605 */
1606struct mbuf *
1607m_defrag(struct mbuf *m0, int how)
c8f5127a
JS
1608{
1609 struct mbuf *m_new;
1610
1611 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1612 return (NULL);
1613 if (m_new != m0)
1614 m_freem(m0);
1615 return (m_new);
1616}
1617
1618struct mbuf *
1619m_defrag_nofree(struct mbuf *m0, int how)
984263bc
MD
1620{
1621 struct mbuf *m_new = NULL, *m_final = NULL;
61721e90 1622 int progress = 0, length, nsize;
984263bc
MD
1623
1624 if (!(m0->m_flags & M_PKTHDR))
1625 return (m0);
1626
1627#ifdef MBUF_STRESS_TEST
1628 if (m_defragrandomfailures) {
0ced1954 1629 int temp = karc4random() & 0xff;
984263bc
MD
1630 if (temp == 0xba)
1631 goto nospace;
1632 }
1633#endif
1634
61721e90 1635 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
984263bc
MD
1636 if (m_final == NULL)
1637 goto nospace;
61721e90 1638 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
984263bc
MD
1639
1640 if (m_dup_pkthdr(m_final, m0, how) == NULL)
1641 goto nospace;
1642
1643 m_new = m_final;
1644
1645 while (progress < m0->m_pkthdr.len) {
1646 length = m0->m_pkthdr.len - progress;
1647 if (length > MCLBYTES)
1648 length = MCLBYTES;
1649
1650 if (m_new == NULL) {
61721e90 1651 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
984263bc
MD
1652 if (m_new == NULL)
1653 goto nospace;
1654 }
1655
1656 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1657 progress += length;
1658 m_new->m_len = length;
1659 if (m_new != m_final)
1660 m_cat(m_final, m_new);
1661 m_new = NULL;
1662 }
1663 if (m0->m_next == NULL)
1664 m_defraguseless++;
984263bc 1665 m_defragpackets++;
c8f5127a
JS
1666 m_defragbytes += m_final->m_pkthdr.len;
1667 return (m_final);
984263bc
MD
1668nospace:
1669 m_defragfailure++;
1670 if (m_new)
1671 m_free(m_new);
61721e90 1672 m_freem(m_final);
984263bc
MD
1673 return (NULL);
1674}
0c33f36d
JH
1675
1676/*
1677 * Move data from uio into mbufs.
0c33f36d
JH
1678 */
1679struct mbuf *
e12241e1 1680m_uiomove(struct uio *uio)
0c33f36d 1681{
0c33f36d 1682 struct mbuf *m; /* current working mbuf */
e12241e1
JH
1683 struct mbuf *head = NULL; /* result mbuf chain */
1684 struct mbuf **mp = &head;
1685 int resid = uio->uio_resid, nsize, flags = M_PKTHDR, error;
0c33f36d 1686
0c33f36d 1687 do {
e12241e1 1688 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
61721e90
JH
1689 if (flags) {
1690 m->m_pkthdr.len = 0;
1691 /* Leave room for protocol headers. */
1692 if (resid < MHLEN)
1693 MH_ALIGN(m, resid);
1694 flags = 0;
0c33f36d 1695 }
61721e90
JH
1696 m->m_len = min(nsize, resid);
1697 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
0c33f36d
JH
1698 if (error) {
1699 m_free(m);
1700 goto failed;
1701 }
0c33f36d
JH
1702 *mp = m;
1703 mp = &m->m_next;
61721e90
JH
1704 head->m_pkthdr.len += m->m_len;
1705 resid -= m->m_len;
0c33f36d
JH
1706 } while (resid > 0);
1707
1708 return (head);
1709
1710failed:
61721e90 1711 m_freem(head);
0c33f36d
JH
1712 return (NULL);
1713}
df80f2ea 1714
50503f0f
JH
1715struct mbuf *
1716m_last(struct mbuf *m)
1717{
1718 while (m->m_next)
1719 m = m->m_next;
1720 return (m);
1721}
1722
df80f2ea
JH
1723/*
1724 * Return the number of bytes in an mbuf chain.
1725 * If lastm is not NULL, also return the last mbuf.
1726 */
1727u_int
1728m_lengthm(struct mbuf *m, struct mbuf **lastm)
1729{
1730 u_int len = 0;
1731 struct mbuf *prev = m;
1732
1733 while (m) {
1734 len += m->m_len;
1735 prev = m;
1736 m = m->m_next;
1737 }
1738 if (lastm != NULL)
1739 *lastm = prev;
1740 return (len);
1741}
1742
1743/*
1744 * Like m_lengthm(), except also keep track of mbuf usage.
1745 */
1746u_int
1747m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
1748{
1749 u_int len = 0, mbcnt = 0;
1750 struct mbuf *prev = m;
1751
1752 while (m) {
1753 len += m->m_len;
1754 mbcnt += MSIZE;
1755 if (m->m_flags & M_EXT)
1756 mbcnt += m->m_ext.ext_size;
1757 prev = m;
1758 m = m->m_next;
1759 }
1760 if (lastm != NULL)
1761 *lastm = prev;
1762 *pmbcnt = mbcnt;
1763 return (len);
1764}