kernel - Fix excessive mbuf use in nfs_realign()
[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
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 $
3f98f485 68 * $DragonFly: src/sys/kern/uipc_mbuf.c,v 1.70 2008/11/20 14:21:01 sephe Exp $
984263bc
MD
69 */
70
71#include "opt_param.h"
72#include "opt_mbuf_stress_test.h"
73#include <sys/param.h>
74#include <sys/systm.h>
75#include <sys/malloc.h>
76#include <sys/mbuf.h>
77#include <sys/kernel.h>
78#include <sys/sysctl.h>
79#include <sys/domain.h>
7b6f875f 80#include <sys/objcache.h>
e9fa4b60 81#include <sys/tree.h>
984263bc 82#include <sys/protosw.h>
0c33f36d 83#include <sys/uio.h>
ef0fdad1 84#include <sys/thread.h>
a2a5ad0d 85#include <sys/globaldata.h>
90775e29 86#include <sys/thread2.h>
984263bc 87
1d16b2b5 88#include <machine/atomic.h>
e54488bb 89#include <machine/limits.h>
1d16b2b5 90
984263bc
MD
91#include <vm/vm.h>
92#include <vm/vm_kern.h>
93#include <vm/vm_extern.h>
94
95#ifdef INVARIANTS
96#include <machine/cpu.h>
97#endif
98
90775e29
MD
99/*
100 * mbuf cluster meta-data
101 */
7b6f875f 102struct mbcluster {
90775e29
MD
103 int32_t mcl_refs;
104 void *mcl_data;
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
4c1e2509 226static u_long mbtypes[SMP_MAXCPU][MT_NTYPES];
90775e29 227
4c1e2509 228static struct mbstat mbstat[SMP_MAXCPU];
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, "");
4c1e2509
JT
257static int do_mbstat(SYSCTL_HANDLER_ARGS);
258
259SYSCTL_PROC(_kern_ipc, KIPC_MBSTAT, mbstat, CTLTYPE_STRUCT|CTLFLAG_RD,
260 0, 0, do_mbstat, "S,mbstat", "");
261
262static int do_mbtypes(SYSCTL_HANDLER_ARGS);
263
264SYSCTL_PROC(_kern_ipc, OID_AUTO, mbtypes, CTLTYPE_ULONG|CTLFLAG_RD,
265 0, 0, do_mbtypes, "LU", "");
266
267static int
268do_mbstat(SYSCTL_HANDLER_ARGS)
269{
270 struct mbstat mbstat_total;
271 struct mbstat *mbstat_totalp;
272 int i;
273
274 bzero(&mbstat_total, sizeof(mbstat_total));
275 mbstat_totalp = &mbstat_total;
276
277 for (i = 0; i < ncpus; i++)
278 {
279 mbstat_total.m_mbufs += mbstat[i].m_mbufs;
280 mbstat_total.m_clusters += mbstat[i].m_clusters;
281 mbstat_total.m_spare += mbstat[i].m_spare;
282 mbstat_total.m_clfree += mbstat[i].m_clfree;
283 mbstat_total.m_drops += mbstat[i].m_drops;
284 mbstat_total.m_wait += mbstat[i].m_wait;
285 mbstat_total.m_drain += mbstat[i].m_drain;
286 mbstat_total.m_mcfail += mbstat[i].m_mcfail;
287 mbstat_total.m_mpfail += mbstat[i].m_mpfail;
288
289 }
290 /*
291 * The following fields are not cumulative fields so just
292 * get their values once.
293 */
294 mbstat_total.m_msize = mbstat[0].m_msize;
295 mbstat_total.m_mclbytes = mbstat[0].m_mclbytes;
296 mbstat_total.m_minclsize = mbstat[0].m_minclsize;
297 mbstat_total.m_mlen = mbstat[0].m_mlen;
298 mbstat_total.m_mhlen = mbstat[0].m_mhlen;
299
300 return(sysctl_handle_opaque(oidp, mbstat_totalp, sizeof(mbstat_total), req));
301}
302
303static int
304do_mbtypes(SYSCTL_HANDLER_ARGS)
305{
306 u_long totals[MT_NTYPES];
307 int i, j;
308
309 for (i = 0; i < MT_NTYPES; i++)
310 totals[i] = 0;
311
312 for (i = 0; i < ncpus; i++)
313 {
314 for (j = 0; j < MT_NTYPES; j++)
315 totals[j] += mbtypes[i][j];
316 }
317
318 return(sysctl_handle_opaque(oidp, totals, sizeof(totals), req));
319}
18c48b9c
MD
320
321/*
322 * These are read-only because we do not currently have any code
323 * to adjust the objcache limits after the fact. The variables
324 * may only be set as boot-time tunables.
325 */
326SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
984263bc 327 &nmbclusters, 0, "Maximum number of mbuf clusters available");
18c48b9c 328SYSCTL_INT(_kern_ipc, OID_AUTO, nmbufs, CTLFLAG_RD, &nmbufs, 0,
984263bc 329 "Maximum number of mbufs available");
7b6f875f 330
984263bc
MD
331SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragpackets, CTLFLAG_RD,
332 &m_defragpackets, 0, "");
333SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragbytes, CTLFLAG_RD,
334 &m_defragbytes, 0, "");
335SYSCTL_INT(_kern_ipc, OID_AUTO, m_defraguseless, CTLFLAG_RD,
336 &m_defraguseless, 0, "");
337SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragfailure, CTLFLAG_RD,
338 &m_defragfailure, 0, "");
339#ifdef MBUF_STRESS_TEST
340SYSCTL_INT(_kern_ipc, OID_AUTO, m_defragrandomfailures, CTLFLAG_RW,
341 &m_defragrandomfailures, 0, "");
342#endif
343
90775e29
MD
344static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
345static MALLOC_DEFINE(M_MBUFCL, "mbufcl", "mbufcl");
7b6f875f 346static MALLOC_DEFINE(M_MCLMETA, "mclmeta", "mclmeta");
90775e29
MD
347
348static void m_reclaim (void);
90775e29
MD
349static void m_mclref(void *arg);
350static void m_mclfree(void *arg);
984263bc
MD
351
352#ifndef NMBCLUSTERS
353#define NMBCLUSTERS (512 + maxusers * 16)
354#endif
355#ifndef NMBUFS
7b6f875f 356#define NMBUFS (nmbclusters * 2)
984263bc
MD
357#endif
358
359/*
360 * Perform sanity checks of tunables declared above.
361 */
362static void
363tunable_mbinit(void *dummy)
364{
984263bc
MD
365 /*
366 * This has to be done before VM init.
367 */
368 nmbclusters = NMBCLUSTERS;
369 TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
370 nmbufs = NMBUFS;
371 TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
372 /* Sanity checks */
373 if (nmbufs < nmbclusters * 2)
374 nmbufs = nmbclusters * 2;
984263bc 375}
ba39e2e0
MD
376SYSINIT(tunable_mbinit, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
377 tunable_mbinit, NULL);
984263bc
MD
378
379/* "number of clusters of pages" */
380#define NCL_INIT 1
381
382#define NMB_INIT 16
383
7b6f875f
JH
384/*
385 * The mbuf object cache only guarantees that m_next and m_nextpkt are
386 * NULL and that m_data points to the beginning of the data area. In
387 * particular, m_len and m_pkthdr.len are uninitialized. It is the
388 * responsibility of the caller to initialize those fields before use.
389 */
390
391static boolean_t __inline
392mbuf_ctor(void *obj, void *private, int ocflags)
984263bc 393{
7b6f875f 394 struct mbuf *m = obj;
984263bc 395
7b6f875f
JH
396 m->m_next = NULL;
397 m->m_nextpkt = NULL;
398 m->m_data = m->m_dat;
399 m->m_flags = 0;
400
401 return (TRUE);
984263bc
MD
402}
403
404/*
7b6f875f 405 * Initialize the mbuf and the packet header fields.
984263bc 406 */
7b6f875f
JH
407static boolean_t
408mbufphdr_ctor(void *obj, void *private, int ocflags)
984263bc 409{
7b6f875f 410 struct mbuf *m = obj;
984263bc 411
7b6f875f
JH
412 m->m_next = NULL;
413 m->m_nextpkt = NULL;
414 m->m_data = m->m_pktdat;
77e294a1 415 m->m_flags = M_PKTHDR | M_PHCACHE;
984263bc 416
7b6f875f
JH
417 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
418 SLIST_INIT(&m->m_pkthdr.tags);
419 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
420 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
421
422 return (TRUE);
984263bc
MD
423}
424
425/*
7b6f875f 426 * A mbcluster object consists of 2K (MCLBYTES) cluster and a refcount.
984263bc 427 */
7b6f875f
JH
428static boolean_t
429mclmeta_ctor(void *obj, void *private, int ocflags)
984263bc 430{
7b6f875f
JH
431 struct mbcluster *cl = obj;
432 void *buf;
433
434 if (ocflags & M_NOWAIT)
efda3bd0 435 buf = kmalloc(MCLBYTES, M_MBUFCL, M_NOWAIT | M_ZERO);
7b6f875f 436 else
efda3bd0 437 buf = kmalloc(MCLBYTES, M_MBUFCL, M_INTWAIT | M_ZERO);
7b6f875f
JH
438 if (buf == NULL)
439 return (FALSE);
77e294a1 440 cl->mcl_refs = 0;
7b6f875f
JH
441 cl->mcl_data = buf;
442 return (TRUE);
443}
984263bc 444
7b6f875f 445static void
c3ef87ca
MD
446mclmeta_dtor(void *obj, void *private)
447{
448 struct mbcluster *mcl = obj;
449
450 KKASSERT(mcl->mcl_refs == 0);
efda3bd0 451 kfree(mcl->mcl_data, M_MBUFCL);
c3ef87ca
MD
452}
453
454static void
7b6f875f
JH
455linkcluster(struct mbuf *m, struct mbcluster *cl)
456{
984263bc 457 /*
7b6f875f
JH
458 * Add the cluster to the mbuf. The caller will detect that the
459 * mbuf now has an attached cluster.
984263bc 460 */
7b6f875f
JH
461 m->m_ext.ext_arg = cl;
462 m->m_ext.ext_buf = cl->mcl_data;
463 m->m_ext.ext_ref = m_mclref;
464 m->m_ext.ext_free = m_mclfree;
465 m->m_ext.ext_size = MCLBYTES;
df8d1020 466 atomic_add_int(&cl->mcl_refs, 1);
984263bc 467
7b6f875f
JH
468 m->m_data = m->m_ext.ext_buf;
469 m->m_flags |= M_EXT | M_EXT_CLUSTER;
984263bc
MD
470}
471
7b6f875f
JH
472static boolean_t
473mbufphdrcluster_ctor(void *obj, void *private, int ocflags)
474{
475 struct mbuf *m = obj;
476 struct mbcluster *cl;
477
478 mbufphdr_ctor(obj, private, ocflags);
479 cl = objcache_get(mclmeta_cache, ocflags);
a5955b15
MD
480 if (cl == NULL) {
481 ++mbstat[mycpu->gd_cpuid].m_drops;
7b6f875f 482 return (FALSE);
a5955b15 483 }
77e294a1 484 m->m_flags |= M_CLCACHE;
7b6f875f
JH
485 linkcluster(m, cl);
486 return (TRUE);
487}
984263bc 488
7b6f875f
JH
489static boolean_t
490mbufcluster_ctor(void *obj, void *private, int ocflags)
984263bc 491{
7b6f875f
JH
492 struct mbuf *m = obj;
493 struct mbcluster *cl;
494
495 mbuf_ctor(obj, private, ocflags);
496 cl = objcache_get(mclmeta_cache, ocflags);
a5955b15
MD
497 if (cl == NULL) {
498 ++mbstat[mycpu->gd_cpuid].m_drops;
7b6f875f 499 return (FALSE);
a5955b15 500 }
77e294a1 501 m->m_flags |= M_CLCACHE;
7b6f875f
JH
502 linkcluster(m, cl);
503 return (TRUE);
504}
984263bc 505
77e294a1
MD
506/*
507 * Used for both the cluster and cluster PHDR caches.
508 *
509 * The mbuf may have lost its cluster due to sharing, deal
510 * with the situation by checking M_EXT.
511 */
7b6f875f
JH
512static void
513mbufcluster_dtor(void *obj, void *private)
984263bc 514{
7b6f875f 515 struct mbuf *m = obj;
77e294a1 516 struct mbcluster *mcl;
984263bc 517
77e294a1
MD
518 if (m->m_flags & M_EXT) {
519 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
520 mcl = m->m_ext.ext_arg;
521 KKASSERT(mcl->mcl_refs == 1);
522 mcl->mcl_refs = 0;
523 objcache_put(mclmeta_cache, mcl);
524 }
984263bc
MD
525}
526
7b6f875f
JH
527struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
528struct objcache_malloc_args mclmeta_malloc_args =
529 { sizeof(struct mbcluster), M_MCLMETA };
530
531/* ARGSUSED*/
90775e29 532static void
7b6f875f 533mbinit(void *dummy)
984263bc 534{
6f21e2f4 535 int mb_limit, cl_limit;
0aa16b5d 536 int limit;
4c1e2509
JT
537 int i;
538
0aa16b5d
SZ
539 /*
540 * Initialize statistics
541 */
542 for (i = 0; i < ncpus; i++) {
4c1e2509
JT
543 atomic_set_long_nonlocked(&mbstat[i].m_msize, MSIZE);
544 atomic_set_long_nonlocked(&mbstat[i].m_mclbytes, MCLBYTES);
545 atomic_set_long_nonlocked(&mbstat[i].m_minclsize, MINCLSIZE);
546 atomic_set_long_nonlocked(&mbstat[i].m_mlen, MLEN);
547 atomic_set_long_nonlocked(&mbstat[i].m_mhlen, MHLEN);
548 }
984263bc 549
0aa16b5d
SZ
550 /*
551 * Create objtect caches and save cluster limits, which will
552 * be used to adjust backing kmalloc pools' limit later.
553 */
554
6f21e2f4 555 mb_limit = cl_limit = 0;
0aa16b5d
SZ
556
557 limit = nmbufs;
558 mbuf_cache = objcache_create("mbuf", &limit, 0,
5b7da64a 559 mbuf_ctor, NULL, NULL,
7b6f875f 560 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 561 mb_limit += limit;
0aa16b5d
SZ
562
563 limit = nmbufs;
564 mbufphdr_cache = objcache_create("mbuf pkt hdr", &limit, 64,
5b7da64a 565 mbufphdr_ctor, NULL, NULL,
7b6f875f 566 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 567 mb_limit += limit;
0aa16b5d
SZ
568
569 cl_limit = nmbclusters;
570 mclmeta_cache = objcache_create("cluster mbuf", &cl_limit, 0,
7b6f875f
JH
571 mclmeta_ctor, mclmeta_dtor, NULL,
572 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
0aa16b5d
SZ
573
574 limit = nmbclusters;
575 mbufcluster_cache = objcache_create("mbuf + cluster", &limit, 0,
7b6f875f
JH
576 mbufcluster_ctor, mbufcluster_dtor, NULL,
577 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 578 mb_limit += limit;
0aa16b5d
SZ
579
580 limit = nmbclusters;
7b6f875f 581 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
0aa16b5d 582 &limit, 64, mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
7b6f875f 583 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 584 mb_limit += limit;
0aa16b5d
SZ
585
586 /*
587 * Adjust backing kmalloc pools' limit
3f98f485
SZ
588 *
589 * NOTE: We raise the limit by another 1/8 to take the effect
590 * of loosememuse into account.
0aa16b5d 591 */
3f98f485 592 cl_limit += cl_limit / 8;
0aa16b5d
SZ
593 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
594 mclmeta_malloc_args.objsize * cl_limit);
595 kmalloc_raise_limit(M_MBUFCL, MCLBYTES * cl_limit);
596
3f98f485 597 mb_limit += mb_limit / 8;
0aa16b5d
SZ
598 kmalloc_raise_limit(mbuf_malloc_args.mtype,
599 mbuf_malloc_args.objsize * mb_limit);
90775e29 600}
984263bc 601
90775e29
MD
602/*
603 * Return the number of references to this mbuf's data. 0 is returned
604 * if the mbuf is not M_EXT, a reference count is returned if it is
7b6f875f 605 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
90775e29
MD
606 */
607int
608m_sharecount(struct mbuf *m)
609{
7b6f875f
JH
610 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
611 case 0:
612 return (0);
613 case M_EXT:
614 return (99);
615 case M_EXT | M_EXT_CLUSTER:
616 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
617 }
618 /* NOTREACHED */
619 return (0); /* to shut up compiler */
90775e29
MD
620}
621
622/*
623 * change mbuf to new type
624 */
625void
626m_chtype(struct mbuf *m, int type)
627{
4c1e2509
JT
628 struct globaldata *gd = mycpu;
629
630 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
631 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
632 atomic_set_short_nonlocked(&m->m_type, type);
984263bc
MD
633}
634
984263bc 635static void
8a3125c6 636m_reclaim(void)
984263bc 637{
1fd87d54
RG
638 struct domain *dp;
639 struct protosw *pr;
984263bc 640
c6339e39 641 crit_enter();
9c70fe43 642 SLIST_FOREACH(dp, &domains, dom_next) {
8a3125c6 643 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
984263bc
MD
644 if (pr->pr_drain)
645 (*pr->pr_drain)();
8a3125c6
MD
646 }
647 }
c6339e39 648 crit_exit();
4c1e2509 649 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_drain, 1);
984263bc
MD
650}
651
7b6f875f
JH
652static void __inline
653updatestats(struct mbuf *m, int type)
654{
4c1e2509 655 struct globaldata *gd = mycpu;
7b6f875f
JH
656 m->m_type = type;
657
e9fa4b60 658 mbuftrack(m);
4c1e2509
JT
659
660 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
661 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
662
7b6f875f
JH
663}
664
984263bc 665/*
7b6f875f 666 * Allocate an mbuf.
984263bc
MD
667 */
668struct mbuf *
8a3125c6 669m_get(int how, int type)
984263bc 670{
12496bdf 671 struct mbuf *m;
7b6f875f
JH
672 int ntries = 0;
673 int ocf = MBTOM(how);
12496bdf 674
7b6f875f
JH
675retryonce:
676
677 m = objcache_get(mbuf_cache, ocf);
678
679 if (m == NULL) {
680 if ((how & MB_TRYWAIT) && ntries++ == 0) {
681 struct objcache *reclaimlist[] = {
682 mbufphdr_cache,
683 mbufcluster_cache, mbufphdrcluster_cache
684 };
685 const int nreclaims = __arysize(reclaimlist);
686
687 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
688 m_reclaim();
689 goto retryonce;
c6339e39 690 }
a5955b15 691 ++mbstat[mycpu->gd_cpuid].m_drops;
7b6f875f 692 return (NULL);
12496bdf 693 }
c6339e39 694
7b6f875f 695 updatestats(m, type);
984263bc
MD
696 return (m);
697}
698
699struct mbuf *
8a3125c6 700m_gethdr(int how, int type)
984263bc 701{
12496bdf 702 struct mbuf *m;
7b6f875f
JH
703 int ocf = MBTOM(how);
704 int ntries = 0;
12496bdf 705
7b6f875f
JH
706retryonce:
707
708 m = objcache_get(mbufphdr_cache, ocf);
709
710 if (m == NULL) {
711 if ((how & MB_TRYWAIT) && ntries++ == 0) {
712 struct objcache *reclaimlist[] = {
713 mbuf_cache,
714 mbufcluster_cache, mbufphdrcluster_cache
715 };
716 const int nreclaims = __arysize(reclaimlist);
717
718 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
719 m_reclaim();
720 goto retryonce;
c6339e39 721 }
a5955b15 722 ++mbstat[mycpu->gd_cpuid].m_drops;
7b6f875f 723 return (NULL);
12496bdf 724 }
c6339e39 725
7b6f875f 726 updatestats(m, type);
984263bc
MD
727 return (m);
728}
729
7b6f875f
JH
730/*
731 * Get a mbuf (not a mbuf cluster!) and zero it.
732 * Deprecated.
733 */
984263bc 734struct mbuf *
8a3125c6 735m_getclr(int how, int type)
984263bc 736{
1fd87d54 737 struct mbuf *m;
984263bc 738
7b6f875f
JH
739 m = m_get(how, type);
740 if (m != NULL)
741 bzero(m->m_data, MLEN);
984263bc
MD
742 return (m);
743}
744
745/*
7b6f875f 746 * Returns an mbuf with an attached cluster.
984263bc
MD
747 * Because many network drivers use this kind of buffers a lot, it is
748 * convenient to keep a small pool of free buffers of this kind.
749 * Even a small size such as 10 gives about 10% improvement in the
750 * forwarding rate in a bridge or router.
984263bc 751 */
984263bc
MD
752struct mbuf *
753m_getcl(int how, short type, int flags)
754{
7b6f875f
JH
755 struct mbuf *m;
756 int ocflags = MBTOM(how);
757 int ntries = 0;
984263bc 758
7b6f875f
JH
759retryonce:
760
761 if (flags & M_PKTHDR)
762 m = objcache_get(mbufphdrcluster_cache, ocflags);
763 else
764 m = objcache_get(mbufcluster_cache, ocflags);
765
766 if (m == NULL) {
767 if ((how & MB_TRYWAIT) && ntries++ == 0) {
768 struct objcache *reclaimlist[1];
769
770 if (flags & M_PKTHDR)
771 reclaimlist[0] = mbufcluster_cache;
772 else
773 reclaimlist[0] = mbufphdrcluster_cache;
774 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
775 m_reclaim();
776 goto retryonce;
984263bc 777 }
a5955b15 778 ++mbstat[mycpu->gd_cpuid].m_drops;
7b6f875f 779 return (NULL);
984263bc 780 }
7b6f875f
JH
781
782 m->m_type = type;
783
e9fa4b60 784 mbuftrack(m);
4c1e2509
JT
785
786 atomic_add_long_nonlocked(&mbtypes[mycpu->gd_cpuid][type], 1);
787 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
7b6f875f 788 return (m);
984263bc
MD
789}
790
791/*
50503f0f
JH
792 * Allocate chain of requested length.
793 */
794struct mbuf *
795m_getc(int len, int how, int type)
796{
797 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
798 int nsize;
799
800 while (len > 0) {
801 n = m_getl(len, how, type, 0, &nsize);
802 if (n == NULL)
803 goto failed;
804 n->m_len = 0;
805 *ntail = n;
806 ntail = &n->m_next;
807 len -= nsize;
808 }
809 return (nfirst);
810
811failed:
812 m_freem(nfirst);
813 return (NULL);
814}
815
816/*
817 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
818 * and return a pointer to the head of the allocated chain. If m0 is
984263bc
MD
819 * non-null, then we assume that it is a single mbuf or an mbuf chain to
820 * which we want len bytes worth of mbufs and/or clusters attached, and so
50503f0f 821 * if we succeed in allocating it, we will just return a pointer to m0.
984263bc
MD
822 *
823 * If we happen to fail at any point during the allocation, we will free
824 * up everything we have already allocated and return NULL.
825 *
50503f0f 826 * Deprecated. Use m_getc() and m_cat() instead.
984263bc
MD
827 */
828struct mbuf *
dc14b0a9 829m_getm(struct mbuf *m0, int len, int type, int how)
984263bc 830{
50503f0f 831 struct mbuf *nfirst;
984263bc 832
50503f0f 833 nfirst = m_getc(len, how, type);
984263bc 834
50503f0f
JH
835 if (m0 != NULL) {
836 m_last(m0)->m_next = nfirst;
837 return (m0);
984263bc
MD
838 }
839
50503f0f 840 return (nfirst);
984263bc
MD
841}
842
843/*
7b6f875f
JH
844 * Adds a cluster to a normal mbuf, M_EXT is set on success.
845 * Deprecated. Use m_getcl() instead.
b6650ec0 846 */
90775e29
MD
847void
848m_mclget(struct mbuf *m, int how)
b6650ec0 849{
7b6f875f 850 struct mbcluster *mcl;
b6650ec0 851
77e294a1 852 KKASSERT((m->m_flags & M_EXT) == 0);
7b6f875f 853 mcl = objcache_get(mclmeta_cache, MBTOM(how));
c3ef87ca
MD
854 if (mcl != NULL) {
855 linkcluster(m, mcl);
4c1e2509 856 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
a5955b15
MD
857 } else {
858 ++mbstat[mycpu->gd_cpuid].m_drops;
c3ef87ca 859 }
b6650ec0
MD
860}
861
df8d1020
MD
862/*
863 * Updates to mbcluster must be MPSAFE. Only an entity which already has
864 * a reference to the cluster can ref it, so we are in no danger of
865 * racing an add with a subtract. But the operation must still be atomic
866 * since multiple entities may have a reference on the cluster.
867 *
868 * m_mclfree() is almost the same but it must contend with two entities
869 * freeing the cluster at the same time. If there is only one reference
870 * count we are the only entity referencing the cluster and no further
871 * locking is required. Otherwise we must protect against a race to 0
872 * with the serializer.
873 */
90775e29 874static void
7b6f875f 875m_mclref(void *arg)
b6650ec0 876{
7b6f875f 877 struct mbcluster *mcl = arg;
90775e29 878
7b6f875f 879 atomic_add_int(&mcl->mcl_refs, 1);
b6650ec0
MD
880}
881
1d16b2b5
MD
882/*
883 * When dereferencing a cluster we have to deal with a N->0 race, where
884 * N entities free their references simultaniously. To do this we use
dee87a60 885 * atomic_fetchadd_int().
1d16b2b5 886 */
90775e29 887static void
7b6f875f 888m_mclfree(void *arg)
b6650ec0 889{
7b6f875f 890 struct mbcluster *mcl = arg;
90775e29 891
dee87a60 892 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1)
77e294a1 893 objcache_put(mclmeta_cache, mcl);
b6650ec0
MD
894}
895
7eccf245 896/*
b6650ec0
MD
897 * Free a single mbuf and any associated external storage. The successor,
898 * if any, is returned.
984263bc 899 *
b6650ec0 900 * We do need to check non-first mbuf for m_aux, since some of existing
984263bc
MD
901 * code does not call M_PREPEND properly.
902 * (example: call to bpf_mtap from drivers)
903 */
984263bc 904struct mbuf *
b6650ec0 905m_free(struct mbuf *m)
984263bc 906{
b6650ec0 907 struct mbuf *n;
4c1e2509 908 struct globaldata *gd = mycpu;
b6650ec0 909
361af367 910 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
4c1e2509 911 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
90775e29 912
7b6f875f 913 n = m->m_next;
90775e29
MD
914
915 /*
7b6f875f
JH
916 * Make sure the mbuf is in constructed state before returning it
917 * to the objcache.
90775e29 918 */
90775e29 919 m->m_next = NULL;
e9fa4b60 920 mbufuntrack(m);
7b6f875f
JH
921#ifdef notyet
922 KKASSERT(m->m_nextpkt == NULL);
923#else
924 if (m->m_nextpkt != NULL) {
7b6f875f
JH
925 static int afewtimes = 10;
926
927 if (afewtimes-- > 0) {
6ea70f76 928 kprintf("mfree: m->m_nextpkt != NULL\n");
7ce2998e 929 print_backtrace(-1);
90775e29 930 }
7b6f875f
JH
931 m->m_nextpkt = NULL;
932 }
933#endif
934 if (m->m_flags & M_PKTHDR) {
7b6f875f 935 m_tag_delete_chain(m); /* eliminate XXX JH */
77e294a1
MD
936 }
937
938 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
939
940 /*
941 * Clean the M_PKTHDR state so we can return the mbuf to its original
942 * cache. This is based on the PHCACHE flag which tells us whether
943 * the mbuf was originally allocated out of a packet-header cache
944 * or a non-packet-header cache.
945 */
946 if (m->m_flags & M_PHCACHE) {
947 m->m_flags |= M_PKTHDR;
948 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
7b6f875f
JH
949 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
950 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
6b1d6bed 951 SLIST_INIT(&m->m_pkthdr.tags);
90775e29 952 }
7b6f875f 953
77e294a1
MD
954 /*
955 * Handle remaining flags combinations. M_CLCACHE tells us whether
956 * the mbuf was originally allocated from a cluster cache or not,
957 * and is totally separate from whether the mbuf is currently
958 * associated with a cluster.
959 */
960 crit_enter();
961 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
962 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
963 /*
964 * mbuf+cluster cache case. The mbuf was allocated from the
965 * combined mbuf_cluster cache and can be returned to the
966 * cache if the cluster hasn't been shared.
967 */
968 if (m_sharecount(m) == 1) {
969 /*
970 * The cluster has not been shared, we can just
971 * reset the data pointer and return the mbuf
972 * to the cluster cache. Note that the reference
973 * count is left intact (it is still associated with
974 * an mbuf).
975 */
976 m->m_data = m->m_ext.ext_buf;
977 if (m->m_flags & M_PHCACHE)
978 objcache_put(mbufphdrcluster_cache, m);
979 else
980 objcache_put(mbufcluster_cache, m);
4c1e2509 981 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
77e294a1
MD
982 } else {
983 /*
984 * Hell. Someone else has a ref on this cluster,
985 * we have to disconnect it which means we can't
986 * put it back into the mbufcluster_cache, we
987 * have to destroy the mbuf.
988 *
cb086467
MD
989 * Other mbuf references to the cluster will typically
990 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
991 *
77e294a1
MD
992 * XXX we could try to connect another cluster to
993 * it.
994 */
7b6f875f
JH
995 m->m_ext.ext_free(m->m_ext.ext_arg);
996 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
77e294a1
MD
997 if (m->m_flags & M_PHCACHE)
998 objcache_dtor(mbufphdrcluster_cache, m);
999 else
1000 objcache_dtor(mbufcluster_cache, m);
7b6f875f 1001 }
77e294a1
MD
1002 break;
1003 case M_EXT | M_EXT_CLUSTER:
1004 /*
1005 * Normal cluster associated with an mbuf that was allocated
1006 * from the normal mbuf pool rather then the cluster pool.
1007 * The cluster has to be independantly disassociated from the
1008 * mbuf.
1009 */
cb086467 1010 if (m_sharecount(m) == 1)
4c1e2509 1011 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
77e294a1
MD
1012 /* fall through */
1013 case M_EXT:
1014 /*
1015 * Normal cluster association case, disconnect the cluster from
1016 * the mbuf. The cluster may or may not be custom.
1017 */
1018 m->m_ext.ext_free(m->m_ext.ext_arg);
1019 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1020 /* fall through */
1021 case 0:
1022 /*
1023 * return the mbuf to the mbuf cache.
1024 */
1025 if (m->m_flags & M_PHCACHE) {
7b6f875f
JH
1026 m->m_data = m->m_pktdat;
1027 objcache_put(mbufphdr_cache, m);
90775e29 1028 } else {
7b6f875f
JH
1029 m->m_data = m->m_dat;
1030 objcache_put(mbuf_cache, m);
90775e29 1031 }
4c1e2509 1032 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
77e294a1
MD
1033 break;
1034 default:
1035 if (!panicstr)
1036 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
1037 break;
b6650ec0 1038 }
77e294a1 1039 crit_exit();
984263bc
MD
1040 return (n);
1041}
1042
1043void
b6650ec0 1044m_freem(struct mbuf *m)
984263bc 1045{
c6339e39 1046 crit_enter();
90775e29
MD
1047 while (m)
1048 m = m_free(m);
c6339e39 1049 crit_exit();
984263bc
MD
1050}
1051
1052/*
df80f2ea 1053 * mbuf utility routines
984263bc
MD
1054 */
1055
1056/*
7b6f875f 1057 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
984263bc
MD
1058 * copy junk along.
1059 */
1060struct mbuf *
8a3125c6 1061m_prepend(struct mbuf *m, int len, int how)
984263bc
MD
1062{
1063 struct mbuf *mn;
1064
c3ef87ca
MD
1065 if (m->m_flags & M_PKTHDR)
1066 mn = m_gethdr(how, m->m_type);
1067 else
1068 mn = m_get(how, m->m_type);
7b6f875f 1069 if (mn == NULL) {
984263bc 1070 m_freem(m);
7b6f875f 1071 return (NULL);
984263bc
MD
1072 }
1073 if (m->m_flags & M_PKTHDR)
1074 M_MOVE_PKTHDR(mn, m);
1075 mn->m_next = m;
1076 m = mn;
1077 if (len < MHLEN)
1078 MH_ALIGN(m, len);
1079 m->m_len = len;
1080 return (m);
1081}
1082
1083/*
1084 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1085 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
74f1caca 1086 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
984263bc
MD
1087 * Note that the copy is read-only, because clusters are not copied,
1088 * only their reference counts are incremented.
1089 */
984263bc 1090struct mbuf *
8a3125c6 1091m_copym(const struct mbuf *m, int off0, int len, int wait)
984263bc 1092{
1fd87d54
RG
1093 struct mbuf *n, **np;
1094 int off = off0;
984263bc
MD
1095 struct mbuf *top;
1096 int copyhdr = 0;
1097
1098 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1099 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1100 if (off == 0 && m->m_flags & M_PKTHDR)
1101 copyhdr = 1;
1102 while (off > 0) {
1103 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1104 if (off < m->m_len)
1105 break;
1106 off -= m->m_len;
1107 m = m->m_next;
1108 }
1109 np = &top;
1110 top = 0;
1111 while (len > 0) {
7b6f875f 1112 if (m == NULL) {
984263bc
MD
1113 KASSERT(len == M_COPYALL,
1114 ("m_copym, length > size of mbuf chain"));
1115 break;
1116 }
c3ef87ca
MD
1117 /*
1118 * Because we are sharing any cluster attachment below,
1119 * be sure to get an mbuf that does not have a cluster
1120 * associated with it.
1121 */
1122 if (copyhdr)
1123 n = m_gethdr(wait, m->m_type);
1124 else
1125 n = m_get(wait, m->m_type);
984263bc 1126 *np = n;
7b6f875f 1127 if (n == NULL)
984263bc
MD
1128 goto nospace;
1129 if (copyhdr) {
1130 if (!m_dup_pkthdr(n, m, wait))
1131 goto nospace;
1132 if (len == M_COPYALL)
1133 n->m_pkthdr.len -= off0;
1134 else
1135 n->m_pkthdr.len = len;
1136 copyhdr = 0;
1137 }
1138 n->m_len = min(len, m->m_len - off);
1139 if (m->m_flags & M_EXT) {
c3ef87ca 1140 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1141 n->m_data = m->m_data + off;
7b6f875f 1142 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1143 n->m_ext = m->m_ext;
b542cd49 1144 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
7eccf245 1145 } else {
984263bc
MD
1146 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1147 (unsigned)n->m_len);
7eccf245 1148 }
984263bc
MD
1149 if (len != M_COPYALL)
1150 len -= n->m_len;
1151 off = 0;
1152 m = m->m_next;
1153 np = &n->m_next;
1154 }
7b6f875f 1155 if (top == NULL)
4c1e2509 1156 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
984263bc
MD
1157 return (top);
1158nospace:
1159 m_freem(top);
4c1e2509 1160 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1161 return (NULL);
984263bc
MD
1162}
1163
1164/*
1165 * Copy an entire packet, including header (which must be present).
1166 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1167 * Note that the copy is read-only, because clusters are not copied,
1168 * only their reference counts are incremented.
1169 * Preserve alignment of the first mbuf so if the creator has left
1170 * some room at the beginning (e.g. for inserting protocol headers)
1171 * the copies also have the room available.
1172 */
1173struct mbuf *
8a3125c6 1174m_copypacket(struct mbuf *m, int how)
984263bc
MD
1175{
1176 struct mbuf *top, *n, *o;
1177
7f3602fe 1178 n = m_gethdr(how, m->m_type);
984263bc
MD
1179 top = n;
1180 if (!n)
1181 goto nospace;
1182
1183 if (!m_dup_pkthdr(n, m, how))
1184 goto nospace;
1185 n->m_len = m->m_len;
1186 if (m->m_flags & M_EXT) {
c3ef87ca 1187 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1188 n->m_data = m->m_data;
7b6f875f 1189 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1190 n->m_ext = m->m_ext;
b542cd49 1191 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1192 } else {
1193 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1194 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1195 }
1196
1197 m = m->m_next;
1198 while (m) {
7b6f875f 1199 o = m_get(how, m->m_type);
984263bc
MD
1200 if (!o)
1201 goto nospace;
1202
1203 n->m_next = o;
1204 n = n->m_next;
1205
1206 n->m_len = m->m_len;
1207 if (m->m_flags & M_EXT) {
c3ef87ca 1208 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1209 n->m_data = m->m_data;
7b6f875f 1210 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1211 n->m_ext = m->m_ext;
b542cd49 1212 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1213 } else {
1214 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1215 }
1216
1217 m = m->m_next;
1218 }
1219 return top;
1220nospace:
1221 m_freem(top);
4c1e2509 1222 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1223 return (NULL);
984263bc
MD
1224}
1225
1226/*
1227 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1228 * continuing for "len" bytes, into the indicated buffer.
1229 */
1230void
8a3125c6 1231m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
984263bc 1232{
1fd87d54 1233 unsigned count;
984263bc
MD
1234
1235 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1236 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1237 while (off > 0) {
1238 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1239 if (off < m->m_len)
1240 break;
1241 off -= m->m_len;
1242 m = m->m_next;
1243 }
1244 while (len > 0) {
1245 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1246 count = min(m->m_len - off, len);
1247 bcopy(mtod(m, caddr_t) + off, cp, count);
1248 len -= count;
1249 cp += count;
1250 off = 0;
1251 m = m->m_next;
1252 }
1253}
1254
1255/*
1256 * Copy a packet header mbuf chain into a completely new chain, including
1257 * copying any mbuf clusters. Use this instead of m_copypacket() when
1258 * you need a writable copy of an mbuf chain.
1259 */
1260struct mbuf *
8a3125c6 1261m_dup(struct mbuf *m, int how)
984263bc
MD
1262{
1263 struct mbuf **p, *top = NULL;
1264 int remain, moff, nsize;
1265
1266 /* Sanity check */
1267 if (m == NULL)
50503f0f 1268 return (NULL);
5e2195bf 1269 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
984263bc
MD
1270
1271 /* While there's more data, get a new mbuf, tack it on, and fill it */
1272 remain = m->m_pkthdr.len;
1273 moff = 0;
1274 p = &top;
1275 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1276 struct mbuf *n;
1277
1278 /* Get the next new mbuf */
50503f0f
JH
1279 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1280 &nsize);
984263bc
MD
1281 if (n == NULL)
1282 goto nospace;
50503f0f 1283 if (top == NULL)
984263bc 1284 if (!m_dup_pkthdr(n, m, how))
50503f0f 1285 goto nospace0;
984263bc
MD
1286
1287 /* Link it into the new chain */
1288 *p = n;
1289 p = &n->m_next;
1290
1291 /* Copy data from original mbuf(s) into new mbuf */
50503f0f 1292 n->m_len = 0;
984263bc
MD
1293 while (n->m_len < nsize && m != NULL) {
1294 int chunk = min(nsize - n->m_len, m->m_len - moff);
1295
1296 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1297 moff += chunk;
1298 n->m_len += chunk;
1299 remain -= chunk;
1300 if (moff == m->m_len) {
1301 m = m->m_next;
1302 moff = 0;
1303 }
1304 }
1305
1306 /* Check correct total mbuf length */
1307 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
50503f0f 1308 ("%s: bogus m_pkthdr.len", __func__));
984263bc
MD
1309 }
1310 return (top);
1311
1312nospace:
1313 m_freem(top);
50503f0f 1314nospace0:
4c1e2509 1315 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
50503f0f 1316 return (NULL);
984263bc
MD
1317}
1318
1319/*
3bf6fec3
MD
1320 * Copy the non-packet mbuf data chain into a new set of mbufs, including
1321 * copying any mbuf clusters. This is typically used to realign a data
1322 * chain by nfs_realign().
1323 *
1324 * The original chain is left intact. how should be MB_WAIT or MB_DONTWAIT
1325 * and NULL can be returned if MB_DONTWAIT is passed.
1326 *
1327 * Be careful to use cluster mbufs, a large mbuf chain converted to non
1328 * cluster mbufs can exhaust our supply of mbufs.
1329 */
1330struct mbuf *
1331m_dup_data(struct mbuf *m, int how)
1332{
1333 struct mbuf **p, *n, *top = NULL;
1334 int mlen, moff, chunk, gsize, nsize;
1335
1336 /*
1337 * Degenerate case
1338 */
1339 if (m == NULL)
1340 return (NULL);
1341
1342 /*
1343 * Optimize the mbuf allocation but do not get too carried away.
1344 */
1345 if (m->m_next || m->m_len > MLEN)
1346 gsize = MCLBYTES;
1347 else
1348 gsize = MLEN;
1349
1350 /* Chain control */
1351 p = &top;
1352 n = NULL;
1353 nsize = 0;
1354
1355 /*
1356 * Scan the mbuf chain until nothing is left, the new mbuf chain
1357 * will be allocated on the fly as needed.
1358 */
1359 while (m) {
1360 mlen = m->m_len;
1361 moff = 0;
1362
1363 while (mlen) {
1364 KKASSERT(m->m_type == MT_DATA);
1365 if (n == NULL) {
1366 n = m_getl(gsize, how, MT_DATA, 0, &nsize);
1367 n->m_len = 0;
1368 if (n == NULL)
1369 goto nospace;
1370 *p = n;
1371 p = &n->m_next;
1372 }
1373 chunk = imin(mlen, nsize);
1374 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1375 mlen -= chunk;
1376 moff += chunk;
1377 n->m_len += chunk;
1378 nsize -= chunk;
1379 if (nsize == 0)
1380 n = NULL;
1381 }
1382 m = m->m_next;
1383 }
1384 *p = NULL;
1385 return(top);
1386nospace:
1387 *p = NULL;
1388 m_freem(top);
1389 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
1390 return (NULL);
1391}
1392
1393/*
984263bc
MD
1394 * Concatenate mbuf chain n to m.
1395 * Both chains must be of the same type (e.g. MT_DATA).
1396 * Any m_pkthdr is not updated.
1397 */
1398void
8a3125c6 1399m_cat(struct mbuf *m, struct mbuf *n)
984263bc 1400{
50503f0f 1401 m = m_last(m);
984263bc
MD
1402 while (n) {
1403 if (m->m_flags & M_EXT ||
1404 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1405 /* just join the two chains */
1406 m->m_next = n;
1407 return;
1408 }
1409 /* splat the data from one into the other */
1410 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1411 (u_int)n->m_len);
1412 m->m_len += n->m_len;
1413 n = m_free(n);
1414 }
1415}
1416
1417void
8a3125c6 1418m_adj(struct mbuf *mp, int req_len)
984263bc 1419{
1fd87d54
RG
1420 int len = req_len;
1421 struct mbuf *m;
1422 int count;
984263bc
MD
1423
1424 if ((m = mp) == NULL)
1425 return;
1426 if (len >= 0) {
1427 /*
1428 * Trim from head.
1429 */
1430 while (m != NULL && len > 0) {
1431 if (m->m_len <= len) {
1432 len -= m->m_len;
1433 m->m_len = 0;
1434 m = m->m_next;
1435 } else {
1436 m->m_len -= len;
1437 m->m_data += len;
1438 len = 0;
1439 }
1440 }
1441 m = mp;
1442 if (mp->m_flags & M_PKTHDR)
1443 m->m_pkthdr.len -= (req_len - len);
1444 } else {
1445 /*
1446 * Trim from tail. Scan the mbuf chain,
1447 * calculating its length and finding the last mbuf.
1448 * If the adjustment only affects this mbuf, then just
1449 * adjust and return. Otherwise, rescan and truncate
1450 * after the remaining size.
1451 */
1452 len = -len;
1453 count = 0;
1454 for (;;) {
1455 count += m->m_len;
60233e58 1456 if (m->m_next == NULL)
984263bc
MD
1457 break;
1458 m = m->m_next;
1459 }
1460 if (m->m_len >= len) {
1461 m->m_len -= len;
1462 if (mp->m_flags & M_PKTHDR)
1463 mp->m_pkthdr.len -= len;
1464 return;
1465 }
1466 count -= len;
1467 if (count < 0)
1468 count = 0;
1469 /*
1470 * Correct length for chain is "count".
1471 * Find the mbuf with last data, adjust its length,
1472 * and toss data from remaining mbufs on chain.
1473 */
1474 m = mp;
1475 if (m->m_flags & M_PKTHDR)
1476 m->m_pkthdr.len = count;
1477 for (; m; m = m->m_next) {
1478 if (m->m_len >= count) {
1479 m->m_len = count;
1480 break;
1481 }
1482 count -= m->m_len;
1483 }
1484 while (m->m_next)
1485 (m = m->m_next) ->m_len = 0;
1486 }
1487}
1488
1489/*
a3768f58
RP
1490 * Set the m_data pointer of a newly-allocated mbuf
1491 * to place an object of the specified size at the
1492 * end of the mbuf, longword aligned.
1493 */
1494void
1495m_align(struct mbuf *m, int len)
1496{
1497 int adjust;
1498
1499 if (m->m_flags & M_EXT)
1500 adjust = m->m_ext.ext_size - len;
1501 else if (m->m_flags & M_PKTHDR)
1502 adjust = MHLEN - len;
1503 else
1504 adjust = MLEN - len;
1505 m->m_data += adjust &~ (sizeof(long)-1);
1506}
1507
1508/*
7b6f875f 1509 * Rearrange an mbuf chain so that len bytes are contiguous
9e4465af
MD
1510 * and in the data area of an mbuf (so that mtod will work for a structure
1511 * of size len). Returns the resulting mbuf chain on success, frees it and
1512 * returns null on failure. If there is room, it will add up to
1513 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1514 * avoid being called next time.
984263bc 1515 */
984263bc 1516struct mbuf *
8a3125c6 1517m_pullup(struct mbuf *n, int len)
984263bc 1518{
1fd87d54
RG
1519 struct mbuf *m;
1520 int count;
984263bc
MD
1521 int space;
1522
1523 /*
1524 * If first mbuf has no cluster, and has room for len bytes
1525 * without shifting current data, pullup into it,
1526 * otherwise allocate a new mbuf to prepend to the chain.
1527 */
7b6f875f
JH
1528 if (!(n->m_flags & M_EXT) &&
1529 n->m_data + len < &n->m_dat[MLEN] &&
1530 n->m_next) {
984263bc
MD
1531 if (n->m_len >= len)
1532 return (n);
1533 m = n;
1534 n = n->m_next;
1535 len -= m->m_len;
1536 } else {
1537 if (len > MHLEN)
1538 goto bad;
c3ef87ca
MD
1539 if (n->m_flags & M_PKTHDR)
1540 m = m_gethdr(MB_DONTWAIT, n->m_type);
1541 else
1542 m = m_get(MB_DONTWAIT, n->m_type);
7b6f875f 1543 if (m == NULL)
984263bc
MD
1544 goto bad;
1545 m->m_len = 0;
1546 if (n->m_flags & M_PKTHDR)
1547 M_MOVE_PKTHDR(m, n);
1548 }
1549 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1550 do {
1551 count = min(min(max(len, max_protohdr), space), n->m_len);
1552 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1553 (unsigned)count);
1554 len -= count;
1555 m->m_len += count;
1556 n->m_len -= count;
1557 space -= count;
1558 if (n->m_len)
1559 n->m_data += count;
1560 else
1561 n = m_free(n);
1562 } while (len > 0 && n);
1563 if (len > 0) {
7b6f875f 1564 m_free(m);
984263bc
MD
1565 goto bad;
1566 }
1567 m->m_next = n;
1568 return (m);
1569bad:
1570 m_freem(n);
4c1e2509 1571 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1572 return (NULL);
984263bc
MD
1573}
1574
1575/*
1576 * Partition an mbuf chain in two pieces, returning the tail --
1577 * all but the first len0 bytes. In case of failure, it returns NULL and
1578 * attempts to restore the chain to its original state.
1579 *
1580 * Note that the resulting mbufs might be read-only, because the new
1581 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1582 * the "breaking point" happens to lie within a cluster mbuf. Use the
1583 * M_WRITABLE() macro to check for this case.
1584 */
1585struct mbuf *
8a3125c6 1586m_split(struct mbuf *m0, int len0, int wait)
984263bc 1587{
1fd87d54 1588 struct mbuf *m, *n;
984263bc
MD
1589 unsigned len = len0, remain;
1590
1591 for (m = m0; m && len > m->m_len; m = m->m_next)
1592 len -= m->m_len;
7b6f875f
JH
1593 if (m == NULL)
1594 return (NULL);
984263bc
MD
1595 remain = m->m_len - len;
1596 if (m0->m_flags & M_PKTHDR) {
7b6f875f
JH
1597 n = m_gethdr(wait, m0->m_type);
1598 if (n == NULL)
1599 return (NULL);
984263bc
MD
1600 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1601 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1602 m0->m_pkthdr.len = len0;
1603 if (m->m_flags & M_EXT)
1604 goto extpacket;
1605 if (remain > MHLEN) {
1606 /* m can't be the lead packet */
1607 MH_ALIGN(n, 0);
1608 n->m_next = m_split(m, len, wait);
7b6f875f
JH
1609 if (n->m_next == NULL) {
1610 m_free(n);
1611 return (NULL);
984263bc
MD
1612 } else {
1613 n->m_len = 0;
1614 return (n);
1615 }
1616 } else
1617 MH_ALIGN(n, remain);
1618 } else if (remain == 0) {
1619 n = m->m_next;
1620 m->m_next = 0;
1621 return (n);
1622 } else {
7b6f875f
JH
1623 n = m_get(wait, m->m_type);
1624 if (n == NULL)
1625 return (NULL);
984263bc
MD
1626 M_ALIGN(n, remain);
1627 }
1628extpacket:
1629 if (m->m_flags & M_EXT) {
c3ef87ca 1630 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1631 n->m_data = m->m_data + len;
7b6f875f 1632 m->m_ext.ext_ref(m->m_ext.ext_arg);
7eccf245 1633 n->m_ext = m->m_ext;
b542cd49 1634 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1635 } else {
1636 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1637 }
1638 n->m_len = remain;
1639 m->m_len = len;
1640 n->m_next = m->m_next;
1641 m->m_next = 0;
1642 return (n);
1643}
50503f0f 1644
984263bc
MD
1645/*
1646 * Routine to copy from device local memory into mbufs.
50503f0f 1647 * Note: "offset" is ill-defined and always called as 0, so ignore it.
984263bc
MD
1648 */
1649struct mbuf *
50503f0f
JH
1650m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1651 void (*copy)(volatile const void *from, volatile void *to, size_t length))
984263bc 1652{
50503f0f
JH
1653 struct mbuf *m, *mfirst = NULL, **mtail;
1654 int nsize, flags;
1655
1656 if (copy == NULL)
1657 copy = bcopy;
1658 mtail = &mfirst;
1659 flags = M_PKTHDR;
1660
1661 while (len > 0) {
1662 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1663 if (m == NULL) {
1664 m_freem(mfirst);
1665 return (NULL);
984263bc 1666 }
50503f0f
JH
1667 m->m_len = min(len, nsize);
1668
1669 if (flags & M_PKTHDR) {
1670 if (len + max_linkhdr <= nsize)
1671 m->m_data += max_linkhdr;
1672 m->m_pkthdr.rcvif = ifp;
1673 m->m_pkthdr.len = len;
1674 flags = 0;
984263bc 1675 }
50503f0f
JH
1676
1677 copy(buf, m->m_data, (unsigned)m->m_len);
1678 buf += m->m_len;
1679 len -= m->m_len;
1680 *mtail = m;
1681 mtail = &m->m_next;
984263bc 1682 }
50503f0f
JH
1683
1684 return (mfirst);
984263bc
MD
1685}
1686
1687/*
cf12ba3c
SZ
1688 * Routine to pad mbuf to the specified length 'padto'.
1689 */
1690int
1691m_devpad(struct mbuf *m, int padto)
1692{
1693 struct mbuf *last = NULL;
1694 int padlen;
1695
1696 if (padto <= m->m_pkthdr.len)
1697 return 0;
1698
1699 padlen = padto - m->m_pkthdr.len;
1700
1701 /* if there's only the packet-header and we can pad there, use it. */
1702 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
1703 last = m;
1704 } else {
1705 /*
1706 * Walk packet chain to find last mbuf. We will either
1707 * pad there, or append a new mbuf and pad it
1708 */
1709 for (last = m; last->m_next != NULL; last = last->m_next)
1710 ; /* EMPTY */
1711
1712 /* `last' now points to last in chain. */
1713 if (M_TRAILINGSPACE(last) < padlen) {
1714 struct mbuf *n;
1715
1716 /* Allocate new empty mbuf, pad it. Compact later. */
1717 MGET(n, MB_DONTWAIT, MT_DATA);
1718 if (n == NULL)
1719 return ENOBUFS;
1720 n->m_len = 0;
1721 last->m_next = n;
1722 last = n;
1723 }
1724 }
1725 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
1726 KKASSERT(M_WRITABLE(last));
1727
1728 /* Now zero the pad area */
1729 bzero(mtod(last, char *) + last->m_len, padlen);
1730 last->m_len += padlen;
1731 m->m_pkthdr.len += padlen;
1732 return 0;
1733}
1734
1735/*
984263bc
MD
1736 * Copy data from a buffer back into the indicated mbuf chain,
1737 * starting "off" bytes from the beginning, extending the mbuf
1738 * chain if necessary.
1739 */
1740void
8a3125c6 1741m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
984263bc 1742{
1fd87d54
RG
1743 int mlen;
1744 struct mbuf *m = m0, *n;
984263bc
MD
1745 int totlen = 0;
1746
7b6f875f 1747 if (m0 == NULL)
984263bc
MD
1748 return;
1749 while (off > (mlen = m->m_len)) {
1750 off -= mlen;
1751 totlen += mlen;
7b6f875f 1752 if (m->m_next == NULL) {
74f1caca 1753 n = m_getclr(MB_DONTWAIT, m->m_type);
7b6f875f 1754 if (n == NULL)
984263bc
MD
1755 goto out;
1756 n->m_len = min(MLEN, len + off);
1757 m->m_next = n;
1758 }
1759 m = m->m_next;
1760 }
1761 while (len > 0) {
1762 mlen = min (m->m_len - off, len);
1763 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1764 cp += mlen;
1765 len -= mlen;
1766 mlen += off;
1767 off = 0;
1768 totlen += mlen;
1769 if (len == 0)
1770 break;
7b6f875f 1771 if (m->m_next == NULL) {
74f1caca 1772 n = m_get(MB_DONTWAIT, m->m_type);
7b6f875f 1773 if (n == NULL)
984263bc
MD
1774 break;
1775 n->m_len = min(MLEN, len);
1776 m->m_next = n;
1777 }
1778 m = m->m_next;
1779 }
1780out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1781 m->m_pkthdr.len = totlen;
1782}
1783
920c9f10 1784/*
bf2cc98c
RP
1785 * Append the specified data to the indicated mbuf chain,
1786 * Extend the mbuf chain if the new data does not fit in
1787 * existing space.
1788 *
1789 * Return 1 if able to complete the job; otherwise 0.
1790 */
1791int
1792m_append(struct mbuf *m0, int len, c_caddr_t cp)
1793{
1794 struct mbuf *m, *n;
1795 int remainder, space;
1796
1797 for (m = m0; m->m_next != NULL; m = m->m_next)
1798 ;
1799 remainder = len;
1800 space = M_TRAILINGSPACE(m);
1801 if (space > 0) {
1802 /*
1803 * Copy into available space.
1804 */
1805 if (space > remainder)
1806 space = remainder;
1807 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1808 m->m_len += space;
1809 cp += space, remainder -= space;
1810 }
1811 while (remainder > 0) {
1812 /*
1813 * Allocate a new mbuf; could check space
1814 * and allocate a cluster instead.
1815 */
1816 n = m_get(MB_DONTWAIT, m->m_type);
1817 if (n == NULL)
1818 break;
1819 n->m_len = min(MLEN, remainder);
1820 bcopy(cp, mtod(n, caddr_t), n->m_len);
1821 cp += n->m_len, remainder -= n->m_len;
1822 m->m_next = n;
1823 m = n;
1824 }
1825 if (m0->m_flags & M_PKTHDR)
1826 m0->m_pkthdr.len += len - remainder;
1827 return (remainder == 0);
1828}
1829
1830/*
920c9f10
AH
1831 * Apply function f to the data in an mbuf chain starting "off" bytes from
1832 * the beginning, continuing for "len" bytes.
1833 */
1834int
1835m_apply(struct mbuf *m, int off, int len,
1836 int (*f)(void *, void *, u_int), void *arg)
1837{
1838 u_int count;
1839 int rval;
1840
1841 KASSERT(off >= 0, ("m_apply, negative off %d", off));
1842 KASSERT(len >= 0, ("m_apply, negative len %d", len));
1843 while (off > 0) {
1844 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1845 if (off < m->m_len)
1846 break;
1847 off -= m->m_len;
1848 m = m->m_next;
1849 }
1850 while (len > 0) {
1851 KASSERT(m != NULL, ("m_apply, offset > size of mbuf chain"));
1852 count = min(m->m_len - off, len);
1853 rval = (*f)(arg, mtod(m, caddr_t) + off, count);
1854 if (rval)
1855 return (rval);
1856 len -= count;
1857 off = 0;
1858 m = m->m_next;
1859 }
1860 return (0);
1861}
1862
1863/*
1864 * Return a pointer to mbuf/offset of location in mbuf chain.
1865 */
1866struct mbuf *
1867m_getptr(struct mbuf *m, int loc, int *off)
1868{
1869
1870 while (loc >= 0) {
1871 /* Normal end of search. */
1872 if (m->m_len > loc) {
1873 *off = loc;
1874 return (m);
1875 } else {
1876 loc -= m->m_len;
1877 if (m->m_next == NULL) {
1878 if (loc == 0) {
1879 /* Point at the end of valid data. */
1880 *off = m->m_len;
1881 return (m);
1882 }
1883 return (NULL);
1884 }
1885 m = m->m_next;
1886 }
1887 }
1888 return (NULL);
1889}
1890
984263bc
MD
1891void
1892m_print(const struct mbuf *m)
1893{
1894 int len;
1895 const struct mbuf *m2;
1896
1897 len = m->m_pkthdr.len;
1898 m2 = m;
1899 while (len) {
6ea70f76 1900 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
984263bc
MD
1901 len -= m2->m_len;
1902 m2 = m2->m_next;
1903 }
1904 return;
1905}
1906
1907/*
1908 * "Move" mbuf pkthdr from "from" to "to".
1909 * "from" must have M_PKTHDR set, and "to" must be empty.
1910 */
1911void
1912m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1913{
e0d05288 1914 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
984263bc 1915
77e294a1 1916 to->m_flags |= from->m_flags & M_COPYFLAGS;
984263bc
MD
1917 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1918 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
984263bc
MD
1919}
1920
1921/*
1922 * Duplicate "from"'s mbuf pkthdr in "to".
1923 * "from" must have M_PKTHDR set, and "to" must be empty.
1924 * In particular, this does a deep copy of the packet tags.
1925 */
1926int
f15db79e 1927m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
984263bc 1928{
7f3602fe
JH
1929 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
1930
4bac35fc 1931 to->m_flags = (from->m_flags & M_COPYFLAGS) |
c4da22e4 1932 (to->m_flags & ~M_COPYFLAGS);
984263bc
MD
1933 to->m_pkthdr = from->m_pkthdr;
1934 SLIST_INIT(&to->m_pkthdr.tags);
1935 return (m_tag_copy_chain(to, from, how));
1936}
1937
1938/*
1939 * Defragment a mbuf chain, returning the shortest possible
1940 * chain of mbufs and clusters. If allocation fails and
1941 * this cannot be completed, NULL will be returned, but
1942 * the passed in chain will be unchanged. Upon success,
1943 * the original chain will be freed, and the new chain
1944 * will be returned.
1945 *
1946 * If a non-packet header is passed in, the original
1947 * mbuf (chain?) will be returned unharmed.
c8f5127a
JS
1948 *
1949 * m_defrag_nofree doesn't free the passed in mbuf.
984263bc
MD
1950 */
1951struct mbuf *
1952m_defrag(struct mbuf *m0, int how)
1953{
c8f5127a
JS
1954 struct mbuf *m_new;
1955
1956 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1957 return (NULL);
1958 if (m_new != m0)
1959 m_freem(m0);
1960 return (m_new);
1961}
1962
1963struct mbuf *
1964m_defrag_nofree(struct mbuf *m0, int how)
1965{
984263bc 1966 struct mbuf *m_new = NULL, *m_final = NULL;
61721e90 1967 int progress = 0, length, nsize;
984263bc
MD
1968
1969 if (!(m0->m_flags & M_PKTHDR))
1970 return (m0);
1971
1972#ifdef MBUF_STRESS_TEST
1973 if (m_defragrandomfailures) {
0ced1954 1974 int temp = karc4random() & 0xff;
984263bc
MD
1975 if (temp == 0xba)
1976 goto nospace;
1977 }
1978#endif
1979
61721e90 1980 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
984263bc
MD
1981 if (m_final == NULL)
1982 goto nospace;
61721e90 1983 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
984263bc 1984
3641b7ca 1985 if (m_dup_pkthdr(m_final, m0, how) == 0)
984263bc
MD
1986 goto nospace;
1987
1988 m_new = m_final;
1989
1990 while (progress < m0->m_pkthdr.len) {
1991 length = m0->m_pkthdr.len - progress;
1992 if (length > MCLBYTES)
1993 length = MCLBYTES;
1994
1995 if (m_new == NULL) {
61721e90 1996 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
984263bc
MD
1997 if (m_new == NULL)
1998 goto nospace;
1999 }
2000
2001 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
2002 progress += length;
2003 m_new->m_len = length;
2004 if (m_new != m_final)
2005 m_cat(m_final, m_new);
2006 m_new = NULL;
2007 }
2008 if (m0->m_next == NULL)
2009 m_defraguseless++;
984263bc 2010 m_defragpackets++;
c8f5127a
JS
2011 m_defragbytes += m_final->m_pkthdr.len;
2012 return (m_final);
984263bc
MD
2013nospace:
2014 m_defragfailure++;
2015 if (m_new)
2016 m_free(m_new);
61721e90 2017 m_freem(m_final);
984263bc
MD
2018 return (NULL);
2019}
0c33f36d
JH
2020
2021/*
2022 * Move data from uio into mbufs.
0c33f36d
JH
2023 */
2024struct mbuf *
e12241e1 2025m_uiomove(struct uio *uio)
0c33f36d 2026{
0c33f36d 2027 struct mbuf *m; /* current working mbuf */
e12241e1
JH
2028 struct mbuf *head = NULL; /* result mbuf chain */
2029 struct mbuf **mp = &head;
e54488bb
MD
2030 int flags = M_PKTHDR;
2031 int nsize;
2032 int error;
2033 int resid;
0c33f36d 2034
0c33f36d 2035 do {
e54488bb
MD
2036 if (uio->uio_resid > INT_MAX)
2037 resid = INT_MAX;
2038 else
2039 resid = (int)uio->uio_resid;
e12241e1 2040 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
61721e90
JH
2041 if (flags) {
2042 m->m_pkthdr.len = 0;
2043 /* Leave room for protocol headers. */
2044 if (resid < MHLEN)
2045 MH_ALIGN(m, resid);
2046 flags = 0;
0c33f36d 2047 }
e54488bb 2048 m->m_len = imin(nsize, resid);
61721e90 2049 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
0c33f36d
JH
2050 if (error) {
2051 m_free(m);
2052 goto failed;
2053 }
0c33f36d
JH
2054 *mp = m;
2055 mp = &m->m_next;
61721e90 2056 head->m_pkthdr.len += m->m_len;
e54488bb 2057 } while (uio->uio_resid > 0);
0c33f36d
JH
2058
2059 return (head);
2060
2061failed:
61721e90 2062 m_freem(head);
0c33f36d
JH
2063 return (NULL);
2064}
df80f2ea 2065
50503f0f
JH
2066struct mbuf *
2067m_last(struct mbuf *m)
2068{
2069 while (m->m_next)
2070 m = m->m_next;
2071 return (m);
2072}
2073
df80f2ea
JH
2074/*
2075 * Return the number of bytes in an mbuf chain.
2076 * If lastm is not NULL, also return the last mbuf.
2077 */
2078u_int
2079m_lengthm(struct mbuf *m, struct mbuf **lastm)
2080{
2081 u_int len = 0;
2082 struct mbuf *prev = m;
2083
2084 while (m) {
2085 len += m->m_len;
2086 prev = m;
2087 m = m->m_next;
2088 }
2089 if (lastm != NULL)
2090 *lastm = prev;
2091 return (len);
2092}
2093
2094/*
2095 * Like m_lengthm(), except also keep track of mbuf usage.
2096 */
2097u_int
2098m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
2099{
2100 u_int len = 0, mbcnt = 0;
2101 struct mbuf *prev = m;
2102
2103 while (m) {
2104 len += m->m_len;
2105 mbcnt += MSIZE;
2106 if (m->m_flags & M_EXT)
2107 mbcnt += m->m_ext.ext_size;
2108 prev = m;
2109 m = m->m_next;
2110 }
2111 if (lastm != NULL)
2112 *lastm = prev;
2113 *pmbcnt = mbcnt;
2114 return (len);
2115}