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