This repository was archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathuipc_mbuf.c
More file actions
8025 lines (7064 loc) · 212 KB
/
uipc_mbuf.c
File metadata and controls
8025 lines (7064 loc) · 212 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1998-2017 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
* Copyright (c) 1982, 1986, 1988, 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
*/
/*
* NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/kernel.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/protosw.h>
#include <sys/domain.h>
#include <sys/queue.h>
#include <sys/proc.h>
#include <dev/random/randomdev.h>
#include <kern/kern_types.h>
#include <kern/simple_lock.h>
#include <kern/queue.h>
#include <kern/sched_prim.h>
#include <kern/backtrace.h>
#include <kern/cpu_number.h>
#include <kern/zalloc.h>
#include <libkern/OSAtomic.h>
#include <libkern/OSDebug.h>
#include <libkern/libkern.h>
#include <IOKit/IOMapper.h>
#include <machine/limits.h>
#include <machine/machine_routines.h>
#if CONFIG_MACF_NET
#include <security/mac_framework.h>
#endif /* MAC_NET */
#include <sys/mcache.h>
#include <net/ntstat.h>
/*
* MBUF IMPLEMENTATION NOTES.
*
* There is a total of 5 per-CPU caches:
*
* MC_MBUF:
* This is a cache of rudimentary objects of MSIZE in size; each
* object represents an mbuf structure. This cache preserves only
* the m_type field of the mbuf during its transactions.
*
* MC_CL:
* This is a cache of rudimentary objects of MCLBYTES in size; each
* object represents a mcluster structure. This cache does not
* preserve the contents of the objects during its transactions.
*
* MC_BIGCL:
* This is a cache of rudimentary objects of MBIGCLBYTES in size; each
* object represents a mbigcluster structure. This cache does not
* preserve the contents of the objects during its transaction.
*
* MC_MBUF_CL:
* This is a cache of mbufs each having a cluster attached to it.
* It is backed by MC_MBUF and MC_CL rudimentary caches. Several
* fields of the mbuf related to the external cluster are preserved
* during transactions.
*
* MC_MBUF_BIGCL:
* This is a cache of mbufs each having a big cluster attached to it.
* It is backed by MC_MBUF and MC_BIGCL rudimentary caches. Several
* fields of the mbuf related to the external cluster are preserved
* during transactions.
*
* OBJECT ALLOCATION:
*
* Allocation requests are handled first at the per-CPU (mcache) layer
* before falling back to the slab layer. Performance is optimal when
* the request is satisfied at the CPU layer because global data/lock
* never gets accessed. When the slab layer is entered for allocation,
* the slab freelist will be checked first for available objects before
* the VM backing store is invoked. Slab layer operations are serialized
* for all of the caches as the mbuf global lock is held most of the time.
* Allocation paths are different depending on the class of objects:
*
* a. Rudimentary object:
*
* { m_get_common(), m_clattach(), m_mclget(),
* m_mclalloc(), m_bigalloc(), m_copym_with_hdrs(),
* composite object allocation }
* | ^
* | |
* | +-----------------------+
* v |
* mcache_alloc/mcache_alloc_ext() mbuf_slab_audit()
* | ^
* v |
* [CPU cache] -------> (found?) -------+
* | |
* v |
* mbuf_slab_alloc() |
* | |
* v |
* +---------> [freelist] -------> (found?) -------+
* | |
* | v
* | m_clalloc()
* | |
* | v
* +---<<---- kmem_mb_alloc()
*
* b. Composite object:
*
* { m_getpackets_internal(), m_allocpacket_internal() }
* | ^
* | |
* | +------ (done) ---------+
* v |
* mcache_alloc/mcache_alloc_ext() mbuf_cslab_audit()
* | ^
* v |
* [CPU cache] -------> (found?) -------+
* | |
* v |
* mbuf_cslab_alloc() |
* | |
* v |
* [freelist] -------> (found?) -------+
* | |
* v |
* (rudimentary object) |
* mcache_alloc/mcache_alloc_ext() ------>>-----+
*
* Auditing notes: If auditing is enabled, buffers will be subjected to
* integrity checks by the audit routine. This is done by verifying their
* contents against DEADBEEF (free) pattern before returning them to caller.
* As part of this step, the routine will also record the transaction and
* pattern-fill the buffers with BADDCAFE (uninitialized) pattern. It will
* also restore any constructed data structure fields if necessary.
*
* OBJECT DEALLOCATION:
*
* Freeing an object simply involves placing it into the CPU cache; this
* pollutes the cache to benefit subsequent allocations. The slab layer
* will only be entered if the object is to be purged out of the cache.
* During normal operations, this happens only when the CPU layer resizes
* its bucket while it's adjusting to the allocation load. Deallocation
* paths are different depending on the class of objects:
*
* a. Rudimentary object:
*
* { m_free(), m_freem_list(), composite object deallocation }
* | ^
* | |
* | +------ (done) ---------+
* v |
* mcache_free/mcache_free_ext() |
* | |
* v |
* mbuf_slab_audit() |
* | |
* v |
* [CPU cache] ---> (not purging?) -----+
* | |
* v |
* mbuf_slab_free() |
* | |
* v |
* [freelist] ----------->>------------+
* (objects get purged to VM only on demand)
*
* b. Composite object:
*
* { m_free(), m_freem_list() }
* | ^
* | |
* | +------ (done) ---------+
* v |
* mcache_free/mcache_free_ext() |
* | |
* v |
* mbuf_cslab_audit() |
* | |
* v |
* [CPU cache] ---> (not purging?) -----+
* | |
* v |
* mbuf_cslab_free() |
* | |
* v |
* [freelist] ---> (not purging?) -----+
* | |
* v |
* (rudimentary object) |
* mcache_free/mcache_free_ext() ------->>------+
*
* Auditing notes: If auditing is enabled, the audit routine will save
* any constructed data structure fields (if necessary) before filling the
* contents of the buffers with DEADBEEF (free) pattern and recording the
* transaction. Buffers that are freed (whether at CPU or slab layer) are
* expected to contain the free pattern.
*
* DEBUGGING:
*
* Debugging can be enabled by adding "mbuf_debug=0x3" to boot-args; this
* translates to the mcache flags (MCF_VERIFY | MCF_AUDIT). Additionally,
* the CPU layer cache can be disabled by setting the MCF_NOCPUCACHE flag,
* i.e. modify the boot argument parameter to "mbuf_debug=0x13". Leak
* detection may also be disabled by setting the MCF_NOLEAKLOG flag, e.g.
* "mbuf_debug=0x113". Note that debugging consumes more CPU and memory.
*
* Each object is associated with exactly one mcache_audit_t structure that
* contains the information related to its last buffer transaction. Given
* an address of an object, the audit structure can be retrieved by finding
* the position of the object relevant to the base address of the cluster:
*
* +------------+ +=============+
* | mbuf addr | | mclaudit[i] |
* +------------+ +=============+
* | | cl_audit[0] |
* i = MTOBG(addr) +-------------+
* | +-----> | cl_audit[1] | -----> mcache_audit_t
* b = BGTOM(i) | +-------------+
* | | | ... |
* x = MCLIDX(b, addr) | +-------------+
* | | | cl_audit[7] |
* +-----------------+ +-------------+
* (e.g. x == 1)
*
* The mclaudit[] array is allocated at initialization time, but its contents
* get populated when the corresponding cluster is created. Because a page
* can be turned into NMBPG number of mbufs, we preserve enough space for the
* mbufs so that there is a 1-to-1 mapping between them. A page that never
* gets (or has not yet) turned into mbufs will use only cl_audit[0] with the
* remaining entries unused. For 16KB cluster, only one entry from the first
* page is allocated and used for the entire object.
*/
/* TODO: should be in header file */
/* kernel translater */
extern vm_offset_t kmem_mb_alloc(vm_map_t, int, int);
extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va);
extern vm_map_t mb_map; /* special map */
/* Global lock */
decl_lck_mtx_data(static, mbuf_mlock_data);
static lck_mtx_t *mbuf_mlock = &mbuf_mlock_data;
static lck_attr_t *mbuf_mlock_attr;
static lck_grp_t *mbuf_mlock_grp;
static lck_grp_attr_t *mbuf_mlock_grp_attr;
/* Back-end (common) layer */
static boolean_t mbuf_worker_needs_wakeup; /* wait channel for mbuf worker */
static int mbuf_worker_ready; /* worker thread is runnable */
static int ncpu; /* number of CPUs */
static ppnum_t *mcl_paddr; /* Array of cluster physical addresses */
static ppnum_t mcl_pages; /* Size of array (# physical pages) */
static ppnum_t mcl_paddr_base; /* Handle returned by IOMapper::iovmAlloc() */
static mcache_t *ref_cache; /* Cache of cluster reference & flags */
static mcache_t *mcl_audit_con_cache; /* Audit contents cache */
static unsigned int mbuf_debug; /* patchable mbuf mcache flags */
static unsigned int mb_normalized; /* number of packets "normalized" */
#define MB_GROWTH_AGGRESSIVE 1 /* Threshold: 1/2 of total */
#define MB_GROWTH_NORMAL 2 /* Threshold: 3/4 of total */
typedef enum {
MC_MBUF = 0, /* Regular mbuf */
MC_CL, /* Cluster */
MC_BIGCL, /* Large (4KB) cluster */
MC_16KCL, /* Jumbo (16KB) cluster */
MC_MBUF_CL, /* mbuf + cluster */
MC_MBUF_BIGCL, /* mbuf + large (4KB) cluster */
MC_MBUF_16KCL /* mbuf + jumbo (16KB) cluster */
} mbuf_class_t;
#define MBUF_CLASS_MIN MC_MBUF
#define MBUF_CLASS_MAX MC_MBUF_16KCL
#define MBUF_CLASS_LAST MC_16KCL
#define MBUF_CLASS_VALID(c) \
((int)(c) >= MBUF_CLASS_MIN && (int)(c) <= MBUF_CLASS_MAX)
#define MBUF_CLASS_COMPOSITE(c) \
((int)(c) > MBUF_CLASS_LAST)
/*
* mbuf specific mcache allocation request flags.
*/
#define MCR_COMP MCR_USR1 /* for MC_MBUF_{CL,BIGCL,16KCL} caches */
/*
* Per-cluster slab structure.
*
* A slab is a cluster control structure that contains one or more object
* chunks; the available chunks are chained in the slab's freelist (sl_head).
* Each time a chunk is taken out of the slab, the slab's reference count
* gets incremented. When all chunks have been taken out, the empty slab
* gets removed (SLF_DETACHED) from the class's slab list. A chunk that is
* returned to a slab causes the slab's reference count to be decremented;
* it also causes the slab to be reinserted back to class's slab list, if
* it's not already done.
*
* Compartmentalizing of the object chunks into slabs allows us to easily
* merge one or more slabs together when the adjacent slabs are idle, as
* well as to convert or move a slab from one class to another; e.g. the
* mbuf cluster slab can be converted to a regular cluster slab when all
* mbufs in the slab have been freed.
*
* A slab may also span across multiple clusters for chunks larger than
* a cluster's size. In this case, only the slab of the first cluster is
* used. The rest of the slabs are marked with SLF_PARTIAL to indicate
* that they are part of the larger slab.
*
* Each slab controls a page of memory.
*/
typedef struct mcl_slab {
struct mcl_slab *sl_next; /* neighboring slab */
u_int8_t sl_class; /* controlling mbuf class */
int8_t sl_refcnt; /* outstanding allocations */
int8_t sl_chunks; /* chunks (bufs) in this slab */
u_int16_t sl_flags; /* slab flags (see below) */
u_int16_t sl_len; /* slab length */
void *sl_base; /* base of allocated memory */
void *sl_head; /* first free buffer */
TAILQ_ENTRY(mcl_slab) sl_link; /* next/prev slab on freelist */
} mcl_slab_t;
#define SLF_MAPPED 0x0001 /* backed by a mapped page */
#define SLF_PARTIAL 0x0002 /* part of another slab */
#define SLF_DETACHED 0x0004 /* not in slab freelist */
/*
* The array of slabs are broken into groups of arrays per 1MB of kernel
* memory to reduce the footprint. Each group is allocated on demand
* whenever a new piece of memory mapped in from the VM crosses the 1MB
* boundary.
*/
#define NSLABSPMB ((1 << MBSHIFT) >> PAGE_SHIFT)
typedef struct mcl_slabg {
mcl_slab_t *slg_slab; /* group of slabs */
} mcl_slabg_t;
/*
* Number of slabs needed to control a 16KB cluster object.
*/
#define NSLABSP16KB (M16KCLBYTES >> PAGE_SHIFT)
/*
* Per-cluster audit structure.
*/
typedef struct {
mcache_audit_t **cl_audit; /* array of audits */
} mcl_audit_t;
typedef struct {
struct thread *msa_thread; /* thread doing transaction */
struct thread *msa_pthread; /* previous transaction thread */
uint32_t msa_tstamp; /* transaction timestamp (ms) */
uint32_t msa_ptstamp; /* prev transaction timestamp (ms) */
uint16_t msa_depth; /* pc stack depth */
uint16_t msa_pdepth; /* previous transaction pc stack */
void *msa_stack[MCACHE_STACK_DEPTH];
void *msa_pstack[MCACHE_STACK_DEPTH];
} mcl_scratch_audit_t;
typedef struct {
/*
* Size of data from the beginning of an mbuf that covers m_hdr,
* pkthdr and m_ext structures. If auditing is enabled, we allocate
* a shadow mbuf structure of this size inside each audit structure,
* and the contents of the real mbuf gets copied into it when the mbuf
* is freed. This allows us to pattern-fill the mbuf for integrity
* check, and to preserve any constructed mbuf fields (e.g. mbuf +
* cluster cache case). Note that we don't save the contents of
* clusters when they are freed; we simply pattern-fill them.
*/
u_int8_t sc_mbuf[(MSIZE - _MHLEN) + sizeof (_m_ext_t)];
mcl_scratch_audit_t sc_scratch __attribute__((aligned(8)));
} mcl_saved_contents_t;
#define AUDIT_CONTENTS_SIZE (sizeof (mcl_saved_contents_t))
#define MCA_SAVED_MBUF_PTR(_mca) \
((struct mbuf *)(void *)((mcl_saved_contents_t *) \
(_mca)->mca_contents)->sc_mbuf)
#define MCA_SAVED_MBUF_SIZE \
(sizeof (((mcl_saved_contents_t *)0)->sc_mbuf))
#define MCA_SAVED_SCRATCH_PTR(_mca) \
(&((mcl_saved_contents_t *)(_mca)->mca_contents)->sc_scratch)
/*
* mbuf specific mcache audit flags
*/
#define MB_INUSE 0x01 /* object has not been returned to slab */
#define MB_COMP_INUSE 0x02 /* object has not been returned to cslab */
#define MB_SCVALID 0x04 /* object has valid saved contents */
/*
* Each of the following two arrays hold up to nmbclusters elements.
*/
static mcl_audit_t *mclaudit; /* array of cluster audit information */
static unsigned int maxclaudit; /* max # of entries in audit table */
static mcl_slabg_t **slabstbl; /* cluster slabs table */
static unsigned int maxslabgrp; /* max # of entries in slabs table */
static unsigned int slabgrp; /* # of entries in slabs table */
/* Globals */
int nclusters; /* # of clusters for non-jumbo (legacy) sizes */
int njcl; /* # of clusters for jumbo sizes */
int njclbytes; /* size of a jumbo cluster */
unsigned char *mbutl; /* first mapped cluster address */
unsigned char *embutl; /* ending virtual address of mclusters */
int _max_linkhdr; /* largest link-level header */
int _max_protohdr; /* largest protocol header */
int max_hdr; /* largest link+protocol header */
int max_datalen; /* MHLEN - max_hdr */
static boolean_t mclverify; /* debug: pattern-checking */
static boolean_t mcltrace; /* debug: stack tracing */
static boolean_t mclfindleak; /* debug: leak detection */
static boolean_t mclexpleak; /* debug: expose leak info to user space */
static struct timeval mb_start; /* beginning of time */
/* mbuf leak detection variables */
static struct mleak_table mleak_table;
static mleak_stat_t *mleak_stat;
#define MLEAK_STAT_SIZE(n) \
__builtin_offsetof(mleak_stat_t, ml_trace[n])
struct mallocation {
mcache_obj_t *element; /* the alloc'ed element, NULL if unused */
u_int32_t trace_index; /* mtrace index for corresponding backtrace */
u_int32_t count; /* How many objects were requested */
u_int64_t hitcount; /* for determining hash effectiveness */
};
struct mtrace {
u_int64_t collisions;
u_int64_t hitcount;
u_int64_t allocs;
u_int64_t depth;
uintptr_t addr[MLEAK_STACK_DEPTH];
};
/* Size must be a power of two for the zhash to be able to just mask off bits */
#define MLEAK_ALLOCATION_MAP_NUM 512
#define MLEAK_TRACE_MAP_NUM 256
/*
* Sample factor for how often to record a trace. This is overwritable
* by the boot-arg mleak_sample_factor.
*/
#define MLEAK_SAMPLE_FACTOR 500
/*
* Number of top leakers recorded.
*/
#define MLEAK_NUM_TRACES 5
#define MB_LEAK_SPACING_64 " "
#define MB_LEAK_SPACING_32 " "
#define MB_LEAK_HDR_32 "\n\
trace [1] trace [2] trace [3] trace [4] trace [5] \n\
---------- ---------- ---------- ---------- ---------- \n\
"
#define MB_LEAK_HDR_64 "\n\
trace [1] trace [2] trace [3] \
trace [4] trace [5] \n\
------------------ ------------------ ------------------ \
------------------ ------------------ \n\
"
static uint32_t mleak_alloc_buckets = MLEAK_ALLOCATION_MAP_NUM;
static uint32_t mleak_trace_buckets = MLEAK_TRACE_MAP_NUM;
/* Hashmaps of allocations and their corresponding traces */
static struct mallocation *mleak_allocations;
static struct mtrace *mleak_traces;
static struct mtrace *mleak_top_trace[MLEAK_NUM_TRACES];
/* Lock to protect mleak tables from concurrent modification */
decl_lck_mtx_data(static, mleak_lock_data);
static lck_mtx_t *mleak_lock = &mleak_lock_data;
static lck_attr_t *mleak_lock_attr;
static lck_grp_t *mleak_lock_grp;
static lck_grp_attr_t *mleak_lock_grp_attr;
/* Lock to protect the completion callback table */
static lck_grp_attr_t *mbuf_tx_compl_tbl_lck_grp_attr = NULL;
static lck_attr_t *mbuf_tx_compl_tbl_lck_attr = NULL;
static lck_grp_t *mbuf_tx_compl_tbl_lck_grp = NULL;
decl_lck_rw_data(, mbuf_tx_compl_tbl_lck_rw_data);
lck_rw_t *mbuf_tx_compl_tbl_lock = &mbuf_tx_compl_tbl_lck_rw_data;
extern u_int32_t high_sb_max;
/* The minimum number of objects that are allocated, to start. */
#define MINCL 32
#define MINBIGCL (MINCL >> 1)
#define MIN16KCL (MINCL >> 2)
/* Low watermarks (only map in pages once free counts go below) */
#define MBIGCL_LOWAT MINBIGCL
#define M16KCL_LOWAT MIN16KCL
typedef struct {
mbuf_class_t mtbl_class; /* class type */
mcache_t *mtbl_cache; /* mcache for this buffer class */
TAILQ_HEAD(mcl_slhead, mcl_slab) mtbl_slablist; /* slab list */
mcache_obj_t *mtbl_cobjlist; /* composite objects freelist */
mb_class_stat_t *mtbl_stats; /* statistics fetchable via sysctl */
u_int32_t mtbl_maxsize; /* maximum buffer size */
int mtbl_minlimit; /* minimum allowed */
int mtbl_maxlimit; /* maximum allowed */
u_int32_t mtbl_wantpurge; /* purge during next reclaim */
uint32_t mtbl_avgtotal; /* average total on iOS */
u_int32_t mtbl_expand; /* worker should expand the class */
} mbuf_table_t;
#define m_class(c) mbuf_table[c].mtbl_class
#define m_cache(c) mbuf_table[c].mtbl_cache
#define m_slablist(c) mbuf_table[c].mtbl_slablist
#define m_cobjlist(c) mbuf_table[c].mtbl_cobjlist
#define m_maxsize(c) mbuf_table[c].mtbl_maxsize
#define m_minlimit(c) mbuf_table[c].mtbl_minlimit
#define m_maxlimit(c) mbuf_table[c].mtbl_maxlimit
#define m_wantpurge(c) mbuf_table[c].mtbl_wantpurge
#define m_avgtotal(c) mbuf_table[c].mtbl_avgtotal
#define m_cname(c) mbuf_table[c].mtbl_stats->mbcl_cname
#define m_size(c) mbuf_table[c].mtbl_stats->mbcl_size
#define m_total(c) mbuf_table[c].mtbl_stats->mbcl_total
#define m_active(c) mbuf_table[c].mtbl_stats->mbcl_active
#define m_infree(c) mbuf_table[c].mtbl_stats->mbcl_infree
#define m_slab_cnt(c) mbuf_table[c].mtbl_stats->mbcl_slab_cnt
#define m_alloc_cnt(c) mbuf_table[c].mtbl_stats->mbcl_alloc_cnt
#define m_free_cnt(c) mbuf_table[c].mtbl_stats->mbcl_free_cnt
#define m_notified(c) mbuf_table[c].mtbl_stats->mbcl_notified
#define m_purge_cnt(c) mbuf_table[c].mtbl_stats->mbcl_purge_cnt
#define m_fail_cnt(c) mbuf_table[c].mtbl_stats->mbcl_fail_cnt
#define m_ctotal(c) mbuf_table[c].mtbl_stats->mbcl_ctotal
#define m_peak(c) mbuf_table[c].mtbl_stats->mbcl_peak_reported
#define m_release_cnt(c) mbuf_table[c].mtbl_stats->mbcl_release_cnt
#define m_region_expand(c) mbuf_table[c].mtbl_expand
static mbuf_table_t mbuf_table[] = {
/*
* The caches for mbufs, regular clusters and big clusters.
* The average total values were based on data gathered by actual
* usage patterns on iOS.
*/
{ MC_MBUF, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_MBUF)),
NULL, NULL, 0, 0, 0, 0, 3000, 0 },
{ MC_CL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_CL)),
NULL, NULL, 0, 0, 0, 0, 2000, 0 },
{ MC_BIGCL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_BIGCL)),
NULL, NULL, 0, 0, 0, 0, 1000, 0 },
{ MC_16KCL, NULL, TAILQ_HEAD_INITIALIZER(m_slablist(MC_16KCL)),
NULL, NULL, 0, 0, 0, 0, 200, 0 },
/*
* The following are special caches; they serve as intermediate
* caches backed by the above rudimentary caches. Each object
* in the cache is an mbuf with a cluster attached to it. Unlike
* the above caches, these intermediate caches do not directly
* deal with the slab structures; instead, the constructed
* cached elements are simply stored in the freelists.
*/
{ MC_MBUF_CL, NULL, { NULL, NULL }, NULL, NULL, 0, 0, 0, 0, 2000, 0 },
{ MC_MBUF_BIGCL, NULL, { NULL, NULL }, NULL, NULL, 0, 0, 0, 0, 1000, 0 },
{ MC_MBUF_16KCL, NULL, { NULL, NULL }, NULL, NULL, 0, 0, 0, 0, 200, 0 },
};
#define NELEM(a) (sizeof (a) / sizeof ((a)[0]))
static void *mb_waitchan = &mbuf_table; /* wait channel for all caches */
static int mb_waiters; /* number of waiters */
boolean_t mb_peak_newreport = FALSE;
boolean_t mb_peak_firstreport = FALSE;
/* generate a report by default after 1 week of uptime */
#define MBUF_PEAK_FIRST_REPORT_THRESHOLD 604800
#define MB_WDT_MAXTIME 10 /* # of secs before watchdog panic */
static struct timeval mb_wdtstart; /* watchdog start timestamp */
static char *mbuf_dump_buf;
#define MBUF_DUMP_BUF_SIZE 2048
/*
* mbuf watchdog is enabled by default on embedded platforms. It is
* also toggeable via the kern.ipc.mb_watchdog sysctl.
* Garbage collection is also enabled by default on embedded platforms.
* mb_drain_maxint controls the amount of time to wait (in seconds) before
* consecutive calls to m_drain().
*/
#if CONFIG_EMBEDDED
static unsigned int mb_watchdog = 1;
static unsigned int mb_drain_maxint = 60;
#else
static unsigned int mb_watchdog = 0;
static unsigned int mb_drain_maxint = 0;
#endif /* CONFIG_EMBEDDED */
uintptr_t mb_obscure_extfree __attribute__((visibility("hidden")));
uintptr_t mb_obscure_extref __attribute__((visibility("hidden")));
/* Red zone */
static u_int32_t mb_redzone_cookie;
static void m_redzone_init(struct mbuf *);
static void m_redzone_verify(struct mbuf *m);
/* The following are used to serialize m_clalloc() */
static boolean_t mb_clalloc_busy;
static void *mb_clalloc_waitchan = &mb_clalloc_busy;
static int mb_clalloc_waiters;
static void mbuf_mtypes_sync(boolean_t);
static int mbstat_sysctl SYSCTL_HANDLER_ARGS;
static void mbuf_stat_sync(void);
static int mb_stat_sysctl SYSCTL_HANDLER_ARGS;
static int mleak_top_trace_sysctl SYSCTL_HANDLER_ARGS;
static int mleak_table_sysctl SYSCTL_HANDLER_ARGS;
static char *mbuf_dump(void);
static void mbuf_table_init(void);
static inline void m_incref(struct mbuf *);
static inline u_int16_t m_decref(struct mbuf *);
static int m_clalloc(const u_int32_t, const int, const u_int32_t);
static void mbuf_worker_thread_init(void);
static mcache_obj_t *slab_alloc(mbuf_class_t, int);
static void slab_free(mbuf_class_t, mcache_obj_t *);
static unsigned int mbuf_slab_alloc(void *, mcache_obj_t ***,
unsigned int, int);
static void mbuf_slab_free(void *, mcache_obj_t *, int);
static void mbuf_slab_audit(void *, mcache_obj_t *, boolean_t);
static void mbuf_slab_notify(void *, u_int32_t);
static unsigned int cslab_alloc(mbuf_class_t, mcache_obj_t ***,
unsigned int);
static unsigned int cslab_free(mbuf_class_t, mcache_obj_t *, int);
static unsigned int mbuf_cslab_alloc(void *, mcache_obj_t ***,
unsigned int, int);
static void mbuf_cslab_free(void *, mcache_obj_t *, int);
static void mbuf_cslab_audit(void *, mcache_obj_t *, boolean_t);
static int freelist_populate(mbuf_class_t, unsigned int, int);
static void freelist_init(mbuf_class_t);
static boolean_t mbuf_cached_above(mbuf_class_t, int);
static boolean_t mbuf_steal(mbuf_class_t, unsigned int);
static void m_reclaim(mbuf_class_t, unsigned int, boolean_t);
static int m_howmany(int, size_t);
static void mbuf_worker_thread(void);
static void mbuf_watchdog(void);
static boolean_t mbuf_sleep(mbuf_class_t, unsigned int, int);
static void mcl_audit_init(void *, mcache_audit_t **, mcache_obj_t **,
size_t, unsigned int);
static void mcl_audit_free(void *, unsigned int);
static mcache_audit_t *mcl_audit_buf2mca(mbuf_class_t, mcache_obj_t *);
static void mcl_audit_mbuf(mcache_audit_t *, void *, boolean_t, boolean_t);
static void mcl_audit_cluster(mcache_audit_t *, void *, size_t, boolean_t,
boolean_t);
static void mcl_audit_restore_mbuf(struct mbuf *, mcache_audit_t *, boolean_t);
static void mcl_audit_save_mbuf(struct mbuf *, mcache_audit_t *);
static void mcl_audit_scratch(mcache_audit_t *);
static void mcl_audit_mcheck_panic(struct mbuf *);
static void mcl_audit_verify_nextptr(void *, mcache_audit_t *);
static void mleak_activate(void);
static void mleak_logger(u_int32_t, mcache_obj_t *, boolean_t);
static boolean_t mleak_log(uintptr_t *, mcache_obj_t *, uint32_t, int);
static void mleak_free(mcache_obj_t *);
static void mleak_sort_traces(void);
static void mleak_update_stats(void);
static mcl_slab_t *slab_get(void *);
static void slab_init(mcl_slab_t *, mbuf_class_t, u_int32_t,
void *, void *, unsigned int, int, int);
static void slab_insert(mcl_slab_t *, mbuf_class_t);
static void slab_remove(mcl_slab_t *, mbuf_class_t);
static boolean_t slab_inrange(mcl_slab_t *, void *);
static void slab_nextptr_panic(mcl_slab_t *, void *);
static void slab_detach(mcl_slab_t *);
static boolean_t slab_is_detached(mcl_slab_t *);
static int m_copyback0(struct mbuf **, int, int, const void *, int, int);
static struct mbuf *m_split0(struct mbuf *, int, int, int);
__private_extern__ void mbuf_report_peak_usage(void);
static boolean_t mbuf_report_usage(mbuf_class_t);
/* flags for m_copyback0 */
#define M_COPYBACK0_COPYBACK 0x0001 /* copyback from cp */
#define M_COPYBACK0_PRESERVE 0x0002 /* preserve original data */
#define M_COPYBACK0_COW 0x0004 /* do copy-on-write */
#define M_COPYBACK0_EXTEND 0x0008 /* extend chain */
/*
* This flag is set for all mbufs that come out of and into the composite
* mbuf + cluster caches, i.e. MC_MBUF_CL and MC_MBUF_BIGCL. mbufs that
* are marked with such a flag have clusters attached to them, and will be
* treated differently when they are freed; instead of being placed back
* into the mbuf and cluster freelists, the composite mbuf + cluster objects
* are placed back into the appropriate composite cache's freelist, and the
* actual freeing is deferred until the composite objects are purged. At
* such a time, this flag will be cleared from the mbufs and the objects
* will be freed into their own separate freelists.
*/
#define EXTF_COMPOSITE 0x1
/*
* This flag indicates that the external cluster is read-only, i.e. it is
* or was referred to by more than one mbufs. Once set, this flag is never
* cleared.
*/
#define EXTF_READONLY 0x2
/*
* This flag indicates that the external cluster is paired with the mbuf.
* Pairing implies an external free routine defined which will be invoked
* when the reference count drops to the minimum at m_free time. This
* flag is never cleared.
*/
#define EXTF_PAIRED 0x4
#define EXTF_MASK \
(EXTF_COMPOSITE | EXTF_READONLY | EXTF_PAIRED)
#define MEXT_MINREF(m) ((m_get_rfa(m))->minref)
#define MEXT_REF(m) ((m_get_rfa(m))->refcnt)
#define MEXT_PREF(m) ((m_get_rfa(m))->prefcnt)
#define MEXT_FLAGS(m) ((m_get_rfa(m))->flags)
#define MEXT_PRIV(m) ((m_get_rfa(m))->priv)
#define MEXT_PMBUF(m) ((m_get_rfa(m))->paired)
#define MEXT_TOKEN(m) ((m_get_rfa(m))->ext_token)
#define MBUF_IS_COMPOSITE(m) \
(MEXT_REF(m) == MEXT_MINREF(m) && \
(MEXT_FLAGS(m) & EXTF_MASK) == EXTF_COMPOSITE)
/*
* This macro can be used to test if the mbuf is paired to an external
* cluster. The test for MEXT_PMBUF being equal to the mbuf in subject
* is important, as EXTF_PAIRED alone is insufficient since it is immutable,
* and thus survives calls to m_free_paired.
*/
#define MBUF_IS_PAIRED(m) \
(((m)->m_flags & M_EXT) && \
(MEXT_FLAGS(m) & EXTF_MASK) == EXTF_PAIRED && \
MEXT_PMBUF(m) == (m))
/*
* Macros used to verify the integrity of the mbuf.
*/
#define _MCHECK(m) { \
if ((m)->m_type != MT_FREE && !MBUF_IS_PAIRED(m)) { \
if (mclaudit == NULL) \
panic("MCHECK: m_type=%d m=%p", \
(u_int16_t)(m)->m_type, m); \
else \
mcl_audit_mcheck_panic(m); \
} \
}
#define MBUF_IN_MAP(addr) \
((unsigned char *)(addr) >= mbutl && \
(unsigned char *)(addr) < embutl)
#define MRANGE(addr) { \
if (!MBUF_IN_MAP(addr)) \
panic("MRANGE: address out of range 0x%p", addr); \
}
/*
* Macro version of mtod.
*/
#define MTOD(m, t) ((t)((m)->m_data))
/*
* Macros to obtain page index given a base cluster address
*/
#define MTOPG(x) (((unsigned char *)x - mbutl) >> PAGE_SHIFT)
#define PGTOM(x) (mbutl + (x << PAGE_SHIFT))
/*
* Macro to find the mbuf index relative to a base.
*/
#define MBPAGEIDX(c, m) \
(((unsigned char *)(m) - (unsigned char *)(c)) >> MSIZESHIFT)
/*
* Same thing for 2KB cluster index.
*/
#define CLPAGEIDX(c, m) \
(((unsigned char *)(m) - (unsigned char *)(c)) >> MCLSHIFT)
/*
* Macro to find 4KB cluster index relative to a base
*/
#define BCLPAGEIDX(c, m) \
(((unsigned char *)(m) - (unsigned char *)(c)) >> MBIGCLSHIFT)
/*
* Macros used during mbuf and cluster initialization.
*/
#define MBUF_INIT_PKTHDR(m) { \
(m)->m_pkthdr.rcvif = NULL; \
(m)->m_pkthdr.pkt_hdr = NULL; \
(m)->m_pkthdr.len = 0; \
(m)->m_pkthdr.csum_flags = 0; \
(m)->m_pkthdr.csum_data = 0; \
(m)->m_pkthdr.vlan_tag = 0; \
m_classifier_init(m, 0); \
m_tag_init(m, 1); \
m_scratch_init(m); \
m_redzone_init(m); \
}
#define MBUF_INIT(m, pkthdr, type) { \
_MCHECK(m); \
(m)->m_next = (m)->m_nextpkt = NULL; \
(m)->m_len = 0; \
(m)->m_type = type; \
if ((pkthdr) == 0) { \
(m)->m_data = (m)->m_dat; \
(m)->m_flags = 0; \
} else { \
(m)->m_data = (m)->m_pktdat; \
(m)->m_flags = M_PKTHDR; \
MBUF_INIT_PKTHDR(m); \
} \
}
#define MEXT_INIT(m, buf, size, free, arg, rfa, min, ref, pref, flag, \
priv, pm) { \
(m)->m_data = (m)->m_ext.ext_buf = (buf); \
(m)->m_flags |= M_EXT; \
m_set_ext((m), (rfa), (free), (arg)); \
(m)->m_ext.ext_size = (size); \
MEXT_MINREF(m) = (min); \
MEXT_REF(m) = (ref); \
MEXT_PREF(m) = (pref); \
MEXT_FLAGS(m) = (flag); \
MEXT_PRIV(m) = (priv); \
MEXT_PMBUF(m) = (pm); \
}
#define MBUF_CL_INIT(m, buf, rfa, ref, flag) \
MEXT_INIT(m, buf, m_maxsize(MC_CL), NULL, NULL, rfa, 0, \
ref, 0, flag, 0, NULL)
#define MBUF_BIGCL_INIT(m, buf, rfa, ref, flag) \
MEXT_INIT(m, buf, m_maxsize(MC_BIGCL), m_bigfree, NULL, rfa, 0, \
ref, 0, flag, 0, NULL)
#define MBUF_16KCL_INIT(m, buf, rfa, ref, flag) \
MEXT_INIT(m, buf, m_maxsize(MC_16KCL), m_16kfree, NULL, rfa, 0, \
ref, 0, flag, 0, NULL)
/*
* Macro to convert BSD malloc sleep flag to mcache's
*/
#define MSLEEPF(f) ((!((f) & M_DONTWAIT)) ? MCR_SLEEP : MCR_NOSLEEP)
/*
* The structure that holds all mbuf class statistics exportable via sysctl.
* Similar to mbstat structure, the mb_stat structure is protected by the
* global mbuf lock. It contains additional information about the classes
* that allows for a more accurate view of the state of the allocator.
*/
struct mb_stat *mb_stat;
struct omb_stat *omb_stat; /* For backwards compatibility */
#define MB_STAT_SIZE(n) \
__builtin_offsetof(mb_stat_t, mbs_class[n])
#define OMB_STAT_SIZE(n) \
((size_t)(&((struct omb_stat *)0)->mbs_class[n]))
/*
* The legacy structure holding all of the mbuf allocation statistics.
* The actual statistics used by the kernel are stored in the mbuf_table
* instead, and are updated atomically while the global mbuf lock is held.
* They are mirrored in mbstat to support legacy applications (e.g. netstat).
* Unlike before, the kernel no longer relies on the contents of mbstat for
* its operations (e.g. cluster expansion) because the structure is exposed
* to outside and could possibly be modified, therefore making it unsafe.
* With the exception of the mbstat.m_mtypes array (see below), all of the
* statistics are updated as they change.
*/
struct mbstat mbstat;
#define MBSTAT_MTYPES_MAX \
(sizeof (mbstat.m_mtypes) / sizeof (mbstat.m_mtypes[0]))
/*
* Allocation statistics related to mbuf types (up to MT_MAX-1) are updated
* atomically and stored in a per-CPU structure which is lock-free; this is
* done in order to avoid writing to the global mbstat data structure which
* would cause false sharing. During sysctl request for kern.ipc.mbstat,
* the statistics across all CPUs will be converged into the mbstat.m_mtypes
* array and returned to the application. Any updates for types greater or
* equal than MT_MAX would be done atomically to the mbstat; this slows down
* performance but is okay since the kernel uses only up to MT_MAX-1 while
* anything beyond that (up to type 255) is considered a corner case.
*/
typedef struct {
unsigned int cpu_mtypes[MT_MAX];
} __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE), packed)) mtypes_cpu_t;
typedef struct {
mtypes_cpu_t mbs_cpu[1];
} mbuf_mtypes_t;
static mbuf_mtypes_t *mbuf_mtypes; /* per-CPU statistics */
#define MBUF_MTYPES_SIZE(n) \
((size_t)(&((mbuf_mtypes_t *)0)->mbs_cpu[n]))
#define MTYPES_CPU(p) \
((mtypes_cpu_t *)(void *)((char *)(p) + MBUF_MTYPES_SIZE(cpu_number())))
#define mtype_stat_add(type, n) { \
if ((unsigned)(type) < MT_MAX) { \
mtypes_cpu_t *mbs = MTYPES_CPU(mbuf_mtypes); \
atomic_add_32(&mbs->cpu_mtypes[type], n); \
} else if ((unsigned)(type) < (unsigned)MBSTAT_MTYPES_MAX) { \
atomic_add_16((int16_t *)&mbstat.m_mtypes[type], n); \
} \
}
#define mtype_stat_sub(t, n) mtype_stat_add(t, -(n))
#define mtype_stat_inc(t) mtype_stat_add(t, 1)
#define mtype_stat_dec(t) mtype_stat_sub(t, 1)
static void
mbuf_mtypes_sync(boolean_t locked)