]> git.proxmox.com Git - mirror_spl.git/blame - module/spl/spl-kmem-cache.c
Fix use-after-free in splat_taskq_test7
[mirror_spl.git] / module / spl / spl-kmem-cache.c
CommitLineData
b34b9563 1/*
e5b9b344
BB
2 * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC.
3 * Copyright (C) 2007 The Regents of the University of California.
4 * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
5 * Written by Brian Behlendorf <behlendorf1@llnl.gov>.
6 * UCRL-CODE-235197
7 *
8 * This file is part of the SPL, Solaris Porting Layer.
9 * For details, see <http://zfsonlinux.org/>.
10 *
11 * The SPL is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2 of the License, or (at your
14 * option) any later version.
15 *
16 * The SPL is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 * for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with the SPL. If not, see <http://www.gnu.org/licenses/>.
b34b9563 23 */
e5b9b344
BB
24
25#include <sys/kmem.h>
26#include <sys/kmem_cache.h>
27#include <sys/taskq.h>
28#include <sys/timer.h>
29#include <sys/vmem.h>
30#include <linux/slab.h>
31#include <linux/swap.h>
32#include <linux/mm_compat.h>
33#include <linux/wait_compat.h>
9f456111 34#include <linux/prefetch.h>
e5b9b344
BB
35
36/*
37 * Within the scope of spl-kmem.c file the kmem_cache_* definitions
38 * are removed to allow access to the real Linux slab allocator.
39 */
40#undef kmem_cache_destroy
41#undef kmem_cache_create
42#undef kmem_cache_alloc
43#undef kmem_cache_free
44
45
a988a35a
RY
46/*
47 * Linux 3.16 replaced smp_mb__{before,after}_{atomic,clear}_{dec,inc,bit}()
48 * with smp_mb__{before,after}_atomic() because they were redundant. This is
49 * only used inside our SLAB allocator, so we implement an internal wrapper
50 * here to give us smp_mb__{before,after}_atomic() on older kernels.
51 */
52#ifndef smp_mb__before_atomic
53#define smp_mb__before_atomic(x) smp_mb__before_clear_bit(x)
54#endif
55
56#ifndef smp_mb__after_atomic
57#define smp_mb__after_atomic(x) smp_mb__after_clear_bit(x)
58#endif
59
e5b9b344
BB
60/*
61 * Cache expiration was implemented because it was part of the default Solaris
62 * kmem_cache behavior. The idea is that per-cpu objects which haven't been
63 * accessed in several seconds should be returned to the cache. On the other
64 * hand Linux slabs never move objects back to the slabs unless there is
65 * memory pressure on the system. By default the Linux method is enabled
66 * because it has been shown to improve responsiveness on low memory systems.
67 * This policy may be changed by setting KMC_EXPIRE_AGE or KMC_EXPIRE_MEM.
68 */
69unsigned int spl_kmem_cache_expire = KMC_EXPIRE_MEM;
70EXPORT_SYMBOL(spl_kmem_cache_expire);
71module_param(spl_kmem_cache_expire, uint, 0644);
72MODULE_PARM_DESC(spl_kmem_cache_expire, "By age (0x1) or low memory (0x2)");
73
1a204968
BB
74/*
75 * Cache magazines are an optimization designed to minimize the cost of
76 * allocating memory. They do this by keeping a per-cpu cache of recently
77 * freed objects, which can then be reallocated without taking a lock. This
78 * can improve performance on highly contended caches. However, because
79 * objects in magazines will prevent otherwise empty slabs from being
80 * immediately released this may not be ideal for low memory machines.
81 *
82 * For this reason spl_kmem_cache_magazine_size can be used to set a maximum
83 * magazine size. When this value is set to 0 the magazine size will be
84 * automatically determined based on the object size. Otherwise magazines
85 * will be limited to 2-256 objects per magazine (i.e per cpu). Magazines
86 * may never be entirely disabled in this implementation.
87 */
88unsigned int spl_kmem_cache_magazine_size = 0;
89module_param(spl_kmem_cache_magazine_size, uint, 0444);
90MODULE_PARM_DESC(spl_kmem_cache_magazine_size,
31f24932 91 "Default magazine size (2-256), set automatically (0)");
1a204968 92
e5b9b344
BB
93/*
94 * The default behavior is to report the number of objects remaining in the
95 * cache. This allows the Linux VM to repeatedly reclaim objects from the
96 * cache when memory is low satisfy other memory allocations. Alternately,
97 * setting this value to KMC_RECLAIM_ONCE limits how aggressively the cache
98 * is reclaimed. This may increase the likelihood of out of memory events.
99 */
100unsigned int spl_kmem_cache_reclaim = 0 /* KMC_RECLAIM_ONCE */;
101module_param(spl_kmem_cache_reclaim, uint, 0644);
102MODULE_PARM_DESC(spl_kmem_cache_reclaim, "Single reclaim pass (0x1)");
103
104unsigned int spl_kmem_cache_obj_per_slab = SPL_KMEM_CACHE_OBJ_PER_SLAB;
105module_param(spl_kmem_cache_obj_per_slab, uint, 0644);
106MODULE_PARM_DESC(spl_kmem_cache_obj_per_slab, "Number of objects per slab");
107
108unsigned int spl_kmem_cache_obj_per_slab_min = SPL_KMEM_CACHE_OBJ_PER_SLAB_MIN;
109module_param(spl_kmem_cache_obj_per_slab_min, uint, 0644);
110MODULE_PARM_DESC(spl_kmem_cache_obj_per_slab_min,
b34b9563 111 "Minimal number of objects per slab");
e5b9b344 112
3018bffa 113unsigned int spl_kmem_cache_max_size = SPL_KMEM_CACHE_MAX_SIZE;
e5b9b344
BB
114module_param(spl_kmem_cache_max_size, uint, 0644);
115MODULE_PARM_DESC(spl_kmem_cache_max_size, "Maximum size of slab in MB");
116
117/*
118 * For small objects the Linux slab allocator should be used to make the most
119 * efficient use of the memory. However, large objects are not supported by
120 * the Linux slab and therefore the SPL implementation is preferred. A cutoff
121 * of 16K was determined to be optimal for architectures using 4K pages.
122 */
123#if PAGE_SIZE == 4096
124unsigned int spl_kmem_cache_slab_limit = 16384;
125#else
126unsigned int spl_kmem_cache_slab_limit = 0;
127#endif
128module_param(spl_kmem_cache_slab_limit, uint, 0644);
129MODULE_PARM_DESC(spl_kmem_cache_slab_limit,
b34b9563 130 "Objects less than N bytes use the Linux slab");
e5b9b344 131
3018bffa
BB
132/*
133 * This value defaults to a threshold designed to avoid allocations which
134 * have been deemed costly by the kernel.
135 */
136unsigned int spl_kmem_cache_kmem_limit =
137 ((1 << (PAGE_ALLOC_COSTLY_ORDER - 1)) * PAGE_SIZE) /
138 SPL_KMEM_CACHE_OBJ_PER_SLAB;
e5b9b344
BB
139module_param(spl_kmem_cache_kmem_limit, uint, 0644);
140MODULE_PARM_DESC(spl_kmem_cache_kmem_limit,
b34b9563 141 "Objects less than N bytes use the kmalloc");
e5b9b344 142
436ad60f
BB
143/*
144 * The number of threads available to allocate new slabs for caches. This
145 * should not need to be tuned but it is available for performance analysis.
146 */
147unsigned int spl_kmem_cache_kmem_threads = 4;
148module_param(spl_kmem_cache_kmem_threads, uint, 0444);
149MODULE_PARM_DESC(spl_kmem_cache_kmem_threads,
150 "Number of spl_kmem_cache threads");
151
e5b9b344
BB
152/*
153 * Slab allocation interfaces
154 *
155 * While the Linux slab implementation was inspired by the Solaris
156 * implementation I cannot use it to emulate the Solaris APIs. I
157 * require two features which are not provided by the Linux slab.
158 *
159 * 1) Constructors AND destructors. Recent versions of the Linux
160 * kernel have removed support for destructors. This is a deal
161 * breaker for the SPL which contains particularly expensive
162 * initializers for mutex's, condition variables, etc. We also
163 * require a minimal level of cleanup for these data types unlike
b34b9563 164 * many Linux data types which do need to be explicitly destroyed.
e5b9b344
BB
165 *
166 * 2) Virtual address space backed slab. Callers of the Solaris slab
167 * expect it to work well for both small are very large allocations.
168 * Because of memory fragmentation the Linux slab which is backed
169 * by kmalloc'ed memory performs very badly when confronted with
170 * large numbers of large allocations. Basing the slab on the
171 * virtual address space removes the need for contiguous pages
172 * and greatly improve performance for large allocations.
173 *
174 * For these reasons, the SPL has its own slab implementation with
175 * the needed features. It is not as highly optimized as either the
176 * Solaris or Linux slabs, but it should get me most of what is
177 * needed until it can be optimized or obsoleted by another approach.
178 *
179 * One serious concern I do have about this method is the relatively
180 * small virtual address space on 32bit arches. This will seriously
181 * constrain the size of the slab caches and their performance.
e5b9b344
BB
182 */
183
184struct list_head spl_kmem_cache_list; /* List of caches */
185struct rw_semaphore spl_kmem_cache_sem; /* Cache list lock */
b34b9563 186taskq_t *spl_kmem_cache_taskq; /* Task queue for ageing / reclaim */
e5b9b344
BB
187
188static void spl_cache_shrink(spl_kmem_cache_t *skc, void *obj);
189
190SPL_SHRINKER_CALLBACK_FWD_DECLARE(spl_kmem_cache_generic_shrinker);
191SPL_SHRINKER_DECLARE(spl_kmem_cache_shrinker,
192 spl_kmem_cache_generic_shrinker, KMC_DEFAULT_SEEKS);
193
194static void *
195kv_alloc(spl_kmem_cache_t *skc, int size, int flags)
196{
c3eabc75 197 gfp_t lflags = kmem_flags_convert(flags);
e5b9b344
BB
198 void *ptr;
199
3018bffa
BB
200 if (skc->skc_flags & KMC_KMEM) {
201 ASSERT(ISP2(size));
c3eabc75 202 ptr = (void *)__get_free_pages(lflags, get_order(size));
3018bffa 203 } else {
b4ad50ac 204 ptr = __vmalloc(size, lflags | __GFP_HIGHMEM, PAGE_KERNEL);
3018bffa 205 }
e5b9b344
BB
206
207 /* Resulting allocated memory will be page aligned */
208 ASSERT(IS_P2ALIGNED(ptr, PAGE_SIZE));
209
b34b9563 210 return (ptr);
e5b9b344
BB
211}
212
213static void
214kv_free(spl_kmem_cache_t *skc, void *ptr, int size)
215{
216 ASSERT(IS_P2ALIGNED(ptr, PAGE_SIZE));
e5b9b344
BB
217
218 /*
219 * The Linux direct reclaim path uses this out of band value to
220 * determine if forward progress is being made. Normally this is
221 * incremented by kmem_freepages() which is part of the various
222 * Linux slab implementations. However, since we are using none
223 * of that infrastructure we are responsible for incrementing it.
224 */
225 if (current->reclaim_state)
226 current->reclaim_state->reclaimed_slab += size >> PAGE_SHIFT;
227
3018bffa
BB
228 if (skc->skc_flags & KMC_KMEM) {
229 ASSERT(ISP2(size));
e5b9b344 230 free_pages((unsigned long)ptr, get_order(size));
3018bffa 231 } else {
e5b9b344 232 vfree(ptr);
3018bffa 233 }
e5b9b344
BB
234}
235
236/*
237 * Required space for each aligned sks.
238 */
239static inline uint32_t
240spl_sks_size(spl_kmem_cache_t *skc)
241{
b34b9563
BB
242 return (P2ROUNDUP_TYPED(sizeof (spl_kmem_slab_t),
243 skc->skc_obj_align, uint32_t));
e5b9b344
BB
244}
245
246/*
247 * Required space for each aligned object.
248 */
249static inline uint32_t
250spl_obj_size(spl_kmem_cache_t *skc)
251{
252 uint32_t align = skc->skc_obj_align;
253
b34b9563
BB
254 return (P2ROUNDUP_TYPED(skc->skc_obj_size, align, uint32_t) +
255 P2ROUNDUP_TYPED(sizeof (spl_kmem_obj_t), align, uint32_t));
e5b9b344
BB
256}
257
258/*
259 * Lookup the spl_kmem_object_t for an object given that object.
260 */
261static inline spl_kmem_obj_t *
262spl_sko_from_obj(spl_kmem_cache_t *skc, void *obj)
263{
b34b9563
BB
264 return (obj + P2ROUNDUP_TYPED(skc->skc_obj_size,
265 skc->skc_obj_align, uint32_t));
e5b9b344
BB
266}
267
268/*
269 * Required space for each offslab object taking in to account alignment
270 * restrictions and the power-of-two requirement of kv_alloc().
271 */
272static inline uint32_t
273spl_offslab_size(spl_kmem_cache_t *skc)
274{
b34b9563 275 return (1UL << (fls64(spl_obj_size(skc)) + 1));
e5b9b344
BB
276}
277
278/*
279 * It's important that we pack the spl_kmem_obj_t structure and the
280 * actual objects in to one large address space to minimize the number
281 * of calls to the allocator. It is far better to do a few large
282 * allocations and then subdivide it ourselves. Now which allocator
283 * we use requires balancing a few trade offs.
284 *
285 * For small objects we use kmem_alloc() because as long as you are
286 * only requesting a small number of pages (ideally just one) its cheap.
287 * However, when you start requesting multiple pages with kmem_alloc()
288 * it gets increasingly expensive since it requires contiguous pages.
289 * For this reason we shift to vmem_alloc() for slabs of large objects
290 * which removes the need for contiguous pages. We do not use
291 * vmem_alloc() in all cases because there is significant locking
292 * overhead in __get_vm_area_node(). This function takes a single
293 * global lock when acquiring an available virtual address range which
294 * serializes all vmem_alloc()'s for all slab caches. Using slightly
295 * different allocation functions for small and large objects should
296 * give us the best of both worlds.
297 *
298 * KMC_ONSLAB KMC_OFFSLAB
299 *
300 * +------------------------+ +-----------------+
301 * | spl_kmem_slab_t --+-+ | | spl_kmem_slab_t |---+-+
302 * | skc_obj_size <-+ | | +-----------------+ | |
303 * | spl_kmem_obj_t | | | |
304 * | skc_obj_size <---+ | +-----------------+ | |
305 * | spl_kmem_obj_t | | | skc_obj_size | <-+ |
306 * | ... v | | spl_kmem_obj_t | |
307 * +------------------------+ +-----------------+ v
308 */
309static spl_kmem_slab_t *
310spl_slab_alloc(spl_kmem_cache_t *skc, int flags)
311{
312 spl_kmem_slab_t *sks;
313 spl_kmem_obj_t *sko, *n;
314 void *base, *obj;
315 uint32_t obj_size, offslab_size = 0;
316 int i, rc = 0;
317
318 base = kv_alloc(skc, skc->skc_slab_size, flags);
319 if (base == NULL)
320 return (NULL);
321
322 sks = (spl_kmem_slab_t *)base;
323 sks->sks_magic = SKS_MAGIC;
324 sks->sks_objs = skc->skc_slab_objs;
325 sks->sks_age = jiffies;
326 sks->sks_cache = skc;
327 INIT_LIST_HEAD(&sks->sks_list);
328 INIT_LIST_HEAD(&sks->sks_free_list);
329 sks->sks_ref = 0;
330 obj_size = spl_obj_size(skc);
331
332 if (skc->skc_flags & KMC_OFFSLAB)
333 offslab_size = spl_offslab_size(skc);
334
335 for (i = 0; i < sks->sks_objs; i++) {
336 if (skc->skc_flags & KMC_OFFSLAB) {
337 obj = kv_alloc(skc, offslab_size, flags);
338 if (!obj) {
339 rc = -ENOMEM;
340 goto out;
341 }
342 } else {
343 obj = base + spl_sks_size(skc) + (i * obj_size);
344 }
345
346 ASSERT(IS_P2ALIGNED(obj, skc->skc_obj_align));
347 sko = spl_sko_from_obj(skc, obj);
348 sko->sko_addr = obj;
349 sko->sko_magic = SKO_MAGIC;
350 sko->sko_slab = sks;
351 INIT_LIST_HEAD(&sko->sko_list);
352 list_add_tail(&sko->sko_list, &sks->sks_free_list);
353 }
354
355out:
356 if (rc) {
357 if (skc->skc_flags & KMC_OFFSLAB)
b34b9563
BB
358 list_for_each_entry_safe(sko,
359 n, &sks->sks_free_list, sko_list)
e5b9b344
BB
360 kv_free(skc, sko->sko_addr, offslab_size);
361
362 kv_free(skc, base, skc->skc_slab_size);
363 sks = NULL;
364 }
365
366 return (sks);
367}
368
369/*
370 * Remove a slab from complete or partial list, it must be called with
371 * the 'skc->skc_lock' held but the actual free must be performed
372 * outside the lock to prevent deadlocking on vmem addresses.
373 */
374static void
375spl_slab_free(spl_kmem_slab_t *sks,
b34b9563 376 struct list_head *sks_list, struct list_head *sko_list)
e5b9b344
BB
377{
378 spl_kmem_cache_t *skc;
379
380 ASSERT(sks->sks_magic == SKS_MAGIC);
381 ASSERT(sks->sks_ref == 0);
382
383 skc = sks->sks_cache;
384 ASSERT(skc->skc_magic == SKC_MAGIC);
385 ASSERT(spin_is_locked(&skc->skc_lock));
386
387 /*
388 * Update slab/objects counters in the cache, then remove the
389 * slab from the skc->skc_partial_list. Finally add the slab
390 * and all its objects in to the private work lists where the
391 * destructors will be called and the memory freed to the system.
392 */
393 skc->skc_obj_total -= sks->sks_objs;
394 skc->skc_slab_total--;
395 list_del(&sks->sks_list);
396 list_add(&sks->sks_list, sks_list);
397 list_splice_init(&sks->sks_free_list, sko_list);
398}
399
400/*
1a204968 401 * Reclaim empty slabs at the end of the partial list.
e5b9b344
BB
402 */
403static void
1a204968 404spl_slab_reclaim(spl_kmem_cache_t *skc)
e5b9b344
BB
405{
406 spl_kmem_slab_t *sks, *m;
407 spl_kmem_obj_t *sko, *n;
408 LIST_HEAD(sks_list);
409 LIST_HEAD(sko_list);
410 uint32_t size = 0;
e5b9b344
BB
411
412 /*
1a204968
BB
413 * Empty slabs and objects must be moved to a private list so they
414 * can be safely freed outside the spin lock. All empty slabs are
415 * at the end of skc->skc_partial_list, therefore once a non-empty
416 * slab is found we can stop scanning.
e5b9b344
BB
417 */
418 spin_lock(&skc->skc_lock);
b34b9563
BB
419 list_for_each_entry_safe_reverse(sks, m,
420 &skc->skc_partial_list, sks_list) {
1a204968
BB
421
422 if (sks->sks_ref > 0)
e5b9b344
BB
423 break;
424
1a204968 425 spl_slab_free(sks, &sks_list, &sko_list);
e5b9b344
BB
426 }
427 spin_unlock(&skc->skc_lock);
428
429 /*
430 * The following two loops ensure all the object destructors are
431 * run, any offslab objects are freed, and the slabs themselves
432 * are freed. This is all done outside the skc->skc_lock since
433 * this allows the destructor to sleep, and allows us to perform
434 * a conditional reschedule when a freeing a large number of
435 * objects and slabs back to the system.
436 */
437 if (skc->skc_flags & KMC_OFFSLAB)
438 size = spl_offslab_size(skc);
439
440 list_for_each_entry_safe(sko, n, &sko_list, sko_list) {
441 ASSERT(sko->sko_magic == SKO_MAGIC);
442
443 if (skc->skc_flags & KMC_OFFSLAB)
444 kv_free(skc, sko->sko_addr, size);
445 }
446
447 list_for_each_entry_safe(sks, m, &sks_list, sks_list) {
448 ASSERT(sks->sks_magic == SKS_MAGIC);
449 kv_free(skc, sks, skc->skc_slab_size);
450 }
451}
452
453static spl_kmem_emergency_t *
454spl_emergency_search(struct rb_root *root, void *obj)
455{
456 struct rb_node *node = root->rb_node;
457 spl_kmem_emergency_t *ske;
458 unsigned long address = (unsigned long)obj;
459
460 while (node) {
461 ske = container_of(node, spl_kmem_emergency_t, ske_node);
462
ee335174 463 if (address < ske->ske_obj)
e5b9b344 464 node = node->rb_left;
ee335174 465 else if (address > ske->ske_obj)
e5b9b344
BB
466 node = node->rb_right;
467 else
b34b9563 468 return (ske);
e5b9b344
BB
469 }
470
b34b9563 471 return (NULL);
e5b9b344
BB
472}
473
474static int
475spl_emergency_insert(struct rb_root *root, spl_kmem_emergency_t *ske)
476{
477 struct rb_node **new = &(root->rb_node), *parent = NULL;
478 spl_kmem_emergency_t *ske_tmp;
ee335174 479 unsigned long address = ske->ske_obj;
e5b9b344
BB
480
481 while (*new) {
482 ske_tmp = container_of(*new, spl_kmem_emergency_t, ske_node);
483
484 parent = *new;
ee335174 485 if (address < ske_tmp->ske_obj)
e5b9b344 486 new = &((*new)->rb_left);
ee335174 487 else if (address > ske_tmp->ske_obj)
e5b9b344
BB
488 new = &((*new)->rb_right);
489 else
b34b9563 490 return (0);
e5b9b344
BB
491 }
492
493 rb_link_node(&ske->ske_node, parent, new);
494 rb_insert_color(&ske->ske_node, root);
495
b34b9563 496 return (1);
e5b9b344
BB
497}
498
499/*
500 * Allocate a single emergency object and track it in a red black tree.
501 */
502static int
503spl_emergency_alloc(spl_kmem_cache_t *skc, int flags, void **obj)
504{
c3eabc75 505 gfp_t lflags = kmem_flags_convert(flags);
e5b9b344 506 spl_kmem_emergency_t *ske;
ee335174 507 int order = get_order(skc->skc_obj_size);
e5b9b344
BB
508 int empty;
509
510 /* Last chance use a partial slab if one now exists */
511 spin_lock(&skc->skc_lock);
512 empty = list_empty(&skc->skc_partial_list);
513 spin_unlock(&skc->skc_lock);
514 if (!empty)
515 return (-EEXIST);
516
c3eabc75 517 ske = kmalloc(sizeof (*ske), lflags);
e5b9b344
BB
518 if (ske == NULL)
519 return (-ENOMEM);
520
ee335174
BB
521 ske->ske_obj = __get_free_pages(lflags, order);
522 if (ske->ske_obj == 0) {
e5b9b344
BB
523 kfree(ske);
524 return (-ENOMEM);
525 }
526
527 spin_lock(&skc->skc_lock);
528 empty = spl_emergency_insert(&skc->skc_emergency_tree, ske);
529 if (likely(empty)) {
530 skc->skc_obj_total++;
531 skc->skc_obj_emergency++;
532 if (skc->skc_obj_emergency > skc->skc_obj_emergency_max)
533 skc->skc_obj_emergency_max = skc->skc_obj_emergency;
534 }
535 spin_unlock(&skc->skc_lock);
536
537 if (unlikely(!empty)) {
ee335174 538 free_pages(ske->ske_obj, order);
e5b9b344
BB
539 kfree(ske);
540 return (-EINVAL);
541 }
542
ee335174 543 *obj = (void *)ske->ske_obj;
e5b9b344
BB
544
545 return (0);
546}
547
548/*
549 * Locate the passed object in the red black tree and free it.
550 */
551static int
552spl_emergency_free(spl_kmem_cache_t *skc, void *obj)
553{
554 spl_kmem_emergency_t *ske;
ee335174 555 int order = get_order(skc->skc_obj_size);
e5b9b344
BB
556
557 spin_lock(&skc->skc_lock);
558 ske = spl_emergency_search(&skc->skc_emergency_tree, obj);
436ad60f 559 if (ske) {
e5b9b344
BB
560 rb_erase(&ske->ske_node, &skc->skc_emergency_tree);
561 skc->skc_obj_emergency--;
562 skc->skc_obj_total--;
563 }
564 spin_unlock(&skc->skc_lock);
565
436ad60f 566 if (ske == NULL)
e5b9b344
BB
567 return (-ENOENT);
568
ee335174 569 free_pages(ske->ske_obj, order);
e5b9b344
BB
570 kfree(ske);
571
572 return (0);
573}
574
575/*
576 * Release objects from the per-cpu magazine back to their slab. The flush
577 * argument contains the max number of entries to remove from the magazine.
578 */
579static void
580__spl_cache_flush(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flush)
581{
582 int i, count = MIN(flush, skm->skm_avail);
583
584 ASSERT(skc->skc_magic == SKC_MAGIC);
585 ASSERT(skm->skm_magic == SKM_MAGIC);
586 ASSERT(spin_is_locked(&skc->skc_lock));
587
588 for (i = 0; i < count; i++)
589 spl_cache_shrink(skc, skm->skm_objs[i]);
590
591 skm->skm_avail -= count;
592 memmove(skm->skm_objs, &(skm->skm_objs[count]),
b34b9563 593 sizeof (void *) * skm->skm_avail);
e5b9b344
BB
594}
595
596static void
597spl_cache_flush(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flush)
598{
599 spin_lock(&skc->skc_lock);
600 __spl_cache_flush(skc, skm, flush);
601 spin_unlock(&skc->skc_lock);
602}
603
604static void
605spl_magazine_age(void *data)
606{
607 spl_kmem_cache_t *skc = (spl_kmem_cache_t *)data;
608 spl_kmem_magazine_t *skm = skc->skc_mag[smp_processor_id()];
609
610 ASSERT(skm->skm_magic == SKM_MAGIC);
611 ASSERT(skm->skm_cpu == smp_processor_id());
612 ASSERT(irqs_disabled());
613
614 /* There are no available objects or they are too young to age out */
615 if ((skm->skm_avail == 0) ||
616 time_before(jiffies, skm->skm_age + skc->skc_delay * HZ))
617 return;
618
619 /*
620 * Because we're executing in interrupt context we may have
621 * interrupted the holder of this lock. To avoid a potential
622 * deadlock return if the lock is contended.
623 */
624 if (!spin_trylock(&skc->skc_lock))
625 return;
626
627 __spl_cache_flush(skc, skm, skm->skm_refill);
628 spin_unlock(&skc->skc_lock);
629}
630
631/*
632 * Called regularly to keep a downward pressure on the cache.
633 *
634 * Objects older than skc->skc_delay seconds in the per-cpu magazines will
635 * be returned to the caches. This is done to prevent idle magazines from
636 * holding memory which could be better used elsewhere. The delay is
637 * present to prevent thrashing the magazine.
638 *
639 * The newly released objects may result in empty partial slabs. Those
640 * slabs should be released to the system. Otherwise moving the objects
641 * out of the magazines is just wasted work.
642 */
643static void
644spl_cache_age(void *data)
645{
646 spl_kmem_cache_t *skc = (spl_kmem_cache_t *)data;
647 taskqid_t id = 0;
648
649 ASSERT(skc->skc_magic == SKC_MAGIC);
650
651 /* Dynamically disabled at run time */
652 if (!(spl_kmem_cache_expire & KMC_EXPIRE_AGE))
653 return;
654
655 atomic_inc(&skc->skc_ref);
656
657 if (!(skc->skc_flags & KMC_NOMAGAZINE))
658 on_each_cpu(spl_magazine_age, skc, 1);
659
1a204968 660 spl_slab_reclaim(skc);
e5b9b344
BB
661
662 while (!test_bit(KMC_BIT_DESTROY, &skc->skc_flags) && !id) {
663 id = taskq_dispatch_delay(
664 spl_kmem_cache_taskq, spl_cache_age, skc, TQ_SLEEP,
665 ddi_get_lbolt() + skc->skc_delay / 3 * HZ);
666
667 /* Destroy issued after dispatch immediately cancel it */
668 if (test_bit(KMC_BIT_DESTROY, &skc->skc_flags) && id)
669 taskq_cancel_id(spl_kmem_cache_taskq, id);
670 }
671
672 spin_lock(&skc->skc_lock);
673 skc->skc_taskqid = id;
674 spin_unlock(&skc->skc_lock);
675
676 atomic_dec(&skc->skc_ref);
677}
678
679/*
680 * Size a slab based on the size of each aligned object plus spl_kmem_obj_t.
681 * When on-slab we want to target spl_kmem_cache_obj_per_slab. However,
682 * for very small objects we may end up with more than this so as not
683 * to waste space in the minimal allocation of a single page. Also for
684 * very large objects we may use as few as spl_kmem_cache_obj_per_slab_min,
685 * lower than this and we will fail.
686 */
687static int
688spl_slab_size(spl_kmem_cache_t *skc, uint32_t *objs, uint32_t *size)
689{
3018bffa 690 uint32_t sks_size, obj_size, max_size, tgt_size, tgt_objs;
e5b9b344
BB
691
692 if (skc->skc_flags & KMC_OFFSLAB) {
3018bffa
BB
693 tgt_objs = spl_kmem_cache_obj_per_slab;
694 tgt_size = P2ROUNDUP(sizeof (spl_kmem_slab_t), PAGE_SIZE);
695
696 if ((skc->skc_flags & KMC_KMEM) &&
697 (spl_obj_size(skc) > (SPL_MAX_ORDER_NR_PAGES * PAGE_SIZE)))
698 return (-ENOSPC);
e5b9b344
BB
699 } else {
700 sks_size = spl_sks_size(skc);
701 obj_size = spl_obj_size(skc);
3018bffa
BB
702 max_size = (spl_kmem_cache_max_size * 1024 * 1024);
703 tgt_size = (spl_kmem_cache_obj_per_slab * obj_size + sks_size);
e5b9b344
BB
704
705 /*
3018bffa
BB
706 * KMC_KMEM slabs are allocated by __get_free_pages() which
707 * rounds up to the nearest order. Knowing this the size
708 * should be rounded up to the next power of two with a hard
709 * maximum defined by the maximum allowed allocation order.
e5b9b344 710 */
3018bffa
BB
711 if (skc->skc_flags & KMC_KMEM) {
712 max_size = SPL_MAX_ORDER_NR_PAGES * PAGE_SIZE;
713 tgt_size = MIN(max_size,
714 PAGE_SIZE * (1 << MAX(get_order(tgt_size) - 1, 1)));
715 }
716
717 if (tgt_size <= max_size) {
718 tgt_objs = (tgt_size - sks_size) / obj_size;
719 } else {
720 tgt_objs = (max_size - sks_size) / obj_size;
721 tgt_size = (tgt_objs * obj_size) + sks_size;
722 }
e5b9b344
BB
723 }
724
3018bffa
BB
725 if (tgt_objs == 0)
726 return (-ENOSPC);
727
728 *objs = tgt_objs;
729 *size = tgt_size;
730
731 return (0);
e5b9b344
BB
732}
733
734/*
735 * Make a guess at reasonable per-cpu magazine size based on the size of
736 * each object and the cost of caching N of them in each magazine. Long
737 * term this should really adapt based on an observed usage heuristic.
738 */
739static int
740spl_magazine_size(spl_kmem_cache_t *skc)
741{
742 uint32_t obj_size = spl_obj_size(skc);
743 int size;
744
1a204968
BB
745 if (spl_kmem_cache_magazine_size > 0)
746 return (MAX(MIN(spl_kmem_cache_magazine_size, 256), 2));
747
e5b9b344
BB
748 /* Per-magazine sizes below assume a 4Kib page size */
749 if (obj_size > (PAGE_SIZE * 256))
750 size = 4; /* Minimum 4Mib per-magazine */
751 else if (obj_size > (PAGE_SIZE * 32))
752 size = 16; /* Minimum 2Mib per-magazine */
753 else if (obj_size > (PAGE_SIZE))
754 size = 64; /* Minimum 256Kib per-magazine */
755 else if (obj_size > (PAGE_SIZE / 4))
756 size = 128; /* Minimum 128Kib per-magazine */
757 else
758 size = 256;
759
760 return (size);
761}
762
763/*
764 * Allocate a per-cpu magazine to associate with a specific core.
765 */
766static spl_kmem_magazine_t *
767spl_magazine_alloc(spl_kmem_cache_t *skc, int cpu)
768{
769 spl_kmem_magazine_t *skm;
b34b9563
BB
770 int size = sizeof (spl_kmem_magazine_t) +
771 sizeof (void *) * skc->skc_mag_size;
e5b9b344 772
c3eabc75 773 skm = kmalloc_node(size, GFP_KERNEL, cpu_to_node(cpu));
e5b9b344
BB
774 if (skm) {
775 skm->skm_magic = SKM_MAGIC;
776 skm->skm_avail = 0;
777 skm->skm_size = skc->skc_mag_size;
778 skm->skm_refill = skc->skc_mag_refill;
779 skm->skm_cache = skc;
780 skm->skm_age = jiffies;
781 skm->skm_cpu = cpu;
782 }
783
784 return (skm);
785}
786
787/*
788 * Free a per-cpu magazine associated with a specific core.
789 */
790static void
791spl_magazine_free(spl_kmem_magazine_t *skm)
792{
e5b9b344
BB
793 ASSERT(skm->skm_magic == SKM_MAGIC);
794 ASSERT(skm->skm_avail == 0);
c3eabc75 795 kfree(skm);
e5b9b344
BB
796}
797
798/*
799 * Create all pre-cpu magazines of reasonable sizes.
800 */
801static int
802spl_magazine_create(spl_kmem_cache_t *skc)
803{
804 int i;
805
806 if (skc->skc_flags & KMC_NOMAGAZINE)
807 return (0);
808
9b13f65d
BB
809 skc->skc_mag = kzalloc(sizeof (spl_kmem_magazine_t *) *
810 num_possible_cpus(), kmem_flags_convert(KM_SLEEP));
e5b9b344
BB
811 skc->skc_mag_size = spl_magazine_size(skc);
812 skc->skc_mag_refill = (skc->skc_mag_size + 1) / 2;
813
9b13f65d 814 for_each_possible_cpu(i) {
e5b9b344
BB
815 skc->skc_mag[i] = spl_magazine_alloc(skc, i);
816 if (!skc->skc_mag[i]) {
817 for (i--; i >= 0; i--)
818 spl_magazine_free(skc->skc_mag[i]);
819
9b13f65d 820 kfree(skc->skc_mag);
e5b9b344
BB
821 return (-ENOMEM);
822 }
823 }
824
825 return (0);
826}
827
828/*
829 * Destroy all pre-cpu magazines.
830 */
831static void
832spl_magazine_destroy(spl_kmem_cache_t *skc)
833{
834 spl_kmem_magazine_t *skm;
835 int i;
836
837 if (skc->skc_flags & KMC_NOMAGAZINE)
838 return;
839
9b13f65d 840 for_each_possible_cpu(i) {
e5b9b344
BB
841 skm = skc->skc_mag[i];
842 spl_cache_flush(skc, skm, skm->skm_avail);
843 spl_magazine_free(skm);
b34b9563 844 }
9b13f65d
BB
845
846 kfree(skc->skc_mag);
e5b9b344
BB
847}
848
849/*
850 * Create a object cache based on the following arguments:
851 * name cache name
852 * size cache object size
853 * align cache object alignment
854 * ctor cache object constructor
855 * dtor cache object destructor
856 * reclaim cache object reclaim
857 * priv cache private data for ctor/dtor/reclaim
858 * vmp unused must be NULL
859 * flags
860 * KMC_NOTOUCH Disable cache object aging (unsupported)
861 * KMC_NODEBUG Disable debugging (unsupported)
862 * KMC_NOHASH Disable hashing (unsupported)
863 * KMC_QCACHE Disable qcache (unsupported)
864 * KMC_NOMAGAZINE Enabled for kmem/vmem, Disabled for Linux slab
865 * KMC_KMEM Force kmem backed cache
866 * KMC_VMEM Force vmem backed cache
867 * KMC_SLAB Force Linux slab backed cache
868 * KMC_OFFSLAB Locate objects off the slab
869 */
870spl_kmem_cache_t *
871spl_kmem_cache_create(char *name, size_t size, size_t align,
b34b9563
BB
872 spl_kmem_ctor_t ctor, spl_kmem_dtor_t dtor, spl_kmem_reclaim_t reclaim,
873 void *priv, void *vmp, int flags)
e5b9b344 874{
c3eabc75 875 gfp_t lflags = kmem_flags_convert(KM_SLEEP);
b34b9563 876 spl_kmem_cache_t *skc;
e5b9b344
BB
877 int rc;
878
879 /*
880 * Unsupported flags
881 */
882 ASSERT0(flags & KMC_NOMAGAZINE);
883 ASSERT0(flags & KMC_NOHASH);
884 ASSERT0(flags & KMC_QCACHE);
885 ASSERT(vmp == NULL);
886
887 might_sleep();
888
c3eabc75 889 skc = kzalloc(sizeof (*skc), lflags);
e5b9b344
BB
890 if (skc == NULL)
891 return (NULL);
892
893 skc->skc_magic = SKC_MAGIC;
894 skc->skc_name_size = strlen(name) + 1;
c3eabc75 895 skc->skc_name = (char *)kmalloc(skc->skc_name_size, lflags);
e5b9b344 896 if (skc->skc_name == NULL) {
c3eabc75 897 kfree(skc);
e5b9b344
BB
898 return (NULL);
899 }
900 strncpy(skc->skc_name, name, skc->skc_name_size);
901
902 skc->skc_ctor = ctor;
903 skc->skc_dtor = dtor;
904 skc->skc_reclaim = reclaim;
905 skc->skc_private = priv;
906 skc->skc_vmp = vmp;
907 skc->skc_linux_cache = NULL;
908 skc->skc_flags = flags;
909 skc->skc_obj_size = size;
910 skc->skc_obj_align = SPL_KMEM_CACHE_ALIGN;
911 skc->skc_delay = SPL_KMEM_CACHE_DELAY;
912 skc->skc_reap = SPL_KMEM_CACHE_REAP;
913 atomic_set(&skc->skc_ref, 0);
914
915 INIT_LIST_HEAD(&skc->skc_list);
916 INIT_LIST_HEAD(&skc->skc_complete_list);
917 INIT_LIST_HEAD(&skc->skc_partial_list);
918 skc->skc_emergency_tree = RB_ROOT;
919 spin_lock_init(&skc->skc_lock);
920 init_waitqueue_head(&skc->skc_waitq);
921 skc->skc_slab_fail = 0;
922 skc->skc_slab_create = 0;
923 skc->skc_slab_destroy = 0;
924 skc->skc_slab_total = 0;
925 skc->skc_slab_alloc = 0;
926 skc->skc_slab_max = 0;
927 skc->skc_obj_total = 0;
928 skc->skc_obj_alloc = 0;
929 skc->skc_obj_max = 0;
930 skc->skc_obj_deadlock = 0;
931 skc->skc_obj_emergency = 0;
932 skc->skc_obj_emergency_max = 0;
933
934 /*
935 * Verify the requested alignment restriction is sane.
936 */
937 if (align) {
938 VERIFY(ISP2(align));
939 VERIFY3U(align, >=, SPL_KMEM_CACHE_ALIGN);
940 VERIFY3U(align, <=, PAGE_SIZE);
941 skc->skc_obj_align = align;
942 }
943
944 /*
945 * When no specific type of slab is requested (kmem, vmem, or
946 * linuxslab) then select a cache type based on the object size
947 * and default tunables.
948 */
949 if (!(skc->skc_flags & (KMC_KMEM | KMC_VMEM | KMC_SLAB))) {
950
951 /*
952 * Objects smaller than spl_kmem_cache_slab_limit can
953 * use the Linux slab for better space-efficiency. By
954 * default this functionality is disabled until its
b34b9563 955 * performance characteristics are fully understood.
e5b9b344
BB
956 */
957 if (spl_kmem_cache_slab_limit &&
958 size <= (size_t)spl_kmem_cache_slab_limit)
959 skc->skc_flags |= KMC_SLAB;
960
961 /*
962 * Small objects, less than spl_kmem_cache_kmem_limit per
963 * object should use kmem because their slabs are small.
964 */
965 else if (spl_obj_size(skc) <= spl_kmem_cache_kmem_limit)
966 skc->skc_flags |= KMC_KMEM;
967
968 /*
969 * All other objects are considered large and are placed
970 * on vmem backed slabs.
971 */
972 else
973 skc->skc_flags |= KMC_VMEM;
974 }
975
976 /*
977 * Given the type of slab allocate the required resources.
978 */
979 if (skc->skc_flags & (KMC_KMEM | KMC_VMEM)) {
980 rc = spl_slab_size(skc,
981 &skc->skc_slab_objs, &skc->skc_slab_size);
982 if (rc)
983 goto out;
984
985 rc = spl_magazine_create(skc);
986 if (rc)
987 goto out;
988 } else {
2ebe3960
BB
989 unsigned long slabflags = 0;
990
3018bffa
BB
991 if (size > (SPL_MAX_KMEM_ORDER_NR_PAGES * PAGE_SIZE)) {
992 rc = EINVAL;
993 goto out;
994 }
995
2ebe3960
BB
996#if defined(SLAB_USERCOPY)
997 /*
998 * Required for PAX-enabled kernels if the slab is to be
999 * used for coping between user and kernel space.
1000 */
1001 slabflags |= SLAB_USERCOPY;
1002#endif
1003
e5b9b344 1004 skc->skc_linux_cache = kmem_cache_create(
2ebe3960 1005 skc->skc_name, size, align, slabflags, NULL);
e5b9b344
BB
1006 if (skc->skc_linux_cache == NULL) {
1007 rc = ENOMEM;
1008 goto out;
1009 }
1010
c3eabc75
BB
1011#if defined(HAVE_KMEM_CACHE_ALLOCFLAGS)
1012 skc->skc_linux_cache->allocflags |= __GFP_COMP;
1013#elif defined(HAVE_KMEM_CACHE_GFPFLAGS)
1014 skc->skc_linux_cache->gfpflags |= __GFP_COMP;
1015#endif
e5b9b344
BB
1016 skc->skc_flags |= KMC_NOMAGAZINE;
1017 }
1018
1019 if (spl_kmem_cache_expire & KMC_EXPIRE_AGE)
1020 skc->skc_taskqid = taskq_dispatch_delay(spl_kmem_cache_taskq,
1021 spl_cache_age, skc, TQ_SLEEP,
1022 ddi_get_lbolt() + skc->skc_delay / 3 * HZ);
1023
1024 down_write(&spl_kmem_cache_sem);
1025 list_add_tail(&skc->skc_list, &spl_kmem_cache_list);
1026 up_write(&spl_kmem_cache_sem);
1027
1028 return (skc);
1029out:
c3eabc75
BB
1030 kfree(skc->skc_name);
1031 kfree(skc);
e5b9b344
BB
1032 return (NULL);
1033}
1034EXPORT_SYMBOL(spl_kmem_cache_create);
1035
1036/*
b34b9563 1037 * Register a move callback for cache defragmentation.
e5b9b344
BB
1038 * XXX: Unimplemented but harmless to stub out for now.
1039 */
1040void
1041spl_kmem_cache_set_move(spl_kmem_cache_t *skc,
1042 kmem_cbrc_t (move)(void *, void *, size_t, void *))
1043{
b34b9563 1044 ASSERT(move != NULL);
e5b9b344
BB
1045}
1046EXPORT_SYMBOL(spl_kmem_cache_set_move);
1047
1048/*
1049 * Destroy a cache and all objects associated with the cache.
1050 */
1051void
1052spl_kmem_cache_destroy(spl_kmem_cache_t *skc)
1053{
1054 DECLARE_WAIT_QUEUE_HEAD(wq);
1055 taskqid_t id;
1056
1057 ASSERT(skc->skc_magic == SKC_MAGIC);
1058 ASSERT(skc->skc_flags & (KMC_KMEM | KMC_VMEM | KMC_SLAB));
1059
1060 down_write(&spl_kmem_cache_sem);
1061 list_del_init(&skc->skc_list);
1062 up_write(&spl_kmem_cache_sem);
1063
1064 /* Cancel any and wait for any pending delayed tasks */
1065 VERIFY(!test_and_set_bit(KMC_BIT_DESTROY, &skc->skc_flags));
1066
1067 spin_lock(&skc->skc_lock);
1068 id = skc->skc_taskqid;
1069 spin_unlock(&skc->skc_lock);
1070
1071 taskq_cancel_id(spl_kmem_cache_taskq, id);
1072
b34b9563
BB
1073 /*
1074 * Wait until all current callers complete, this is mainly
e5b9b344 1075 * to catch the case where a low memory situation triggers a
b34b9563
BB
1076 * cache reaping action which races with this destroy.
1077 */
e5b9b344
BB
1078 wait_event(wq, atomic_read(&skc->skc_ref) == 0);
1079
1080 if (skc->skc_flags & (KMC_KMEM | KMC_VMEM)) {
1081 spl_magazine_destroy(skc);
1a204968 1082 spl_slab_reclaim(skc);
e5b9b344
BB
1083 } else {
1084 ASSERT(skc->skc_flags & KMC_SLAB);
1085 kmem_cache_destroy(skc->skc_linux_cache);
1086 }
1087
1088 spin_lock(&skc->skc_lock);
1089
b34b9563
BB
1090 /*
1091 * Validate there are no objects in use and free all the
1092 * spl_kmem_slab_t, spl_kmem_obj_t, and object buffers.
1093 */
e5b9b344
BB
1094 ASSERT3U(skc->skc_slab_alloc, ==, 0);
1095 ASSERT3U(skc->skc_obj_alloc, ==, 0);
1096 ASSERT3U(skc->skc_slab_total, ==, 0);
1097 ASSERT3U(skc->skc_obj_total, ==, 0);
1098 ASSERT3U(skc->skc_obj_emergency, ==, 0);
1099 ASSERT(list_empty(&skc->skc_complete_list));
1100
e5b9b344
BB
1101 spin_unlock(&skc->skc_lock);
1102
c3eabc75
BB
1103 kfree(skc->skc_name);
1104 kfree(skc);
e5b9b344
BB
1105}
1106EXPORT_SYMBOL(spl_kmem_cache_destroy);
1107
1108/*
1109 * Allocate an object from a slab attached to the cache. This is used to
1110 * repopulate the per-cpu magazine caches in batches when they run low.
1111 */
1112static void *
1113spl_cache_obj(spl_kmem_cache_t *skc, spl_kmem_slab_t *sks)
1114{
1115 spl_kmem_obj_t *sko;
1116
1117 ASSERT(skc->skc_magic == SKC_MAGIC);
1118 ASSERT(sks->sks_magic == SKS_MAGIC);
1119 ASSERT(spin_is_locked(&skc->skc_lock));
1120
1121 sko = list_entry(sks->sks_free_list.next, spl_kmem_obj_t, sko_list);
1122 ASSERT(sko->sko_magic == SKO_MAGIC);
1123 ASSERT(sko->sko_addr != NULL);
1124
1125 /* Remove from sks_free_list */
1126 list_del_init(&sko->sko_list);
1127
1128 sks->sks_age = jiffies;
1129 sks->sks_ref++;
1130 skc->skc_obj_alloc++;
1131
1132 /* Track max obj usage statistics */
1133 if (skc->skc_obj_alloc > skc->skc_obj_max)
1134 skc->skc_obj_max = skc->skc_obj_alloc;
1135
1136 /* Track max slab usage statistics */
1137 if (sks->sks_ref == 1) {
1138 skc->skc_slab_alloc++;
1139
1140 if (skc->skc_slab_alloc > skc->skc_slab_max)
1141 skc->skc_slab_max = skc->skc_slab_alloc;
1142 }
1143
b34b9563 1144 return (sko->sko_addr);
e5b9b344
BB
1145}
1146
1147/*
1148 * Generic slab allocation function to run by the global work queues.
1149 * It is responsible for allocating a new slab, linking it in to the list
1150 * of partial slabs, and then waking any waiters.
1151 */
1152static void
1153spl_cache_grow_work(void *data)
1154{
1155 spl_kmem_alloc_t *ska = (spl_kmem_alloc_t *)data;
1156 spl_kmem_cache_t *skc = ska->ska_cache;
1157 spl_kmem_slab_t *sks;
1158
c2fa0945 1159 fstrans_cookie_t cookie = spl_fstrans_mark();
c3eabc75 1160 sks = spl_slab_alloc(skc, ska->ska_flags);
c2fa0945 1161 spl_fstrans_unmark(cookie);
b4ad50ac 1162
e5b9b344
BB
1163 spin_lock(&skc->skc_lock);
1164 if (sks) {
1165 skc->skc_slab_total++;
1166 skc->skc_obj_total += sks->sks_objs;
1167 list_add_tail(&sks->sks_list, &skc->skc_partial_list);
1168 }
1169
1170 atomic_dec(&skc->skc_ref);
a988a35a 1171 smp_mb__before_atomic();
e5b9b344
BB
1172 clear_bit(KMC_BIT_GROWING, &skc->skc_flags);
1173 clear_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags);
a988a35a 1174 smp_mb__after_atomic();
e5b9b344
BB
1175 wake_up_all(&skc->skc_waitq);
1176 spin_unlock(&skc->skc_lock);
1177
1178 kfree(ska);
1179}
1180
1181/*
1182 * Returns non-zero when a new slab should be available.
1183 */
1184static int
1185spl_cache_grow_wait(spl_kmem_cache_t *skc)
1186{
b34b9563 1187 return (!test_bit(KMC_BIT_GROWING, &skc->skc_flags));
e5b9b344
BB
1188}
1189
1190/*
1191 * No available objects on any slabs, create a new slab. Note that this
1192 * functionality is disabled for KMC_SLAB caches which are backed by the
1193 * Linux slab.
1194 */
1195static int
1196spl_cache_grow(spl_kmem_cache_t *skc, int flags, void **obj)
1197{
c3eabc75 1198 int remaining, rc = 0;
e5b9b344 1199
c3eabc75 1200 ASSERT0(flags & ~KM_PUBLIC_MASK);
e5b9b344
BB
1201 ASSERT(skc->skc_magic == SKC_MAGIC);
1202 ASSERT((skc->skc_flags & KMC_SLAB) == 0);
1203 might_sleep();
1204 *obj = NULL;
1205
1206 /*
1207 * Before allocating a new slab wait for any reaping to complete and
1208 * then return so the local magazine can be rechecked for new objects.
1209 */
1210 if (test_bit(KMC_BIT_REAPING, &skc->skc_flags)) {
1211 rc = spl_wait_on_bit(&skc->skc_flags, KMC_BIT_REAPING,
1212 TASK_UNINTERRUPTIBLE);
1213 return (rc ? rc : -EAGAIN);
1214 }
1215
1216 /*
1217 * This is handled by dispatching a work request to the global work
1218 * queue. This allows us to asynchronously allocate a new slab while
1219 * retaining the ability to safely fall back to a smaller synchronous
1220 * allocations to ensure forward progress is always maintained.
1221 */
1222 if (test_and_set_bit(KMC_BIT_GROWING, &skc->skc_flags) == 0) {
1223 spl_kmem_alloc_t *ska;
1224
c3eabc75 1225 ska = kmalloc(sizeof (*ska), kmem_flags_convert(flags));
e5b9b344 1226 if (ska == NULL) {
a988a35a
RY
1227 clear_bit_unlock(KMC_BIT_GROWING, &skc->skc_flags);
1228 smp_mb__after_atomic();
e5b9b344
BB
1229 wake_up_all(&skc->skc_waitq);
1230 return (-ENOMEM);
1231 }
1232
1233 atomic_inc(&skc->skc_ref);
1234 ska->ska_cache = skc;
c3eabc75 1235 ska->ska_flags = flags;
e5b9b344
BB
1236 taskq_init_ent(&ska->ska_tqe);
1237 taskq_dispatch_ent(spl_kmem_cache_taskq,
1238 spl_cache_grow_work, ska, 0, &ska->ska_tqe);
1239 }
1240
1241 /*
1242 * The goal here is to only detect the rare case where a virtual slab
1243 * allocation has deadlocked. We must be careful to minimize the use
1244 * of emergency objects which are more expensive to track. Therefore,
1245 * we set a very long timeout for the asynchronous allocation and if
1246 * the timeout is reached the cache is flagged as deadlocked. From
1247 * this point only new emergency objects will be allocated until the
1248 * asynchronous allocation completes and clears the deadlocked flag.
1249 */
1250 if (test_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags)) {
1251 rc = spl_emergency_alloc(skc, flags, obj);
1252 } else {
1253 remaining = wait_event_timeout(skc->skc_waitq,
e50e6cc9 1254 spl_cache_grow_wait(skc), HZ / 10);
e5b9b344 1255
436ad60f 1256 if (!remaining) {
e5b9b344
BB
1257 spin_lock(&skc->skc_lock);
1258 if (test_bit(KMC_BIT_GROWING, &skc->skc_flags)) {
1259 set_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags);
1260 skc->skc_obj_deadlock++;
1261 }
1262 spin_unlock(&skc->skc_lock);
1263 }
1264
1265 rc = -ENOMEM;
1266 }
1267
1268 return (rc);
1269}
1270
1271/*
1272 * Refill a per-cpu magazine with objects from the slabs for this cache.
1273 * Ideally the magazine can be repopulated using existing objects which have
1274 * been released, however if we are unable to locate enough free objects new
1275 * slabs of objects will be created. On success NULL is returned, otherwise
1276 * the address of a single emergency object is returned for use by the caller.
1277 */
1278static void *
1279spl_cache_refill(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flags)
1280{
1281 spl_kmem_slab_t *sks;
1282 int count = 0, rc, refill;
1283 void *obj = NULL;
1284
1285 ASSERT(skc->skc_magic == SKC_MAGIC);
1286 ASSERT(skm->skm_magic == SKM_MAGIC);
1287
1288 refill = MIN(skm->skm_refill, skm->skm_size - skm->skm_avail);
1289 spin_lock(&skc->skc_lock);
1290
1291 while (refill > 0) {
1292 /* No slabs available we may need to grow the cache */
1293 if (list_empty(&skc->skc_partial_list)) {
1294 spin_unlock(&skc->skc_lock);
1295
1296 local_irq_enable();
1297 rc = spl_cache_grow(skc, flags, &obj);
1298 local_irq_disable();
1299
1300 /* Emergency object for immediate use by caller */
1301 if (rc == 0 && obj != NULL)
1302 return (obj);
1303
1304 if (rc)
1305 goto out;
1306
1307 /* Rescheduled to different CPU skm is not local */
1308 if (skm != skc->skc_mag[smp_processor_id()])
1309 goto out;
1310
b34b9563
BB
1311 /*
1312 * Potentially rescheduled to the same CPU but
e5b9b344 1313 * allocations may have occurred from this CPU while
b34b9563
BB
1314 * we were sleeping so recalculate max refill.
1315 */
e5b9b344
BB
1316 refill = MIN(refill, skm->skm_size - skm->skm_avail);
1317
1318 spin_lock(&skc->skc_lock);
1319 continue;
1320 }
1321
1322 /* Grab the next available slab */
1323 sks = list_entry((&skc->skc_partial_list)->next,
b34b9563 1324 spl_kmem_slab_t, sks_list);
e5b9b344
BB
1325 ASSERT(sks->sks_magic == SKS_MAGIC);
1326 ASSERT(sks->sks_ref < sks->sks_objs);
1327 ASSERT(!list_empty(&sks->sks_free_list));
1328
b34b9563
BB
1329 /*
1330 * Consume as many objects as needed to refill the requested
1331 * cache. We must also be careful not to overfill it.
1332 */
1333 while (sks->sks_ref < sks->sks_objs && refill-- > 0 &&
1334 ++count) {
e5b9b344
BB
1335 ASSERT(skm->skm_avail < skm->skm_size);
1336 ASSERT(count < skm->skm_size);
b34b9563
BB
1337 skm->skm_objs[skm->skm_avail++] =
1338 spl_cache_obj(skc, sks);
e5b9b344
BB
1339 }
1340
1341 /* Move slab to skc_complete_list when full */
1342 if (sks->sks_ref == sks->sks_objs) {
1343 list_del(&sks->sks_list);
1344 list_add(&sks->sks_list, &skc->skc_complete_list);
1345 }
1346 }
1347
1348 spin_unlock(&skc->skc_lock);
1349out:
1350 return (NULL);
1351}
1352
1353/*
1354 * Release an object back to the slab from which it came.
1355 */
1356static void
1357spl_cache_shrink(spl_kmem_cache_t *skc, void *obj)
1358{
1359 spl_kmem_slab_t *sks = NULL;
1360 spl_kmem_obj_t *sko = NULL;
1361
1362 ASSERT(skc->skc_magic == SKC_MAGIC);
1363 ASSERT(spin_is_locked(&skc->skc_lock));
1364
1365 sko = spl_sko_from_obj(skc, obj);
1366 ASSERT(sko->sko_magic == SKO_MAGIC);
1367 sks = sko->sko_slab;
1368 ASSERT(sks->sks_magic == SKS_MAGIC);
1369 ASSERT(sks->sks_cache == skc);
1370 list_add(&sko->sko_list, &sks->sks_free_list);
1371
1372 sks->sks_age = jiffies;
1373 sks->sks_ref--;
1374 skc->skc_obj_alloc--;
1375
b34b9563
BB
1376 /*
1377 * Move slab to skc_partial_list when no longer full. Slabs
e5b9b344 1378 * are added to the head to keep the partial list is quasi-full
b34b9563
BB
1379 * sorted order. Fuller at the head, emptier at the tail.
1380 */
e5b9b344
BB
1381 if (sks->sks_ref == (sks->sks_objs - 1)) {
1382 list_del(&sks->sks_list);
1383 list_add(&sks->sks_list, &skc->skc_partial_list);
1384 }
1385
b34b9563
BB
1386 /*
1387 * Move empty slabs to the end of the partial list so
1388 * they can be easily found and freed during reclamation.
1389 */
e5b9b344
BB
1390 if (sks->sks_ref == 0) {
1391 list_del(&sks->sks_list);
1392 list_add_tail(&sks->sks_list, &skc->skc_partial_list);
1393 skc->skc_slab_alloc--;
1394 }
1395}
1396
1397/*
1398 * Allocate an object from the per-cpu magazine, or if the magazine
1399 * is empty directly allocate from a slab and repopulate the magazine.
1400 */
1401void *
1402spl_kmem_cache_alloc(spl_kmem_cache_t *skc, int flags)
1403{
1404 spl_kmem_magazine_t *skm;
1405 void *obj = NULL;
1406
c3eabc75 1407 ASSERT0(flags & ~KM_PUBLIC_MASK);
e5b9b344
BB
1408 ASSERT(skc->skc_magic == SKC_MAGIC);
1409 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
e5b9b344 1410
e5b9b344
BB
1411 /*
1412 * Allocate directly from a Linux slab. All optimizations are left
1413 * to the underlying cache we only need to guarantee that KM_SLEEP
1414 * callers will never fail.
1415 */
1416 if (skc->skc_flags & KMC_SLAB) {
1417 struct kmem_cache *slc = skc->skc_linux_cache;
e5b9b344 1418 do {
c3eabc75 1419 obj = kmem_cache_alloc(slc, kmem_flags_convert(flags));
e5b9b344
BB
1420 } while ((obj == NULL) && !(flags & KM_NOSLEEP));
1421
1422 goto ret;
1423 }
1424
1425 local_irq_disable();
1426
1427restart:
b34b9563
BB
1428 /*
1429 * Safe to update per-cpu structure without lock, but
e5b9b344
BB
1430 * in the restart case we must be careful to reacquire
1431 * the local magazine since this may have changed
b34b9563
BB
1432 * when we need to grow the cache.
1433 */
e5b9b344
BB
1434 skm = skc->skc_mag[smp_processor_id()];
1435 ASSERT(skm->skm_magic == SKM_MAGIC);
1436
1437 if (likely(skm->skm_avail)) {
1438 /* Object available in CPU cache, use it */
1439 obj = skm->skm_objs[--skm->skm_avail];
1440 skm->skm_age = jiffies;
1441 } else {
1442 obj = spl_cache_refill(skc, skm, flags);
3018bffa 1443 if ((obj == NULL) && !(flags & KM_NOSLEEP))
e5b9b344 1444 goto restart;
3018bffa
BB
1445
1446 local_irq_enable();
1447 goto ret;
e5b9b344
BB
1448 }
1449
1450 local_irq_enable();
1451 ASSERT(obj);
1452 ASSERT(IS_P2ALIGNED(obj, skc->skc_obj_align));
1453
1454ret:
1455 /* Pre-emptively migrate object to CPU L1 cache */
1456 if (obj) {
1457 if (obj && skc->skc_ctor)
1458 skc->skc_ctor(obj, skc->skc_private, flags);
1459 else
1460 prefetchw(obj);
1461 }
1462
e5b9b344
BB
1463 return (obj);
1464}
e5b9b344
BB
1465EXPORT_SYMBOL(spl_kmem_cache_alloc);
1466
1467/*
1468 * Free an object back to the local per-cpu magazine, there is no
1469 * guarantee that this is the same magazine the object was originally
1470 * allocated from. We may need to flush entire from the magazine
1471 * back to the slabs to make space.
1472 */
1473void
1474spl_kmem_cache_free(spl_kmem_cache_t *skc, void *obj)
1475{
1476 spl_kmem_magazine_t *skm;
1477 unsigned long flags;
1a204968 1478 int do_reclaim = 0;
436ad60f 1479 int do_emergency = 0;
e5b9b344
BB
1480
1481 ASSERT(skc->skc_magic == SKC_MAGIC);
1482 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
e5b9b344
BB
1483
1484 /*
1485 * Run the destructor
1486 */
1487 if (skc->skc_dtor)
1488 skc->skc_dtor(obj, skc->skc_private);
1489
1490 /*
1491 * Free the object from the Linux underlying Linux slab.
1492 */
1493 if (skc->skc_flags & KMC_SLAB) {
1494 kmem_cache_free(skc->skc_linux_cache, obj);
4699d76d 1495 return;
e5b9b344
BB
1496 }
1497
1498 /*
436ad60f
BB
1499 * While a cache has outstanding emergency objects all freed objects
1500 * must be checked. However, since emergency objects will never use
1501 * a virtual address these objects can be safely excluded as an
1502 * optimization.
e5b9b344 1503 */
436ad60f
BB
1504 if (!is_vmalloc_addr(obj)) {
1505 spin_lock(&skc->skc_lock);
1506 do_emergency = (skc->skc_obj_emergency > 0);
1507 spin_unlock(&skc->skc_lock);
1508
1509 if (do_emergency && (spl_emergency_free(skc, obj) == 0))
4699d76d 1510 return;
e5b9b344
BB
1511 }
1512
1513 local_irq_save(flags);
1514
b34b9563
BB
1515 /*
1516 * Safe to update per-cpu structure without lock, but
e5b9b344
BB
1517 * no remote memory allocation tracking is being performed
1518 * it is entirely possible to allocate an object from one
b34b9563
BB
1519 * CPU cache and return it to another.
1520 */
e5b9b344
BB
1521 skm = skc->skc_mag[smp_processor_id()];
1522 ASSERT(skm->skm_magic == SKM_MAGIC);
1523
1a204968
BB
1524 /*
1525 * Per-CPU cache full, flush it to make space for this object,
1526 * this may result in an empty slab which can be reclaimed once
1527 * interrupts are re-enabled.
1528 */
1529 if (unlikely(skm->skm_avail >= skm->skm_size)) {
e5b9b344 1530 spl_cache_flush(skc, skm, skm->skm_refill);
1a204968
BB
1531 do_reclaim = 1;
1532 }
e5b9b344
BB
1533
1534 /* Available space in cache, use it */
1535 skm->skm_objs[skm->skm_avail++] = obj;
1536
1537 local_irq_restore(flags);
1a204968
BB
1538
1539 if (do_reclaim)
1540 spl_slab_reclaim(skc);
e5b9b344
BB
1541}
1542EXPORT_SYMBOL(spl_kmem_cache_free);
1543
1544/*
1545 * The generic shrinker function for all caches. Under Linux a shrinker
1546 * may not be tightly coupled with a slab cache. In fact Linux always
1547 * systematically tries calling all registered shrinker callbacks which
1548 * report that they contain unused objects. Because of this we only
1549 * register one shrinker function in the shim layer for all slab caches.
1550 * We always attempt to shrink all caches when this generic shrinker
1551 * is called.
1552 *
1553 * If sc->nr_to_scan is zero, the caller is requesting a query of the
1554 * number of objects which can potentially be freed. If it is nonzero,
1555 * the request is to free that many objects.
1556 *
1557 * Linux kernels >= 3.12 have the count_objects and scan_objects callbacks
1558 * in struct shrinker and also require the shrinker to return the number
1559 * of objects freed.
1560 *
1561 * Older kernels require the shrinker to return the number of freeable
1562 * objects following the freeing of nr_to_free.
1563 *
1564 * Linux semantics differ from those under Solaris, which are to
1565 * free all available objects which may (and probably will) be more
1566 * objects than the requested nr_to_scan.
1567 */
1568static spl_shrinker_t
1569__spl_kmem_cache_generic_shrinker(struct shrinker *shrink,
1570 struct shrink_control *sc)
1571{
1572 spl_kmem_cache_t *skc;
1573 int alloc = 0;
1574
ae26dd00
TC
1575 /*
1576 * No shrinking in a transaction context. Can cause deadlocks.
1577 */
1578 if (sc->nr_to_scan && spl_fstrans_check())
1579 return (SHRINK_STOP);
1580
e5b9b344
BB
1581 down_read(&spl_kmem_cache_sem);
1582 list_for_each_entry(skc, &spl_kmem_cache_list, skc_list) {
1583 if (sc->nr_to_scan) {
1584#ifdef HAVE_SPLIT_SHRINKER_CALLBACK
1585 uint64_t oldalloc = skc->skc_obj_alloc;
1586 spl_kmem_cache_reap_now(skc,
b34b9563 1587 MAX(sc->nr_to_scan>>fls64(skc->skc_slab_objs), 1));
e5b9b344
BB
1588 if (oldalloc > skc->skc_obj_alloc)
1589 alloc += oldalloc - skc->skc_obj_alloc;
1590#else
1591 spl_kmem_cache_reap_now(skc,
b34b9563 1592 MAX(sc->nr_to_scan>>fls64(skc->skc_slab_objs), 1));
e5b9b344
BB
1593 alloc += skc->skc_obj_alloc;
1594#endif /* HAVE_SPLIT_SHRINKER_CALLBACK */
1595 } else {
1596 /* Request to query number of freeable objects */
1597 alloc += skc->skc_obj_alloc;
1598 }
1599 }
1600 up_read(&spl_kmem_cache_sem);
1601
1602 /*
1603 * When KMC_RECLAIM_ONCE is set allow only a single reclaim pass.
1604 * This functionality only exists to work around a rare issue where
1605 * shrink_slabs() is repeatedly invoked by many cores causing the
1606 * system to thrash.
1607 */
1608 if ((spl_kmem_cache_reclaim & KMC_RECLAIM_ONCE) && sc->nr_to_scan)
1609 return (SHRINK_STOP);
1610
1611 return (MAX(alloc, 0));
1612}
1613
1614SPL_SHRINKER_CALLBACK_WRAPPER(spl_kmem_cache_generic_shrinker);
1615
1616/*
1617 * Call the registered reclaim function for a cache. Depending on how
1618 * many and which objects are released it may simply repopulate the
1619 * local magazine which will then need to age-out. Objects which cannot
1620 * fit in the magazine we will be released back to their slabs which will
1621 * also need to age out before being release. This is all just best
1622 * effort and we do not want to thrash creating and destroying slabs.
1623 */
1624void
1625spl_kmem_cache_reap_now(spl_kmem_cache_t *skc, int count)
1626{
1627 ASSERT(skc->skc_magic == SKC_MAGIC);
1628 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
1629
1630 atomic_inc(&skc->skc_ref);
1631
1632 /*
3e7e6f34 1633 * Execute the registered reclaim callback if it exists.
e5b9b344
BB
1634 */
1635 if (skc->skc_flags & KMC_SLAB) {
1636 if (skc->skc_reclaim)
1637 skc->skc_reclaim(skc->skc_private);
e5b9b344
BB
1638 goto out;
1639 }
1640
1641 /*
1642 * Prevent concurrent cache reaping when contended.
1643 */
1644 if (test_and_set_bit(KMC_BIT_REAPING, &skc->skc_flags))
1645 goto out;
1646
1647 /*
1648 * When a reclaim function is available it may be invoked repeatedly
1649 * until at least a single slab can be freed. This ensures that we
1650 * do free memory back to the system. This helps minimize the chance
1651 * of an OOM event when the bulk of memory is used by the slab.
1652 *
1653 * When free slabs are already available the reclaim callback will be
1654 * skipped. Additionally, if no forward progress is detected despite
1655 * a reclaim function the cache will be skipped to avoid deadlock.
1656 *
1657 * Longer term this would be the correct place to add the code which
1658 * repacks the slabs in order minimize fragmentation.
1659 */
1660 if (skc->skc_reclaim) {
1661 uint64_t objects = UINT64_MAX;
1662 int do_reclaim;
1663
1664 do {
1665 spin_lock(&skc->skc_lock);
1666 do_reclaim =
1667 (skc->skc_slab_total > 0) &&
b34b9563 1668 ((skc->skc_slab_total-skc->skc_slab_alloc) == 0) &&
e5b9b344
BB
1669 (skc->skc_obj_alloc < objects);
1670
1671 objects = skc->skc_obj_alloc;
1672 spin_unlock(&skc->skc_lock);
1673
1674 if (do_reclaim)
1675 skc->skc_reclaim(skc->skc_private);
1676
1677 } while (do_reclaim);
1678 }
1679
1a204968 1680 /* Reclaim from the magazine and free all now empty slabs. */
e5b9b344
BB
1681 if (spl_kmem_cache_expire & KMC_EXPIRE_MEM) {
1682 spl_kmem_magazine_t *skm;
1683 unsigned long irq_flags;
1684
1685 local_irq_save(irq_flags);
1686 skm = skc->skc_mag[smp_processor_id()];
1687 spl_cache_flush(skc, skm, skm->skm_avail);
1688 local_irq_restore(irq_flags);
1689 }
1690
1a204968 1691 spl_slab_reclaim(skc);
a988a35a
RY
1692 clear_bit_unlock(KMC_BIT_REAPING, &skc->skc_flags);
1693 smp_mb__after_atomic();
e5b9b344
BB
1694 wake_up_bit(&skc->skc_flags, KMC_BIT_REAPING);
1695out:
1696 atomic_dec(&skc->skc_ref);
1697}
1698EXPORT_SYMBOL(spl_kmem_cache_reap_now);
1699
1700/*
1701 * Reap all free slabs from all registered caches.
1702 */
1703void
1704spl_kmem_reap(void)
1705{
1706 struct shrink_control sc;
1707
1708 sc.nr_to_scan = KMC_REAP_CHUNK;
1709 sc.gfp_mask = GFP_KERNEL;
1710
1711 (void) __spl_kmem_cache_generic_shrinker(NULL, &sc);
1712}
1713EXPORT_SYMBOL(spl_kmem_reap);
1714
1715int
1716spl_kmem_cache_init(void)
1717{
1718 init_rwsem(&spl_kmem_cache_sem);
1719 INIT_LIST_HEAD(&spl_kmem_cache_list);
1720 spl_kmem_cache_taskq = taskq_create("spl_kmem_cache",
9dc5ffbe 1721 spl_kmem_cache_kmem_threads, maxclsyspri,
3c82160f
BB
1722 spl_kmem_cache_kmem_threads * 8, INT_MAX,
1723 TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
e5b9b344
BB
1724 spl_register_shrinker(&spl_kmem_cache_shrinker);
1725
1726 return (0);
1727}
1728
1729void
1730spl_kmem_cache_fini(void)
1731{
1732 spl_unregister_shrinker(&spl_kmem_cache_shrinker);
1733 taskq_destroy(spl_kmem_cache_taskq);
1734}