]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_mbuf.c
Add an external mbuf buffer type that holds multiple unmapped pages.
[FreeBSD/FreeBSD.git] / sys / kern / kern_mbuf.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004, 2005,
5  *      Bosko Milekic <bmilekic@FreeBSD.org>.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_param.h"
34
35 #include <sys/param.h>
36 #include <sys/conf.h>
37 #include <sys/domainset.h>
38 #include <sys/malloc.h>
39 #include <sys/systm.h>
40 #include <sys/mbuf.h>
41 #include <sys/domain.h>
42 #include <sys/eventhandler.h>
43 #include <sys/kernel.h>
44 #include <sys/limits.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/protosw.h>
48 #include <sys/sf_buf.h>
49 #include <sys/smp.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52
53 #include <net/if.h>
54 #include <net/if_var.h>
55
56 #include <vm/vm.h>
57 #include <vm/vm_extern.h>
58 #include <vm/vm_kern.h>
59 #include <vm/vm_page.h>
60 #include <vm/vm_map.h>
61 #include <vm/uma.h>
62 #include <vm/uma_dbg.h>
63
64 /*
65  * In FreeBSD, Mbufs and Mbuf Clusters are allocated from UMA
66  * Zones.
67  *
68  * Mbuf Clusters (2K, contiguous) are allocated from the Cluster
69  * Zone.  The Zone can be capped at kern.ipc.nmbclusters, if the
70  * administrator so desires.
71  *
72  * Mbufs are allocated from a UMA Master Zone called the Mbuf
73  * Zone.
74  *
75  * Additionally, FreeBSD provides a Packet Zone, which it
76  * configures as a Secondary Zone to the Mbuf Master Zone,
77  * thus sharing backend Slab kegs with the Mbuf Master Zone.
78  *
79  * Thus common-case allocations and locking are simplified:
80  *
81  *  m_clget()                m_getcl()
82  *    |                         |
83  *    |   .------------>[(Packet Cache)]    m_get(), m_gethdr()
84  *    |   |             [     Packet   ]            |
85  *  [(Cluster Cache)]   [    Secondary ]   [ (Mbuf Cache)     ]
86  *  [ Cluster Zone  ]   [     Zone     ]   [ Mbuf Master Zone ]
87  *        |                       \________         |
88  *  [ Cluster Keg   ]                      \       /
89  *        |                              [ Mbuf Keg   ]
90  *  [ Cluster Slabs ]                         |
91  *        |                              [ Mbuf Slabs ]
92  *         \____________(VM)_________________/
93  *
94  *
95  * Whenever an object is allocated with uma_zalloc() out of
96  * one of the Zones its _ctor_ function is executed.  The same
97  * for any deallocation through uma_zfree() the _dtor_ function
98  * is executed.
99  *
100  * Caches are per-CPU and are filled from the Master Zone.
101  *
102  * Whenever an object is allocated from the underlying global
103  * memory pool it gets pre-initialized with the _zinit_ functions.
104  * When the Keg's are overfull objects get decommissioned with
105  * _zfini_ functions and free'd back to the global memory pool.
106  *
107  */
108
109 int nmbufs;                     /* limits number of mbufs */
110 int nmbclusters;                /* limits number of mbuf clusters */
111 int nmbjumbop;                  /* limits number of page size jumbo clusters */
112 int nmbjumbo9;                  /* limits number of 9k jumbo clusters */
113 int nmbjumbo16;                 /* limits number of 16k jumbo clusters */
114
115 static quad_t maxmbufmem;       /* overall real memory limit for all mbufs */
116
117 SYSCTL_QUAD(_kern_ipc, OID_AUTO, maxmbufmem, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &maxmbufmem, 0,
118     "Maximum real memory allocatable to various mbuf types");
119
120 static counter_u64_t snd_tag_count;
121 SYSCTL_COUNTER_U64(_kern_ipc, OID_AUTO, num_snd_tags, CTLFLAG_RW,
122     &snd_tag_count, "# of active mbuf send tags");
123
124 /*
125  * tunable_mbinit() has to be run before any mbuf allocations are done.
126  */
127 static void
128 tunable_mbinit(void *dummy)
129 {
130         quad_t realmem;
131
132         /*
133          * The default limit for all mbuf related memory is 1/2 of all
134          * available kernel memory (physical or kmem).
135          * At most it can be 3/4 of available kernel memory.
136          */
137         realmem = qmin((quad_t)physmem * PAGE_SIZE, vm_kmem_size);
138         maxmbufmem = realmem / 2;
139         TUNABLE_QUAD_FETCH("kern.ipc.maxmbufmem", &maxmbufmem);
140         if (maxmbufmem > realmem / 4 * 3)
141                 maxmbufmem = realmem / 4 * 3;
142
143         TUNABLE_INT_FETCH("kern.ipc.nmbclusters", &nmbclusters);
144         if (nmbclusters == 0)
145                 nmbclusters = maxmbufmem / MCLBYTES / 4;
146
147         TUNABLE_INT_FETCH("kern.ipc.nmbjumbop", &nmbjumbop);
148         if (nmbjumbop == 0)
149                 nmbjumbop = maxmbufmem / MJUMPAGESIZE / 4;
150
151         TUNABLE_INT_FETCH("kern.ipc.nmbjumbo9", &nmbjumbo9);
152         if (nmbjumbo9 == 0)
153                 nmbjumbo9 = maxmbufmem / MJUM9BYTES / 6;
154
155         TUNABLE_INT_FETCH("kern.ipc.nmbjumbo16", &nmbjumbo16);
156         if (nmbjumbo16 == 0)
157                 nmbjumbo16 = maxmbufmem / MJUM16BYTES / 6;
158
159         /*
160          * We need at least as many mbufs as we have clusters of
161          * the various types added together.
162          */
163         TUNABLE_INT_FETCH("kern.ipc.nmbufs", &nmbufs);
164         if (nmbufs < nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16)
165                 nmbufs = lmax(maxmbufmem / MSIZE / 5,
166                     nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16);
167 }
168 SYSINIT(tunable_mbinit, SI_SUB_KMEM, SI_ORDER_MIDDLE, tunable_mbinit, NULL);
169
170 static int
171 sysctl_nmbclusters(SYSCTL_HANDLER_ARGS)
172 {
173         int error, newnmbclusters;
174
175         newnmbclusters = nmbclusters;
176         error = sysctl_handle_int(oidp, &newnmbclusters, 0, req);
177         if (error == 0 && req->newptr && newnmbclusters != nmbclusters) {
178                 if (newnmbclusters > nmbclusters &&
179                     nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
180                         nmbclusters = newnmbclusters;
181                         nmbclusters = uma_zone_set_max(zone_clust, nmbclusters);
182                         EVENTHANDLER_INVOKE(nmbclusters_change);
183                 } else
184                         error = EINVAL;
185         }
186         return (error);
187 }
188 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbclusters, CTLTYPE_INT|CTLFLAG_RW,
189 &nmbclusters, 0, sysctl_nmbclusters, "IU",
190     "Maximum number of mbuf clusters allowed");
191
192 static int
193 sysctl_nmbjumbop(SYSCTL_HANDLER_ARGS)
194 {
195         int error, newnmbjumbop;
196
197         newnmbjumbop = nmbjumbop;
198         error = sysctl_handle_int(oidp, &newnmbjumbop, 0, req);
199         if (error == 0 && req->newptr && newnmbjumbop != nmbjumbop) {
200                 if (newnmbjumbop > nmbjumbop &&
201                     nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
202                         nmbjumbop = newnmbjumbop;
203                         nmbjumbop = uma_zone_set_max(zone_jumbop, nmbjumbop);
204                 } else
205                         error = EINVAL;
206         }
207         return (error);
208 }
209 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbop, CTLTYPE_INT|CTLFLAG_RW,
210 &nmbjumbop, 0, sysctl_nmbjumbop, "IU",
211     "Maximum number of mbuf page size jumbo clusters allowed");
212
213 static int
214 sysctl_nmbjumbo9(SYSCTL_HANDLER_ARGS)
215 {
216         int error, newnmbjumbo9;
217
218         newnmbjumbo9 = nmbjumbo9;
219         error = sysctl_handle_int(oidp, &newnmbjumbo9, 0, req);
220         if (error == 0 && req->newptr && newnmbjumbo9 != nmbjumbo9) {
221                 if (newnmbjumbo9 > nmbjumbo9 &&
222                     nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
223                         nmbjumbo9 = newnmbjumbo9;
224                         nmbjumbo9 = uma_zone_set_max(zone_jumbo9, nmbjumbo9);
225                 } else
226                         error = EINVAL;
227         }
228         return (error);
229 }
230 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbo9, CTLTYPE_INT|CTLFLAG_RW,
231 &nmbjumbo9, 0, sysctl_nmbjumbo9, "IU",
232     "Maximum number of mbuf 9k jumbo clusters allowed");
233
234 static int
235 sysctl_nmbjumbo16(SYSCTL_HANDLER_ARGS)
236 {
237         int error, newnmbjumbo16;
238
239         newnmbjumbo16 = nmbjumbo16;
240         error = sysctl_handle_int(oidp, &newnmbjumbo16, 0, req);
241         if (error == 0 && req->newptr && newnmbjumbo16 != nmbjumbo16) {
242                 if (newnmbjumbo16 > nmbjumbo16 &&
243                     nmbufs >= nmbclusters + nmbjumbop + nmbjumbo9 + nmbjumbo16) {
244                         nmbjumbo16 = newnmbjumbo16;
245                         nmbjumbo16 = uma_zone_set_max(zone_jumbo16, nmbjumbo16);
246                 } else
247                         error = EINVAL;
248         }
249         return (error);
250 }
251 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbjumbo16, CTLTYPE_INT|CTLFLAG_RW,
252 &nmbjumbo16, 0, sysctl_nmbjumbo16, "IU",
253     "Maximum number of mbuf 16k jumbo clusters allowed");
254
255 static int
256 sysctl_nmbufs(SYSCTL_HANDLER_ARGS)
257 {
258         int error, newnmbufs;
259
260         newnmbufs = nmbufs;
261         error = sysctl_handle_int(oidp, &newnmbufs, 0, req);
262         if (error == 0 && req->newptr && newnmbufs != nmbufs) {
263                 if (newnmbufs > nmbufs) {
264                         nmbufs = newnmbufs;
265                         nmbufs = uma_zone_set_max(zone_mbuf, nmbufs);
266                         EVENTHANDLER_INVOKE(nmbufs_change);
267                 } else
268                         error = EINVAL;
269         }
270         return (error);
271 }
272 SYSCTL_PROC(_kern_ipc, OID_AUTO, nmbufs, CTLTYPE_INT|CTLFLAG_RW,
273 &nmbufs, 0, sysctl_nmbufs, "IU",
274     "Maximum number of mbufs allowed");
275
276 /*
277  * Zones from which we allocate.
278  */
279 uma_zone_t      zone_mbuf;
280 uma_zone_t      zone_clust;
281 uma_zone_t      zone_pack;
282 uma_zone_t      zone_jumbop;
283 uma_zone_t      zone_jumbo9;
284 uma_zone_t      zone_jumbo16;
285 uma_zone_t      zone_extpgs;
286
287 /*
288  * Local prototypes.
289  */
290 static int      mb_ctor_mbuf(void *, int, void *, int);
291 static int      mb_ctor_clust(void *, int, void *, int);
292 static int      mb_ctor_pack(void *, int, void *, int);
293 static void     mb_dtor_mbuf(void *, int, void *);
294 static void     mb_dtor_pack(void *, int, void *);
295 static int      mb_zinit_pack(void *, int, int);
296 static void     mb_zfini_pack(void *, int);
297 static void     mb_reclaim(uma_zone_t, int);
298 static void    *mbuf_jumbo_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
299
300 /* Ensure that MSIZE is a power of 2. */
301 CTASSERT((((MSIZE - 1) ^ MSIZE) + 1) >> 1 == MSIZE);
302
303 _Static_assert(sizeof(struct mbuf_ext_pgs) == 256,
304     "mbuf_ext_pgs size mismatch");
305
306 /*
307  * Initialize FreeBSD Network buffer allocation.
308  */
309 static void
310 mbuf_init(void *dummy)
311 {
312
313         /*
314          * Configure UMA zones for Mbufs, Clusters, and Packets.
315          */
316         zone_mbuf = uma_zcreate(MBUF_MEM_NAME, MSIZE,
317             mb_ctor_mbuf, mb_dtor_mbuf,
318 #ifdef INVARIANTS
319             trash_init, trash_fini,
320 #else
321             NULL, NULL,
322 #endif
323             MSIZE - 1, UMA_ZONE_MAXBUCKET);
324         if (nmbufs > 0)
325                 nmbufs = uma_zone_set_max(zone_mbuf, nmbufs);
326         uma_zone_set_warning(zone_mbuf, "kern.ipc.nmbufs limit reached");
327         uma_zone_set_maxaction(zone_mbuf, mb_reclaim);
328
329         zone_clust = uma_zcreate(MBUF_CLUSTER_MEM_NAME, MCLBYTES,
330             mb_ctor_clust,
331 #ifdef INVARIANTS
332             trash_dtor, trash_init, trash_fini,
333 #else
334             NULL, NULL, NULL,
335 #endif
336             UMA_ALIGN_PTR, 0);
337         if (nmbclusters > 0)
338                 nmbclusters = uma_zone_set_max(zone_clust, nmbclusters);
339         uma_zone_set_warning(zone_clust, "kern.ipc.nmbclusters limit reached");
340         uma_zone_set_maxaction(zone_clust, mb_reclaim);
341
342         zone_pack = uma_zsecond_create(MBUF_PACKET_MEM_NAME, mb_ctor_pack,
343             mb_dtor_pack, mb_zinit_pack, mb_zfini_pack, zone_mbuf);
344
345         /* Make jumbo frame zone too. Page size, 9k and 16k. */
346         zone_jumbop = uma_zcreate(MBUF_JUMBOP_MEM_NAME, MJUMPAGESIZE,
347             mb_ctor_clust,
348 #ifdef INVARIANTS
349             trash_dtor, trash_init, trash_fini,
350 #else
351             NULL, NULL, NULL,
352 #endif
353             UMA_ALIGN_PTR, 0);
354         if (nmbjumbop > 0)
355                 nmbjumbop = uma_zone_set_max(zone_jumbop, nmbjumbop);
356         uma_zone_set_warning(zone_jumbop, "kern.ipc.nmbjumbop limit reached");
357         uma_zone_set_maxaction(zone_jumbop, mb_reclaim);
358
359         zone_jumbo9 = uma_zcreate(MBUF_JUMBO9_MEM_NAME, MJUM9BYTES,
360             mb_ctor_clust,
361 #ifdef INVARIANTS
362             trash_dtor, trash_init, trash_fini,
363 #else
364             NULL, NULL, NULL,
365 #endif
366             UMA_ALIGN_PTR, 0);
367         uma_zone_set_allocf(zone_jumbo9, mbuf_jumbo_alloc);
368         if (nmbjumbo9 > 0)
369                 nmbjumbo9 = uma_zone_set_max(zone_jumbo9, nmbjumbo9);
370         uma_zone_set_warning(zone_jumbo9, "kern.ipc.nmbjumbo9 limit reached");
371         uma_zone_set_maxaction(zone_jumbo9, mb_reclaim);
372
373         zone_jumbo16 = uma_zcreate(MBUF_JUMBO16_MEM_NAME, MJUM16BYTES,
374             mb_ctor_clust,
375 #ifdef INVARIANTS
376             trash_dtor, trash_init, trash_fini,
377 #else
378             NULL, NULL, NULL,
379 #endif
380             UMA_ALIGN_PTR, 0);
381         uma_zone_set_allocf(zone_jumbo16, mbuf_jumbo_alloc);
382         if (nmbjumbo16 > 0)
383                 nmbjumbo16 = uma_zone_set_max(zone_jumbo16, nmbjumbo16);
384         uma_zone_set_warning(zone_jumbo16, "kern.ipc.nmbjumbo16 limit reached");
385         uma_zone_set_maxaction(zone_jumbo16, mb_reclaim);
386
387         zone_extpgs = uma_zcreate(MBUF_EXTPGS_MEM_NAME,
388             sizeof(struct mbuf_ext_pgs),
389 #ifdef INVARIANTS
390             trash_ctor, trash_dtor, trash_init, trash_fini,
391 #else
392             NULL, NULL, NULL, NULL,
393 #endif
394             UMA_ALIGN_CACHE, 0);
395
396         /*
397          * Hook event handler for low-memory situation, used to
398          * drain protocols and push data back to the caches (UMA
399          * later pushes it back to VM).
400          */
401         EVENTHANDLER_REGISTER(vm_lowmem, mb_reclaim, NULL,
402             EVENTHANDLER_PRI_FIRST);
403
404         snd_tag_count = counter_u64_alloc(M_WAITOK);
405 }
406 SYSINIT(mbuf, SI_SUB_MBUF, SI_ORDER_FIRST, mbuf_init, NULL);
407
408 #ifdef NETDUMP
409 /*
410  * netdump makes use of a pre-allocated pool of mbufs and clusters.  When
411  * netdump is configured, we initialize a set of UMA cache zones which return
412  * items from this pool.  At panic-time, the regular UMA zone pointers are
413  * overwritten with those of the cache zones so that drivers may allocate and
414  * free mbufs and clusters without attempting to allocate physical memory.
415  *
416  * We keep mbufs and clusters in a pair of mbuf queues.  In particular, for
417  * the purpose of caching clusters, we treat them as mbufs.
418  */
419 static struct mbufq nd_mbufq =
420     { STAILQ_HEAD_INITIALIZER(nd_mbufq.mq_head), 0, INT_MAX };
421 static struct mbufq nd_clustq =
422     { STAILQ_HEAD_INITIALIZER(nd_clustq.mq_head), 0, INT_MAX };
423
424 static int nd_clsize;
425 static uma_zone_t nd_zone_mbuf;
426 static uma_zone_t nd_zone_clust;
427 static uma_zone_t nd_zone_pack;
428
429 static int
430 nd_buf_import(void *arg, void **store, int count, int domain __unused,
431     int flags)
432 {
433         struct mbufq *q;
434         struct mbuf *m;
435         int i;
436
437         q = arg;
438
439         for (i = 0; i < count; i++) {
440                 m = mbufq_dequeue(q);
441                 if (m == NULL)
442                         break;
443                 trash_init(m, q == &nd_mbufq ? MSIZE : nd_clsize, flags);
444                 store[i] = m;
445         }
446         KASSERT((flags & M_WAITOK) == 0 || i == count,
447             ("%s: ran out of pre-allocated mbufs", __func__));
448         return (i);
449 }
450
451 static void
452 nd_buf_release(void *arg, void **store, int count)
453 {
454         struct mbufq *q;
455         struct mbuf *m;
456         int i;
457
458         q = arg;
459
460         for (i = 0; i < count; i++) {
461                 m = store[i];
462                 (void)mbufq_enqueue(q, m);
463         }
464 }
465
466 static int
467 nd_pack_import(void *arg __unused, void **store, int count, int domain __unused,
468     int flags __unused)
469 {
470         struct mbuf *m;
471         void *clust;
472         int i;
473
474         for (i = 0; i < count; i++) {
475                 m = m_get(MT_DATA, M_NOWAIT);
476                 if (m == NULL)
477                         break;
478                 clust = uma_zalloc(nd_zone_clust, M_NOWAIT);
479                 if (clust == NULL) {
480                         m_free(m);
481                         break;
482                 }
483                 mb_ctor_clust(clust, nd_clsize, m, 0);
484                 store[i] = m;
485         }
486         KASSERT((flags & M_WAITOK) == 0 || i == count,
487             ("%s: ran out of pre-allocated mbufs", __func__));
488         return (i);
489 }
490
491 static void
492 nd_pack_release(void *arg __unused, void **store, int count)
493 {
494         struct mbuf *m;
495         void *clust;
496         int i;
497
498         for (i = 0; i < count; i++) {
499                 m = store[i];
500                 clust = m->m_ext.ext_buf;
501                 uma_zfree(nd_zone_clust, clust);
502                 uma_zfree(nd_zone_mbuf, m);
503         }
504 }
505
506 /*
507  * Free the pre-allocated mbufs and clusters reserved for netdump, and destroy
508  * the corresponding UMA cache zones.
509  */
510 void
511 netdump_mbuf_drain(void)
512 {
513         struct mbuf *m;
514         void *item;
515
516         if (nd_zone_mbuf != NULL) {
517                 uma_zdestroy(nd_zone_mbuf);
518                 nd_zone_mbuf = NULL;
519         }
520         if (nd_zone_clust != NULL) {
521                 uma_zdestroy(nd_zone_clust);
522                 nd_zone_clust = NULL;
523         }
524         if (nd_zone_pack != NULL) {
525                 uma_zdestroy(nd_zone_pack);
526                 nd_zone_pack = NULL;
527         }
528
529         while ((m = mbufq_dequeue(&nd_mbufq)) != NULL)
530                 m_free(m);
531         while ((item = mbufq_dequeue(&nd_clustq)) != NULL)
532                 uma_zfree(m_getzone(nd_clsize), item);
533 }
534
535 /*
536  * Callback invoked immediately prior to starting a netdump.
537  */
538 void
539 netdump_mbuf_dump(void)
540 {
541
542         /*
543          * All cluster zones return buffers of the size requested by the
544          * drivers.  It's up to the driver to reinitialize the zones if the
545          * MTU of a netdump-enabled interface changes.
546          */
547         printf("netdump: overwriting mbuf zone pointers\n");
548         zone_mbuf = nd_zone_mbuf;
549         zone_clust = nd_zone_clust;
550         zone_pack = nd_zone_pack;
551         zone_jumbop = nd_zone_clust;
552         zone_jumbo9 = nd_zone_clust;
553         zone_jumbo16 = nd_zone_clust;
554 }
555
556 /*
557  * Reinitialize the netdump mbuf+cluster pool and cache zones.
558  */
559 void
560 netdump_mbuf_reinit(int nmbuf, int nclust, int clsize)
561 {
562         struct mbuf *m;
563         void *item;
564
565         netdump_mbuf_drain();
566
567         nd_clsize = clsize;
568
569         nd_zone_mbuf = uma_zcache_create("netdump_" MBUF_MEM_NAME,
570             MSIZE, mb_ctor_mbuf, mb_dtor_mbuf,
571 #ifdef INVARIANTS
572             trash_init, trash_fini,
573 #else
574             NULL, NULL,
575 #endif
576             nd_buf_import, nd_buf_release,
577             &nd_mbufq, UMA_ZONE_NOBUCKET);
578
579         nd_zone_clust = uma_zcache_create("netdump_" MBUF_CLUSTER_MEM_NAME,
580             clsize, mb_ctor_clust,
581 #ifdef INVARIANTS
582             trash_dtor, trash_init, trash_fini,
583 #else
584             NULL, NULL, NULL,
585 #endif
586             nd_buf_import, nd_buf_release,
587             &nd_clustq, UMA_ZONE_NOBUCKET);
588
589         nd_zone_pack = uma_zcache_create("netdump_" MBUF_PACKET_MEM_NAME,
590             MCLBYTES, mb_ctor_pack, mb_dtor_pack, NULL, NULL,
591             nd_pack_import, nd_pack_release,
592             NULL, UMA_ZONE_NOBUCKET);
593
594         while (nmbuf-- > 0) {
595                 m = m_get(MT_DATA, M_WAITOK);
596                 uma_zfree(nd_zone_mbuf, m);
597         }
598         while (nclust-- > 0) {
599                 item = uma_zalloc(m_getzone(nd_clsize), M_WAITOK);
600                 uma_zfree(nd_zone_clust, item);
601         }
602 }
603 #endif /* NETDUMP */
604
605 /*
606  * UMA backend page allocator for the jumbo frame zones.
607  *
608  * Allocates kernel virtual memory that is backed by contiguous physical
609  * pages.
610  */
611 static void *
612 mbuf_jumbo_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
613     int wait)
614 {
615
616         /* Inform UMA that this allocator uses kernel_map/object. */
617         *flags = UMA_SLAB_KERNEL;
618         return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
619             bytes, wait, (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0,
620             VM_MEMATTR_DEFAULT));
621 }
622
623 /*
624  * Constructor for Mbuf master zone.
625  *
626  * The 'arg' pointer points to a mb_args structure which
627  * contains call-specific information required to support the
628  * mbuf allocation API.  See mbuf.h.
629  */
630 static int
631 mb_ctor_mbuf(void *mem, int size, void *arg, int how)
632 {
633         struct mbuf *m;
634         struct mb_args *args;
635         int error;
636         int flags;
637         short type;
638
639 #ifdef INVARIANTS
640         trash_ctor(mem, size, arg, how);
641 #endif
642         args = (struct mb_args *)arg;
643         type = args->type;
644
645         /*
646          * The mbuf is initialized later.  The caller has the
647          * responsibility to set up any MAC labels too.
648          */
649         if (type == MT_NOINIT)
650                 return (0);
651
652         m = (struct mbuf *)mem;
653         flags = args->flags;
654         MPASS((flags & M_NOFREE) == 0);
655
656         error = m_init(m, how, type, flags);
657
658         return (error);
659 }
660
661 /*
662  * The Mbuf master zone destructor.
663  */
664 static void
665 mb_dtor_mbuf(void *mem, int size, void *arg)
666 {
667         struct mbuf *m;
668         unsigned long flags;
669
670         m = (struct mbuf *)mem;
671         flags = (unsigned long)arg;
672
673         KASSERT((m->m_flags & M_NOFREE) == 0, ("%s: M_NOFREE set", __func__));
674         if (!(flags & MB_DTOR_SKIP) && (m->m_flags & M_PKTHDR) && !SLIST_EMPTY(&m->m_pkthdr.tags))
675                 m_tag_delete_chain(m, NULL);
676 #ifdef INVARIANTS
677         trash_dtor(mem, size, arg);
678 #endif
679 }
680
681 /*
682  * The Mbuf Packet zone destructor.
683  */
684 static void
685 mb_dtor_pack(void *mem, int size, void *arg)
686 {
687         struct mbuf *m;
688
689         m = (struct mbuf *)mem;
690         if ((m->m_flags & M_PKTHDR) != 0)
691                 m_tag_delete_chain(m, NULL);
692
693         /* Make sure we've got a clean cluster back. */
694         KASSERT((m->m_flags & M_EXT) == M_EXT, ("%s: M_EXT not set", __func__));
695         KASSERT(m->m_ext.ext_buf != NULL, ("%s: ext_buf == NULL", __func__));
696         KASSERT(m->m_ext.ext_free == NULL, ("%s: ext_free != NULL", __func__));
697         KASSERT(m->m_ext.ext_arg1 == NULL, ("%s: ext_arg1 != NULL", __func__));
698         KASSERT(m->m_ext.ext_arg2 == NULL, ("%s: ext_arg2 != NULL", __func__));
699         KASSERT(m->m_ext.ext_size == MCLBYTES, ("%s: ext_size != MCLBYTES", __func__));
700         KASSERT(m->m_ext.ext_type == EXT_PACKET, ("%s: ext_type != EXT_PACKET", __func__));
701 #ifdef INVARIANTS
702         trash_dtor(m->m_ext.ext_buf, MCLBYTES, arg);
703 #endif
704         /*
705          * If there are processes blocked on zone_clust, waiting for pages
706          * to be freed up, * cause them to be woken up by draining the
707          * packet zone.  We are exposed to a race here * (in the check for
708          * the UMA_ZFLAG_FULL) where we might miss the flag set, but that
709          * is deliberate. We don't want to acquire the zone lock for every
710          * mbuf free.
711          */
712         if (uma_zone_exhausted_nolock(zone_clust))
713                 zone_drain(zone_pack);
714 }
715
716 /*
717  * The Cluster and Jumbo[PAGESIZE|9|16] zone constructor.
718  *
719  * Here the 'arg' pointer points to the Mbuf which we
720  * are configuring cluster storage for.  If 'arg' is
721  * empty we allocate just the cluster without setting
722  * the mbuf to it.  See mbuf.h.
723  */
724 static int
725 mb_ctor_clust(void *mem, int size, void *arg, int how)
726 {
727         struct mbuf *m;
728
729 #ifdef INVARIANTS
730         trash_ctor(mem, size, arg, how);
731 #endif
732         m = (struct mbuf *)arg;
733         if (m != NULL) {
734                 m->m_ext.ext_buf = (char *)mem;
735                 m->m_data = m->m_ext.ext_buf;
736                 m->m_flags |= M_EXT;
737                 m->m_ext.ext_free = NULL;
738                 m->m_ext.ext_arg1 = NULL;
739                 m->m_ext.ext_arg2 = NULL;
740                 m->m_ext.ext_size = size;
741                 m->m_ext.ext_type = m_gettype(size);
742                 m->m_ext.ext_flags = EXT_FLAG_EMBREF;
743                 m->m_ext.ext_count = 1;
744         }
745
746         return (0);
747 }
748
749 /*
750  * The Packet secondary zone's init routine, executed on the
751  * object's transition from mbuf keg slab to zone cache.
752  */
753 static int
754 mb_zinit_pack(void *mem, int size, int how)
755 {
756         struct mbuf *m;
757
758         m = (struct mbuf *)mem;         /* m is virgin. */
759         if (uma_zalloc_arg(zone_clust, m, how) == NULL ||
760             m->m_ext.ext_buf == NULL)
761                 return (ENOMEM);
762         m->m_ext.ext_type = EXT_PACKET; /* Override. */
763 #ifdef INVARIANTS
764         trash_init(m->m_ext.ext_buf, MCLBYTES, how);
765 #endif
766         return (0);
767 }
768
769 /*
770  * The Packet secondary zone's fini routine, executed on the
771  * object's transition from zone cache to keg slab.
772  */
773 static void
774 mb_zfini_pack(void *mem, int size)
775 {
776         struct mbuf *m;
777
778         m = (struct mbuf *)mem;
779 #ifdef INVARIANTS
780         trash_fini(m->m_ext.ext_buf, MCLBYTES);
781 #endif
782         uma_zfree_arg(zone_clust, m->m_ext.ext_buf, NULL);
783 #ifdef INVARIANTS
784         trash_dtor(mem, size, NULL);
785 #endif
786 }
787
788 /*
789  * The "packet" keg constructor.
790  */
791 static int
792 mb_ctor_pack(void *mem, int size, void *arg, int how)
793 {
794         struct mbuf *m;
795         struct mb_args *args;
796         int error, flags;
797         short type;
798
799         m = (struct mbuf *)mem;
800         args = (struct mb_args *)arg;
801         flags = args->flags;
802         type = args->type;
803         MPASS((flags & M_NOFREE) == 0);
804
805 #ifdef INVARIANTS
806         trash_ctor(m->m_ext.ext_buf, MCLBYTES, arg, how);
807 #endif
808
809         error = m_init(m, how, type, flags);
810
811         /* m_ext is already initialized. */
812         m->m_data = m->m_ext.ext_buf;
813         m->m_flags = (flags | M_EXT);
814
815         return (error);
816 }
817
818 /*
819  * This is the protocol drain routine.  Called by UMA whenever any of the
820  * mbuf zones is closed to its limit.
821  *
822  * No locks should be held when this is called.  The drain routines have to
823  * presently acquire some locks which raises the possibility of lock order
824  * reversal.
825  */
826 static void
827 mb_reclaim(uma_zone_t zone __unused, int pending __unused)
828 {
829         struct domain *dp;
830         struct protosw *pr;
831
832         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK | WARN_PANIC, NULL, __func__);
833
834         for (dp = domains; dp != NULL; dp = dp->dom_next)
835                 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
836                         if (pr->pr_drain != NULL)
837                                 (*pr->pr_drain)();
838 }
839
840 /*
841  * Free "count" units of I/O from an mbuf chain.  They could be held
842  * in EXT_PGS or just as a normal mbuf.  This code is intended to be
843  * called in an error path (I/O error, closed connection, etc).
844  */
845 void
846 mb_free_notready(struct mbuf *m, int count)
847 {
848         int i;
849
850         for (i = 0; i < count && m != NULL; i++) {
851                 if ((m->m_flags & M_EXT) != 0 &&
852                     m->m_ext.ext_type == EXT_PGS) {
853                         m->m_ext.ext_pgs->nrdy--;
854                         if (m->m_ext.ext_pgs->nrdy != 0)
855                                 continue;
856                 }
857                 m = m_free(m);
858         }
859         KASSERT(i == count, ("Removed only %d items from %p", i, m));
860 }
861
862 /*
863  * Compress an unmapped mbuf into a simple mbuf when it holds a small
864  * amount of data.  This is used as a DOS defense to avoid having
865  * small packets tie up wired pages, an ext_pgs structure, and an
866  * mbuf.  Since this converts the existing mbuf in place, it can only
867  * be used if there are no other references to 'm'.
868  */
869 int
870 mb_unmapped_compress(struct mbuf *m)
871 {
872         volatile u_int *refcnt;
873         struct mbuf m_temp;
874
875         /*
876          * Assert that 'm' does not have a packet header.  If 'm' had
877          * a packet header, it would only be able to hold MHLEN bytes
878          * and m_data would have to be initialized differently.
879          */
880         KASSERT((m->m_flags & M_PKTHDR) == 0 && (m->m_flags & M_EXT) &&
881             m->m_ext.ext_type == EXT_PGS,
882             ("%s: m %p !M_EXT or !EXT_PGS or M_PKTHDR", __func__, m));
883         KASSERT(m->m_len <= MLEN, ("m_len too large %p", m));
884
885         if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
886                 refcnt = &m->m_ext.ext_count;
887         } else {
888                 KASSERT(m->m_ext.ext_cnt != NULL,
889                     ("%s: no refcounting pointer on %p", __func__, m));
890                 refcnt = m->m_ext.ext_cnt;
891         }
892
893         if (*refcnt != 1)
894                 return (EBUSY);
895
896         /*
897          * Copy mbuf header and m_ext portion of 'm' to 'm_temp' to
898          * create a "fake" EXT_PGS mbuf that can be used with
899          * m_copydata() as well as the ext_free callback.
900          */
901         memcpy(&m_temp, m, offsetof(struct mbuf, m_ext) + sizeof (m->m_ext));
902         m_temp.m_next = NULL;
903         m_temp.m_nextpkt = NULL;
904
905         /* Turn 'm' into a "normal" mbuf. */
906         m->m_flags &= ~(M_EXT | M_RDONLY | M_NOMAP);
907         m->m_data = m->m_dat;
908
909         /* Copy data from template's ext_pgs. */
910         m_copydata(&m_temp, 0, m_temp.m_len, mtod(m, caddr_t));
911
912         /* Free the backing pages. */
913         m_temp.m_ext.ext_free(&m_temp);
914
915         /* Finally, free the ext_pgs struct. */
916         uma_zfree(zone_extpgs, m_temp.m_ext.ext_pgs);
917         return (0);
918 }
919
920 /*
921  * These next few routines are used to permit downgrading an unmapped
922  * mbuf to a chain of mapped mbufs.  This is used when an interface
923  * doesn't supported unmapped mbufs or if checksums need to be
924  * computed in software.
925  *
926  * Each unmapped mbuf is converted to a chain of mbufs.  First, any
927  * TLS header data is stored in a regular mbuf.  Second, each page of
928  * unmapped data is stored in an mbuf with an EXT_SFBUF external
929  * cluster.  These mbufs use an sf_buf to provide a valid KVA for the
930  * associated physical page.  They also hold a reference on the
931  * original EXT_PGS mbuf to ensure the physical page doesn't go away.
932  * Finally, any TLS trailer data is stored in a regular mbuf.
933  *
934  * mb_unmapped_free_mext() is the ext_free handler for the EXT_SFBUF
935  * mbufs.  It frees the associated sf_buf and releases its reference
936  * on the original EXT_PGS mbuf.
937  *
938  * _mb_unmapped_to_ext() is a helper function that converts a single
939  * unmapped mbuf into a chain of mbufs.
940  *
941  * mb_unmapped_to_ext() is the public function that walks an mbuf
942  * chain converting any unmapped mbufs to mapped mbufs.  It returns
943  * the new chain of unmapped mbufs on success.  On failure it frees
944  * the original mbuf chain and returns NULL.
945  */
946 static void
947 mb_unmapped_free_mext(struct mbuf *m)
948 {
949         struct sf_buf *sf;
950         struct mbuf *old_m;
951
952         sf = m->m_ext.ext_arg1;
953         sf_buf_free(sf);
954
955         /* Drop the reference on the backing EXT_PGS mbuf. */
956         old_m = m->m_ext.ext_arg2;
957         mb_free_ext(old_m);
958 }
959
960 static struct mbuf *
961 _mb_unmapped_to_ext(struct mbuf *m)
962 {
963         struct mbuf_ext_pgs *ext_pgs;
964         struct mbuf *m_new, *top, *prev, *mref;
965         struct sf_buf *sf;
966         vm_page_t pg;
967         int i, len, off, pglen, pgoff, seglen, segoff;
968         volatile u_int *refcnt;
969         u_int ref_inc = 0;
970
971         MBUF_EXT_PGS_ASSERT(m);
972         ext_pgs = m->m_ext.ext_pgs;
973         len = m->m_len;
974         KASSERT(ext_pgs->tls == NULL, ("%s: can't convert TLS mbuf %p",
975             __func__, m));
976
977         /* See if this is the mbuf that holds the embedded refcount. */
978         if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
979                 refcnt = &m->m_ext.ext_count;
980                 mref = m;
981         } else {
982                 KASSERT(m->m_ext.ext_cnt != NULL,
983                     ("%s: no refcounting pointer on %p", __func__, m));
984                 refcnt = m->m_ext.ext_cnt;
985                 mref = __containerof(refcnt, struct mbuf, m_ext.ext_count);
986         }
987
988         /* Skip over any data removed from the front. */
989         off = mtod(m, vm_offset_t);
990
991         top = NULL;
992         if (ext_pgs->hdr_len != 0) {
993                 if (off >= ext_pgs->hdr_len) {
994                         off -= ext_pgs->hdr_len;
995                 } else {
996                         seglen = ext_pgs->hdr_len - off;
997                         segoff = off;
998                         seglen = min(seglen, len);
999                         off = 0;
1000                         len -= seglen;
1001                         m_new = m_get(M_NOWAIT, MT_DATA);
1002                         if (m_new == NULL)
1003                                 goto fail;
1004                         m_new->m_len = seglen;
1005                         prev = top = m_new;
1006                         memcpy(mtod(m_new, void *), &ext_pgs->hdr[segoff],
1007                             seglen);
1008                 }
1009         }
1010         pgoff = ext_pgs->first_pg_off;
1011         for (i = 0; i < ext_pgs->npgs && len > 0; i++) {
1012                 pglen = mbuf_ext_pg_len(ext_pgs, i, pgoff);
1013                 if (off >= pglen) {
1014                         off -= pglen;
1015                         pgoff = 0;
1016                         continue;
1017                 }
1018                 seglen = pglen - off;
1019                 segoff = pgoff + off;
1020                 off = 0;
1021                 seglen = min(seglen, len);
1022                 len -= seglen;
1023
1024                 pg = PHYS_TO_VM_PAGE(ext_pgs->pa[i]);
1025                 m_new = m_get(M_NOWAIT, MT_DATA);
1026                 if (m_new == NULL)
1027                         goto fail;
1028                 if (top == NULL) {
1029                         top = prev = m_new;
1030                 } else {
1031                         prev->m_next = m_new;
1032                         prev = m_new;
1033                 }
1034                 sf = sf_buf_alloc(pg, SFB_NOWAIT);
1035                 if (sf == NULL)
1036                         goto fail;
1037
1038                 ref_inc++;
1039                 m_extadd(m_new, (char *)sf_buf_kva(sf), PAGE_SIZE,
1040                     mb_unmapped_free_mext, sf, mref, M_RDONLY, EXT_SFBUF);
1041                 m_new->m_data += segoff;
1042                 m_new->m_len = seglen;
1043
1044                 pgoff = 0;
1045         };
1046         if (len != 0) {
1047                 KASSERT((off + len) <= ext_pgs->trail_len,
1048                     ("off + len > trail (%d + %d > %d)", off, len,
1049                     ext_pgs->trail_len));
1050                 m_new = m_get(M_NOWAIT, MT_DATA);
1051                 if (m_new == NULL)
1052                         goto fail;
1053                 if (top == NULL)
1054                         top = m_new;
1055                 else
1056                         prev->m_next = m_new;
1057                 m_new->m_len = len;
1058                 memcpy(mtod(m_new, void *), &ext_pgs->trail[off], len);
1059         }
1060
1061         if (ref_inc != 0) {
1062                 /*
1063                  * Obtain an additional reference on the old mbuf for
1064                  * each created EXT_SFBUF mbuf.  They will be dropped
1065                  * in mb_unmapped_free_mext().
1066                  */
1067                 if (*refcnt == 1)
1068                         *refcnt += ref_inc;
1069                 else
1070                         atomic_add_int(refcnt, ref_inc);
1071         }
1072         m_free(m);
1073         return (top);
1074
1075 fail:
1076         if (ref_inc != 0) {
1077                 /*
1078                  * Obtain an additional reference on the old mbuf for
1079                  * each created EXT_SFBUF mbuf.  They will be
1080                  * immediately dropped when these mbufs are freed
1081                  * below.
1082                  */
1083                 if (*refcnt == 1)
1084                         *refcnt += ref_inc;
1085                 else
1086                         atomic_add_int(refcnt, ref_inc);
1087         }
1088         m_free(m);
1089         m_freem(top);
1090         return (NULL);
1091 }
1092
1093 struct mbuf *
1094 mb_unmapped_to_ext(struct mbuf *top)
1095 {
1096         struct mbuf *m, *next, *prev = NULL;
1097
1098         prev = NULL;
1099         for (m = top; m != NULL; m = next) {
1100                 /* m might be freed, so cache the next pointer. */
1101                 next = m->m_next;
1102                 if (m->m_flags & M_NOMAP) {
1103                         if (prev != NULL) {
1104                                 /*
1105                                  * Remove 'm' from the new chain so
1106                                  * that the 'top' chain terminates
1107                                  * before 'm' in case 'top' is freed
1108                                  * due to an error.
1109                                  */
1110                                 prev->m_next = NULL;
1111                         }
1112                         m = _mb_unmapped_to_ext(m);
1113                         if (m == NULL) {
1114                                 m_freem(top);
1115                                 m_freem(next);
1116                                 return (NULL);
1117                         }
1118                         if (prev == NULL) {
1119                                 top = m;
1120                         } else {
1121                                 prev->m_next = m;
1122                         }
1123
1124                         /*
1125                          * Replaced one mbuf with a chain, so we must
1126                          * find the end of chain.
1127                          */
1128                         prev = m_last(m);
1129                 } else {
1130                         if (prev != NULL) {
1131                                 prev->m_next = m;
1132                         }
1133                         prev = m;
1134                 }
1135         }
1136         return (top);
1137 }
1138
1139 /*
1140  * Allocate an empty EXT_PGS mbuf.  The ext_free routine is
1141  * responsible for freeing any pages backing this mbuf when it is
1142  * freed.
1143  */
1144 struct mbuf *
1145 mb_alloc_ext_pgs(int how, bool pkthdr, m_ext_free_t ext_free)
1146 {
1147         struct mbuf *m;
1148         struct mbuf_ext_pgs *ext_pgs;
1149
1150         if (pkthdr)
1151                 m = m_gethdr(how, MT_DATA);
1152         else
1153                 m = m_get(how, MT_DATA);
1154         if (m == NULL)
1155                 return (NULL);
1156
1157         ext_pgs = uma_zalloc(zone_extpgs, how);
1158         if (ext_pgs == NULL) {
1159                 m_free(m);
1160                 return (NULL);
1161         }
1162         ext_pgs->npgs = 0;
1163         ext_pgs->nrdy = 0;
1164         ext_pgs->first_pg_off = 0;
1165         ext_pgs->last_pg_len = 0;
1166         ext_pgs->hdr_len = 0;
1167         ext_pgs->trail_len = 0;
1168         ext_pgs->tls = NULL;
1169         ext_pgs->so = NULL;
1170         m->m_data = NULL;
1171         m->m_flags |= (M_EXT | M_RDONLY | M_NOMAP);
1172         m->m_ext.ext_type = EXT_PGS;
1173         m->m_ext.ext_flags = EXT_FLAG_EMBREF;
1174         m->m_ext.ext_count = 1;
1175         m->m_ext.ext_pgs = ext_pgs;
1176         m->m_ext.ext_size = 0;
1177         m->m_ext.ext_free = ext_free;
1178         return (m);
1179 }
1180
1181 #ifdef INVARIANT_SUPPORT
1182 void
1183 mb_ext_pgs_check(struct mbuf_ext_pgs *ext_pgs)
1184 {
1185
1186         /*
1187          * NB: This expects a non-empty buffer (npgs > 0 and
1188          * last_pg_len > 0).
1189          */
1190         KASSERT(ext_pgs->npgs > 0,
1191             ("ext_pgs with no valid pages: %p", ext_pgs));
1192         KASSERT(ext_pgs->npgs <= nitems(ext_pgs->pa),
1193             ("ext_pgs with too many pages: %p", ext_pgs));
1194         KASSERT(ext_pgs->nrdy <= ext_pgs->npgs,
1195             ("ext_pgs with too many ready pages: %p", ext_pgs));
1196         KASSERT(ext_pgs->first_pg_off < PAGE_SIZE,
1197             ("ext_pgs with too large page offset: %p", ext_pgs));
1198         KASSERT(ext_pgs->last_pg_len > 0,
1199             ("ext_pgs with zero last page length: %p", ext_pgs));
1200         KASSERT(ext_pgs->last_pg_len <= PAGE_SIZE,
1201             ("ext_pgs with too large last page length: %p", ext_pgs));
1202         if (ext_pgs->npgs == 1) {
1203                 KASSERT(ext_pgs->first_pg_off + ext_pgs->last_pg_len <=
1204                     PAGE_SIZE, ("ext_pgs with single page too large: %p",
1205                     ext_pgs));
1206         }
1207         KASSERT(ext_pgs->hdr_len <= sizeof(ext_pgs->hdr),
1208             ("ext_pgs with too large header length: %p", ext_pgs));
1209         KASSERT(ext_pgs->trail_len <= sizeof(ext_pgs->trail),
1210             ("ext_pgs with too large header length: %p", ext_pgs));
1211 }
1212 #endif
1213
1214 /*
1215  * Clean up after mbufs with M_EXT storage attached to them if the
1216  * reference count hits 1.
1217  */
1218 void
1219 mb_free_ext(struct mbuf *m)
1220 {
1221         volatile u_int *refcnt;
1222         struct mbuf *mref;
1223         int freembuf;
1224
1225         KASSERT(m->m_flags & M_EXT, ("%s: M_EXT not set on %p", __func__, m));
1226
1227         /* See if this is the mbuf that holds the embedded refcount. */
1228         if (m->m_ext.ext_flags & EXT_FLAG_EMBREF) {
1229                 refcnt = &m->m_ext.ext_count;
1230                 mref = m;
1231         } else {
1232                 KASSERT(m->m_ext.ext_cnt != NULL,
1233                     ("%s: no refcounting pointer on %p", __func__, m));
1234                 refcnt = m->m_ext.ext_cnt;
1235                 mref = __containerof(refcnt, struct mbuf, m_ext.ext_count);
1236         }
1237
1238         /*
1239          * Check if the header is embedded in the cluster.  It is
1240          * important that we can't touch any of the mbuf fields
1241          * after we have freed the external storage, since mbuf
1242          * could have been embedded in it.  For now, the mbufs
1243          * embedded into the cluster are always of type EXT_EXTREF,
1244          * and for this type we won't free the mref.
1245          */
1246         if (m->m_flags & M_NOFREE) {
1247                 freembuf = 0;
1248                 KASSERT(m->m_ext.ext_type == EXT_EXTREF ||
1249                     m->m_ext.ext_type == EXT_RXRING,
1250                     ("%s: no-free mbuf %p has wrong type", __func__, m));
1251         } else
1252                 freembuf = 1;
1253
1254         /* Free attached storage if this mbuf is the only reference to it. */
1255         if (*refcnt == 1 || atomic_fetchadd_int(refcnt, -1) == 1) {
1256                 switch (m->m_ext.ext_type) {
1257                 case EXT_PACKET:
1258                         /* The packet zone is special. */
1259                         if (*refcnt == 0)
1260                                 *refcnt = 1;
1261                         uma_zfree(zone_pack, mref);
1262                         break;
1263                 case EXT_CLUSTER:
1264                         uma_zfree(zone_clust, m->m_ext.ext_buf);
1265                         uma_zfree(zone_mbuf, mref);
1266                         break;
1267                 case EXT_JUMBOP:
1268                         uma_zfree(zone_jumbop, m->m_ext.ext_buf);
1269                         uma_zfree(zone_mbuf, mref);
1270                         break;
1271                 case EXT_JUMBO9:
1272                         uma_zfree(zone_jumbo9, m->m_ext.ext_buf);
1273                         uma_zfree(zone_mbuf, mref);
1274                         break;
1275                 case EXT_JUMBO16:
1276                         uma_zfree(zone_jumbo16, m->m_ext.ext_buf);
1277                         uma_zfree(zone_mbuf, mref);
1278                         break;
1279                 case EXT_PGS:
1280                         uma_zfree(zone_extpgs, mref->m_ext.ext_pgs);
1281                         uma_zfree(zone_mbuf, mref);
1282                         break;
1283                 case EXT_SFBUF:
1284                 case EXT_NET_DRV:
1285                 case EXT_MOD_TYPE:
1286                 case EXT_DISPOSABLE:
1287                         KASSERT(mref->m_ext.ext_free != NULL,
1288                             ("%s: ext_free not set", __func__));
1289                         mref->m_ext.ext_free(mref);
1290                         uma_zfree(zone_mbuf, mref);
1291                         break;
1292                 case EXT_EXTREF:
1293                         KASSERT(m->m_ext.ext_free != NULL,
1294                             ("%s: ext_free not set", __func__));
1295                         m->m_ext.ext_free(m);
1296                         break;
1297                 case EXT_RXRING:
1298                         KASSERT(m->m_ext.ext_free == NULL,
1299                             ("%s: ext_free is set", __func__));
1300                         break;
1301                 default:
1302                         KASSERT(m->m_ext.ext_type == 0,
1303                             ("%s: unknown ext_type", __func__));
1304                 }
1305         }
1306
1307         if (freembuf && m != mref)
1308                 uma_zfree(zone_mbuf, m);
1309 }
1310
1311 /*
1312  * Official mbuf(9) allocation KPI for stack and drivers:
1313  *
1314  * m_get()      - a single mbuf without any attachments, sys/mbuf.h.
1315  * m_gethdr()   - a single mbuf initialized as M_PKTHDR, sys/mbuf.h.
1316  * m_getcl()    - an mbuf + 2k cluster, sys/mbuf.h.
1317  * m_clget()    - attach cluster to already allocated mbuf.
1318  * m_cljget()   - attach jumbo cluster to already allocated mbuf.
1319  * m_get2()     - allocate minimum mbuf that would fit size argument.
1320  * m_getm2()    - allocate a chain of mbufs/clusters.
1321  * m_extadd()   - attach external cluster to mbuf.
1322  *
1323  * m_free()     - free single mbuf with its tags and ext, sys/mbuf.h.
1324  * m_freem()    - free chain of mbufs.
1325  */
1326
1327 int
1328 m_clget(struct mbuf *m, int how)
1329 {
1330
1331         KASSERT((m->m_flags & M_EXT) == 0, ("%s: mbuf %p has M_EXT",
1332             __func__, m));
1333         m->m_ext.ext_buf = (char *)NULL;
1334         uma_zalloc_arg(zone_clust, m, how);
1335         /*
1336          * On a cluster allocation failure, drain the packet zone and retry,
1337          * we might be able to loosen a few clusters up on the drain.
1338          */
1339         if ((how & M_NOWAIT) && (m->m_ext.ext_buf == NULL)) {
1340                 zone_drain(zone_pack);
1341                 uma_zalloc_arg(zone_clust, m, how);
1342         }
1343         MBUF_PROBE2(m__clget, m, how);
1344         return (m->m_flags & M_EXT);
1345 }
1346
1347 /*
1348  * m_cljget() is different from m_clget() as it can allocate clusters without
1349  * attaching them to an mbuf.  In that case the return value is the pointer
1350  * to the cluster of the requested size.  If an mbuf was specified, it gets
1351  * the cluster attached to it and the return value can be safely ignored.
1352  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
1353  */
1354 void *
1355 m_cljget(struct mbuf *m, int how, int size)
1356 {
1357         uma_zone_t zone;
1358         void *retval;
1359
1360         if (m != NULL) {
1361                 KASSERT((m->m_flags & M_EXT) == 0, ("%s: mbuf %p has M_EXT",
1362                     __func__, m));
1363                 m->m_ext.ext_buf = NULL;
1364         }
1365
1366         zone = m_getzone(size);
1367         retval = uma_zalloc_arg(zone, m, how);
1368
1369         MBUF_PROBE4(m__cljget, m, how, size, retval);
1370
1371         return (retval);
1372 }
1373
1374 /*
1375  * m_get2() allocates minimum mbuf that would fit "size" argument.
1376  */
1377 struct mbuf *
1378 m_get2(int size, int how, short type, int flags)
1379 {
1380         struct mb_args args;
1381         struct mbuf *m, *n;
1382
1383         args.flags = flags;
1384         args.type = type;
1385
1386         if (size <= MHLEN || (size <= MLEN && (flags & M_PKTHDR) == 0))
1387                 return (uma_zalloc_arg(zone_mbuf, &args, how));
1388         if (size <= MCLBYTES)
1389                 return (uma_zalloc_arg(zone_pack, &args, how));
1390
1391         if (size > MJUMPAGESIZE)
1392                 return (NULL);
1393
1394         m = uma_zalloc_arg(zone_mbuf, &args, how);
1395         if (m == NULL)
1396                 return (NULL);
1397
1398         n = uma_zalloc_arg(zone_jumbop, m, how);
1399         if (n == NULL) {
1400                 uma_zfree(zone_mbuf, m);
1401                 return (NULL);
1402         }
1403
1404         return (m);
1405 }
1406
1407 /*
1408  * m_getjcl() returns an mbuf with a cluster of the specified size attached.
1409  * For size it takes MCLBYTES, MJUMPAGESIZE, MJUM9BYTES, MJUM16BYTES.
1410  */
1411 struct mbuf *
1412 m_getjcl(int how, short type, int flags, int size)
1413 {
1414         struct mb_args args;
1415         struct mbuf *m, *n;
1416         uma_zone_t zone;
1417
1418         if (size == MCLBYTES)
1419                 return m_getcl(how, type, flags);
1420
1421         args.flags = flags;
1422         args.type = type;
1423
1424         m = uma_zalloc_arg(zone_mbuf, &args, how);
1425         if (m == NULL)
1426                 return (NULL);
1427
1428         zone = m_getzone(size);
1429         n = uma_zalloc_arg(zone, m, how);
1430         if (n == NULL) {
1431                 uma_zfree(zone_mbuf, m);
1432                 return (NULL);
1433         }
1434         return (m);
1435 }
1436
1437 /*
1438  * Allocate a given length worth of mbufs and/or clusters (whatever fits
1439  * best) and return a pointer to the top of the allocated chain.  If an
1440  * existing mbuf chain is provided, then we will append the new chain
1441  * to the existing one and return a pointer to the provided mbuf.
1442  */
1443 struct mbuf *
1444 m_getm2(struct mbuf *m, int len, int how, short type, int flags)
1445 {
1446         struct mbuf *mb, *nm = NULL, *mtail = NULL;
1447
1448         KASSERT(len >= 0, ("%s: len is < 0", __func__));
1449
1450         /* Validate flags. */
1451         flags &= (M_PKTHDR | M_EOR);
1452
1453         /* Packet header mbuf must be first in chain. */
1454         if ((flags & M_PKTHDR) && m != NULL)
1455                 flags &= ~M_PKTHDR;
1456
1457         /* Loop and append maximum sized mbufs to the chain tail. */
1458         while (len > 0) {
1459                 if (len > MCLBYTES)
1460                         mb = m_getjcl(how, type, (flags & M_PKTHDR),
1461                             MJUMPAGESIZE);
1462                 else if (len >= MINCLSIZE)
1463                         mb = m_getcl(how, type, (flags & M_PKTHDR));
1464                 else if (flags & M_PKTHDR)
1465                         mb = m_gethdr(how, type);
1466                 else
1467                         mb = m_get(how, type);
1468
1469                 /* Fail the whole operation if one mbuf can't be allocated. */
1470                 if (mb == NULL) {
1471                         if (nm != NULL)
1472                                 m_freem(nm);
1473                         return (NULL);
1474                 }
1475
1476                 /* Book keeping. */
1477                 len -= M_SIZE(mb);
1478                 if (mtail != NULL)
1479                         mtail->m_next = mb;
1480                 else
1481                         nm = mb;
1482                 mtail = mb;
1483                 flags &= ~M_PKTHDR;     /* Only valid on the first mbuf. */
1484         }
1485         if (flags & M_EOR)
1486                 mtail->m_flags |= M_EOR;  /* Only valid on the last mbuf. */
1487
1488         /* If mbuf was supplied, append new chain to the end of it. */
1489         if (m != NULL) {
1490                 for (mtail = m; mtail->m_next != NULL; mtail = mtail->m_next)
1491                         ;
1492                 mtail->m_next = nm;
1493                 mtail->m_flags &= ~M_EOR;
1494         } else
1495                 m = nm;
1496
1497         return (m);
1498 }
1499
1500 /*-
1501  * Configure a provided mbuf to refer to the provided external storage
1502  * buffer and setup a reference count for said buffer.
1503  *
1504  * Arguments:
1505  *    mb     The existing mbuf to which to attach the provided buffer.
1506  *    buf    The address of the provided external storage buffer.
1507  *    size   The size of the provided buffer.
1508  *    freef  A pointer to a routine that is responsible for freeing the
1509  *           provided external storage buffer.
1510  *    args   A pointer to an argument structure (of any type) to be passed
1511  *           to the provided freef routine (may be NULL).
1512  *    flags  Any other flags to be passed to the provided mbuf.
1513  *    type   The type that the external storage buffer should be
1514  *           labeled with.
1515  *
1516  * Returns:
1517  *    Nothing.
1518  */
1519 void
1520 m_extadd(struct mbuf *mb, char *buf, u_int size, m_ext_free_t freef,
1521     void *arg1, void *arg2, int flags, int type)
1522 {
1523
1524         KASSERT(type != EXT_CLUSTER, ("%s: EXT_CLUSTER not allowed", __func__));
1525
1526         mb->m_flags |= (M_EXT | flags);
1527         mb->m_ext.ext_buf = buf;
1528         mb->m_data = mb->m_ext.ext_buf;
1529         mb->m_ext.ext_size = size;
1530         mb->m_ext.ext_free = freef;
1531         mb->m_ext.ext_arg1 = arg1;
1532         mb->m_ext.ext_arg2 = arg2;
1533         mb->m_ext.ext_type = type;
1534
1535         if (type != EXT_EXTREF) {
1536                 mb->m_ext.ext_count = 1;
1537                 mb->m_ext.ext_flags = EXT_FLAG_EMBREF;
1538         } else
1539                 mb->m_ext.ext_flags = 0;
1540 }
1541
1542 /*
1543  * Free an entire chain of mbufs and associated external buffers, if
1544  * applicable.
1545  */
1546 void
1547 m_freem(struct mbuf *mb)
1548 {
1549
1550         MBUF_PROBE1(m__freem, mb);
1551         while (mb != NULL)
1552                 mb = m_free(mb);
1553 }
1554
1555 void
1556 m_snd_tag_init(struct m_snd_tag *mst, struct ifnet *ifp)
1557 {
1558
1559         if_ref(ifp);
1560         mst->ifp = ifp;
1561         refcount_init(&mst->refcount, 1);
1562         counter_u64_add(snd_tag_count, 1);
1563 }
1564
1565 void
1566 m_snd_tag_destroy(struct m_snd_tag *mst)
1567 {
1568         struct ifnet *ifp;
1569
1570         ifp = mst->ifp;
1571         ifp->if_snd_tag_free(mst);
1572         if_rele(ifp);
1573         counter_u64_add(snd_tag_count, -1);
1574 }