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