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