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