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