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