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