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