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