xref: /xnu-12377.1.9/bsd/sys/mcache.h (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 2006-2019 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 #ifndef _SYS_MCACHE_H
29 #define _SYS_MCACHE_H
30 
31 #ifdef KERNEL_PRIVATE
32 
33 #ifdef  __cplusplus
34 extern "C" {
35 #endif
36 
37 #include <sys/types.h>
38 #include <sys/queue.h>
39 #include <mach/boolean.h>
40 #include <kern/locks.h>
41 #include <libkern/OSAtomic.h>
42 
43 #ifdef ASSERT
44 #undef ASSERT
45 #endif
46 
47 #ifdef VERIFY
48 #undef VERIFY
49 #endif
50 
51 /*
52  * Unlike VERIFY(), ASSERT() is evaluated only in DEBUG/DEVELOPMENT build.
53  */
54 #define VERIFY(EX)      \
55 	((void)(__probable((EX)) || assfail(#EX, __FILE__, __LINE__)))
56 #if (DEBUG || DEVELOPMENT)
57 #define ASSERT(EX)      VERIFY(EX)
58 #else
59 #define ASSERT(EX)      ((void)0)
60 #endif
61 
62 /*
63  * Use CPU_CACHE_LINE_SIZE instead of MAX_CPU_CACHE_LINE_SIZE, unless
64  * wasting space is of no concern.
65  */
66 #define MAX_CPU_CACHE_LINE_SIZE 128
67 #define CPU_CACHE_LINE_SIZE     mcache_cache_line_size()
68 
69 #ifndef IS_P2ALIGNED
70 #define IS_P2ALIGNED(v, a) \
71 	((((uintptr_t)(v)) & ((uintptr_t)(a) - 1)) == 0)
72 #endif /* IS_P2ALIGNED */
73 
74 #ifndef P2ROUNDUP
75 #define P2ROUNDUP(x, align) \
76 	(-(-((uintptr_t)(x)) & -((uintptr_t)align)))
77 #endif /* P2ROUNDUP */
78 
79 #ifndef P2ROUNDDOWN
80 #define P2ROUNDDOWN(x, align) \
81 	(((uintptr_t)(x)) & ~((uintptr_t)(align) - 1))
82 #endif /* P2ROUNDDOWN */
83 
84 #ifndef P2ALIGN
85 #define P2ALIGN(x, align) \
86 	((uintptr_t)(x) & -((uintptr_t)(align)))
87 #endif /* P2ALIGN */
88 
89 #define MCACHE_FREE_PATTERN             0xdeadbeefdeadbeefULL
90 #define MCACHE_UNINITIALIZED_PATTERN    0xbaddcafebaddcafeULL
91 
92 /*
93  * mcache allocation request flags.
94  *
95  * MCR_NOSLEEP and MCR_FAILOK are mutually exclusive.  The latter is used
96  * by the mbuf allocator to handle the implementation of several caches that
97  * involve multiple layers of mcache.  It implies a best effort blocking
98  * allocation request; if the request cannot be satisfied, the caller will
99  * be blocked until further notice, similar to MCR_SLEEP, except that upon
100  * a wake up it will return immediately to the caller regardless of whether
101  * the request can been fulfilled.
102  *
103  * MCR_TRYHARD implies a non-blocking allocation request, regardless of
104  * whether MCR_NOSLEEP is set.  It informs the allocator that the request
105  * should not cause the calling thread to block, and that it must have
106  * exhausted all possible schemes to fulfill the request, including doing
107  * reclaims and/or purges, before returning to the caller.
108  *
109  * Regular mcache clients should only use MCR_SLEEP or MCR_NOSLEEP.
110  */
111 #define MCR_SLEEP       0x0000          /* same as M_WAITOK */
112 #define MCR_NOSLEEP     0x0001          /* same as M_NOWAIT */
113 #define MCR_FAILOK      0x0100          /* private, for internal use only */
114 #define MCR_TRYHARD     0x0200          /* private, for internal use only */
115 #define MCR_USR1        0x1000          /* private, for internal use only */
116 
117 #define MCR_NONBLOCKING (MCR_NOSLEEP | MCR_FAILOK | MCR_TRYHARD)
118 
119 /*
120  * Generic one-way linked list element structure.  This is used to handle
121  * mcache_alloc_ext() requests in order to chain the allocated objects
122  * together before returning them to the caller.
123  */
124 typedef struct mcache_obj {
125 	struct mcache_obj       *obj_next;
126 } mcache_obj_t;
127 
128 typedef struct mcache_bkt {
129 	void            *bkt_next;      /* next bucket in list */
130 	struct mcache_bkttype *bkt_type; /* bucket type */
131 	void            *bkt_obj[1];    /* one or more objects */
132 } mcache_bkt_t;
133 
134 typedef struct mcache_bktlist {
135 	mcache_bkt_t    *bl_list;       /* bucket list */
136 	u_int32_t       bl_total;       /* number of buckets */
137 	u_int32_t       bl_min;         /* min since last update */
138 	u_int32_t       bl_reaplimit;   /* max reapable buckets */
139 	u_int64_t       bl_alloc;       /* allocations from this list */
140 } mcache_bktlist_t;
141 
142 typedef struct mcache_bkttype {
143 	int             bt_bktsize;     /* bucket size (number of elements) */
144 	size_t          bt_minbuf;      /* all smaller buffers qualify */
145 	size_t          bt_maxbuf;      /* no larger bfufers qualify */
146 	struct mcache   *bt_cache;      /* bucket cache */
147 } mcache_bkttype_t;
148 
149 typedef struct mcache_cpu {
150 	decl_lck_mtx_data(, cc_lock);
151 	mcache_bkt_t    *cc_filled;     /* the currently filled bucket */
152 	mcache_bkt_t    *cc_pfilled;    /* the previously filled bucket */
153 	u_int64_t       cc_alloc;       /* allocations from this cpu */
154 	u_int64_t       cc_free;        /* frees to this cpu */
155 	int             cc_objs;        /* number of objects in filled bkt */
156 	int             cc_pobjs;       /* number of objects in previous bkt */
157 	int             cc_bktsize;     /* number of elements in a full bkt */
158 } __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE))) mcache_cpu_t;
159 
160 typedef unsigned int (*mcache_allocfn_t)(void *, mcache_obj_t ***,
161     unsigned int, int);
162 typedef void (*mcache_freefn_t)(void *, mcache_obj_t *, boolean_t);
163 typedef void (*mcache_auditfn_t)(void *, mcache_obj_t *, boolean_t);
164 typedef void (*mcache_logfn_t)(u_int32_t, mcache_obj_t *, boolean_t);
165 typedef void (*mcache_notifyfn_t)(void *, u_int32_t);
166 
167 typedef struct mcache {
168 	/*
169 	 * Cache properties
170 	 */
171 	LIST_ENTRY(mcache) mc_list;     /* cache linkage */
172 	char            mc_name[32];    /* cache name */
173 	struct zone     *mc_slab_zone;  /* backend zone allocator */
174 	mcache_allocfn_t mc_slab_alloc; /* slab layer allocate callback */
175 	mcache_freefn_t mc_slab_free;   /* slab layer free callback */
176 	mcache_auditfn_t mc_slab_audit; /* slab layer audit callback */
177 	mcache_logfn_t mc_slab_log;     /* slab layer log callback */
178 	mcache_notifyfn_t mc_slab_notify; /* slab layer notify callback */
179 	void            *mc_private;    /* opaque arg to callbacks */
180 	size_t          mc_bufsize;     /* object size */
181 	size_t          mc_align;       /* object alignment */
182 	u_int32_t       mc_flags;       /* cache creation flags */
183 	u_int32_t       mc_purge_cnt;   /* # of purges requested by slab */
184 	u_int32_t       mc_enable_cnt;  /* # of reenables due to purges */
185 	u_int32_t       mc_waiter_cnt;  /* # of slab layer waiters */
186 	u_int32_t       mc_wretry_cnt;  /* # of wait retries */
187 	u_int32_t       mc_nwretry_cnt; /* # of no-wait retry attempts */
188 	u_int32_t       mc_nwfail_cnt;  /* # of no-wait retries that failed */
189 	decl_lck_mtx_data(, mc_sync_lock); /* protects purges and reenables */
190 	lck_grp_t       *mc_sync_lock_grp;
191 	/*
192 	 * Keep CPU and buckets layers lock statistics separate.
193 	 */
194 	lck_grp_t       *mc_cpu_lock_grp;
195 
196 	/*
197 	 * Bucket layer common to all CPUs
198 	 */
199 	decl_lck_mtx_data(, mc_bkt_lock);
200 	lck_grp_t       *mc_bkt_lock_grp;
201 	mcache_bkttype_t *cache_bkttype;        /* bucket type */
202 	mcache_bktlist_t mc_full;               /* full buckets */
203 	mcache_bktlist_t mc_empty;              /* empty buckets */
204 	size_t          mc_chunksize;           /* bufsize + alignment */
205 	u_int32_t       mc_bkt_contention;      /* lock contention count */
206 	u_int32_t       mc_bkt_contention_prev; /* previous snapshot */
207 
208 	/*
209 	 * Per-CPU layer, aligned at cache line boundary
210 	 */
211 	mcache_cpu_t    mc_cpu[1]
212 	__attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE)));
213 } mcache_t;
214 
215 #define MCACHE_ALIGN    8       /* default guaranteed alignment */
216 
217 /* Valid values for mc_flags */
218 #define MCF_VERIFY      0x00000001      /* enable verification */
219 #define MCF_TRACE       0x00000002      /* enable transaction auditing */
220 #define MCF_NOCPUCACHE  0x00000010      /* disable CPU layer caching */
221 #define MCF_NOLEAKLOG   0x00000100      /* disable leak logging */
222 #define MCF_EXPLEAKLOG  0x00000200      /* expose leak info to user space */
223 
224 #define MCF_DEBUG       (MCF_VERIFY | MCF_TRACE)
225 #define MCF_FLAGS_MASK  \
226 	(MCF_DEBUG | MCF_NOCPUCACHE | MCF_NOLEAKLOG | MCF_EXPLEAKLOG)
227 
228 /* Valid values for notify callback */
229 #define MCN_RETRYALLOC  0x00000001      /* Allocation should be retried */
230 
231 #define MCACHE_STACK_DEPTH 16
232 
233 #define MCA_TRN_MAX     2               /* Number of transactions to record */
234 
235 #define DUMP_MCA_BUF_SIZE       512
236 
237 typedef struct mcache_audit {
238 	struct mcache_audit *mca_next;  /* next audit struct */
239 	void            *mca_addr;      /* address of buffer */
240 	mcache_t        *mca_cache;     /* parent cache of the buffer */
241 	size_t          mca_contents_size; /* size of saved contents */
242 	void            *mca_contents;  /* user-specific saved contents */
243 	void            *mca_uptr;      /* user-specific pointer */
244 	uint32_t        mca_uflags;     /* user-specific flags */
245 	uint32_t        mca_next_trn;
246 	struct mca_trn {
247 		struct thread   *mca_thread;    /* thread doing transaction */
248 		uint32_t        mca_tstamp;
249 		uint16_t        mca_depth;
250 		void            *mca_stack[MCACHE_STACK_DEPTH];
251 	} mca_trns[MCA_TRN_MAX];
252 } mcache_audit_t;
253 
254 __private_extern__ int assfail(const char *, const char *, int) __abortlike;
255 __private_extern__ void mcache_init(void);
256 __private_extern__ unsigned int mcache_getflags(void);
257 __private_extern__ unsigned int mcache_cache_line_size(void);
258 __private_extern__ mcache_t *mcache_create(const char *, size_t,
259     size_t, u_int32_t, int);
260 __private_extern__ void *mcache_alloc(mcache_t *, int);
261 __private_extern__ void mcache_free(mcache_t *, void *);
262 __private_extern__ mcache_t *mcache_create_ext(const char *, size_t,
263     mcache_allocfn_t, mcache_freefn_t, mcache_auditfn_t, mcache_logfn_t,
264     mcache_notifyfn_t, void *__unsafe_indexable, u_int32_t, int);
265 __private_extern__ void mcache_destroy(mcache_t *);
266 __private_extern__ unsigned int mcache_alloc_ext(mcache_t *, mcache_obj_t **,
267     unsigned int, int);
268 __private_extern__ void mcache_free_ext(mcache_t *, mcache_obj_t *);
269 __private_extern__ void mcache_reap(void);
270 __private_extern__ void mcache_reap_now(mcache_t *, boolean_t);
271 __private_extern__ boolean_t mcache_purge_cache(mcache_t *, boolean_t);
272 __private_extern__ void mcache_waiter_inc(mcache_t *);
273 __private_extern__ void mcache_waiter_dec(mcache_t *);
274 __private_extern__ boolean_t mcache_bkt_isempty(mcache_t *);
275 
276 struct timeval;
277 __private_extern__ void mcache_buffer_log(mcache_audit_t *, void *, mcache_t *,
278     struct timeval *);
279 __private_extern__ void mcache_set_pattern(u_int64_t, void *, size_t);
280 __private_extern__ void *mcache_verify_pattern(u_int64_t, void *, size_t);
281 __private_extern__ void mcache_audit_free_verify(mcache_audit_t *,
282     void *, size_t, size_t);
283 __private_extern__ void mcache_audit_free_verify_set(mcache_audit_t *,
284     void *, size_t, size_t);
285 __private_extern__ char *mcache_dump_mca(char buf[DUMP_MCA_BUF_SIZE], mcache_audit_t *);
286 
287 extern mcache_t *mcache_audit_cache;
288 
289 #ifdef  __cplusplus
290 }
291 #endif
292 
293 #endif /* KERNEL_PRIVATE */
294 
295 #endif /* _SYS_MCACHE_H */
296