AMD64 - Refactor uio_resid and size_t assumptions.
[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);
480 if (cl == NULL)
481 return (FALSE);
77e294a1 482 m->m_flags |= M_CLCACHE;
7b6f875f
JH
483 linkcluster(m, cl);
484 return (TRUE);
485}
984263bc 486
7b6f875f
JH
487static boolean_t
488mbufcluster_ctor(void *obj, void *private, int ocflags)
984263bc 489{
7b6f875f
JH
490 struct mbuf *m = obj;
491 struct mbcluster *cl;
492
493 mbuf_ctor(obj, private, ocflags);
494 cl = objcache_get(mclmeta_cache, ocflags);
495 if (cl == NULL)
496 return (FALSE);
77e294a1 497 m->m_flags |= M_CLCACHE;
7b6f875f
JH
498 linkcluster(m, cl);
499 return (TRUE);
500}
984263bc 501
77e294a1
MD
502/*
503 * Used for both the cluster and cluster PHDR caches.
504 *
505 * The mbuf may have lost its cluster due to sharing, deal
506 * with the situation by checking M_EXT.
507 */
7b6f875f
JH
508static void
509mbufcluster_dtor(void *obj, void *private)
984263bc 510{
7b6f875f 511 struct mbuf *m = obj;
77e294a1 512 struct mbcluster *mcl;
984263bc 513
77e294a1
MD
514 if (m->m_flags & M_EXT) {
515 KKASSERT((m->m_flags & M_EXT_CLUSTER) != 0);
516 mcl = m->m_ext.ext_arg;
517 KKASSERT(mcl->mcl_refs == 1);
518 mcl->mcl_refs = 0;
519 objcache_put(mclmeta_cache, mcl);
520 }
984263bc
MD
521}
522
7b6f875f
JH
523struct objcache_malloc_args mbuf_malloc_args = { MSIZE, M_MBUF };
524struct objcache_malloc_args mclmeta_malloc_args =
525 { sizeof(struct mbcluster), M_MCLMETA };
526
527/* ARGSUSED*/
90775e29 528static void
7b6f875f 529mbinit(void *dummy)
984263bc 530{
6f21e2f4 531 int mb_limit, cl_limit;
0aa16b5d 532 int limit;
4c1e2509
JT
533 int i;
534
0aa16b5d
SZ
535 /*
536 * Initialize statistics
537 */
538 for (i = 0; i < ncpus; i++) {
4c1e2509
JT
539 atomic_set_long_nonlocked(&mbstat[i].m_msize, MSIZE);
540 atomic_set_long_nonlocked(&mbstat[i].m_mclbytes, MCLBYTES);
541 atomic_set_long_nonlocked(&mbstat[i].m_minclsize, MINCLSIZE);
542 atomic_set_long_nonlocked(&mbstat[i].m_mlen, MLEN);
543 atomic_set_long_nonlocked(&mbstat[i].m_mhlen, MHLEN);
544 }
984263bc 545
0aa16b5d
SZ
546 /*
547 * Create objtect caches and save cluster limits, which will
548 * be used to adjust backing kmalloc pools' limit later.
549 */
550
6f21e2f4 551 mb_limit = cl_limit = 0;
0aa16b5d
SZ
552
553 limit = nmbufs;
554 mbuf_cache = objcache_create("mbuf", &limit, 0,
5b7da64a 555 mbuf_ctor, NULL, NULL,
7b6f875f 556 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 557 mb_limit += limit;
0aa16b5d
SZ
558
559 limit = nmbufs;
560 mbufphdr_cache = objcache_create("mbuf pkt hdr", &limit, 64,
5b7da64a 561 mbufphdr_ctor, NULL, NULL,
7b6f875f 562 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 563 mb_limit += limit;
0aa16b5d
SZ
564
565 cl_limit = nmbclusters;
566 mclmeta_cache = objcache_create("cluster mbuf", &cl_limit, 0,
7b6f875f
JH
567 mclmeta_ctor, mclmeta_dtor, NULL,
568 objcache_malloc_alloc, objcache_malloc_free, &mclmeta_malloc_args);
0aa16b5d
SZ
569
570 limit = nmbclusters;
571 mbufcluster_cache = objcache_create("mbuf + cluster", &limit, 0,
7b6f875f
JH
572 mbufcluster_ctor, mbufcluster_dtor, NULL,
573 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 574 mb_limit += limit;
0aa16b5d
SZ
575
576 limit = nmbclusters;
7b6f875f 577 mbufphdrcluster_cache = objcache_create("mbuf pkt hdr + cluster",
0aa16b5d 578 &limit, 64, mbufphdrcluster_ctor, mbufcluster_dtor, NULL,
7b6f875f 579 objcache_malloc_alloc, objcache_malloc_free, &mbuf_malloc_args);
6f21e2f4 580 mb_limit += limit;
0aa16b5d
SZ
581
582 /*
583 * Adjust backing kmalloc pools' limit
3f98f485
SZ
584 *
585 * NOTE: We raise the limit by another 1/8 to take the effect
586 * of loosememuse into account.
0aa16b5d 587 */
3f98f485 588 cl_limit += cl_limit / 8;
0aa16b5d
SZ
589 kmalloc_raise_limit(mclmeta_malloc_args.mtype,
590 mclmeta_malloc_args.objsize * cl_limit);
591 kmalloc_raise_limit(M_MBUFCL, MCLBYTES * cl_limit);
592
3f98f485 593 mb_limit += mb_limit / 8;
0aa16b5d
SZ
594 kmalloc_raise_limit(mbuf_malloc_args.mtype,
595 mbuf_malloc_args.objsize * mb_limit);
90775e29 596}
984263bc 597
90775e29
MD
598/*
599 * Return the number of references to this mbuf's data. 0 is returned
600 * if the mbuf is not M_EXT, a reference count is returned if it is
7b6f875f 601 * M_EXT | M_EXT_CLUSTER, and 99 is returned if it is a special M_EXT.
90775e29
MD
602 */
603int
604m_sharecount(struct mbuf *m)
605{
7b6f875f
JH
606 switch (m->m_flags & (M_EXT | M_EXT_CLUSTER)) {
607 case 0:
608 return (0);
609 case M_EXT:
610 return (99);
611 case M_EXT | M_EXT_CLUSTER:
612 return (((struct mbcluster *)m->m_ext.ext_arg)->mcl_refs);
613 }
614 /* NOTREACHED */
615 return (0); /* to shut up compiler */
90775e29
MD
616}
617
618/*
619 * change mbuf to new type
620 */
621void
622m_chtype(struct mbuf *m, int type)
623{
4c1e2509
JT
624 struct globaldata *gd = mycpu;
625
626 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
627 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
628 atomic_set_short_nonlocked(&m->m_type, type);
984263bc
MD
629}
630
984263bc 631static void
8a3125c6 632m_reclaim(void)
984263bc 633{
1fd87d54
RG
634 struct domain *dp;
635 struct protosw *pr;
984263bc 636
c6339e39 637 crit_enter();
9c70fe43 638 SLIST_FOREACH(dp, &domains, dom_next) {
8a3125c6 639 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
984263bc
MD
640 if (pr->pr_drain)
641 (*pr->pr_drain)();
8a3125c6
MD
642 }
643 }
c6339e39 644 crit_exit();
4c1e2509 645 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_drain, 1);
984263bc
MD
646}
647
7b6f875f
JH
648static void __inline
649updatestats(struct mbuf *m, int type)
650{
4c1e2509 651 struct globaldata *gd = mycpu;
7b6f875f
JH
652 m->m_type = type;
653
e9fa4b60 654 mbuftrack(m);
4c1e2509
JT
655
656 atomic_add_long_nonlocked(&mbtypes[gd->gd_cpuid][type], 1);
657 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
658
7b6f875f
JH
659}
660
984263bc 661/*
7b6f875f 662 * Allocate an mbuf.
984263bc
MD
663 */
664struct mbuf *
8a3125c6 665m_get(int how, int type)
984263bc 666{
12496bdf 667 struct mbuf *m;
7b6f875f
JH
668 int ntries = 0;
669 int ocf = MBTOM(how);
12496bdf 670
7b6f875f
JH
671retryonce:
672
673 m = objcache_get(mbuf_cache, ocf);
674
675 if (m == NULL) {
676 if ((how & MB_TRYWAIT) && ntries++ == 0) {
677 struct objcache *reclaimlist[] = {
678 mbufphdr_cache,
679 mbufcluster_cache, mbufphdrcluster_cache
680 };
681 const int nreclaims = __arysize(reclaimlist);
682
683 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
684 m_reclaim();
685 goto retryonce;
c6339e39 686 }
7b6f875f 687 return (NULL);
12496bdf 688 }
c6339e39 689
7b6f875f 690 updatestats(m, type);
984263bc
MD
691 return (m);
692}
693
694struct mbuf *
8a3125c6 695m_gethdr(int how, int type)
984263bc 696{
12496bdf 697 struct mbuf *m;
7b6f875f
JH
698 int ocf = MBTOM(how);
699 int ntries = 0;
12496bdf 700
7b6f875f
JH
701retryonce:
702
703 m = objcache_get(mbufphdr_cache, ocf);
704
705 if (m == NULL) {
706 if ((how & MB_TRYWAIT) && ntries++ == 0) {
707 struct objcache *reclaimlist[] = {
708 mbuf_cache,
709 mbufcluster_cache, mbufphdrcluster_cache
710 };
711 const int nreclaims = __arysize(reclaimlist);
712
713 if (!objcache_reclaimlist(reclaimlist, nreclaims, ocf))
714 m_reclaim();
715 goto retryonce;
c6339e39 716 }
7b6f875f 717 return (NULL);
12496bdf 718 }
c6339e39 719
7b6f875f 720 updatestats(m, type);
984263bc
MD
721 return (m);
722}
723
7b6f875f
JH
724/*
725 * Get a mbuf (not a mbuf cluster!) and zero it.
726 * Deprecated.
727 */
984263bc 728struct mbuf *
8a3125c6 729m_getclr(int how, int type)
984263bc 730{
1fd87d54 731 struct mbuf *m;
984263bc 732
7b6f875f
JH
733 m = m_get(how, type);
734 if (m != NULL)
735 bzero(m->m_data, MLEN);
984263bc
MD
736 return (m);
737}
738
739/*
7b6f875f 740 * Returns an mbuf with an attached cluster.
984263bc
MD
741 * Because many network drivers use this kind of buffers a lot, it is
742 * convenient to keep a small pool of free buffers of this kind.
743 * Even a small size such as 10 gives about 10% improvement in the
744 * forwarding rate in a bridge or router.
984263bc 745 */
984263bc
MD
746struct mbuf *
747m_getcl(int how, short type, int flags)
748{
7b6f875f
JH
749 struct mbuf *m;
750 int ocflags = MBTOM(how);
751 int ntries = 0;
984263bc 752
7b6f875f
JH
753retryonce:
754
755 if (flags & M_PKTHDR)
756 m = objcache_get(mbufphdrcluster_cache, ocflags);
757 else
758 m = objcache_get(mbufcluster_cache, ocflags);
759
760 if (m == NULL) {
761 if ((how & MB_TRYWAIT) && ntries++ == 0) {
762 struct objcache *reclaimlist[1];
763
764 if (flags & M_PKTHDR)
765 reclaimlist[0] = mbufcluster_cache;
766 else
767 reclaimlist[0] = mbufphdrcluster_cache;
768 if (!objcache_reclaimlist(reclaimlist, 1, ocflags))
769 m_reclaim();
770 goto retryonce;
984263bc 771 }
7b6f875f 772 return (NULL);
984263bc 773 }
7b6f875f
JH
774
775 m->m_type = type;
776
e9fa4b60 777 mbuftrack(m);
4c1e2509
JT
778
779 atomic_add_long_nonlocked(&mbtypes[mycpu->gd_cpuid][type], 1);
780 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
7b6f875f 781 return (m);
984263bc
MD
782}
783
784/*
50503f0f
JH
785 * Allocate chain of requested length.
786 */
787struct mbuf *
788m_getc(int len, int how, int type)
789{
790 struct mbuf *n, *nfirst = NULL, **ntail = &nfirst;
791 int nsize;
792
793 while (len > 0) {
794 n = m_getl(len, how, type, 0, &nsize);
795 if (n == NULL)
796 goto failed;
797 n->m_len = 0;
798 *ntail = n;
799 ntail = &n->m_next;
800 len -= nsize;
801 }
802 return (nfirst);
803
804failed:
805 m_freem(nfirst);
806 return (NULL);
807}
808
809/*
810 * Allocate len-worth of mbufs and/or mbuf clusters (whatever fits best)
811 * and return a pointer to the head of the allocated chain. If m0 is
984263bc
MD
812 * non-null, then we assume that it is a single mbuf or an mbuf chain to
813 * which we want len bytes worth of mbufs and/or clusters attached, and so
50503f0f 814 * if we succeed in allocating it, we will just return a pointer to m0.
984263bc
MD
815 *
816 * If we happen to fail at any point during the allocation, we will free
817 * up everything we have already allocated and return NULL.
818 *
50503f0f 819 * Deprecated. Use m_getc() and m_cat() instead.
984263bc
MD
820 */
821struct mbuf *
dc14b0a9 822m_getm(struct mbuf *m0, int len, int type, int how)
984263bc 823{
50503f0f 824 struct mbuf *nfirst;
984263bc 825
50503f0f 826 nfirst = m_getc(len, how, type);
984263bc 827
50503f0f
JH
828 if (m0 != NULL) {
829 m_last(m0)->m_next = nfirst;
830 return (m0);
984263bc
MD
831 }
832
50503f0f 833 return (nfirst);
984263bc
MD
834}
835
836/*
7b6f875f
JH
837 * Adds a cluster to a normal mbuf, M_EXT is set on success.
838 * Deprecated. Use m_getcl() instead.
b6650ec0 839 */
90775e29
MD
840void
841m_mclget(struct mbuf *m, int how)
b6650ec0 842{
7b6f875f 843 struct mbcluster *mcl;
b6650ec0 844
77e294a1 845 KKASSERT((m->m_flags & M_EXT) == 0);
7b6f875f 846 mcl = objcache_get(mclmeta_cache, MBTOM(how));
c3ef87ca
MD
847 if (mcl != NULL) {
848 linkcluster(m, mcl);
4c1e2509 849 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
c3ef87ca 850 }
b6650ec0
MD
851}
852
df8d1020
MD
853/*
854 * Updates to mbcluster must be MPSAFE. Only an entity which already has
855 * a reference to the cluster can ref it, so we are in no danger of
856 * racing an add with a subtract. But the operation must still be atomic
857 * since multiple entities may have a reference on the cluster.
858 *
859 * m_mclfree() is almost the same but it must contend with two entities
860 * freeing the cluster at the same time. If there is only one reference
861 * count we are the only entity referencing the cluster and no further
862 * locking is required. Otherwise we must protect against a race to 0
863 * with the serializer.
864 */
90775e29 865static void
7b6f875f 866m_mclref(void *arg)
b6650ec0 867{
7b6f875f 868 struct mbcluster *mcl = arg;
90775e29 869
7b6f875f 870 atomic_add_int(&mcl->mcl_refs, 1);
b6650ec0
MD
871}
872
1d16b2b5
MD
873/*
874 * When dereferencing a cluster we have to deal with a N->0 race, where
875 * N entities free their references simultaniously. To do this we use
dee87a60 876 * atomic_fetchadd_int().
1d16b2b5 877 */
90775e29 878static void
7b6f875f 879m_mclfree(void *arg)
b6650ec0 880{
7b6f875f 881 struct mbcluster *mcl = arg;
90775e29 882
dee87a60 883 if (atomic_fetchadd_int(&mcl->mcl_refs, -1) == 1)
77e294a1 884 objcache_put(mclmeta_cache, mcl);
b6650ec0
MD
885}
886
7eccf245 887/*
b6650ec0
MD
888 * Free a single mbuf and any associated external storage. The successor,
889 * if any, is returned.
984263bc 890 *
b6650ec0 891 * We do need to check non-first mbuf for m_aux, since some of existing
984263bc
MD
892 * code does not call M_PREPEND properly.
893 * (example: call to bpf_mtap from drivers)
894 */
984263bc 895struct mbuf *
b6650ec0 896m_free(struct mbuf *m)
984263bc 897{
b6650ec0 898 struct mbuf *n;
4c1e2509 899 struct globaldata *gd = mycpu;
b6650ec0 900
361af367 901 KASSERT(m->m_type != MT_FREE, ("freeing free mbuf %p", m));
4c1e2509 902 atomic_subtract_long_nonlocked(&mbtypes[gd->gd_cpuid][m->m_type], 1);
90775e29 903
7b6f875f 904 n = m->m_next;
90775e29
MD
905
906 /*
7b6f875f
JH
907 * Make sure the mbuf is in constructed state before returning it
908 * to the objcache.
90775e29 909 */
90775e29 910 m->m_next = NULL;
e9fa4b60 911 mbufuntrack(m);
7b6f875f
JH
912#ifdef notyet
913 KKASSERT(m->m_nextpkt == NULL);
914#else
915 if (m->m_nextpkt != NULL) {
7b6f875f
JH
916 static int afewtimes = 10;
917
918 if (afewtimes-- > 0) {
6ea70f76 919 kprintf("mfree: m->m_nextpkt != NULL\n");
1e5fb84b 920 print_backtrace();
90775e29 921 }
7b6f875f
JH
922 m->m_nextpkt = NULL;
923 }
924#endif
925 if (m->m_flags & M_PKTHDR) {
7b6f875f 926 m_tag_delete_chain(m); /* eliminate XXX JH */
77e294a1
MD
927 }
928
929 m->m_flags &= (M_EXT | M_EXT_CLUSTER | M_CLCACHE | M_PHCACHE);
930
931 /*
932 * Clean the M_PKTHDR state so we can return the mbuf to its original
933 * cache. This is based on the PHCACHE flag which tells us whether
934 * the mbuf was originally allocated out of a packet-header cache
935 * or a non-packet-header cache.
936 */
937 if (m->m_flags & M_PHCACHE) {
938 m->m_flags |= M_PKTHDR;
939 m->m_pkthdr.rcvif = NULL; /* eliminate XXX JH */
7b6f875f
JH
940 m->m_pkthdr.csum_flags = 0; /* eliminate XXX JH */
941 m->m_pkthdr.fw_flags = 0; /* eliminate XXX JH */
6b1d6bed 942 SLIST_INIT(&m->m_pkthdr.tags);
90775e29 943 }
7b6f875f 944
77e294a1
MD
945 /*
946 * Handle remaining flags combinations. M_CLCACHE tells us whether
947 * the mbuf was originally allocated from a cluster cache or not,
948 * and is totally separate from whether the mbuf is currently
949 * associated with a cluster.
950 */
951 crit_enter();
952 switch(m->m_flags & (M_CLCACHE | M_EXT | M_EXT_CLUSTER)) {
953 case M_CLCACHE | M_EXT | M_EXT_CLUSTER:
954 /*
955 * mbuf+cluster cache case. The mbuf was allocated from the
956 * combined mbuf_cluster cache and can be returned to the
957 * cache if the cluster hasn't been shared.
958 */
959 if (m_sharecount(m) == 1) {
960 /*
961 * The cluster has not been shared, we can just
962 * reset the data pointer and return the mbuf
963 * to the cluster cache. Note that the reference
964 * count is left intact (it is still associated with
965 * an mbuf).
966 */
967 m->m_data = m->m_ext.ext_buf;
968 if (m->m_flags & M_PHCACHE)
969 objcache_put(mbufphdrcluster_cache, m);
970 else
971 objcache_put(mbufcluster_cache, m);
4c1e2509 972 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
77e294a1
MD
973 } else {
974 /*
975 * Hell. Someone else has a ref on this cluster,
976 * we have to disconnect it which means we can't
977 * put it back into the mbufcluster_cache, we
978 * have to destroy the mbuf.
979 *
cb086467
MD
980 * Other mbuf references to the cluster will typically
981 * be M_EXT | M_EXT_CLUSTER but without M_CLCACHE.
982 *
77e294a1
MD
983 * XXX we could try to connect another cluster to
984 * it.
985 */
7b6f875f
JH
986 m->m_ext.ext_free(m->m_ext.ext_arg);
987 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
77e294a1
MD
988 if (m->m_flags & M_PHCACHE)
989 objcache_dtor(mbufphdrcluster_cache, m);
990 else
991 objcache_dtor(mbufcluster_cache, m);
7b6f875f 992 }
77e294a1
MD
993 break;
994 case M_EXT | M_EXT_CLUSTER:
995 /*
996 * Normal cluster associated with an mbuf that was allocated
997 * from the normal mbuf pool rather then the cluster pool.
998 * The cluster has to be independantly disassociated from the
999 * mbuf.
1000 */
cb086467 1001 if (m_sharecount(m) == 1)
4c1e2509 1002 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_clusters, 1);
77e294a1
MD
1003 /* fall through */
1004 case M_EXT:
1005 /*
1006 * Normal cluster association case, disconnect the cluster from
1007 * the mbuf. The cluster may or may not be custom.
1008 */
1009 m->m_ext.ext_free(m->m_ext.ext_arg);
1010 m->m_flags &= ~(M_EXT | M_EXT_CLUSTER);
1011 /* fall through */
1012 case 0:
1013 /*
1014 * return the mbuf to the mbuf cache.
1015 */
1016 if (m->m_flags & M_PHCACHE) {
7b6f875f
JH
1017 m->m_data = m->m_pktdat;
1018 objcache_put(mbufphdr_cache, m);
90775e29 1019 } else {
7b6f875f
JH
1020 m->m_data = m->m_dat;
1021 objcache_put(mbuf_cache, m);
90775e29 1022 }
4c1e2509 1023 atomic_subtract_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mbufs, 1);
77e294a1
MD
1024 break;
1025 default:
1026 if (!panicstr)
1027 panic("bad mbuf flags %p %08x\n", m, m->m_flags);
1028 break;
b6650ec0 1029 }
77e294a1 1030 crit_exit();
984263bc
MD
1031 return (n);
1032}
1033
1034void
b6650ec0 1035m_freem(struct mbuf *m)
984263bc 1036{
c6339e39 1037 crit_enter();
90775e29
MD
1038 while (m)
1039 m = m_free(m);
c6339e39 1040 crit_exit();
984263bc
MD
1041}
1042
1043/*
df80f2ea 1044 * mbuf utility routines
984263bc
MD
1045 */
1046
1047/*
7b6f875f 1048 * Lesser-used path for M_PREPEND: allocate new mbuf to prepend to chain and
984263bc
MD
1049 * copy junk along.
1050 */
1051struct mbuf *
8a3125c6 1052m_prepend(struct mbuf *m, int len, int how)
984263bc
MD
1053{
1054 struct mbuf *mn;
1055
c3ef87ca
MD
1056 if (m->m_flags & M_PKTHDR)
1057 mn = m_gethdr(how, m->m_type);
1058 else
1059 mn = m_get(how, m->m_type);
7b6f875f 1060 if (mn == NULL) {
984263bc 1061 m_freem(m);
7b6f875f 1062 return (NULL);
984263bc
MD
1063 }
1064 if (m->m_flags & M_PKTHDR)
1065 M_MOVE_PKTHDR(mn, m);
1066 mn->m_next = m;
1067 m = mn;
1068 if (len < MHLEN)
1069 MH_ALIGN(m, len);
1070 m->m_len = len;
1071 return (m);
1072}
1073
1074/*
1075 * Make a copy of an mbuf chain starting "off0" bytes from the beginning,
1076 * continuing for "len" bytes. If len is M_COPYALL, copy to end of mbuf.
74f1caca 1077 * The wait parameter is a choice of MB_WAIT/MB_DONTWAIT from caller.
984263bc
MD
1078 * Note that the copy is read-only, because clusters are not copied,
1079 * only their reference counts are incremented.
1080 */
984263bc 1081struct mbuf *
8a3125c6 1082m_copym(const struct mbuf *m, int off0, int len, int wait)
984263bc 1083{
1fd87d54
RG
1084 struct mbuf *n, **np;
1085 int off = off0;
984263bc
MD
1086 struct mbuf *top;
1087 int copyhdr = 0;
1088
1089 KASSERT(off >= 0, ("m_copym, negative off %d", off));
1090 KASSERT(len >= 0, ("m_copym, negative len %d", len));
1091 if (off == 0 && m->m_flags & M_PKTHDR)
1092 copyhdr = 1;
1093 while (off > 0) {
1094 KASSERT(m != NULL, ("m_copym, offset > size of mbuf chain"));
1095 if (off < m->m_len)
1096 break;
1097 off -= m->m_len;
1098 m = m->m_next;
1099 }
1100 np = &top;
1101 top = 0;
1102 while (len > 0) {
7b6f875f 1103 if (m == NULL) {
984263bc
MD
1104 KASSERT(len == M_COPYALL,
1105 ("m_copym, length > size of mbuf chain"));
1106 break;
1107 }
c3ef87ca
MD
1108 /*
1109 * Because we are sharing any cluster attachment below,
1110 * be sure to get an mbuf that does not have a cluster
1111 * associated with it.
1112 */
1113 if (copyhdr)
1114 n = m_gethdr(wait, m->m_type);
1115 else
1116 n = m_get(wait, m->m_type);
984263bc 1117 *np = n;
7b6f875f 1118 if (n == NULL)
984263bc
MD
1119 goto nospace;
1120 if (copyhdr) {
1121 if (!m_dup_pkthdr(n, m, wait))
1122 goto nospace;
1123 if (len == M_COPYALL)
1124 n->m_pkthdr.len -= off0;
1125 else
1126 n->m_pkthdr.len = len;
1127 copyhdr = 0;
1128 }
1129 n->m_len = min(len, m->m_len - off);
1130 if (m->m_flags & M_EXT) {
c3ef87ca 1131 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1132 n->m_data = m->m_data + off;
7b6f875f 1133 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1134 n->m_ext = m->m_ext;
b542cd49 1135 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
7eccf245 1136 } else {
984263bc
MD
1137 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
1138 (unsigned)n->m_len);
7eccf245 1139 }
984263bc
MD
1140 if (len != M_COPYALL)
1141 len -= n->m_len;
1142 off = 0;
1143 m = m->m_next;
1144 np = &n->m_next;
1145 }
7b6f875f 1146 if (top == NULL)
4c1e2509 1147 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
984263bc
MD
1148 return (top);
1149nospace:
1150 m_freem(top);
4c1e2509 1151 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1152 return (NULL);
984263bc
MD
1153}
1154
1155/*
1156 * Copy an entire packet, including header (which must be present).
1157 * An optimization of the common case `m_copym(m, 0, M_COPYALL, how)'.
1158 * Note that the copy is read-only, because clusters are not copied,
1159 * only their reference counts are incremented.
1160 * Preserve alignment of the first mbuf so if the creator has left
1161 * some room at the beginning (e.g. for inserting protocol headers)
1162 * the copies also have the room available.
1163 */
1164struct mbuf *
8a3125c6 1165m_copypacket(struct mbuf *m, int how)
984263bc
MD
1166{
1167 struct mbuf *top, *n, *o;
1168
7f3602fe 1169 n = m_gethdr(how, m->m_type);
984263bc
MD
1170 top = n;
1171 if (!n)
1172 goto nospace;
1173
1174 if (!m_dup_pkthdr(n, m, how))
1175 goto nospace;
1176 n->m_len = m->m_len;
1177 if (m->m_flags & M_EXT) {
c3ef87ca 1178 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1179 n->m_data = m->m_data;
7b6f875f 1180 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1181 n->m_ext = m->m_ext;
b542cd49 1182 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1183 } else {
1184 n->m_data = n->m_pktdat + (m->m_data - m->m_pktdat );
1185 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1186 }
1187
1188 m = m->m_next;
1189 while (m) {
7b6f875f 1190 o = m_get(how, m->m_type);
984263bc
MD
1191 if (!o)
1192 goto nospace;
1193
1194 n->m_next = o;
1195 n = n->m_next;
1196
1197 n->m_len = m->m_len;
1198 if (m->m_flags & M_EXT) {
c3ef87ca 1199 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1200 n->m_data = m->m_data;
7b6f875f 1201 m->m_ext.ext_ref(m->m_ext.ext_arg);
984263bc 1202 n->m_ext = m->m_ext;
b542cd49 1203 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1204 } else {
1205 bcopy(mtod(m, char *), mtod(n, char *), n->m_len);
1206 }
1207
1208 m = m->m_next;
1209 }
1210 return top;
1211nospace:
1212 m_freem(top);
4c1e2509 1213 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1214 return (NULL);
984263bc
MD
1215}
1216
1217/*
1218 * Copy data from an mbuf chain starting "off" bytes from the beginning,
1219 * continuing for "len" bytes, into the indicated buffer.
1220 */
1221void
8a3125c6 1222m_copydata(const struct mbuf *m, int off, int len, caddr_t cp)
984263bc 1223{
1fd87d54 1224 unsigned count;
984263bc
MD
1225
1226 KASSERT(off >= 0, ("m_copydata, negative off %d", off));
1227 KASSERT(len >= 0, ("m_copydata, negative len %d", len));
1228 while (off > 0) {
1229 KASSERT(m != NULL, ("m_copydata, offset > size of mbuf chain"));
1230 if (off < m->m_len)
1231 break;
1232 off -= m->m_len;
1233 m = m->m_next;
1234 }
1235 while (len > 0) {
1236 KASSERT(m != NULL, ("m_copydata, length > size of mbuf chain"));
1237 count = min(m->m_len - off, len);
1238 bcopy(mtod(m, caddr_t) + off, cp, count);
1239 len -= count;
1240 cp += count;
1241 off = 0;
1242 m = m->m_next;
1243 }
1244}
1245
1246/*
1247 * Copy a packet header mbuf chain into a completely new chain, including
1248 * copying any mbuf clusters. Use this instead of m_copypacket() when
1249 * you need a writable copy of an mbuf chain.
1250 */
1251struct mbuf *
8a3125c6 1252m_dup(struct mbuf *m, int how)
984263bc
MD
1253{
1254 struct mbuf **p, *top = NULL;
1255 int remain, moff, nsize;
1256
1257 /* Sanity check */
1258 if (m == NULL)
50503f0f 1259 return (NULL);
5e2195bf 1260 KASSERT((m->m_flags & M_PKTHDR) != 0, ("%s: !PKTHDR", __func__));
984263bc
MD
1261
1262 /* While there's more data, get a new mbuf, tack it on, and fill it */
1263 remain = m->m_pkthdr.len;
1264 moff = 0;
1265 p = &top;
1266 while (remain > 0 || top == NULL) { /* allow m->m_pkthdr.len == 0 */
1267 struct mbuf *n;
1268
1269 /* Get the next new mbuf */
50503f0f
JH
1270 n = m_getl(remain, how, m->m_type, top == NULL ? M_PKTHDR : 0,
1271 &nsize);
984263bc
MD
1272 if (n == NULL)
1273 goto nospace;
50503f0f 1274 if (top == NULL)
984263bc 1275 if (!m_dup_pkthdr(n, m, how))
50503f0f 1276 goto nospace0;
984263bc
MD
1277
1278 /* Link it into the new chain */
1279 *p = n;
1280 p = &n->m_next;
1281
1282 /* Copy data from original mbuf(s) into new mbuf */
50503f0f 1283 n->m_len = 0;
984263bc
MD
1284 while (n->m_len < nsize && m != NULL) {
1285 int chunk = min(nsize - n->m_len, m->m_len - moff);
1286
1287 bcopy(m->m_data + moff, n->m_data + n->m_len, chunk);
1288 moff += chunk;
1289 n->m_len += chunk;
1290 remain -= chunk;
1291 if (moff == m->m_len) {
1292 m = m->m_next;
1293 moff = 0;
1294 }
1295 }
1296
1297 /* Check correct total mbuf length */
1298 KASSERT((remain > 0 && m != NULL) || (remain == 0 && m == NULL),
50503f0f 1299 ("%s: bogus m_pkthdr.len", __func__));
984263bc
MD
1300 }
1301 return (top);
1302
1303nospace:
1304 m_freem(top);
50503f0f 1305nospace0:
4c1e2509 1306 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
50503f0f 1307 return (NULL);
984263bc
MD
1308}
1309
1310/*
1311 * Concatenate mbuf chain n to m.
1312 * Both chains must be of the same type (e.g. MT_DATA).
1313 * Any m_pkthdr is not updated.
1314 */
1315void
8a3125c6 1316m_cat(struct mbuf *m, struct mbuf *n)
984263bc 1317{
50503f0f 1318 m = m_last(m);
984263bc
MD
1319 while (n) {
1320 if (m->m_flags & M_EXT ||
1321 m->m_data + m->m_len + n->m_len >= &m->m_dat[MLEN]) {
1322 /* just join the two chains */
1323 m->m_next = n;
1324 return;
1325 }
1326 /* splat the data from one into the other */
1327 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1328 (u_int)n->m_len);
1329 m->m_len += n->m_len;
1330 n = m_free(n);
1331 }
1332}
1333
1334void
8a3125c6 1335m_adj(struct mbuf *mp, int req_len)
984263bc 1336{
1fd87d54
RG
1337 int len = req_len;
1338 struct mbuf *m;
1339 int count;
984263bc
MD
1340
1341 if ((m = mp) == NULL)
1342 return;
1343 if (len >= 0) {
1344 /*
1345 * Trim from head.
1346 */
1347 while (m != NULL && len > 0) {
1348 if (m->m_len <= len) {
1349 len -= m->m_len;
1350 m->m_len = 0;
1351 m = m->m_next;
1352 } else {
1353 m->m_len -= len;
1354 m->m_data += len;
1355 len = 0;
1356 }
1357 }
1358 m = mp;
1359 if (mp->m_flags & M_PKTHDR)
1360 m->m_pkthdr.len -= (req_len - len);
1361 } else {
1362 /*
1363 * Trim from tail. Scan the mbuf chain,
1364 * calculating its length and finding the last mbuf.
1365 * If the adjustment only affects this mbuf, then just
1366 * adjust and return. Otherwise, rescan and truncate
1367 * after the remaining size.
1368 */
1369 len = -len;
1370 count = 0;
1371 for (;;) {
1372 count += m->m_len;
60233e58 1373 if (m->m_next == NULL)
984263bc
MD
1374 break;
1375 m = m->m_next;
1376 }
1377 if (m->m_len >= len) {
1378 m->m_len -= len;
1379 if (mp->m_flags & M_PKTHDR)
1380 mp->m_pkthdr.len -= len;
1381 return;
1382 }
1383 count -= len;
1384 if (count < 0)
1385 count = 0;
1386 /*
1387 * Correct length for chain is "count".
1388 * Find the mbuf with last data, adjust its length,
1389 * and toss data from remaining mbufs on chain.
1390 */
1391 m = mp;
1392 if (m->m_flags & M_PKTHDR)
1393 m->m_pkthdr.len = count;
1394 for (; m; m = m->m_next) {
1395 if (m->m_len >= count) {
1396 m->m_len = count;
1397 break;
1398 }
1399 count -= m->m_len;
1400 }
1401 while (m->m_next)
1402 (m = m->m_next) ->m_len = 0;
1403 }
1404}
1405
1406/*
7b6f875f 1407 * Rearrange an mbuf chain so that len bytes are contiguous
9e4465af
MD
1408 * and in the data area of an mbuf (so that mtod will work for a structure
1409 * of size len). Returns the resulting mbuf chain on success, frees it and
1410 * returns null on failure. If there is room, it will add up to
1411 * max_protohdr-len extra bytes to the contiguous region in an attempt to
1412 * avoid being called next time.
984263bc 1413 */
984263bc 1414struct mbuf *
8a3125c6 1415m_pullup(struct mbuf *n, int len)
984263bc 1416{
1fd87d54
RG
1417 struct mbuf *m;
1418 int count;
984263bc
MD
1419 int space;
1420
1421 /*
1422 * If first mbuf has no cluster, and has room for len bytes
1423 * without shifting current data, pullup into it,
1424 * otherwise allocate a new mbuf to prepend to the chain.
1425 */
7b6f875f
JH
1426 if (!(n->m_flags & M_EXT) &&
1427 n->m_data + len < &n->m_dat[MLEN] &&
1428 n->m_next) {
984263bc
MD
1429 if (n->m_len >= len)
1430 return (n);
1431 m = n;
1432 n = n->m_next;
1433 len -= m->m_len;
1434 } else {
1435 if (len > MHLEN)
1436 goto bad;
c3ef87ca
MD
1437 if (n->m_flags & M_PKTHDR)
1438 m = m_gethdr(MB_DONTWAIT, n->m_type);
1439 else
1440 m = m_get(MB_DONTWAIT, n->m_type);
7b6f875f 1441 if (m == NULL)
984263bc
MD
1442 goto bad;
1443 m->m_len = 0;
1444 if (n->m_flags & M_PKTHDR)
1445 M_MOVE_PKTHDR(m, n);
1446 }
1447 space = &m->m_dat[MLEN] - (m->m_data + m->m_len);
1448 do {
1449 count = min(min(max(len, max_protohdr), space), n->m_len);
1450 bcopy(mtod(n, caddr_t), mtod(m, caddr_t) + m->m_len,
1451 (unsigned)count);
1452 len -= count;
1453 m->m_len += count;
1454 n->m_len -= count;
1455 space -= count;
1456 if (n->m_len)
1457 n->m_data += count;
1458 else
1459 n = m_free(n);
1460 } while (len > 0 && n);
1461 if (len > 0) {
7b6f875f 1462 m_free(m);
984263bc
MD
1463 goto bad;
1464 }
1465 m->m_next = n;
1466 return (m);
1467bad:
1468 m_freem(n);
4c1e2509 1469 atomic_add_long_nonlocked(&mbstat[mycpu->gd_cpuid].m_mcfail, 1);
7b6f875f 1470 return (NULL);
984263bc
MD
1471}
1472
1473/*
1474 * Partition an mbuf chain in two pieces, returning the tail --
1475 * all but the first len0 bytes. In case of failure, it returns NULL and
1476 * attempts to restore the chain to its original state.
1477 *
1478 * Note that the resulting mbufs might be read-only, because the new
1479 * mbuf can end up sharing an mbuf cluster with the original mbuf if
1480 * the "breaking point" happens to lie within a cluster mbuf. Use the
1481 * M_WRITABLE() macro to check for this case.
1482 */
1483struct mbuf *
8a3125c6 1484m_split(struct mbuf *m0, int len0, int wait)
984263bc 1485{
1fd87d54 1486 struct mbuf *m, *n;
984263bc
MD
1487 unsigned len = len0, remain;
1488
1489 for (m = m0; m && len > m->m_len; m = m->m_next)
1490 len -= m->m_len;
7b6f875f
JH
1491 if (m == NULL)
1492 return (NULL);
984263bc
MD
1493 remain = m->m_len - len;
1494 if (m0->m_flags & M_PKTHDR) {
7b6f875f
JH
1495 n = m_gethdr(wait, m0->m_type);
1496 if (n == NULL)
1497 return (NULL);
984263bc
MD
1498 n->m_pkthdr.rcvif = m0->m_pkthdr.rcvif;
1499 n->m_pkthdr.len = m0->m_pkthdr.len - len0;
1500 m0->m_pkthdr.len = len0;
1501 if (m->m_flags & M_EXT)
1502 goto extpacket;
1503 if (remain > MHLEN) {
1504 /* m can't be the lead packet */
1505 MH_ALIGN(n, 0);
1506 n->m_next = m_split(m, len, wait);
7b6f875f
JH
1507 if (n->m_next == NULL) {
1508 m_free(n);
1509 return (NULL);
984263bc
MD
1510 } else {
1511 n->m_len = 0;
1512 return (n);
1513 }
1514 } else
1515 MH_ALIGN(n, remain);
1516 } else if (remain == 0) {
1517 n = m->m_next;
1518 m->m_next = 0;
1519 return (n);
1520 } else {
7b6f875f
JH
1521 n = m_get(wait, m->m_type);
1522 if (n == NULL)
1523 return (NULL);
984263bc
MD
1524 M_ALIGN(n, remain);
1525 }
1526extpacket:
1527 if (m->m_flags & M_EXT) {
c3ef87ca 1528 KKASSERT((n->m_flags & M_EXT) == 0);
984263bc 1529 n->m_data = m->m_data + len;
7b6f875f 1530 m->m_ext.ext_ref(m->m_ext.ext_arg);
7eccf245 1531 n->m_ext = m->m_ext;
b542cd49 1532 n->m_flags |= m->m_flags & (M_EXT | M_EXT_CLUSTER);
984263bc
MD
1533 } else {
1534 bcopy(mtod(m, caddr_t) + len, mtod(n, caddr_t), remain);
1535 }
1536 n->m_len = remain;
1537 m->m_len = len;
1538 n->m_next = m->m_next;
1539 m->m_next = 0;
1540 return (n);
1541}
50503f0f 1542
984263bc
MD
1543/*
1544 * Routine to copy from device local memory into mbufs.
50503f0f 1545 * Note: "offset" is ill-defined and always called as 0, so ignore it.
984263bc
MD
1546 */
1547struct mbuf *
50503f0f
JH
1548m_devget(char *buf, int len, int offset, struct ifnet *ifp,
1549 void (*copy)(volatile const void *from, volatile void *to, size_t length))
984263bc 1550{
50503f0f
JH
1551 struct mbuf *m, *mfirst = NULL, **mtail;
1552 int nsize, flags;
1553
1554 if (copy == NULL)
1555 copy = bcopy;
1556 mtail = &mfirst;
1557 flags = M_PKTHDR;
1558
1559 while (len > 0) {
1560 m = m_getl(len, MB_DONTWAIT, MT_DATA, flags, &nsize);
1561 if (m == NULL) {
1562 m_freem(mfirst);
1563 return (NULL);
984263bc 1564 }
50503f0f
JH
1565 m->m_len = min(len, nsize);
1566
1567 if (flags & M_PKTHDR) {
1568 if (len + max_linkhdr <= nsize)
1569 m->m_data += max_linkhdr;
1570 m->m_pkthdr.rcvif = ifp;
1571 m->m_pkthdr.len = len;
1572 flags = 0;
984263bc 1573 }
50503f0f
JH
1574
1575 copy(buf, m->m_data, (unsigned)m->m_len);
1576 buf += m->m_len;
1577 len -= m->m_len;
1578 *mtail = m;
1579 mtail = &m->m_next;
984263bc 1580 }
50503f0f
JH
1581
1582 return (mfirst);
984263bc
MD
1583}
1584
1585/*
cf12ba3c
SZ
1586 * Routine to pad mbuf to the specified length 'padto'.
1587 */
1588int
1589m_devpad(struct mbuf *m, int padto)
1590{
1591 struct mbuf *last = NULL;
1592 int padlen;
1593
1594 if (padto <= m->m_pkthdr.len)
1595 return 0;
1596
1597 padlen = padto - m->m_pkthdr.len;
1598
1599 /* if there's only the packet-header and we can pad there, use it. */
1600 if (m->m_pkthdr.len == m->m_len && M_TRAILINGSPACE(m) >= padlen) {
1601 last = m;
1602 } else {
1603 /*
1604 * Walk packet chain to find last mbuf. We will either
1605 * pad there, or append a new mbuf and pad it
1606 */
1607 for (last = m; last->m_next != NULL; last = last->m_next)
1608 ; /* EMPTY */
1609
1610 /* `last' now points to last in chain. */
1611 if (M_TRAILINGSPACE(last) < padlen) {
1612 struct mbuf *n;
1613
1614 /* Allocate new empty mbuf, pad it. Compact later. */
1615 MGET(n, MB_DONTWAIT, MT_DATA);
1616 if (n == NULL)
1617 return ENOBUFS;
1618 n->m_len = 0;
1619 last->m_next = n;
1620 last = n;
1621 }
1622 }
1623 KKASSERT(M_TRAILINGSPACE(last) >= padlen);
1624 KKASSERT(M_WRITABLE(last));
1625
1626 /* Now zero the pad area */
1627 bzero(mtod(last, char *) + last->m_len, padlen);
1628 last->m_len += padlen;
1629 m->m_pkthdr.len += padlen;
1630 return 0;
1631}
1632
1633/*
984263bc
MD
1634 * Copy data from a buffer back into the indicated mbuf chain,
1635 * starting "off" bytes from the beginning, extending the mbuf
1636 * chain if necessary.
1637 */
1638void
8a3125c6 1639m_copyback(struct mbuf *m0, int off, int len, caddr_t cp)
984263bc 1640{
1fd87d54
RG
1641 int mlen;
1642 struct mbuf *m = m0, *n;
984263bc
MD
1643 int totlen = 0;
1644
7b6f875f 1645 if (m0 == NULL)
984263bc
MD
1646 return;
1647 while (off > (mlen = m->m_len)) {
1648 off -= mlen;
1649 totlen += mlen;
7b6f875f 1650 if (m->m_next == NULL) {
74f1caca 1651 n = m_getclr(MB_DONTWAIT, m->m_type);
7b6f875f 1652 if (n == NULL)
984263bc
MD
1653 goto out;
1654 n->m_len = min(MLEN, len + off);
1655 m->m_next = n;
1656 }
1657 m = m->m_next;
1658 }
1659 while (len > 0) {
1660 mlen = min (m->m_len - off, len);
1661 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1662 cp += mlen;
1663 len -= mlen;
1664 mlen += off;
1665 off = 0;
1666 totlen += mlen;
1667 if (len == 0)
1668 break;
7b6f875f 1669 if (m->m_next == NULL) {
74f1caca 1670 n = m_get(MB_DONTWAIT, m->m_type);
7b6f875f 1671 if (n == NULL)
984263bc
MD
1672 break;
1673 n->m_len = min(MLEN, len);
1674 m->m_next = n;
1675 }
1676 m = m->m_next;
1677 }
1678out: if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1679 m->m_pkthdr.len = totlen;
1680}
1681
1682void
1683m_print(const struct mbuf *m)
1684{
1685 int len;
1686 const struct mbuf *m2;
1687
1688 len = m->m_pkthdr.len;
1689 m2 = m;
1690 while (len) {
6ea70f76 1691 kprintf("%p %*D\n", m2, m2->m_len, (u_char *)m2->m_data, "-");
984263bc
MD
1692 len -= m2->m_len;
1693 m2 = m2->m_next;
1694 }
1695 return;
1696}
1697
1698/*
1699 * "Move" mbuf pkthdr from "from" to "to".
1700 * "from" must have M_PKTHDR set, and "to" must be empty.
1701 */
1702void
1703m_move_pkthdr(struct mbuf *to, struct mbuf *from)
1704{
e0d05288 1705 KASSERT((to->m_flags & M_PKTHDR), ("m_move_pkthdr: not packet header"));
984263bc 1706
77e294a1 1707 to->m_flags |= from->m_flags & M_COPYFLAGS;
984263bc
MD
1708 to->m_pkthdr = from->m_pkthdr; /* especially tags */
1709 SLIST_INIT(&from->m_pkthdr.tags); /* purge tags from src */
984263bc
MD
1710}
1711
1712/*
1713 * Duplicate "from"'s mbuf pkthdr in "to".
1714 * "from" must have M_PKTHDR set, and "to" must be empty.
1715 * In particular, this does a deep copy of the packet tags.
1716 */
1717int
f15db79e 1718m_dup_pkthdr(struct mbuf *to, const struct mbuf *from, int how)
984263bc 1719{
7f3602fe
JH
1720 KASSERT((to->m_flags & M_PKTHDR), ("m_dup_pkthdr: not packet header"));
1721
4bac35fc 1722 to->m_flags = (from->m_flags & M_COPYFLAGS) |
c4da22e4 1723 (to->m_flags & ~M_COPYFLAGS);
984263bc
MD
1724 to->m_pkthdr = from->m_pkthdr;
1725 SLIST_INIT(&to->m_pkthdr.tags);
1726 return (m_tag_copy_chain(to, from, how));
1727}
1728
1729/*
1730 * Defragment a mbuf chain, returning the shortest possible
1731 * chain of mbufs and clusters. If allocation fails and
1732 * this cannot be completed, NULL will be returned, but
1733 * the passed in chain will be unchanged. Upon success,
1734 * the original chain will be freed, and the new chain
1735 * will be returned.
1736 *
1737 * If a non-packet header is passed in, the original
1738 * mbuf (chain?) will be returned unharmed.
c8f5127a
JS
1739 *
1740 * m_defrag_nofree doesn't free the passed in mbuf.
984263bc
MD
1741 */
1742struct mbuf *
1743m_defrag(struct mbuf *m0, int how)
1744{
c8f5127a
JS
1745 struct mbuf *m_new;
1746
1747 if ((m_new = m_defrag_nofree(m0, how)) == NULL)
1748 return (NULL);
1749 if (m_new != m0)
1750 m_freem(m0);
1751 return (m_new);
1752}
1753
1754struct mbuf *
1755m_defrag_nofree(struct mbuf *m0, int how)
1756{
984263bc 1757 struct mbuf *m_new = NULL, *m_final = NULL;
61721e90 1758 int progress = 0, length, nsize;
984263bc
MD
1759
1760 if (!(m0->m_flags & M_PKTHDR))
1761 return (m0);
1762
1763#ifdef MBUF_STRESS_TEST
1764 if (m_defragrandomfailures) {
0ced1954 1765 int temp = karc4random() & 0xff;
984263bc
MD
1766 if (temp == 0xba)
1767 goto nospace;
1768 }
1769#endif
1770
61721e90 1771 m_final = m_getl(m0->m_pkthdr.len, how, MT_DATA, M_PKTHDR, &nsize);
984263bc
MD
1772 if (m_final == NULL)
1773 goto nospace;
61721e90 1774 m_final->m_len = 0; /* in case m0->m_pkthdr.len is zero */
984263bc 1775
3641b7ca 1776 if (m_dup_pkthdr(m_final, m0, how) == 0)
984263bc
MD
1777 goto nospace;
1778
1779 m_new = m_final;
1780
1781 while (progress < m0->m_pkthdr.len) {
1782 length = m0->m_pkthdr.len - progress;
1783 if (length > MCLBYTES)
1784 length = MCLBYTES;
1785
1786 if (m_new == NULL) {
61721e90 1787 m_new = m_getl(length, how, MT_DATA, 0, &nsize);
984263bc
MD
1788 if (m_new == NULL)
1789 goto nospace;
1790 }
1791
1792 m_copydata(m0, progress, length, mtod(m_new, caddr_t));
1793 progress += length;
1794 m_new->m_len = length;
1795 if (m_new != m_final)
1796 m_cat(m_final, m_new);
1797 m_new = NULL;
1798 }
1799 if (m0->m_next == NULL)
1800 m_defraguseless++;
984263bc 1801 m_defragpackets++;
c8f5127a
JS
1802 m_defragbytes += m_final->m_pkthdr.len;
1803 return (m_final);
984263bc
MD
1804nospace:
1805 m_defragfailure++;
1806 if (m_new)
1807 m_free(m_new);
61721e90 1808 m_freem(m_final);
984263bc
MD
1809 return (NULL);
1810}
0c33f36d
JH
1811
1812/*
1813 * Move data from uio into mbufs.
0c33f36d
JH
1814 */
1815struct mbuf *
e12241e1 1816m_uiomove(struct uio *uio)
0c33f36d 1817{
0c33f36d 1818 struct mbuf *m; /* current working mbuf */
e12241e1
JH
1819 struct mbuf *head = NULL; /* result mbuf chain */
1820 struct mbuf **mp = &head;
e54488bb
MD
1821 int flags = M_PKTHDR;
1822 int nsize;
1823 int error;
1824 int resid;
0c33f36d 1825
0c33f36d 1826 do {
e54488bb
MD
1827 if (uio->uio_resid > INT_MAX)
1828 resid = INT_MAX;
1829 else
1830 resid = (int)uio->uio_resid;
e12241e1 1831 m = m_getl(resid, MB_WAIT, MT_DATA, flags, &nsize);
61721e90
JH
1832 if (flags) {
1833 m->m_pkthdr.len = 0;
1834 /* Leave room for protocol headers. */
1835 if (resid < MHLEN)
1836 MH_ALIGN(m, resid);
1837 flags = 0;
0c33f36d 1838 }
e54488bb 1839 m->m_len = imin(nsize, resid);
61721e90 1840 error = uiomove(mtod(m, caddr_t), m->m_len, uio);
0c33f36d
JH
1841 if (error) {
1842 m_free(m);
1843 goto failed;
1844 }
0c33f36d
JH
1845 *mp = m;
1846 mp = &m->m_next;
61721e90 1847 head->m_pkthdr.len += m->m_len;
e54488bb 1848 } while (uio->uio_resid > 0);
0c33f36d
JH
1849
1850 return (head);
1851
1852failed:
61721e90 1853 m_freem(head);
0c33f36d
JH
1854 return (NULL);
1855}
df80f2ea 1856
50503f0f
JH
1857struct mbuf *
1858m_last(struct mbuf *m)
1859{
1860 while (m->m_next)
1861 m = m->m_next;
1862 return (m);
1863}
1864
df80f2ea
JH
1865/*
1866 * Return the number of bytes in an mbuf chain.
1867 * If lastm is not NULL, also return the last mbuf.
1868 */
1869u_int
1870m_lengthm(struct mbuf *m, struct mbuf **lastm)
1871{
1872 u_int len = 0;
1873 struct mbuf *prev = m;
1874
1875 while (m) {
1876 len += m->m_len;
1877 prev = m;
1878 m = m->m_next;
1879 }
1880 if (lastm != NULL)
1881 *lastm = prev;
1882 return (len);
1883}
1884
1885/*
1886 * Like m_lengthm(), except also keep track of mbuf usage.
1887 */
1888u_int
1889m_countm(struct mbuf *m, struct mbuf **lastm, u_int *pmbcnt)
1890{
1891 u_int len = 0, mbcnt = 0;
1892 struct mbuf *prev = m;
1893
1894 while (m) {
1895 len += m->m_len;
1896 mbcnt += MSIZE;
1897 if (m->m_flags & M_EXT)
1898 mbcnt += m->m_ext.ext_size;
1899 prev = m;
1900 m = m->m_next;
1901 }
1902 if (lastm != NULL)
1903 *lastm = prev;
1904 *pmbcnt = mbcnt;
1905 return (len);
1906}