]> git.proxmox.com Git - mirror_spl.git/blob - module/spl/spl-kmem.c
Remove spl_invalidate_inodes()
[mirror_spl.git] / module / spl / spl-kmem.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://github.com/behlendorf/spl/>.
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 * Solaris Porting Layer (SPL) Kmem Implementation.
25 \*****************************************************************************/
26
27 #include <sys/kmem.h>
28 #include <spl-debug.h>
29
30 #ifdef SS_DEBUG_SUBSYS
31 #undef SS_DEBUG_SUBSYS
32 #endif
33
34 #define SS_DEBUG_SUBSYS SS_KMEM
35
36 /*
37 * The minimum amount of memory measured in pages to be free at all
38 * times on the system. This is similar to Linux's zone->pages_min
39 * multiplied by the number of zones and is sized based on that.
40 */
41 pgcnt_t minfree = 0;
42 EXPORT_SYMBOL(minfree);
43
44 /*
45 * The desired amount of memory measured in pages to be free at all
46 * times on the system. This is similar to Linux's zone->pages_low
47 * multiplied by the number of zones and is sized based on that.
48 * Assuming all zones are being used roughly equally, when we drop
49 * below this threshold asynchronous page reclamation is triggered.
50 */
51 pgcnt_t desfree = 0;
52 EXPORT_SYMBOL(desfree);
53
54 /*
55 * When above this amount of memory measures in pages the system is
56 * determined to have enough free memory. This is similar to Linux's
57 * zone->pages_high multiplied by the number of zones and is sized based
58 * on that. Assuming all zones are being used roughly equally, when
59 * asynchronous page reclamation reaches this threshold it stops.
60 */
61 pgcnt_t lotsfree = 0;
62 EXPORT_SYMBOL(lotsfree);
63
64 /* Unused always 0 in this implementation */
65 pgcnt_t needfree = 0;
66 EXPORT_SYMBOL(needfree);
67
68 pgcnt_t swapfs_minfree = 0;
69 EXPORT_SYMBOL(swapfs_minfree);
70
71 pgcnt_t swapfs_reserve = 0;
72 EXPORT_SYMBOL(swapfs_reserve);
73
74 vmem_t *heap_arena = NULL;
75 EXPORT_SYMBOL(heap_arena);
76
77 vmem_t *zio_alloc_arena = NULL;
78 EXPORT_SYMBOL(zio_alloc_arena);
79
80 vmem_t *zio_arena = NULL;
81 EXPORT_SYMBOL(zio_arena);
82
83 #ifndef HAVE_GET_VMALLOC_INFO
84 get_vmalloc_info_t get_vmalloc_info_fn = SYMBOL_POISON;
85 EXPORT_SYMBOL(get_vmalloc_info_fn);
86 #endif /* HAVE_GET_VMALLOC_INFO */
87
88 #ifdef HAVE_PGDAT_HELPERS
89 # ifndef HAVE_FIRST_ONLINE_PGDAT
90 first_online_pgdat_t first_online_pgdat_fn = SYMBOL_POISON;
91 EXPORT_SYMBOL(first_online_pgdat_fn);
92 # endif /* HAVE_FIRST_ONLINE_PGDAT */
93
94 # ifndef HAVE_NEXT_ONLINE_PGDAT
95 next_online_pgdat_t next_online_pgdat_fn = SYMBOL_POISON;
96 EXPORT_SYMBOL(next_online_pgdat_fn);
97 # endif /* HAVE_NEXT_ONLINE_PGDAT */
98
99 # ifndef HAVE_NEXT_ZONE
100 next_zone_t next_zone_fn = SYMBOL_POISON;
101 EXPORT_SYMBOL(next_zone_fn);
102 # endif /* HAVE_NEXT_ZONE */
103
104 #else /* HAVE_PGDAT_HELPERS */
105
106 # ifndef HAVE_PGDAT_LIST
107 struct pglist_data *pgdat_list_addr = SYMBOL_POISON;
108 EXPORT_SYMBOL(pgdat_list_addr);
109 # endif /* HAVE_PGDAT_LIST */
110
111 #endif /* HAVE_PGDAT_HELPERS */
112
113 #ifdef NEED_GET_ZONE_COUNTS
114 # ifndef HAVE_GET_ZONE_COUNTS
115 get_zone_counts_t get_zone_counts_fn = SYMBOL_POISON;
116 EXPORT_SYMBOL(get_zone_counts_fn);
117 # endif /* HAVE_GET_ZONE_COUNTS */
118
119 unsigned long
120 spl_global_page_state(spl_zone_stat_item_t item)
121 {
122 unsigned long active;
123 unsigned long inactive;
124 unsigned long free;
125
126 get_zone_counts(&active, &inactive, &free);
127 switch (item) {
128 case SPL_NR_FREE_PAGES: return free;
129 case SPL_NR_INACTIVE: return inactive;
130 case SPL_NR_ACTIVE: return active;
131 default: ASSERT(0); /* Unsupported */
132 }
133
134 return 0;
135 }
136 #else
137 # ifdef HAVE_GLOBAL_PAGE_STATE
138 unsigned long
139 spl_global_page_state(spl_zone_stat_item_t item)
140 {
141 unsigned long pages = 0;
142
143 switch (item) {
144 case SPL_NR_FREE_PAGES:
145 # ifdef HAVE_ZONE_STAT_ITEM_NR_FREE_PAGES
146 pages += global_page_state(NR_FREE_PAGES);
147 # endif
148 break;
149 case SPL_NR_INACTIVE:
150 # ifdef HAVE_ZONE_STAT_ITEM_NR_INACTIVE
151 pages += global_page_state(NR_INACTIVE);
152 # endif
153 # ifdef HAVE_ZONE_STAT_ITEM_NR_INACTIVE_ANON
154 pages += global_page_state(NR_INACTIVE_ANON);
155 # endif
156 # ifdef HAVE_ZONE_STAT_ITEM_NR_INACTIVE_FILE
157 pages += global_page_state(NR_INACTIVE_FILE);
158 # endif
159 break;
160 case SPL_NR_ACTIVE:
161 # ifdef HAVE_ZONE_STAT_ITEM_NR_ACTIVE
162 pages += global_page_state(NR_ACTIVE);
163 # endif
164 # ifdef HAVE_ZONE_STAT_ITEM_NR_ACTIVE_ANON
165 pages += global_page_state(NR_ACTIVE_ANON);
166 # endif
167 # ifdef HAVE_ZONE_STAT_ITEM_NR_ACTIVE_FILE
168 pages += global_page_state(NR_ACTIVE_FILE);
169 # endif
170 break;
171 default:
172 ASSERT(0); /* Unsupported */
173 }
174
175 return pages;
176 }
177 # else
178 # error "Both global_page_state() and get_zone_counts() unavailable"
179 # endif /* HAVE_GLOBAL_PAGE_STATE */
180 #endif /* NEED_GET_ZONE_COUNTS */
181 EXPORT_SYMBOL(spl_global_page_state);
182
183 #ifndef HAVE_SHRINK_DCACHE_MEMORY
184 shrink_dcache_memory_t shrink_dcache_memory_fn = SYMBOL_POISON;
185 EXPORT_SYMBOL(shrink_dcache_memory_fn);
186 #endif /* HAVE_SHRINK_DCACHE_MEMORY */
187
188 #ifndef HAVE_SHRINK_ICACHE_MEMORY
189 shrink_icache_memory_t shrink_icache_memory_fn = SYMBOL_POISON;
190 EXPORT_SYMBOL(shrink_icache_memory_fn);
191 #endif /* HAVE_SHRINK_ICACHE_MEMORY */
192
193 pgcnt_t
194 spl_kmem_availrmem(void)
195 {
196 /* The amount of easily available memory */
197 return (spl_global_page_state(SPL_NR_FREE_PAGES) +
198 spl_global_page_state(SPL_NR_INACTIVE));
199 }
200 EXPORT_SYMBOL(spl_kmem_availrmem);
201
202 size_t
203 vmem_size(vmem_t *vmp, int typemask)
204 {
205 struct vmalloc_info vmi;
206 size_t size = 0;
207
208 ASSERT(vmp == NULL);
209 ASSERT(typemask & (VMEM_ALLOC | VMEM_FREE));
210
211 get_vmalloc_info(&vmi);
212 if (typemask & VMEM_ALLOC)
213 size += (size_t)vmi.used;
214
215 if (typemask & VMEM_FREE)
216 size += (size_t)(VMALLOC_TOTAL - vmi.used);
217
218 return size;
219 }
220 EXPORT_SYMBOL(vmem_size);
221
222 int
223 kmem_debugging(void)
224 {
225 return 0;
226 }
227 EXPORT_SYMBOL(kmem_debugging);
228
229 #ifndef HAVE_KVASPRINTF
230 /* Simplified asprintf. */
231 char *kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
232 {
233 unsigned int len;
234 char *p;
235 va_list aq;
236
237 va_copy(aq, ap);
238 len = vsnprintf(NULL, 0, fmt, aq);
239 va_end(aq);
240
241 p = kmalloc(len+1, gfp);
242 if (!p)
243 return NULL;
244
245 vsnprintf(p, len+1, fmt, ap);
246
247 return p;
248 }
249 EXPORT_SYMBOL(kvasprintf);
250 #endif /* HAVE_KVASPRINTF */
251
252 char *
253 kmem_vasprintf(const char *fmt, va_list ap)
254 {
255 va_list aq;
256 char *ptr;
257
258 do {
259 va_copy(aq, ap);
260 ptr = kvasprintf(GFP_KERNEL, fmt, aq);
261 va_end(aq);
262 } while (ptr == NULL);
263
264 return ptr;
265 }
266 EXPORT_SYMBOL(kmem_vasprintf);
267
268 char *
269 kmem_asprintf(const char *fmt, ...)
270 {
271 va_list ap;
272 char *ptr;
273
274 do {
275 va_start(ap, fmt);
276 ptr = kvasprintf(GFP_KERNEL, fmt, ap);
277 va_end(ap);
278 } while (ptr == NULL);
279
280 return ptr;
281 }
282 EXPORT_SYMBOL(kmem_asprintf);
283
284 static char *
285 __strdup(const char *str, int flags)
286 {
287 char *ptr;
288 int n;
289
290 n = strlen(str);
291 ptr = kmalloc_nofail(n + 1, flags);
292 if (ptr)
293 memcpy(ptr, str, n + 1);
294
295 return ptr;
296 }
297
298 char *
299 strdup(const char *str)
300 {
301 return __strdup(str, KM_SLEEP);
302 }
303 EXPORT_SYMBOL(strdup);
304
305 void
306 strfree(char *str)
307 {
308 kfree(str);
309 }
310 EXPORT_SYMBOL(strfree);
311
312 /*
313 * Memory allocation interfaces and debugging for basic kmem_*
314 * and vmem_* style memory allocation. When DEBUG_KMEM is enabled
315 * the SPL will keep track of the total memory allocated, and
316 * report any memory leaked when the module is unloaded.
317 */
318 #ifdef DEBUG_KMEM
319
320 /* Shim layer memory accounting */
321 # ifdef HAVE_ATOMIC64_T
322 atomic64_t kmem_alloc_used = ATOMIC64_INIT(0);
323 unsigned long long kmem_alloc_max = 0;
324 atomic64_t vmem_alloc_used = ATOMIC64_INIT(0);
325 unsigned long long vmem_alloc_max = 0;
326 # else /* HAVE_ATOMIC64_T */
327 atomic_t kmem_alloc_used = ATOMIC_INIT(0);
328 unsigned long long kmem_alloc_max = 0;
329 atomic_t vmem_alloc_used = ATOMIC_INIT(0);
330 unsigned long long vmem_alloc_max = 0;
331 # endif /* HAVE_ATOMIC64_T */
332
333 EXPORT_SYMBOL(kmem_alloc_used);
334 EXPORT_SYMBOL(kmem_alloc_max);
335 EXPORT_SYMBOL(vmem_alloc_used);
336 EXPORT_SYMBOL(vmem_alloc_max);
337
338 /* When DEBUG_KMEM_TRACKING is enabled not only will total bytes be tracked
339 * but also the location of every alloc and free. When the SPL module is
340 * unloaded a list of all leaked addresses and where they were allocated
341 * will be dumped to the console. Enabling this feature has a significant
342 * impact on performance but it makes finding memory leaks straight forward.
343 *
344 * Not surprisingly with debugging enabled the xmem_locks are very highly
345 * contended particularly on xfree(). If we want to run with this detailed
346 * debugging enabled for anything other than debugging we need to minimize
347 * the contention by moving to a lock per xmem_table entry model.
348 */
349 # ifdef DEBUG_KMEM_TRACKING
350
351 # define KMEM_HASH_BITS 10
352 # define KMEM_TABLE_SIZE (1 << KMEM_HASH_BITS)
353
354 # define VMEM_HASH_BITS 10
355 # define VMEM_TABLE_SIZE (1 << VMEM_HASH_BITS)
356
357 typedef struct kmem_debug {
358 struct hlist_node kd_hlist; /* Hash node linkage */
359 struct list_head kd_list; /* List of all allocations */
360 void *kd_addr; /* Allocation pointer */
361 size_t kd_size; /* Allocation size */
362 const char *kd_func; /* Allocation function */
363 int kd_line; /* Allocation line */
364 } kmem_debug_t;
365
366 spinlock_t kmem_lock;
367 struct hlist_head kmem_table[KMEM_TABLE_SIZE];
368 struct list_head kmem_list;
369
370 spinlock_t vmem_lock;
371 struct hlist_head vmem_table[VMEM_TABLE_SIZE];
372 struct list_head vmem_list;
373
374 EXPORT_SYMBOL(kmem_lock);
375 EXPORT_SYMBOL(kmem_table);
376 EXPORT_SYMBOL(kmem_list);
377
378 EXPORT_SYMBOL(vmem_lock);
379 EXPORT_SYMBOL(vmem_table);
380 EXPORT_SYMBOL(vmem_list);
381
382 static kmem_debug_t *
383 kmem_del_init(spinlock_t *lock, struct hlist_head *table, int bits, const void *addr)
384 {
385 struct hlist_head *head;
386 struct hlist_node *node;
387 struct kmem_debug *p;
388 unsigned long flags;
389 SENTRY;
390
391 spin_lock_irqsave(lock, flags);
392
393 head = &table[hash_ptr(addr, bits)];
394 hlist_for_each_entry_rcu(p, node, head, kd_hlist) {
395 if (p->kd_addr == addr) {
396 hlist_del_init(&p->kd_hlist);
397 list_del_init(&p->kd_list);
398 spin_unlock_irqrestore(lock, flags);
399 return p;
400 }
401 }
402
403 spin_unlock_irqrestore(lock, flags);
404
405 SRETURN(NULL);
406 }
407
408 void *
409 kmem_alloc_track(size_t size, int flags, const char *func, int line,
410 int node_alloc, int node)
411 {
412 void *ptr = NULL;
413 kmem_debug_t *dptr;
414 unsigned long irq_flags;
415 SENTRY;
416
417 /* Function may be called with KM_NOSLEEP so failure is possible */
418 dptr = (kmem_debug_t *) kmalloc_nofail(sizeof(kmem_debug_t),
419 flags & ~__GFP_ZERO);
420
421 if (unlikely(dptr == NULL)) {
422 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING, "debug "
423 "kmem_alloc(%ld, 0x%x) at %s:%d failed (%lld/%llu)\n",
424 sizeof(kmem_debug_t), flags, func, line,
425 kmem_alloc_used_read(), kmem_alloc_max);
426 } else {
427 /*
428 * Marked unlikely because we should never be doing this,
429 * we tolerate to up 2 pages but a single page is best.
430 */
431 if (unlikely((size > PAGE_SIZE*2) && !(flags & KM_NODEBUG))) {
432 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING, "large "
433 "kmem_alloc(%llu, 0x%x) at %s:%d (%lld/%llu)\n",
434 (unsigned long long) size, flags, func, line,
435 kmem_alloc_used_read(), kmem_alloc_max);
436 spl_debug_dumpstack(NULL);
437 }
438
439 /*
440 * We use __strdup() below because the string pointed to by
441 * __FUNCTION__ might not be available by the time we want
442 * to print it since the module might have been unloaded.
443 * This can only fail in the KM_NOSLEEP case.
444 */
445 dptr->kd_func = __strdup(func, flags & ~__GFP_ZERO);
446 if (unlikely(dptr->kd_func == NULL)) {
447 kfree(dptr);
448 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
449 "debug __strdup() at %s:%d failed (%lld/%llu)\n",
450 func, line, kmem_alloc_used_read(), kmem_alloc_max);
451 goto out;
452 }
453
454 /* Use the correct allocator */
455 if (node_alloc) {
456 ASSERT(!(flags & __GFP_ZERO));
457 ptr = kmalloc_node_nofail(size, flags, node);
458 } else if (flags & __GFP_ZERO) {
459 ptr = kzalloc_nofail(size, flags & ~__GFP_ZERO);
460 } else {
461 ptr = kmalloc_nofail(size, flags);
462 }
463
464 if (unlikely(ptr == NULL)) {
465 kfree(dptr->kd_func);
466 kfree(dptr);
467 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING, "kmem_alloc"
468 "(%llu, 0x%x) at %s:%d failed (%lld/%llu)\n",
469 (unsigned long long) size, flags, func, line,
470 kmem_alloc_used_read(), kmem_alloc_max);
471 goto out;
472 }
473
474 kmem_alloc_used_add(size);
475 if (unlikely(kmem_alloc_used_read() > kmem_alloc_max))
476 kmem_alloc_max = kmem_alloc_used_read();
477
478 INIT_HLIST_NODE(&dptr->kd_hlist);
479 INIT_LIST_HEAD(&dptr->kd_list);
480
481 dptr->kd_addr = ptr;
482 dptr->kd_size = size;
483 dptr->kd_line = line;
484
485 spin_lock_irqsave(&kmem_lock, irq_flags);
486 hlist_add_head_rcu(&dptr->kd_hlist,
487 &kmem_table[hash_ptr(ptr, KMEM_HASH_BITS)]);
488 list_add_tail(&dptr->kd_list, &kmem_list);
489 spin_unlock_irqrestore(&kmem_lock, irq_flags);
490
491 SDEBUG_LIMIT(SD_INFO,
492 "kmem_alloc(%llu, 0x%x) at %s:%d = %p (%lld/%llu)\n",
493 (unsigned long long) size, flags, func, line, ptr,
494 kmem_alloc_used_read(), kmem_alloc_max);
495 }
496 out:
497 SRETURN(ptr);
498 }
499 EXPORT_SYMBOL(kmem_alloc_track);
500
501 void
502 kmem_free_track(const void *ptr, size_t size)
503 {
504 kmem_debug_t *dptr;
505 SENTRY;
506
507 ASSERTF(ptr || size > 0, "ptr: %p, size: %llu", ptr,
508 (unsigned long long) size);
509
510 dptr = kmem_del_init(&kmem_lock, kmem_table, KMEM_HASH_BITS, ptr);
511
512 /* Must exist in hash due to kmem_alloc() */
513 ASSERT(dptr);
514
515 /* Size must match */
516 ASSERTF(dptr->kd_size == size, "kd_size (%llu) != size (%llu), "
517 "kd_func = %s, kd_line = %d\n", (unsigned long long) dptr->kd_size,
518 (unsigned long long) size, dptr->kd_func, dptr->kd_line);
519
520 kmem_alloc_used_sub(size);
521 SDEBUG_LIMIT(SD_INFO, "kmem_free(%p, %llu) (%lld/%llu)\n", ptr,
522 (unsigned long long) size, kmem_alloc_used_read(),
523 kmem_alloc_max);
524
525 kfree(dptr->kd_func);
526
527 memset(dptr, 0x5a, sizeof(kmem_debug_t));
528 kfree(dptr);
529
530 memset(ptr, 0x5a, size);
531 kfree(ptr);
532
533 SEXIT;
534 }
535 EXPORT_SYMBOL(kmem_free_track);
536
537 void *
538 vmem_alloc_track(size_t size, int flags, const char *func, int line)
539 {
540 void *ptr = NULL;
541 kmem_debug_t *dptr;
542 unsigned long irq_flags;
543 SENTRY;
544
545 ASSERT(flags & KM_SLEEP);
546
547 /* Function may be called with KM_NOSLEEP so failure is possible */
548 dptr = (kmem_debug_t *) kmalloc_nofail(sizeof(kmem_debug_t),
549 flags & ~__GFP_ZERO);
550 if (unlikely(dptr == NULL)) {
551 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING, "debug "
552 "vmem_alloc(%ld, 0x%x) at %s:%d failed (%lld/%llu)\n",
553 sizeof(kmem_debug_t), flags, func, line,
554 vmem_alloc_used_read(), vmem_alloc_max);
555 } else {
556 /*
557 * We use __strdup() below because the string pointed to by
558 * __FUNCTION__ might not be available by the time we want
559 * to print it, since the module might have been unloaded.
560 * This can never fail because we have already asserted
561 * that flags is KM_SLEEP.
562 */
563 dptr->kd_func = __strdup(func, flags & ~__GFP_ZERO);
564 if (unlikely(dptr->kd_func == NULL)) {
565 kfree(dptr);
566 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
567 "debug __strdup() at %s:%d failed (%lld/%llu)\n",
568 func, line, vmem_alloc_used_read(), vmem_alloc_max);
569 goto out;
570 }
571
572 /* Use the correct allocator */
573 if (flags & __GFP_ZERO) {
574 ptr = vzalloc_nofail(size, flags & ~__GFP_ZERO);
575 } else {
576 ptr = vmalloc_nofail(size, flags);
577 }
578
579 if (unlikely(ptr == NULL)) {
580 kfree(dptr->kd_func);
581 kfree(dptr);
582 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING, "vmem_alloc"
583 "(%llu, 0x%x) at %s:%d failed (%lld/%llu)\n",
584 (unsigned long long) size, flags, func, line,
585 vmem_alloc_used_read(), vmem_alloc_max);
586 goto out;
587 }
588
589 vmem_alloc_used_add(size);
590 if (unlikely(vmem_alloc_used_read() > vmem_alloc_max))
591 vmem_alloc_max = vmem_alloc_used_read();
592
593 INIT_HLIST_NODE(&dptr->kd_hlist);
594 INIT_LIST_HEAD(&dptr->kd_list);
595
596 dptr->kd_addr = ptr;
597 dptr->kd_size = size;
598 dptr->kd_line = line;
599
600 spin_lock_irqsave(&vmem_lock, irq_flags);
601 hlist_add_head_rcu(&dptr->kd_hlist,
602 &vmem_table[hash_ptr(ptr, VMEM_HASH_BITS)]);
603 list_add_tail(&dptr->kd_list, &vmem_list);
604 spin_unlock_irqrestore(&vmem_lock, irq_flags);
605
606 SDEBUG_LIMIT(SD_INFO,
607 "vmem_alloc(%llu, 0x%x) at %s:%d = %p (%lld/%llu)\n",
608 (unsigned long long) size, flags, func, line,
609 ptr, vmem_alloc_used_read(), vmem_alloc_max);
610 }
611 out:
612 SRETURN(ptr);
613 }
614 EXPORT_SYMBOL(vmem_alloc_track);
615
616 void
617 vmem_free_track(const void *ptr, size_t size)
618 {
619 kmem_debug_t *dptr;
620 SENTRY;
621
622 ASSERTF(ptr || size > 0, "ptr: %p, size: %llu", ptr,
623 (unsigned long long) size);
624
625 dptr = kmem_del_init(&vmem_lock, vmem_table, VMEM_HASH_BITS, ptr);
626
627 /* Must exist in hash due to vmem_alloc() */
628 ASSERT(dptr);
629
630 /* Size must match */
631 ASSERTF(dptr->kd_size == size, "kd_size (%llu) != size (%llu), "
632 "kd_func = %s, kd_line = %d\n", (unsigned long long) dptr->kd_size,
633 (unsigned long long) size, dptr->kd_func, dptr->kd_line);
634
635 vmem_alloc_used_sub(size);
636 SDEBUG_LIMIT(SD_INFO, "vmem_free(%p, %llu) (%lld/%llu)\n", ptr,
637 (unsigned long long) size, vmem_alloc_used_read(),
638 vmem_alloc_max);
639
640 kfree(dptr->kd_func);
641
642 memset(dptr, 0x5a, sizeof(kmem_debug_t));
643 kfree(dptr);
644
645 memset(ptr, 0x5a, size);
646 vfree(ptr);
647
648 SEXIT;
649 }
650 EXPORT_SYMBOL(vmem_free_track);
651
652 # else /* DEBUG_KMEM_TRACKING */
653
654 void *
655 kmem_alloc_debug(size_t size, int flags, const char *func, int line,
656 int node_alloc, int node)
657 {
658 void *ptr;
659 SENTRY;
660
661 /*
662 * Marked unlikely because we should never be doing this,
663 * we tolerate to up 2 pages but a single page is best.
664 */
665 if (unlikely((size > PAGE_SIZE * 2) && !(flags & KM_NODEBUG))) {
666 SDEBUG(SD_CONSOLE | SD_WARNING,
667 "large kmem_alloc(%llu, 0x%x) at %s:%d (%lld/%llu)\n",
668 (unsigned long long) size, flags, func, line,
669 kmem_alloc_used_read(), kmem_alloc_max);
670 dump_stack();
671 }
672
673 /* Use the correct allocator */
674 if (node_alloc) {
675 ASSERT(!(flags & __GFP_ZERO));
676 ptr = kmalloc_node_nofail(size, flags, node);
677 } else if (flags & __GFP_ZERO) {
678 ptr = kzalloc_nofail(size, flags & (~__GFP_ZERO));
679 } else {
680 ptr = kmalloc_nofail(size, flags);
681 }
682
683 if (unlikely(ptr == NULL)) {
684 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
685 "kmem_alloc(%llu, 0x%x) at %s:%d failed (%lld/%llu)\n",
686 (unsigned long long) size, flags, func, line,
687 kmem_alloc_used_read(), kmem_alloc_max);
688 } else {
689 kmem_alloc_used_add(size);
690 if (unlikely(kmem_alloc_used_read() > kmem_alloc_max))
691 kmem_alloc_max = kmem_alloc_used_read();
692
693 SDEBUG_LIMIT(SD_INFO,
694 "kmem_alloc(%llu, 0x%x) at %s:%d = %p (%lld/%llu)\n",
695 (unsigned long long) size, flags, func, line, ptr,
696 kmem_alloc_used_read(), kmem_alloc_max);
697 }
698
699 SRETURN(ptr);
700 }
701 EXPORT_SYMBOL(kmem_alloc_debug);
702
703 void
704 kmem_free_debug(const void *ptr, size_t size)
705 {
706 SENTRY;
707
708 ASSERTF(ptr || size > 0, "ptr: %p, size: %llu", ptr,
709 (unsigned long long) size);
710
711 kmem_alloc_used_sub(size);
712 SDEBUG_LIMIT(SD_INFO, "kmem_free(%p, %llu) (%lld/%llu)\n", ptr,
713 (unsigned long long) size, kmem_alloc_used_read(),
714 kmem_alloc_max);
715 kfree(ptr);
716
717 SEXIT;
718 }
719 EXPORT_SYMBOL(kmem_free_debug);
720
721 void *
722 vmem_alloc_debug(size_t size, int flags, const char *func, int line)
723 {
724 void *ptr;
725 SENTRY;
726
727 ASSERT(flags & KM_SLEEP);
728
729 /* Use the correct allocator */
730 if (flags & __GFP_ZERO) {
731 ptr = vzalloc_nofail(size, flags & (~__GFP_ZERO));
732 } else {
733 ptr = vmalloc_nofail(size, flags);
734 }
735
736 if (unlikely(ptr == NULL)) {
737 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
738 "vmem_alloc(%llu, 0x%x) at %s:%d failed (%lld/%llu)\n",
739 (unsigned long long) size, flags, func, line,
740 vmem_alloc_used_read(), vmem_alloc_max);
741 } else {
742 vmem_alloc_used_add(size);
743 if (unlikely(vmem_alloc_used_read() > vmem_alloc_max))
744 vmem_alloc_max = vmem_alloc_used_read();
745
746 SDEBUG_LIMIT(SD_INFO, "vmem_alloc(%llu, 0x%x) = %p "
747 "(%lld/%llu)\n", (unsigned long long) size, flags, ptr,
748 vmem_alloc_used_read(), vmem_alloc_max);
749 }
750
751 SRETURN(ptr);
752 }
753 EXPORT_SYMBOL(vmem_alloc_debug);
754
755 void
756 vmem_free_debug(const void *ptr, size_t size)
757 {
758 SENTRY;
759
760 ASSERTF(ptr || size > 0, "ptr: %p, size: %llu", ptr,
761 (unsigned long long) size);
762
763 vmem_alloc_used_sub(size);
764 SDEBUG_LIMIT(SD_INFO, "vmem_free(%p, %llu) (%lld/%llu)\n", ptr,
765 (unsigned long long) size, vmem_alloc_used_read(),
766 vmem_alloc_max);
767 vfree(ptr);
768
769 SEXIT;
770 }
771 EXPORT_SYMBOL(vmem_free_debug);
772
773 # endif /* DEBUG_KMEM_TRACKING */
774 #endif /* DEBUG_KMEM */
775
776 /*
777 * Slab allocation interfaces
778 *
779 * While the Linux slab implementation was inspired by the Solaris
780 * implementation I cannot use it to emulate the Solaris APIs. I
781 * require two features which are not provided by the Linux slab.
782 *
783 * 1) Constructors AND destructors. Recent versions of the Linux
784 * kernel have removed support for destructors. This is a deal
785 * breaker for the SPL which contains particularly expensive
786 * initializers for mutex's, condition variables, etc. We also
787 * require a minimal level of cleanup for these data types unlike
788 * many Linux data type which do need to be explicitly destroyed.
789 *
790 * 2) Virtual address space backed slab. Callers of the Solaris slab
791 * expect it to work well for both small are very large allocations.
792 * Because of memory fragmentation the Linux slab which is backed
793 * by kmalloc'ed memory performs very badly when confronted with
794 * large numbers of large allocations. Basing the slab on the
795 * virtual address space removes the need for contiguous pages
796 * and greatly improve performance for large allocations.
797 *
798 * For these reasons, the SPL has its own slab implementation with
799 * the needed features. It is not as highly optimized as either the
800 * Solaris or Linux slabs, but it should get me most of what is
801 * needed until it can be optimized or obsoleted by another approach.
802 *
803 * One serious concern I do have about this method is the relatively
804 * small virtual address space on 32bit arches. This will seriously
805 * constrain the size of the slab caches and their performance.
806 *
807 * XXX: Improve the partial slab list by carefully maintaining a
808 * strict ordering of fullest to emptiest slabs based on
809 * the slab reference count. This guarantees the when freeing
810 * slabs back to the system we need only linearly traverse the
811 * last N slabs in the list to discover all the freeable slabs.
812 *
813 * XXX: NUMA awareness for optionally allocating memory close to a
814 * particular core. This can be advantageous if you know the slab
815 * object will be short lived and primarily accessed from one core.
816 *
817 * XXX: Slab coloring may also yield performance improvements and would
818 * be desirable to implement.
819 */
820
821 struct list_head spl_kmem_cache_list; /* List of caches */
822 struct rw_semaphore spl_kmem_cache_sem; /* Cache list lock */
823 taskq_t *spl_kmem_cache_taskq; /* Task queue for ageing / reclaim */
824
825 static void spl_cache_shrink(spl_kmem_cache_t *skc, void *obj);
826
827 SPL_SHRINKER_CALLBACK_FWD_DECLARE(spl_kmem_cache_generic_shrinker);
828 SPL_SHRINKER_DECLARE(spl_kmem_cache_shrinker,
829 spl_kmem_cache_generic_shrinker, KMC_DEFAULT_SEEKS);
830
831 static void *
832 kv_alloc(spl_kmem_cache_t *skc, int size, int flags)
833 {
834 void *ptr;
835
836 ASSERT(ISP2(size));
837
838 if (skc->skc_flags & KMC_KMEM)
839 ptr = (void *)__get_free_pages(flags, get_order(size));
840 else
841 ptr = __vmalloc(size, flags | __GFP_HIGHMEM, PAGE_KERNEL);
842
843 /* Resulting allocated memory will be page aligned */
844 ASSERT(IS_P2ALIGNED(ptr, PAGE_SIZE));
845
846 return ptr;
847 }
848
849 static void
850 kv_free(spl_kmem_cache_t *skc, void *ptr, int size)
851 {
852 ASSERT(IS_P2ALIGNED(ptr, PAGE_SIZE));
853 ASSERT(ISP2(size));
854
855 /*
856 * The Linux direct reclaim path uses this out of band value to
857 * determine if forward progress is being made. Normally this is
858 * incremented by kmem_freepages() which is part of the various
859 * Linux slab implementations. However, since we are using none
860 * of that infrastructure we are responsible for incrementing it.
861 */
862 if (current->reclaim_state)
863 current->reclaim_state->reclaimed_slab += size >> PAGE_SHIFT;
864
865 if (skc->skc_flags & KMC_KMEM)
866 free_pages((unsigned long)ptr, get_order(size));
867 else
868 vfree(ptr);
869 }
870
871 /*
872 * Required space for each aligned sks.
873 */
874 static inline uint32_t
875 spl_sks_size(spl_kmem_cache_t *skc)
876 {
877 return P2ROUNDUP_TYPED(sizeof(spl_kmem_slab_t),
878 skc->skc_obj_align, uint32_t);
879 }
880
881 /*
882 * Required space for each aligned object.
883 */
884 static inline uint32_t
885 spl_obj_size(spl_kmem_cache_t *skc)
886 {
887 uint32_t align = skc->skc_obj_align;
888
889 return P2ROUNDUP_TYPED(skc->skc_obj_size, align, uint32_t) +
890 P2ROUNDUP_TYPED(sizeof(spl_kmem_obj_t), align, uint32_t);
891 }
892
893 /*
894 * Lookup the spl_kmem_object_t for an object given that object.
895 */
896 static inline spl_kmem_obj_t *
897 spl_sko_from_obj(spl_kmem_cache_t *skc, void *obj)
898 {
899 return obj + P2ROUNDUP_TYPED(skc->skc_obj_size,
900 skc->skc_obj_align, uint32_t);
901 }
902
903 /*
904 * Required space for each offslab object taking in to account alignment
905 * restrictions and the power-of-two requirement of kv_alloc().
906 */
907 static inline uint32_t
908 spl_offslab_size(spl_kmem_cache_t *skc)
909 {
910 return 1UL << (highbit(spl_obj_size(skc)) + 1);
911 }
912
913 /*
914 * It's important that we pack the spl_kmem_obj_t structure and the
915 * actual objects in to one large address space to minimize the number
916 * of calls to the allocator. It is far better to do a few large
917 * allocations and then subdivide it ourselves. Now which allocator
918 * we use requires balancing a few trade offs.
919 *
920 * For small objects we use kmem_alloc() because as long as you are
921 * only requesting a small number of pages (ideally just one) its cheap.
922 * However, when you start requesting multiple pages with kmem_alloc()
923 * it gets increasingly expensive since it requires contiguous pages.
924 * For this reason we shift to vmem_alloc() for slabs of large objects
925 * which removes the need for contiguous pages. We do not use
926 * vmem_alloc() in all cases because there is significant locking
927 * overhead in __get_vm_area_node(). This function takes a single
928 * global lock when acquiring an available virtual address range which
929 * serializes all vmem_alloc()'s for all slab caches. Using slightly
930 * different allocation functions for small and large objects should
931 * give us the best of both worlds.
932 *
933 * KMC_ONSLAB KMC_OFFSLAB
934 *
935 * +------------------------+ +-----------------+
936 * | spl_kmem_slab_t --+-+ | | spl_kmem_slab_t |---+-+
937 * | skc_obj_size <-+ | | +-----------------+ | |
938 * | spl_kmem_obj_t | | | |
939 * | skc_obj_size <---+ | +-----------------+ | |
940 * | spl_kmem_obj_t | | | skc_obj_size | <-+ |
941 * | ... v | | spl_kmem_obj_t | |
942 * +------------------------+ +-----------------+ v
943 */
944 static spl_kmem_slab_t *
945 spl_slab_alloc(spl_kmem_cache_t *skc, int flags)
946 {
947 spl_kmem_slab_t *sks;
948 spl_kmem_obj_t *sko, *n;
949 void *base, *obj;
950 uint32_t obj_size, offslab_size = 0;
951 int i, rc = 0;
952
953 base = kv_alloc(skc, skc->skc_slab_size, flags);
954 if (base == NULL)
955 SRETURN(NULL);
956
957 sks = (spl_kmem_slab_t *)base;
958 sks->sks_magic = SKS_MAGIC;
959 sks->sks_objs = skc->skc_slab_objs;
960 sks->sks_age = jiffies;
961 sks->sks_cache = skc;
962 INIT_LIST_HEAD(&sks->sks_list);
963 INIT_LIST_HEAD(&sks->sks_free_list);
964 sks->sks_ref = 0;
965 obj_size = spl_obj_size(skc);
966
967 if (skc->skc_flags & KMC_OFFSLAB)
968 offslab_size = spl_offslab_size(skc);
969
970 for (i = 0; i < sks->sks_objs; i++) {
971 if (skc->skc_flags & KMC_OFFSLAB) {
972 obj = kv_alloc(skc, offslab_size, flags);
973 if (!obj)
974 SGOTO(out, rc = -ENOMEM);
975 } else {
976 obj = base + spl_sks_size(skc) + (i * obj_size);
977 }
978
979 ASSERT(IS_P2ALIGNED(obj, skc->skc_obj_align));
980 sko = spl_sko_from_obj(skc, obj);
981 sko->sko_addr = obj;
982 sko->sko_magic = SKO_MAGIC;
983 sko->sko_slab = sks;
984 INIT_LIST_HEAD(&sko->sko_list);
985 list_add_tail(&sko->sko_list, &sks->sks_free_list);
986 }
987
988 list_for_each_entry(sko, &sks->sks_free_list, sko_list)
989 if (skc->skc_ctor)
990 skc->skc_ctor(sko->sko_addr, skc->skc_private, flags);
991 out:
992 if (rc) {
993 if (skc->skc_flags & KMC_OFFSLAB)
994 list_for_each_entry_safe(sko, n, &sks->sks_free_list,
995 sko_list)
996 kv_free(skc, sko->sko_addr, offslab_size);
997
998 kv_free(skc, base, skc->skc_slab_size);
999 sks = NULL;
1000 }
1001
1002 SRETURN(sks);
1003 }
1004
1005 /*
1006 * Remove a slab from complete or partial list, it must be called with
1007 * the 'skc->skc_lock' held but the actual free must be performed
1008 * outside the lock to prevent deadlocking on vmem addresses.
1009 */
1010 static void
1011 spl_slab_free(spl_kmem_slab_t *sks,
1012 struct list_head *sks_list, struct list_head *sko_list)
1013 {
1014 spl_kmem_cache_t *skc;
1015 SENTRY;
1016
1017 ASSERT(sks->sks_magic == SKS_MAGIC);
1018 ASSERT(sks->sks_ref == 0);
1019
1020 skc = sks->sks_cache;
1021 ASSERT(skc->skc_magic == SKC_MAGIC);
1022 ASSERT(spin_is_locked(&skc->skc_lock));
1023
1024 /*
1025 * Update slab/objects counters in the cache, then remove the
1026 * slab from the skc->skc_partial_list. Finally add the slab
1027 * and all its objects in to the private work lists where the
1028 * destructors will be called and the memory freed to the system.
1029 */
1030 skc->skc_obj_total -= sks->sks_objs;
1031 skc->skc_slab_total--;
1032 list_del(&sks->sks_list);
1033 list_add(&sks->sks_list, sks_list);
1034 list_splice_init(&sks->sks_free_list, sko_list);
1035
1036 SEXIT;
1037 }
1038
1039 /*
1040 * Traverses all the partial slabs attached to a cache and free those
1041 * which which are currently empty, and have not been touched for
1042 * skc_delay seconds to avoid thrashing. The count argument is
1043 * passed to optionally cap the number of slabs reclaimed, a count
1044 * of zero means try and reclaim everything. When flag is set we
1045 * always free an available slab regardless of age.
1046 */
1047 static void
1048 spl_slab_reclaim(spl_kmem_cache_t *skc, int count, int flag)
1049 {
1050 spl_kmem_slab_t *sks, *m;
1051 spl_kmem_obj_t *sko, *n;
1052 LIST_HEAD(sks_list);
1053 LIST_HEAD(sko_list);
1054 uint32_t size = 0;
1055 int i = 0;
1056 SENTRY;
1057
1058 /*
1059 * Move empty slabs and objects which have not been touched in
1060 * skc_delay seconds on to private lists to be freed outside
1061 * the spin lock. This delay time is important to avoid thrashing
1062 * however when flag is set the delay will not be used.
1063 */
1064 spin_lock(&skc->skc_lock);
1065 list_for_each_entry_safe_reverse(sks,m,&skc->skc_partial_list,sks_list){
1066 /*
1067 * All empty slabs are at the end of skc->skc_partial_list,
1068 * therefore once a non-empty slab is found we can stop
1069 * scanning. Additionally, stop when reaching the target
1070 * reclaim 'count' if a non-zero threshold is given.
1071 */
1072 if ((sks->sks_ref > 0) || (count && i >= count))
1073 break;
1074
1075 if (time_after(jiffies,sks->sks_age+skc->skc_delay*HZ)||flag) {
1076 spl_slab_free(sks, &sks_list, &sko_list);
1077 i++;
1078 }
1079 }
1080 spin_unlock(&skc->skc_lock);
1081
1082 /*
1083 * The following two loops ensure all the object destructors are
1084 * run, any offslab objects are freed, and the slabs themselves
1085 * are freed. This is all done outside the skc->skc_lock since
1086 * this allows the destructor to sleep, and allows us to perform
1087 * a conditional reschedule when a freeing a large number of
1088 * objects and slabs back to the system.
1089 */
1090 if (skc->skc_flags & KMC_OFFSLAB)
1091 size = spl_offslab_size(skc);
1092
1093 list_for_each_entry_safe(sko, n, &sko_list, sko_list) {
1094 ASSERT(sko->sko_magic == SKO_MAGIC);
1095
1096 if (skc->skc_dtor)
1097 skc->skc_dtor(sko->sko_addr, skc->skc_private);
1098
1099 if (skc->skc_flags & KMC_OFFSLAB)
1100 kv_free(skc, sko->sko_addr, size);
1101
1102 cond_resched();
1103 }
1104
1105 list_for_each_entry_safe(sks, m, &sks_list, sks_list) {
1106 ASSERT(sks->sks_magic == SKS_MAGIC);
1107 kv_free(skc, sks, skc->skc_slab_size);
1108 cond_resched();
1109 }
1110
1111 SEXIT;
1112 }
1113
1114 static spl_kmem_emergency_t *
1115 spl_emergency_search(struct rb_root *root, void *obj)
1116 {
1117 struct rb_node *node = root->rb_node;
1118 spl_kmem_emergency_t *ske;
1119 unsigned long address = (unsigned long)obj;
1120
1121 while (node) {
1122 ske = container_of(node, spl_kmem_emergency_t, ske_node);
1123
1124 if (address < (unsigned long)ske->ske_obj)
1125 node = node->rb_left;
1126 else if (address > (unsigned long)ske->ske_obj)
1127 node = node->rb_right;
1128 else
1129 return ske;
1130 }
1131
1132 return NULL;
1133 }
1134
1135 static int
1136 spl_emergency_insert(struct rb_root *root, spl_kmem_emergency_t *ske)
1137 {
1138 struct rb_node **new = &(root->rb_node), *parent = NULL;
1139 spl_kmem_emergency_t *ske_tmp;
1140 unsigned long address = (unsigned long)ske->ske_obj;
1141
1142 while (*new) {
1143 ske_tmp = container_of(*new, spl_kmem_emergency_t, ske_node);
1144
1145 parent = *new;
1146 if (address < (unsigned long)ske_tmp->ske_obj)
1147 new = &((*new)->rb_left);
1148 else if (address > (unsigned long)ske_tmp->ske_obj)
1149 new = &((*new)->rb_right);
1150 else
1151 return 0;
1152 }
1153
1154 rb_link_node(&ske->ske_node, parent, new);
1155 rb_insert_color(&ske->ske_node, root);
1156
1157 return 1;
1158 }
1159
1160 /*
1161 * Allocate a single emergency object and track it in a red black tree.
1162 */
1163 static int
1164 spl_emergency_alloc(spl_kmem_cache_t *skc, int flags, void **obj)
1165 {
1166 spl_kmem_emergency_t *ske;
1167 int empty;
1168 SENTRY;
1169
1170 /* Last chance use a partial slab if one now exists */
1171 spin_lock(&skc->skc_lock);
1172 empty = list_empty(&skc->skc_partial_list);
1173 spin_unlock(&skc->skc_lock);
1174 if (!empty)
1175 SRETURN(-EEXIST);
1176
1177 ske = kmalloc(sizeof(*ske), flags);
1178 if (ske == NULL)
1179 SRETURN(-ENOMEM);
1180
1181 ske->ske_obj = kmalloc(skc->skc_obj_size, flags);
1182 if (ske->ske_obj == NULL) {
1183 kfree(ske);
1184 SRETURN(-ENOMEM);
1185 }
1186
1187 spin_lock(&skc->skc_lock);
1188 empty = spl_emergency_insert(&skc->skc_emergency_tree, ske);
1189 if (likely(empty)) {
1190 skc->skc_obj_total++;
1191 skc->skc_obj_emergency++;
1192 if (skc->skc_obj_emergency > skc->skc_obj_emergency_max)
1193 skc->skc_obj_emergency_max = skc->skc_obj_emergency;
1194 }
1195 spin_unlock(&skc->skc_lock);
1196
1197 if (unlikely(!empty)) {
1198 kfree(ske->ske_obj);
1199 kfree(ske);
1200 SRETURN(-EINVAL);
1201 }
1202
1203 if (skc->skc_ctor)
1204 skc->skc_ctor(ske->ske_obj, skc->skc_private, flags);
1205
1206 *obj = ske->ske_obj;
1207
1208 SRETURN(0);
1209 }
1210
1211 /*
1212 * Locate the passed object in the red black tree and free it.
1213 */
1214 static int
1215 spl_emergency_free(spl_kmem_cache_t *skc, void *obj)
1216 {
1217 spl_kmem_emergency_t *ske;
1218 SENTRY;
1219
1220 spin_lock(&skc->skc_lock);
1221 ske = spl_emergency_search(&skc->skc_emergency_tree, obj);
1222 if (likely(ske)) {
1223 rb_erase(&ske->ske_node, &skc->skc_emergency_tree);
1224 skc->skc_obj_emergency--;
1225 skc->skc_obj_total--;
1226 }
1227 spin_unlock(&skc->skc_lock);
1228
1229 if (unlikely(ske == NULL))
1230 SRETURN(-ENOENT);
1231
1232 if (skc->skc_dtor)
1233 skc->skc_dtor(ske->ske_obj, skc->skc_private);
1234
1235 kfree(ske->ske_obj);
1236 kfree(ske);
1237
1238 SRETURN(0);
1239 }
1240
1241 /*
1242 * Release objects from the per-cpu magazine back to their slab. The flush
1243 * argument contains the max number of entries to remove from the magazine.
1244 */
1245 static void
1246 __spl_cache_flush(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flush)
1247 {
1248 int i, count = MIN(flush, skm->skm_avail);
1249 SENTRY;
1250
1251 ASSERT(skc->skc_magic == SKC_MAGIC);
1252 ASSERT(skm->skm_magic == SKM_MAGIC);
1253 ASSERT(spin_is_locked(&skc->skc_lock));
1254
1255 for (i = 0; i < count; i++)
1256 spl_cache_shrink(skc, skm->skm_objs[i]);
1257
1258 skm->skm_avail -= count;
1259 memmove(skm->skm_objs, &(skm->skm_objs[count]),
1260 sizeof(void *) * skm->skm_avail);
1261
1262 SEXIT;
1263 }
1264
1265 static void
1266 spl_cache_flush(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flush)
1267 {
1268 spin_lock(&skc->skc_lock);
1269 __spl_cache_flush(skc, skm, flush);
1270 spin_unlock(&skc->skc_lock);
1271 }
1272
1273 static void
1274 spl_magazine_age(void *data)
1275 {
1276 spl_kmem_cache_t *skc = (spl_kmem_cache_t *)data;
1277 spl_kmem_magazine_t *skm = skc->skc_mag[smp_processor_id()];
1278
1279 ASSERT(skm->skm_magic == SKM_MAGIC);
1280 ASSERT(skm->skm_cpu == smp_processor_id());
1281 ASSERT(irqs_disabled());
1282
1283 /* There are no available objects or they are too young to age out */
1284 if ((skm->skm_avail == 0) ||
1285 time_before(jiffies, skm->skm_age + skc->skc_delay * HZ))
1286 return;
1287
1288 /*
1289 * Because we're executing in interrupt context we may have
1290 * interrupted the holder of this lock. To avoid a potential
1291 * deadlock return if the lock is contended.
1292 */
1293 if (!spin_trylock(&skc->skc_lock))
1294 return;
1295
1296 __spl_cache_flush(skc, skm, skm->skm_refill);
1297 spin_unlock(&skc->skc_lock);
1298 }
1299
1300 /*
1301 * Called regularly to keep a downward pressure on the cache.
1302 *
1303 * Objects older than skc->skc_delay seconds in the per-cpu magazines will
1304 * be returned to the caches. This is done to prevent idle magazines from
1305 * holding memory which could be better used elsewhere. The delay is
1306 * present to prevent thrashing the magazine.
1307 *
1308 * The newly released objects may result in empty partial slabs. Those
1309 * slabs should be released to the system. Otherwise moving the objects
1310 * out of the magazines is just wasted work.
1311 */
1312 static void
1313 spl_cache_age(void *data)
1314 {
1315 spl_kmem_cache_t *skc = (spl_kmem_cache_t *)data;
1316 taskqid_t id = 0;
1317
1318 ASSERT(skc->skc_magic == SKC_MAGIC);
1319
1320 atomic_inc(&skc->skc_ref);
1321 spl_on_each_cpu(spl_magazine_age, skc, 1);
1322 spl_slab_reclaim(skc, skc->skc_reap, 0);
1323
1324 while (!test_bit(KMC_BIT_DESTROY, &skc->skc_flags) && !id) {
1325 id = taskq_dispatch_delay(
1326 spl_kmem_cache_taskq, spl_cache_age, skc, TQ_SLEEP,
1327 ddi_get_lbolt() + skc->skc_delay / 3 * HZ);
1328
1329 /* Destroy issued after dispatch immediately cancel it */
1330 if (test_bit(KMC_BIT_DESTROY, &skc->skc_flags) && id)
1331 taskq_cancel_id(spl_kmem_cache_taskq, id);
1332 }
1333
1334 spin_lock(&skc->skc_lock);
1335 skc->skc_taskqid = id;
1336 spin_unlock(&skc->skc_lock);
1337
1338 atomic_dec(&skc->skc_ref);
1339 }
1340
1341 /*
1342 * Size a slab based on the size of each aligned object plus spl_kmem_obj_t.
1343 * When on-slab we want to target SPL_KMEM_CACHE_OBJ_PER_SLAB. However,
1344 * for very small objects we may end up with more than this so as not
1345 * to waste space in the minimal allocation of a single page. Also for
1346 * very large objects we may use as few as SPL_KMEM_CACHE_OBJ_PER_SLAB_MIN,
1347 * lower than this and we will fail.
1348 */
1349 static int
1350 spl_slab_size(spl_kmem_cache_t *skc, uint32_t *objs, uint32_t *size)
1351 {
1352 uint32_t sks_size, obj_size, max_size;
1353
1354 if (skc->skc_flags & KMC_OFFSLAB) {
1355 *objs = SPL_KMEM_CACHE_OBJ_PER_SLAB;
1356 *size = sizeof(spl_kmem_slab_t);
1357 } else {
1358 sks_size = spl_sks_size(skc);
1359 obj_size = spl_obj_size(skc);
1360
1361 if (skc->skc_flags & KMC_KMEM)
1362 max_size = ((uint32_t)1 << (MAX_ORDER-3)) * PAGE_SIZE;
1363 else
1364 max_size = (32 * 1024 * 1024);
1365
1366 /* Power of two sized slab */
1367 for (*size = PAGE_SIZE; *size <= max_size; *size *= 2) {
1368 *objs = (*size - sks_size) / obj_size;
1369 if (*objs >= SPL_KMEM_CACHE_OBJ_PER_SLAB)
1370 SRETURN(0);
1371 }
1372
1373 /*
1374 * Unable to satisfy target objects per slab, fall back to
1375 * allocating a maximally sized slab and assuming it can
1376 * contain the minimum objects count use it. If not fail.
1377 */
1378 *size = max_size;
1379 *objs = (*size - sks_size) / obj_size;
1380 if (*objs >= SPL_KMEM_CACHE_OBJ_PER_SLAB_MIN)
1381 SRETURN(0);
1382 }
1383
1384 SRETURN(-ENOSPC);
1385 }
1386
1387 /*
1388 * Make a guess at reasonable per-cpu magazine size based on the size of
1389 * each object and the cost of caching N of them in each magazine. Long
1390 * term this should really adapt based on an observed usage heuristic.
1391 */
1392 static int
1393 spl_magazine_size(spl_kmem_cache_t *skc)
1394 {
1395 uint32_t obj_size = spl_obj_size(skc);
1396 int size;
1397 SENTRY;
1398
1399 /* Per-magazine sizes below assume a 4Kib page size */
1400 if (obj_size > (PAGE_SIZE * 256))
1401 size = 4; /* Minimum 4Mib per-magazine */
1402 else if (obj_size > (PAGE_SIZE * 32))
1403 size = 16; /* Minimum 2Mib per-magazine */
1404 else if (obj_size > (PAGE_SIZE))
1405 size = 64; /* Minimum 256Kib per-magazine */
1406 else if (obj_size > (PAGE_SIZE / 4))
1407 size = 128; /* Minimum 128Kib per-magazine */
1408 else
1409 size = 256;
1410
1411 SRETURN(size);
1412 }
1413
1414 /*
1415 * Allocate a per-cpu magazine to associate with a specific core.
1416 */
1417 static spl_kmem_magazine_t *
1418 spl_magazine_alloc(spl_kmem_cache_t *skc, int cpu)
1419 {
1420 spl_kmem_magazine_t *skm;
1421 int size = sizeof(spl_kmem_magazine_t) +
1422 sizeof(void *) * skc->skc_mag_size;
1423 SENTRY;
1424
1425 skm = kmem_alloc_node(size, KM_SLEEP, cpu_to_node(cpu));
1426 if (skm) {
1427 skm->skm_magic = SKM_MAGIC;
1428 skm->skm_avail = 0;
1429 skm->skm_size = skc->skc_mag_size;
1430 skm->skm_refill = skc->skc_mag_refill;
1431 skm->skm_cache = skc;
1432 skm->skm_age = jiffies;
1433 skm->skm_cpu = cpu;
1434 }
1435
1436 SRETURN(skm);
1437 }
1438
1439 /*
1440 * Free a per-cpu magazine associated with a specific core.
1441 */
1442 static void
1443 spl_magazine_free(spl_kmem_magazine_t *skm)
1444 {
1445 int size = sizeof(spl_kmem_magazine_t) +
1446 sizeof(void *) * skm->skm_size;
1447
1448 SENTRY;
1449 ASSERT(skm->skm_magic == SKM_MAGIC);
1450 ASSERT(skm->skm_avail == 0);
1451
1452 kmem_free(skm, size);
1453 SEXIT;
1454 }
1455
1456 /*
1457 * Create all pre-cpu magazines of reasonable sizes.
1458 */
1459 static int
1460 spl_magazine_create(spl_kmem_cache_t *skc)
1461 {
1462 int i;
1463 SENTRY;
1464
1465 skc->skc_mag_size = spl_magazine_size(skc);
1466 skc->skc_mag_refill = (skc->skc_mag_size + 1) / 2;
1467
1468 for_each_online_cpu(i) {
1469 skc->skc_mag[i] = spl_magazine_alloc(skc, i);
1470 if (!skc->skc_mag[i]) {
1471 for (i--; i >= 0; i--)
1472 spl_magazine_free(skc->skc_mag[i]);
1473
1474 SRETURN(-ENOMEM);
1475 }
1476 }
1477
1478 SRETURN(0);
1479 }
1480
1481 /*
1482 * Destroy all pre-cpu magazines.
1483 */
1484 static void
1485 spl_magazine_destroy(spl_kmem_cache_t *skc)
1486 {
1487 spl_kmem_magazine_t *skm;
1488 int i;
1489 SENTRY;
1490
1491 for_each_online_cpu(i) {
1492 skm = skc->skc_mag[i];
1493 spl_cache_flush(skc, skm, skm->skm_avail);
1494 spl_magazine_free(skm);
1495 }
1496
1497 SEXIT;
1498 }
1499
1500 /*
1501 * Create a object cache based on the following arguments:
1502 * name cache name
1503 * size cache object size
1504 * align cache object alignment
1505 * ctor cache object constructor
1506 * dtor cache object destructor
1507 * reclaim cache object reclaim
1508 * priv cache private data for ctor/dtor/reclaim
1509 * vmp unused must be NULL
1510 * flags
1511 * KMC_NOTOUCH Disable cache object aging (unsupported)
1512 * KMC_NODEBUG Disable debugging (unsupported)
1513 * KMC_NOMAGAZINE Disable magazine (unsupported)
1514 * KMC_NOHASH Disable hashing (unsupported)
1515 * KMC_QCACHE Disable qcache (unsupported)
1516 * KMC_KMEM Force kmem backed cache
1517 * KMC_VMEM Force vmem backed cache
1518 * KMC_OFFSLAB Locate objects off the slab
1519 */
1520 spl_kmem_cache_t *
1521 spl_kmem_cache_create(char *name, size_t size, size_t align,
1522 spl_kmem_ctor_t ctor,
1523 spl_kmem_dtor_t dtor,
1524 spl_kmem_reclaim_t reclaim,
1525 void *priv, void *vmp, int flags)
1526 {
1527 spl_kmem_cache_t *skc;
1528 int rc;
1529 SENTRY;
1530
1531 ASSERTF(!(flags & KMC_NOMAGAZINE), "Bad KMC_NOMAGAZINE (%x)\n", flags);
1532 ASSERTF(!(flags & KMC_NOHASH), "Bad KMC_NOHASH (%x)\n", flags);
1533 ASSERTF(!(flags & KMC_QCACHE), "Bad KMC_QCACHE (%x)\n", flags);
1534 ASSERT(vmp == NULL);
1535
1536 might_sleep();
1537
1538 /*
1539 * Allocate memory for a new cache an initialize it. Unfortunately,
1540 * this usually ends up being a large allocation of ~32k because
1541 * we need to allocate enough memory for the worst case number of
1542 * cpus in the magazine, skc_mag[NR_CPUS]. Because of this we
1543 * explicitly pass KM_NODEBUG to suppress the kmem warning
1544 */
1545 skc = kmem_zalloc(sizeof(*skc), KM_SLEEP| KM_NODEBUG);
1546 if (skc == NULL)
1547 SRETURN(NULL);
1548
1549 skc->skc_magic = SKC_MAGIC;
1550 skc->skc_name_size = strlen(name) + 1;
1551 skc->skc_name = (char *)kmem_alloc(skc->skc_name_size, KM_SLEEP);
1552 if (skc->skc_name == NULL) {
1553 kmem_free(skc, sizeof(*skc));
1554 SRETURN(NULL);
1555 }
1556 strncpy(skc->skc_name, name, skc->skc_name_size);
1557
1558 skc->skc_ctor = ctor;
1559 skc->skc_dtor = dtor;
1560 skc->skc_reclaim = reclaim;
1561 skc->skc_private = priv;
1562 skc->skc_vmp = vmp;
1563 skc->skc_flags = flags;
1564 skc->skc_obj_size = size;
1565 skc->skc_obj_align = SPL_KMEM_CACHE_ALIGN;
1566 skc->skc_delay = SPL_KMEM_CACHE_DELAY;
1567 skc->skc_reap = SPL_KMEM_CACHE_REAP;
1568 atomic_set(&skc->skc_ref, 0);
1569
1570 INIT_LIST_HEAD(&skc->skc_list);
1571 INIT_LIST_HEAD(&skc->skc_complete_list);
1572 INIT_LIST_HEAD(&skc->skc_partial_list);
1573 skc->skc_emergency_tree = RB_ROOT;
1574 spin_lock_init(&skc->skc_lock);
1575 init_waitqueue_head(&skc->skc_waitq);
1576 skc->skc_slab_fail = 0;
1577 skc->skc_slab_create = 0;
1578 skc->skc_slab_destroy = 0;
1579 skc->skc_slab_total = 0;
1580 skc->skc_slab_alloc = 0;
1581 skc->skc_slab_max = 0;
1582 skc->skc_obj_total = 0;
1583 skc->skc_obj_alloc = 0;
1584 skc->skc_obj_max = 0;
1585 skc->skc_obj_deadlock = 0;
1586 skc->skc_obj_emergency = 0;
1587 skc->skc_obj_emergency_max = 0;
1588
1589 if (align) {
1590 VERIFY(ISP2(align));
1591 VERIFY3U(align, >=, SPL_KMEM_CACHE_ALIGN); /* Min alignment */
1592 VERIFY3U(align, <=, PAGE_SIZE); /* Max alignment */
1593 skc->skc_obj_align = align;
1594 }
1595
1596 /* If none passed select a cache type based on object size */
1597 if (!(skc->skc_flags & (KMC_KMEM | KMC_VMEM))) {
1598 if (spl_obj_size(skc) < (PAGE_SIZE / 8))
1599 skc->skc_flags |= KMC_KMEM;
1600 else
1601 skc->skc_flags |= KMC_VMEM;
1602 }
1603
1604 rc = spl_slab_size(skc, &skc->skc_slab_objs, &skc->skc_slab_size);
1605 if (rc)
1606 SGOTO(out, rc);
1607
1608 rc = spl_magazine_create(skc);
1609 if (rc)
1610 SGOTO(out, rc);
1611
1612 skc->skc_taskqid = taskq_dispatch_delay(spl_kmem_cache_taskq,
1613 spl_cache_age, skc, TQ_SLEEP,
1614 ddi_get_lbolt() + skc->skc_delay / 3 * HZ);
1615
1616 down_write(&spl_kmem_cache_sem);
1617 list_add_tail(&skc->skc_list, &spl_kmem_cache_list);
1618 up_write(&spl_kmem_cache_sem);
1619
1620 SRETURN(skc);
1621 out:
1622 kmem_free(skc->skc_name, skc->skc_name_size);
1623 kmem_free(skc, sizeof(*skc));
1624 SRETURN(NULL);
1625 }
1626 EXPORT_SYMBOL(spl_kmem_cache_create);
1627
1628 /*
1629 * Register a move callback to for cache defragmentation.
1630 * XXX: Unimplemented but harmless to stub out for now.
1631 */
1632 void
1633 spl_kmem_cache_set_move(spl_kmem_cache_t *skc,
1634 kmem_cbrc_t (move)(void *, void *, size_t, void *))
1635 {
1636 ASSERT(move != NULL);
1637 }
1638 EXPORT_SYMBOL(spl_kmem_cache_set_move);
1639
1640 /*
1641 * Destroy a cache and all objects associated with the cache.
1642 */
1643 void
1644 spl_kmem_cache_destroy(spl_kmem_cache_t *skc)
1645 {
1646 DECLARE_WAIT_QUEUE_HEAD(wq);
1647 taskqid_t id;
1648 SENTRY;
1649
1650 ASSERT(skc->skc_magic == SKC_MAGIC);
1651
1652 down_write(&spl_kmem_cache_sem);
1653 list_del_init(&skc->skc_list);
1654 up_write(&spl_kmem_cache_sem);
1655
1656 /* Cancel any and wait for any pending delayed tasks */
1657 VERIFY(!test_and_set_bit(KMC_BIT_DESTROY, &skc->skc_flags));
1658
1659 spin_lock(&skc->skc_lock);
1660 id = skc->skc_taskqid;
1661 spin_unlock(&skc->skc_lock);
1662
1663 taskq_cancel_id(spl_kmem_cache_taskq, id);
1664
1665 /* Wait until all current callers complete, this is mainly
1666 * to catch the case where a low memory situation triggers a
1667 * cache reaping action which races with this destroy. */
1668 wait_event(wq, atomic_read(&skc->skc_ref) == 0);
1669
1670 spl_magazine_destroy(skc);
1671 spl_slab_reclaim(skc, 0, 1);
1672 spin_lock(&skc->skc_lock);
1673
1674 /* Validate there are no objects in use and free all the
1675 * spl_kmem_slab_t, spl_kmem_obj_t, and object buffers. */
1676 ASSERT3U(skc->skc_slab_alloc, ==, 0);
1677 ASSERT3U(skc->skc_obj_alloc, ==, 0);
1678 ASSERT3U(skc->skc_slab_total, ==, 0);
1679 ASSERT3U(skc->skc_obj_total, ==, 0);
1680 ASSERT3U(skc->skc_obj_emergency, ==, 0);
1681 ASSERT(list_empty(&skc->skc_complete_list));
1682
1683 kmem_free(skc->skc_name, skc->skc_name_size);
1684 spin_unlock(&skc->skc_lock);
1685
1686 kmem_free(skc, sizeof(*skc));
1687
1688 SEXIT;
1689 }
1690 EXPORT_SYMBOL(spl_kmem_cache_destroy);
1691
1692 /*
1693 * Allocate an object from a slab attached to the cache. This is used to
1694 * repopulate the per-cpu magazine caches in batches when they run low.
1695 */
1696 static void *
1697 spl_cache_obj(spl_kmem_cache_t *skc, spl_kmem_slab_t *sks)
1698 {
1699 spl_kmem_obj_t *sko;
1700
1701 ASSERT(skc->skc_magic == SKC_MAGIC);
1702 ASSERT(sks->sks_magic == SKS_MAGIC);
1703 ASSERT(spin_is_locked(&skc->skc_lock));
1704
1705 sko = list_entry(sks->sks_free_list.next, spl_kmem_obj_t, sko_list);
1706 ASSERT(sko->sko_magic == SKO_MAGIC);
1707 ASSERT(sko->sko_addr != NULL);
1708
1709 /* Remove from sks_free_list */
1710 list_del_init(&sko->sko_list);
1711
1712 sks->sks_age = jiffies;
1713 sks->sks_ref++;
1714 skc->skc_obj_alloc++;
1715
1716 /* Track max obj usage statistics */
1717 if (skc->skc_obj_alloc > skc->skc_obj_max)
1718 skc->skc_obj_max = skc->skc_obj_alloc;
1719
1720 /* Track max slab usage statistics */
1721 if (sks->sks_ref == 1) {
1722 skc->skc_slab_alloc++;
1723
1724 if (skc->skc_slab_alloc > skc->skc_slab_max)
1725 skc->skc_slab_max = skc->skc_slab_alloc;
1726 }
1727
1728 return sko->sko_addr;
1729 }
1730
1731 /*
1732 * Generic slab allocation function to run by the global work queues.
1733 * It is responsible for allocating a new slab, linking it in to the list
1734 * of partial slabs, and then waking any waiters.
1735 */
1736 static void
1737 spl_cache_grow_work(void *data)
1738 {
1739 spl_kmem_alloc_t *ska = (spl_kmem_alloc_t *)data;
1740 spl_kmem_cache_t *skc = ska->ska_cache;
1741 spl_kmem_slab_t *sks;
1742
1743 sks = spl_slab_alloc(skc, ska->ska_flags | __GFP_NORETRY | KM_NODEBUG);
1744 spin_lock(&skc->skc_lock);
1745 if (sks) {
1746 skc->skc_slab_total++;
1747 skc->skc_obj_total += sks->sks_objs;
1748 list_add_tail(&sks->sks_list, &skc->skc_partial_list);
1749 }
1750
1751 atomic_dec(&skc->skc_ref);
1752 clear_bit(KMC_BIT_GROWING, &skc->skc_flags);
1753 clear_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags);
1754 wake_up_all(&skc->skc_waitq);
1755 spin_unlock(&skc->skc_lock);
1756
1757 kfree(ska);
1758 }
1759
1760 /*
1761 * Returns non-zero when a new slab should be available.
1762 */
1763 static int
1764 spl_cache_grow_wait(spl_kmem_cache_t *skc)
1765 {
1766 return !test_bit(KMC_BIT_GROWING, &skc->skc_flags);
1767 }
1768
1769 static int
1770 spl_cache_reclaim_wait(void *word)
1771 {
1772 schedule();
1773 return 0;
1774 }
1775
1776 /*
1777 * No available objects on any slabs, create a new slab.
1778 */
1779 static int
1780 spl_cache_grow(spl_kmem_cache_t *skc, int flags, void **obj)
1781 {
1782 int remaining, rc;
1783 SENTRY;
1784
1785 ASSERT(skc->skc_magic == SKC_MAGIC);
1786 might_sleep();
1787 *obj = NULL;
1788
1789 /*
1790 * Before allocating a new slab wait for any reaping to complete and
1791 * then return so the local magazine can be rechecked for new objects.
1792 */
1793 if (test_bit(KMC_BIT_REAPING, &skc->skc_flags)) {
1794 rc = wait_on_bit(&skc->skc_flags, KMC_BIT_REAPING,
1795 spl_cache_reclaim_wait, TASK_UNINTERRUPTIBLE);
1796 SRETURN(rc ? rc : -EAGAIN);
1797 }
1798
1799 /*
1800 * This is handled by dispatching a work request to the global work
1801 * queue. This allows us to asynchronously allocate a new slab while
1802 * retaining the ability to safely fall back to a smaller synchronous
1803 * allocations to ensure forward progress is always maintained.
1804 */
1805 if (test_and_set_bit(KMC_BIT_GROWING, &skc->skc_flags) == 0) {
1806 spl_kmem_alloc_t *ska;
1807
1808 ska = kmalloc(sizeof(*ska), flags);
1809 if (ska == NULL) {
1810 clear_bit(KMC_BIT_GROWING, &skc->skc_flags);
1811 wake_up_all(&skc->skc_waitq);
1812 SRETURN(-ENOMEM);
1813 }
1814
1815 atomic_inc(&skc->skc_ref);
1816 ska->ska_cache = skc;
1817 ska->ska_flags = flags & ~__GFP_FS;
1818 taskq_init_ent(&ska->ska_tqe);
1819 taskq_dispatch_ent(spl_kmem_cache_taskq,
1820 spl_cache_grow_work, ska, 0, &ska->ska_tqe);
1821 }
1822
1823 /*
1824 * The goal here is to only detect the rare case where a virtual slab
1825 * allocation has deadlocked. We must be careful to minimize the use
1826 * of emergency objects which are more expensive to track. Therefore,
1827 * we set a very long timeout for the asynchronous allocation and if
1828 * the timeout is reached the cache is flagged as deadlocked. From
1829 * this point only new emergency objects will be allocated until the
1830 * asynchronous allocation completes and clears the deadlocked flag.
1831 */
1832 if (test_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags)) {
1833 rc = spl_emergency_alloc(skc, flags, obj);
1834 } else {
1835 remaining = wait_event_timeout(skc->skc_waitq,
1836 spl_cache_grow_wait(skc), HZ);
1837
1838 if (!remaining && test_bit(KMC_BIT_VMEM, &skc->skc_flags)) {
1839 spin_lock(&skc->skc_lock);
1840 if (test_bit(KMC_BIT_GROWING, &skc->skc_flags)) {
1841 set_bit(KMC_BIT_DEADLOCKED, &skc->skc_flags);
1842 skc->skc_obj_deadlock++;
1843 }
1844 spin_unlock(&skc->skc_lock);
1845 }
1846
1847 rc = -ENOMEM;
1848 }
1849
1850 SRETURN(rc);
1851 }
1852
1853 /*
1854 * Refill a per-cpu magazine with objects from the slabs for this cache.
1855 * Ideally the magazine can be repopulated using existing objects which have
1856 * been released, however if we are unable to locate enough free objects new
1857 * slabs of objects will be created. On success NULL is returned, otherwise
1858 * the address of a single emergency object is returned for use by the caller.
1859 */
1860 static void *
1861 spl_cache_refill(spl_kmem_cache_t *skc, spl_kmem_magazine_t *skm, int flags)
1862 {
1863 spl_kmem_slab_t *sks;
1864 int count = 0, rc, refill;
1865 void *obj = NULL;
1866 SENTRY;
1867
1868 ASSERT(skc->skc_magic == SKC_MAGIC);
1869 ASSERT(skm->skm_magic == SKM_MAGIC);
1870
1871 refill = MIN(skm->skm_refill, skm->skm_size - skm->skm_avail);
1872 spin_lock(&skc->skc_lock);
1873
1874 while (refill > 0) {
1875 /* No slabs available we may need to grow the cache */
1876 if (list_empty(&skc->skc_partial_list)) {
1877 spin_unlock(&skc->skc_lock);
1878
1879 local_irq_enable();
1880 rc = spl_cache_grow(skc, flags, &obj);
1881 local_irq_disable();
1882
1883 /* Emergency object for immediate use by caller */
1884 if (rc == 0 && obj != NULL)
1885 SRETURN(obj);
1886
1887 if (rc)
1888 SGOTO(out, rc);
1889
1890 /* Rescheduled to different CPU skm is not local */
1891 if (skm != skc->skc_mag[smp_processor_id()])
1892 SGOTO(out, rc);
1893
1894 /* Potentially rescheduled to the same CPU but
1895 * allocations may have occurred from this CPU while
1896 * we were sleeping so recalculate max refill. */
1897 refill = MIN(refill, skm->skm_size - skm->skm_avail);
1898
1899 spin_lock(&skc->skc_lock);
1900 continue;
1901 }
1902
1903 /* Grab the next available slab */
1904 sks = list_entry((&skc->skc_partial_list)->next,
1905 spl_kmem_slab_t, sks_list);
1906 ASSERT(sks->sks_magic == SKS_MAGIC);
1907 ASSERT(sks->sks_ref < sks->sks_objs);
1908 ASSERT(!list_empty(&sks->sks_free_list));
1909
1910 /* Consume as many objects as needed to refill the requested
1911 * cache. We must also be careful not to overfill it. */
1912 while (sks->sks_ref < sks->sks_objs && refill-- > 0 && ++count) {
1913 ASSERT(skm->skm_avail < skm->skm_size);
1914 ASSERT(count < skm->skm_size);
1915 skm->skm_objs[skm->skm_avail++]=spl_cache_obj(skc,sks);
1916 }
1917
1918 /* Move slab to skc_complete_list when full */
1919 if (sks->sks_ref == sks->sks_objs) {
1920 list_del(&sks->sks_list);
1921 list_add(&sks->sks_list, &skc->skc_complete_list);
1922 }
1923 }
1924
1925 spin_unlock(&skc->skc_lock);
1926 out:
1927 SRETURN(NULL);
1928 }
1929
1930 /*
1931 * Release an object back to the slab from which it came.
1932 */
1933 static void
1934 spl_cache_shrink(spl_kmem_cache_t *skc, void *obj)
1935 {
1936 spl_kmem_slab_t *sks = NULL;
1937 spl_kmem_obj_t *sko = NULL;
1938 SENTRY;
1939
1940 ASSERT(skc->skc_magic == SKC_MAGIC);
1941 ASSERT(spin_is_locked(&skc->skc_lock));
1942
1943 sko = spl_sko_from_obj(skc, obj);
1944 ASSERT(sko->sko_magic == SKO_MAGIC);
1945 sks = sko->sko_slab;
1946 ASSERT(sks->sks_magic == SKS_MAGIC);
1947 ASSERT(sks->sks_cache == skc);
1948 list_add(&sko->sko_list, &sks->sks_free_list);
1949
1950 sks->sks_age = jiffies;
1951 sks->sks_ref--;
1952 skc->skc_obj_alloc--;
1953
1954 /* Move slab to skc_partial_list when no longer full. Slabs
1955 * are added to the head to keep the partial list is quasi-full
1956 * sorted order. Fuller at the head, emptier at the tail. */
1957 if (sks->sks_ref == (sks->sks_objs - 1)) {
1958 list_del(&sks->sks_list);
1959 list_add(&sks->sks_list, &skc->skc_partial_list);
1960 }
1961
1962 /* Move empty slabs to the end of the partial list so
1963 * they can be easily found and freed during reclamation. */
1964 if (sks->sks_ref == 0) {
1965 list_del(&sks->sks_list);
1966 list_add_tail(&sks->sks_list, &skc->skc_partial_list);
1967 skc->skc_slab_alloc--;
1968 }
1969
1970 SEXIT;
1971 }
1972
1973 /*
1974 * Allocate an object from the per-cpu magazine, or if the magazine
1975 * is empty directly allocate from a slab and repopulate the magazine.
1976 */
1977 void *
1978 spl_kmem_cache_alloc(spl_kmem_cache_t *skc, int flags)
1979 {
1980 spl_kmem_magazine_t *skm;
1981 unsigned long irq_flags;
1982 void *obj = NULL;
1983 SENTRY;
1984
1985 ASSERT(skc->skc_magic == SKC_MAGIC);
1986 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
1987 ASSERT(flags & KM_SLEEP);
1988 atomic_inc(&skc->skc_ref);
1989 local_irq_save(irq_flags);
1990
1991 restart:
1992 /* Safe to update per-cpu structure without lock, but
1993 * in the restart case we must be careful to reacquire
1994 * the local magazine since this may have changed
1995 * when we need to grow the cache. */
1996 skm = skc->skc_mag[smp_processor_id()];
1997 ASSERTF(skm->skm_magic == SKM_MAGIC, "%x != %x: %s/%p/%p %x/%x/%x\n",
1998 skm->skm_magic, SKM_MAGIC, skc->skc_name, skc, skm,
1999 skm->skm_size, skm->skm_refill, skm->skm_avail);
2000
2001 if (likely(skm->skm_avail)) {
2002 /* Object available in CPU cache, use it */
2003 obj = skm->skm_objs[--skm->skm_avail];
2004 skm->skm_age = jiffies;
2005 } else {
2006 obj = spl_cache_refill(skc, skm, flags);
2007 if (obj == NULL)
2008 SGOTO(restart, obj = NULL);
2009 }
2010
2011 local_irq_restore(irq_flags);
2012 ASSERT(obj);
2013 ASSERT(IS_P2ALIGNED(obj, skc->skc_obj_align));
2014
2015 /* Pre-emptively migrate object to CPU L1 cache */
2016 prefetchw(obj);
2017 atomic_dec(&skc->skc_ref);
2018
2019 SRETURN(obj);
2020 }
2021 EXPORT_SYMBOL(spl_kmem_cache_alloc);
2022
2023 /*
2024 * Free an object back to the local per-cpu magazine, there is no
2025 * guarantee that this is the same magazine the object was originally
2026 * allocated from. We may need to flush entire from the magazine
2027 * back to the slabs to make space.
2028 */
2029 void
2030 spl_kmem_cache_free(spl_kmem_cache_t *skc, void *obj)
2031 {
2032 spl_kmem_magazine_t *skm;
2033 unsigned long flags;
2034 SENTRY;
2035
2036 ASSERT(skc->skc_magic == SKC_MAGIC);
2037 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
2038 atomic_inc(&skc->skc_ref);
2039
2040 /*
2041 * Only virtual slabs may have emergency objects and these objects
2042 * are guaranteed to have physical addresses. They must be removed
2043 * from the tree of emergency objects and the freed.
2044 */
2045 if ((skc->skc_flags & KMC_VMEM) && !kmem_virt(obj))
2046 SGOTO(out, spl_emergency_free(skc, obj));
2047
2048 local_irq_save(flags);
2049
2050 /* Safe to update per-cpu structure without lock, but
2051 * no remote memory allocation tracking is being performed
2052 * it is entirely possible to allocate an object from one
2053 * CPU cache and return it to another. */
2054 skm = skc->skc_mag[smp_processor_id()];
2055 ASSERT(skm->skm_magic == SKM_MAGIC);
2056
2057 /* Per-CPU cache full, flush it to make space */
2058 if (unlikely(skm->skm_avail >= skm->skm_size))
2059 spl_cache_flush(skc, skm, skm->skm_refill);
2060
2061 /* Available space in cache, use it */
2062 skm->skm_objs[skm->skm_avail++] = obj;
2063
2064 local_irq_restore(flags);
2065 out:
2066 atomic_dec(&skc->skc_ref);
2067
2068 SEXIT;
2069 }
2070 EXPORT_SYMBOL(spl_kmem_cache_free);
2071
2072 /*
2073 * The generic shrinker function for all caches. Under Linux a shrinker
2074 * may not be tightly coupled with a slab cache. In fact Linux always
2075 * systematically tries calling all registered shrinker callbacks which
2076 * report that they contain unused objects. Because of this we only
2077 * register one shrinker function in the shim layer for all slab caches.
2078 * We always attempt to shrink all caches when this generic shrinker
2079 * is called. The shrinker should return the number of free objects
2080 * in the cache when called with nr_to_scan == 0 but not attempt to
2081 * free any objects. When nr_to_scan > 0 it is a request that nr_to_scan
2082 * objects should be freed, which differs from Solaris semantics.
2083 * Solaris semantics are to free all available objects which may (and
2084 * probably will) be more objects than the requested nr_to_scan.
2085 */
2086 static int
2087 __spl_kmem_cache_generic_shrinker(struct shrinker *shrink,
2088 struct shrink_control *sc)
2089 {
2090 spl_kmem_cache_t *skc;
2091 int unused = 0;
2092
2093 down_read(&spl_kmem_cache_sem);
2094 list_for_each_entry(skc, &spl_kmem_cache_list, skc_list) {
2095 if (sc->nr_to_scan)
2096 spl_kmem_cache_reap_now(skc,
2097 MAX(sc->nr_to_scan >> fls64(skc->skc_slab_objs), 1));
2098
2099 /*
2100 * Presume everything alloc'ed in reclaimable, this ensures
2101 * we are called again with nr_to_scan > 0 so can try and
2102 * reclaim. The exact number is not important either so
2103 * we forgo taking this already highly contented lock.
2104 */
2105 unused += skc->skc_obj_alloc;
2106 }
2107 up_read(&spl_kmem_cache_sem);
2108
2109 return (unused * sysctl_vfs_cache_pressure) / 100;
2110 }
2111
2112 SPL_SHRINKER_CALLBACK_WRAPPER(spl_kmem_cache_generic_shrinker);
2113
2114 /*
2115 * Call the registered reclaim function for a cache. Depending on how
2116 * many and which objects are released it may simply repopulate the
2117 * local magazine which will then need to age-out. Objects which cannot
2118 * fit in the magazine we will be released back to their slabs which will
2119 * also need to age out before being release. This is all just best
2120 * effort and we do not want to thrash creating and destroying slabs.
2121 */
2122 void
2123 spl_kmem_cache_reap_now(spl_kmem_cache_t *skc, int count)
2124 {
2125 SENTRY;
2126
2127 ASSERT(skc->skc_magic == SKC_MAGIC);
2128 ASSERT(!test_bit(KMC_BIT_DESTROY, &skc->skc_flags));
2129
2130 /* Prevent concurrent cache reaping when contended */
2131 if (test_and_set_bit(KMC_BIT_REAPING, &skc->skc_flags)) {
2132 SEXIT;
2133 return;
2134 }
2135
2136 atomic_inc(&skc->skc_ref);
2137
2138 /*
2139 * When a reclaim function is available it may be invoked repeatedly
2140 * until at least a single slab can be freed. This ensures that we
2141 * do free memory back to the system. This helps minimize the chance
2142 * of an OOM event when the bulk of memory is used by the slab.
2143 *
2144 * When free slabs are already available the reclaim callback will be
2145 * skipped. Additionally, if no forward progress is detected despite
2146 * a reclaim function the cache will be skipped to avoid deadlock.
2147 *
2148 * Longer term this would be the correct place to add the code which
2149 * repacks the slabs in order minimize fragmentation.
2150 */
2151 if (skc->skc_reclaim) {
2152 uint64_t objects = UINT64_MAX;
2153 int do_reclaim;
2154
2155 do {
2156 spin_lock(&skc->skc_lock);
2157 do_reclaim =
2158 (skc->skc_slab_total > 0) &&
2159 ((skc->skc_slab_total - skc->skc_slab_alloc) == 0) &&
2160 (skc->skc_obj_alloc < objects);
2161
2162 objects = skc->skc_obj_alloc;
2163 spin_unlock(&skc->skc_lock);
2164
2165 if (do_reclaim)
2166 skc->skc_reclaim(skc->skc_private);
2167
2168 } while (do_reclaim);
2169 }
2170
2171 /* Reclaim from the cache, ignoring it's age and delay. */
2172 spl_slab_reclaim(skc, count, 1);
2173 clear_bit(KMC_BIT_REAPING, &skc->skc_flags);
2174 smp_mb__after_clear_bit();
2175 wake_up_bit(&skc->skc_flags, KMC_BIT_REAPING);
2176
2177 atomic_dec(&skc->skc_ref);
2178
2179 SEXIT;
2180 }
2181 EXPORT_SYMBOL(spl_kmem_cache_reap_now);
2182
2183 /*
2184 * Reap all free slabs from all registered caches.
2185 */
2186 void
2187 spl_kmem_reap(void)
2188 {
2189 struct shrink_control sc;
2190
2191 sc.nr_to_scan = KMC_REAP_CHUNK;
2192 sc.gfp_mask = GFP_KERNEL;
2193
2194 __spl_kmem_cache_generic_shrinker(NULL, &sc);
2195 }
2196 EXPORT_SYMBOL(spl_kmem_reap);
2197
2198 #if defined(DEBUG_KMEM) && defined(DEBUG_KMEM_TRACKING)
2199 static char *
2200 spl_sprintf_addr(kmem_debug_t *kd, char *str, int len, int min)
2201 {
2202 int size = ((len - 1) < kd->kd_size) ? (len - 1) : kd->kd_size;
2203 int i, flag = 1;
2204
2205 ASSERT(str != NULL && len >= 17);
2206 memset(str, 0, len);
2207
2208 /* Check for a fully printable string, and while we are at
2209 * it place the printable characters in the passed buffer. */
2210 for (i = 0; i < size; i++) {
2211 str[i] = ((char *)(kd->kd_addr))[i];
2212 if (isprint(str[i])) {
2213 continue;
2214 } else {
2215 /* Minimum number of printable characters found
2216 * to make it worthwhile to print this as ascii. */
2217 if (i > min)
2218 break;
2219
2220 flag = 0;
2221 break;
2222 }
2223 }
2224
2225 if (!flag) {
2226 sprintf(str, "%02x%02x%02x%02x%02x%02x%02x%02x",
2227 *((uint8_t *)kd->kd_addr),
2228 *((uint8_t *)kd->kd_addr + 2),
2229 *((uint8_t *)kd->kd_addr + 4),
2230 *((uint8_t *)kd->kd_addr + 6),
2231 *((uint8_t *)kd->kd_addr + 8),
2232 *((uint8_t *)kd->kd_addr + 10),
2233 *((uint8_t *)kd->kd_addr + 12),
2234 *((uint8_t *)kd->kd_addr + 14));
2235 }
2236
2237 return str;
2238 }
2239
2240 static int
2241 spl_kmem_init_tracking(struct list_head *list, spinlock_t *lock, int size)
2242 {
2243 int i;
2244 SENTRY;
2245
2246 spin_lock_init(lock);
2247 INIT_LIST_HEAD(list);
2248
2249 for (i = 0; i < size; i++)
2250 INIT_HLIST_HEAD(&kmem_table[i]);
2251
2252 SRETURN(0);
2253 }
2254
2255 static void
2256 spl_kmem_fini_tracking(struct list_head *list, spinlock_t *lock)
2257 {
2258 unsigned long flags;
2259 kmem_debug_t *kd;
2260 char str[17];
2261 SENTRY;
2262
2263 spin_lock_irqsave(lock, flags);
2264 if (!list_empty(list))
2265 printk(KERN_WARNING "%-16s %-5s %-16s %s:%s\n", "address",
2266 "size", "data", "func", "line");
2267
2268 list_for_each_entry(kd, list, kd_list)
2269 printk(KERN_WARNING "%p %-5d %-16s %s:%d\n", kd->kd_addr,
2270 (int)kd->kd_size, spl_sprintf_addr(kd, str, 17, 8),
2271 kd->kd_func, kd->kd_line);
2272
2273 spin_unlock_irqrestore(lock, flags);
2274 SEXIT;
2275 }
2276 #else /* DEBUG_KMEM && DEBUG_KMEM_TRACKING */
2277 #define spl_kmem_init_tracking(list, lock, size)
2278 #define spl_kmem_fini_tracking(list, lock)
2279 #endif /* DEBUG_KMEM && DEBUG_KMEM_TRACKING */
2280
2281 static void
2282 spl_kmem_init_globals(void)
2283 {
2284 struct zone *zone;
2285
2286 /* For now all zones are includes, it may be wise to restrict
2287 * this to normal and highmem zones if we see problems. */
2288 for_each_zone(zone) {
2289
2290 if (!populated_zone(zone))
2291 continue;
2292
2293 minfree += min_wmark_pages(zone);
2294 desfree += low_wmark_pages(zone);
2295 lotsfree += high_wmark_pages(zone);
2296 }
2297
2298 /* Solaris default values */
2299 swapfs_minfree = MAX(2*1024*1024 >> PAGE_SHIFT, physmem >> 3);
2300 swapfs_reserve = MIN(4*1024*1024 >> PAGE_SHIFT, physmem >> 4);
2301 }
2302
2303 /*
2304 * Called at module init when it is safe to use spl_kallsyms_lookup_name()
2305 */
2306 int
2307 spl_kmem_init_kallsyms_lookup(void)
2308 {
2309 #ifndef HAVE_GET_VMALLOC_INFO
2310 get_vmalloc_info_fn = (get_vmalloc_info_t)
2311 spl_kallsyms_lookup_name("get_vmalloc_info");
2312 if (!get_vmalloc_info_fn) {
2313 printk(KERN_ERR "Error: Unknown symbol get_vmalloc_info\n");
2314 return -EFAULT;
2315 }
2316 #endif /* HAVE_GET_VMALLOC_INFO */
2317
2318 #ifdef HAVE_PGDAT_HELPERS
2319 # ifndef HAVE_FIRST_ONLINE_PGDAT
2320 first_online_pgdat_fn = (first_online_pgdat_t)
2321 spl_kallsyms_lookup_name("first_online_pgdat");
2322 if (!first_online_pgdat_fn) {
2323 printk(KERN_ERR "Error: Unknown symbol first_online_pgdat\n");
2324 return -EFAULT;
2325 }
2326 # endif /* HAVE_FIRST_ONLINE_PGDAT */
2327
2328 # ifndef HAVE_NEXT_ONLINE_PGDAT
2329 next_online_pgdat_fn = (next_online_pgdat_t)
2330 spl_kallsyms_lookup_name("next_online_pgdat");
2331 if (!next_online_pgdat_fn) {
2332 printk(KERN_ERR "Error: Unknown symbol next_online_pgdat\n");
2333 return -EFAULT;
2334 }
2335 # endif /* HAVE_NEXT_ONLINE_PGDAT */
2336
2337 # ifndef HAVE_NEXT_ZONE
2338 next_zone_fn = (next_zone_t)
2339 spl_kallsyms_lookup_name("next_zone");
2340 if (!next_zone_fn) {
2341 printk(KERN_ERR "Error: Unknown symbol next_zone\n");
2342 return -EFAULT;
2343 }
2344 # endif /* HAVE_NEXT_ZONE */
2345
2346 #else /* HAVE_PGDAT_HELPERS */
2347
2348 # ifndef HAVE_PGDAT_LIST
2349 pgdat_list_addr = *(struct pglist_data **)
2350 spl_kallsyms_lookup_name("pgdat_list");
2351 if (!pgdat_list_addr) {
2352 printk(KERN_ERR "Error: Unknown symbol pgdat_list\n");
2353 return -EFAULT;
2354 }
2355 # endif /* HAVE_PGDAT_LIST */
2356 #endif /* HAVE_PGDAT_HELPERS */
2357
2358 #if defined(NEED_GET_ZONE_COUNTS) && !defined(HAVE_GET_ZONE_COUNTS)
2359 get_zone_counts_fn = (get_zone_counts_t)
2360 spl_kallsyms_lookup_name("get_zone_counts");
2361 if (!get_zone_counts_fn) {
2362 printk(KERN_ERR "Error: Unknown symbol get_zone_counts\n");
2363 return -EFAULT;
2364 }
2365 #endif /* NEED_GET_ZONE_COUNTS && !HAVE_GET_ZONE_COUNTS */
2366
2367 /*
2368 * It is now safe to initialize the global tunings which rely on
2369 * the use of the for_each_zone() macro. This macro in turns
2370 * depends on the *_pgdat symbols which are now available.
2371 */
2372 spl_kmem_init_globals();
2373
2374 #ifndef HAVE_SHRINK_DCACHE_MEMORY
2375 /* When shrink_dcache_memory_fn == NULL support is disabled */
2376 shrink_dcache_memory_fn = (shrink_dcache_memory_t)
2377 spl_kallsyms_lookup_name("shrink_dcache_memory");
2378 #endif /* HAVE_SHRINK_DCACHE_MEMORY */
2379
2380 #ifndef HAVE_SHRINK_ICACHE_MEMORY
2381 /* When shrink_icache_memory_fn == NULL support is disabled */
2382 shrink_icache_memory_fn = (shrink_icache_memory_t)
2383 spl_kallsyms_lookup_name("shrink_icache_memory");
2384 #endif /* HAVE_SHRINK_ICACHE_MEMORY */
2385
2386 return 0;
2387 }
2388
2389 int
2390 spl_kmem_init(void)
2391 {
2392 int rc = 0;
2393 SENTRY;
2394
2395 init_rwsem(&spl_kmem_cache_sem);
2396 INIT_LIST_HEAD(&spl_kmem_cache_list);
2397 spl_kmem_cache_taskq = taskq_create("spl_kmem_cache",
2398 1, maxclsyspri, 1, 32, TASKQ_PREPOPULATE);
2399
2400 spl_register_shrinker(&spl_kmem_cache_shrinker);
2401
2402 #ifdef DEBUG_KMEM
2403 kmem_alloc_used_set(0);
2404 vmem_alloc_used_set(0);
2405
2406 spl_kmem_init_tracking(&kmem_list, &kmem_lock, KMEM_TABLE_SIZE);
2407 spl_kmem_init_tracking(&vmem_list, &vmem_lock, VMEM_TABLE_SIZE);
2408 #endif
2409 SRETURN(rc);
2410 }
2411
2412 void
2413 spl_kmem_fini(void)
2414 {
2415 #ifdef DEBUG_KMEM
2416 /* Display all unreclaimed memory addresses, including the
2417 * allocation size and the first few bytes of what's located
2418 * at that address to aid in debugging. Performance is not
2419 * a serious concern here since it is module unload time. */
2420 if (kmem_alloc_used_read() != 0)
2421 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
2422 "kmem leaked %ld/%ld bytes\n",
2423 kmem_alloc_used_read(), kmem_alloc_max);
2424
2425
2426 if (vmem_alloc_used_read() != 0)
2427 SDEBUG_LIMIT(SD_CONSOLE | SD_WARNING,
2428 "vmem leaked %ld/%ld bytes\n",
2429 vmem_alloc_used_read(), vmem_alloc_max);
2430
2431 spl_kmem_fini_tracking(&kmem_list, &kmem_lock);
2432 spl_kmem_fini_tracking(&vmem_list, &vmem_lock);
2433 #endif /* DEBUG_KMEM */
2434 SENTRY;
2435
2436 spl_unregister_shrinker(&spl_kmem_cache_shrinker);
2437 taskq_destroy(spl_kmem_cache_taskq);
2438
2439 SEXIT;
2440 }