source: mainline/kernel/generic/src/mm/slab.c@ 207e8880

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 207e8880 was 1066041, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

preemption_disable: Turned functions into macros. Moved THREAD, AS, TASK, CPU into thread.h, as.h, task.h, cpu.h to fix the include hell that ensued.

  • Property mode set to 100644
File size: 26.3 KB
Line 
1/*
2 * Copyright (c) 2006 Ondrej Palkovsky
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup genericmm
30 * @{
31 */
32
33/**
34 * @file
35 * @brief Slab allocator.
36 *
37 * The slab allocator is closely modelled after OpenSolaris slab allocator.
38 * @see http://www.usenix.org/events/usenix01/full_papers/bonwick/bonwick_html/
39 *
40 * with the following exceptions:
41 * @li empty slabs are deallocated immediately
42 * (in Linux they are kept in linked list, in Solaris ???)
43 * @li empty magazines are deallocated when not needed
44 * (in Solaris they are held in linked list in slab cache)
45 *
46 * Following features are not currently supported but would be easy to do:
47 * @li cache coloring
48 * @li dynamic magazine growing (different magazine sizes are already
49 * supported, but we would need to adjust allocation strategy)
50 *
51 * The slab allocator supports per-CPU caches ('magazines') to facilitate
52 * good SMP scaling.
53 *
54 * When a new object is being allocated, it is first checked, if it is
55 * available in a CPU-bound magazine. If it is not found there, it is
56 * allocated from a CPU-shared slab - if a partially full one is found,
57 * it is used, otherwise a new one is allocated.
58 *
59 * When an object is being deallocated, it is put to a CPU-bound magazine.
60 * If there is no such magazine, a new one is allocated (if this fails,
61 * the object is deallocated into slab). If the magazine is full, it is
62 * put into cpu-shared list of magazines and a new one is allocated.
63 *
64 * The CPU-bound magazine is actually a pair of magazines in order to avoid
65 * thrashing when somebody is allocating/deallocating 1 item at the magazine
66 * size boundary. LIFO order is enforced, which should avoid fragmentation
67 * as much as possible.
68 *
69 * Every cache contains list of full slabs and list of partially full slabs.
70 * Empty slabs are immediately freed (thrashing will be avoided because
71 * of magazines).
72 *
73 * The slab information structure is kept inside the data area, if possible.
74 * The cache can be marked that it should not use magazines. This is used
75 * only for slab related caches to avoid deadlocks and infinite recursion
76 * (the slab allocator uses itself for allocating all it's control structures).
77 *
78 * The slab allocator allocates a lot of space and does not free it. When
79 * the frame allocator fails to allocate a frame, it calls slab_reclaim().
80 * It tries 'light reclaim' first, then brutal reclaim. The light reclaim
81 * releases slabs from cpu-shared magazine-list, until at least 1 slab
82 * is deallocated in each cache (this algorithm should probably change).
83 * The brutal reclaim removes all cached objects, even from CPU-bound
84 * magazines.
85 *
86 * @todo
87 * For better CPU-scaling the magazine allocation strategy should
88 * be extended. Currently, if the cache does not have magazine, it asks
89 * for non-cpu cached magazine cache to provide one. It might be feasible
90 * to add cpu-cached magazine cache (which would allocate it's magazines
91 * from non-cpu-cached mag. cache). This would provide a nice per-cpu
92 * buffer. The other possibility is to use the per-cache
93 * 'empty-magazine-list', which decreases competing for 1 per-system
94 * magazine cache.
95 *
96 * @todo
97 * It might be good to add granularity of locks even to slab level,
98 * we could then try_spinlock over all partial slabs and thus improve
99 * scalability even on slab level.
100 *
101 */
102
103#include <synch/spinlock.h>
104#include <mm/slab.h>
105#include <adt/list.h>
106#include <memstr.h>
107#include <align.h>
108#include <mm/frame.h>
109#include <config.h>
110#include <print.h>
111#include <arch.h>
112#include <panic.h>
113#include <debug.h>
114#include <bitops.h>
115#include <macros.h>
116#include <cpu.h>
117
118IRQ_SPINLOCK_STATIC_INITIALIZE(slab_cache_lock);
119static LIST_INITIALIZE(slab_cache_list);
120
121/** Magazine cache */
122static slab_cache_t mag_cache;
123
124/** Cache for cache descriptors */
125static slab_cache_t slab_cache_cache;
126
127/** Cache for external slab descriptors
128 * This time we want per-cpu cache, so do not make it static
129 * - using slab for internal slab structures will not deadlock,
130 * as all slab structures are 'small' - control structures of
131 * their caches do not require further allocation
132 */
133static slab_cache_t *slab_extern_cache;
134
135/** Caches for malloc */
136static slab_cache_t *malloc_caches[SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1];
137
138static const char *malloc_names[] = {
139 "malloc-16",
140 "malloc-32",
141 "malloc-64",
142 "malloc-128",
143 "malloc-256",
144 "malloc-512",
145 "malloc-1K",
146 "malloc-2K",
147 "malloc-4K",
148 "malloc-8K",
149 "malloc-16K",
150 "malloc-32K",
151 "malloc-64K",
152 "malloc-128K",
153 "malloc-256K",
154 "malloc-512K",
155 "malloc-1M",
156 "malloc-2M",
157 "malloc-4M"
158};
159
160/** Slab descriptor */
161typedef struct {
162 slab_cache_t *cache; /**< Pointer to parent cache. */
163 link_t link; /**< List of full/partial slabs. */
164 void *start; /**< Start address of first available item. */
165 size_t available; /**< Count of available items in this slab. */
166 size_t nextavail; /**< The index of next available item. */
167} slab_t;
168
169#ifdef CONFIG_DEBUG
170static unsigned int _slab_initialized = 0;
171#endif
172
173/**************************************/
174/* Slab allocation functions */
175/**************************************/
176
177/** Allocate frames for slab space and initialize
178 *
179 */
180NO_TRACE static slab_t *slab_space_alloc(slab_cache_t *cache,
181 unsigned int flags)
182{
183 size_t zone = 0;
184
185 void *data = frame_alloc_generic(cache->order, FRAME_KA | flags, &zone);
186 if (!data) {
187 return NULL;
188 }
189
190 slab_t *slab;
191 size_t fsize;
192
193 if (!(cache->flags & SLAB_CACHE_SLINSIDE)) {
194 slab = slab_alloc(slab_extern_cache, flags);
195 if (!slab) {
196 frame_free(KA2PA(data));
197 return NULL;
198 }
199 } else {
200 fsize = (PAGE_SIZE << cache->order);
201 slab = data + fsize - sizeof(*slab);
202 }
203
204 /* Fill in slab structures */
205 size_t i;
206 for (i = 0; i < ((size_t) 1 << cache->order); i++)
207 frame_set_parent(ADDR2PFN(KA2PA(data)) + i, slab, zone);
208
209 slab->start = data;
210 slab->available = cache->objects;
211 slab->nextavail = 0;
212 slab->cache = cache;
213
214 for (i = 0; i < cache->objects; i++)
215 *((size_t *) (slab->start + i * cache->size)) = i + 1;
216
217 atomic_inc(&cache->allocated_slabs);
218 return slab;
219}
220
221/** Deallocate space associated with slab
222 *
223 * @return number of freed frames
224 *
225 */
226NO_TRACE static size_t slab_space_free(slab_cache_t *cache, slab_t *slab)
227{
228 frame_free(KA2PA(slab->start));
229 if (!(cache->flags & SLAB_CACHE_SLINSIDE))
230 slab_free(slab_extern_cache, slab);
231
232 atomic_dec(&cache->allocated_slabs);
233
234 return (1 << cache->order);
235}
236
237/** Map object to slab structure */
238NO_TRACE static slab_t *obj2slab(void *obj)
239{
240 return (slab_t *) frame_get_parent(ADDR2PFN(KA2PA(obj)), 0);
241}
242
243/******************/
244/* Slab functions */
245/******************/
246
247/** Return object to slab and call a destructor
248 *
249 * @param slab If the caller knows directly slab of the object, otherwise NULL
250 *
251 * @return Number of freed pages
252 *
253 */
254NO_TRACE static size_t slab_obj_destroy(slab_cache_t *cache, void *obj,
255 slab_t *slab)
256{
257 if (!slab)
258 slab = obj2slab(obj);
259
260 ASSERT(slab->cache == cache);
261
262 size_t freed = 0;
263
264 if (cache->destructor)
265 freed = cache->destructor(obj);
266
267 irq_spinlock_lock(&cache->slablock, true);
268 ASSERT(slab->available < cache->objects);
269
270 *((size_t *) obj) = slab->nextavail;
271 slab->nextavail = (obj - slab->start) / cache->size;
272 slab->available++;
273
274 /* Move it to correct list */
275 if (slab->available == cache->objects) {
276 /* Free associated memory */
277 list_remove(&slab->link);
278 irq_spinlock_unlock(&cache->slablock, true);
279
280 return freed + slab_space_free(cache, slab);
281 } else if (slab->available == 1) {
282 /* It was in full, move to partial */
283 list_remove(&slab->link);
284 list_prepend(&slab->link, &cache->partial_slabs);
285 }
286
287 irq_spinlock_unlock(&cache->slablock, true);
288 return freed;
289}
290
291/** Take new object from slab or create new if needed
292 *
293 * @return Object address or null
294 *
295 */
296NO_TRACE static void *slab_obj_create(slab_cache_t *cache, unsigned int flags)
297{
298 irq_spinlock_lock(&cache->slablock, true);
299
300 slab_t *slab;
301
302 if (list_empty(&cache->partial_slabs)) {
303 /*
304 * Allow recursion and reclaiming
305 * - this should work, as the slab control structures
306 * are small and do not need to allocate with anything
307 * other than frame_alloc when they are allocating,
308 * that's why we should get recursion at most 1-level deep
309 *
310 */
311 irq_spinlock_unlock(&cache->slablock, true);
312 slab = slab_space_alloc(cache, flags);
313 if (!slab)
314 return NULL;
315
316 irq_spinlock_lock(&cache->slablock, true);
317 } else {
318 slab = list_get_instance(list_first(&cache->partial_slabs),
319 slab_t, link);
320 list_remove(&slab->link);
321 }
322
323 void *obj = slab->start + slab->nextavail * cache->size;
324 slab->nextavail = *((size_t *) obj);
325 slab->available--;
326
327 if (!slab->available)
328 list_prepend(&slab->link, &cache->full_slabs);
329 else
330 list_prepend(&slab->link, &cache->partial_slabs);
331
332 irq_spinlock_unlock(&cache->slablock, true);
333
334 if ((cache->constructor) && (cache->constructor(obj, flags))) {
335 /* Bad, bad, construction failed */
336 slab_obj_destroy(cache, obj, slab);
337 return NULL;
338 }
339
340 return obj;
341}
342
343/****************************/
344/* CPU-Cache slab functions */
345/****************************/
346
347/** Find a full magazine in cache, take it from list and return it
348 *
349 * @param first If true, return first, else last mag.
350 *
351 */
352NO_TRACE static slab_magazine_t *get_mag_from_cache(slab_cache_t *cache,
353 bool first)
354{
355 slab_magazine_t *mag = NULL;
356 link_t *cur;
357
358 irq_spinlock_lock(&cache->maglock, true);
359 if (!list_empty(&cache->magazines)) {
360 if (first)
361 cur = list_first(&cache->magazines);
362 else
363 cur = list_last(&cache->magazines);
364
365 mag = list_get_instance(cur, slab_magazine_t, link);
366 list_remove(&mag->link);
367 atomic_dec(&cache->magazine_counter);
368 }
369 irq_spinlock_unlock(&cache->maglock, true);
370
371 return mag;
372}
373
374/** Prepend magazine to magazine list in cache
375 *
376 */
377NO_TRACE static void put_mag_to_cache(slab_cache_t *cache,
378 slab_magazine_t *mag)
379{
380 irq_spinlock_lock(&cache->maglock, true);
381
382 list_prepend(&mag->link, &cache->magazines);
383 atomic_inc(&cache->magazine_counter);
384
385 irq_spinlock_unlock(&cache->maglock, true);
386}
387
388/** Free all objects in magazine and free memory associated with magazine
389 *
390 * @return Number of freed pages
391 *
392 */
393NO_TRACE static size_t magazine_destroy(slab_cache_t *cache,
394 slab_magazine_t *mag)
395{
396 size_t i;
397 size_t frames = 0;
398
399 for (i = 0; i < mag->busy; i++) {
400 frames += slab_obj_destroy(cache, mag->objs[i], NULL);
401 atomic_dec(&cache->cached_objs);
402 }
403
404 slab_free(&mag_cache, mag);
405
406 return frames;
407}
408
409/** Find full magazine, set it as current and return it
410 *
411 */
412NO_TRACE static slab_magazine_t *get_full_current_mag(slab_cache_t *cache)
413{
414 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
415 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
416
417 ASSERT(irq_spinlock_locked(&cache->mag_cache[CPU->id].lock));
418
419 if (cmag) { /* First try local CPU magazines */
420 if (cmag->busy)
421 return cmag;
422
423 if ((lastmag) && (lastmag->busy)) {
424 cache->mag_cache[CPU->id].current = lastmag;
425 cache->mag_cache[CPU->id].last = cmag;
426 return lastmag;
427 }
428 }
429
430 /* Local magazines are empty, import one from magazine list */
431 slab_magazine_t *newmag = get_mag_from_cache(cache, 1);
432 if (!newmag)
433 return NULL;
434
435 if (lastmag)
436 magazine_destroy(cache, lastmag);
437
438 cache->mag_cache[CPU->id].last = cmag;
439 cache->mag_cache[CPU->id].current = newmag;
440
441 return newmag;
442}
443
444/** Try to find object in CPU-cache magazines
445 *
446 * @return Pointer to object or NULL if not available
447 *
448 */
449NO_TRACE static void *magazine_obj_get(slab_cache_t *cache)
450{
451 if (!CPU)
452 return NULL;
453
454 irq_spinlock_lock(&cache->mag_cache[CPU->id].lock, true);
455
456 slab_magazine_t *mag = get_full_current_mag(cache);
457 if (!mag) {
458 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
459 return NULL;
460 }
461
462 void *obj = mag->objs[--mag->busy];
463 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
464
465 atomic_dec(&cache->cached_objs);
466
467 return obj;
468}
469
470/** Assure that the current magazine is empty, return pointer to it,
471 * or NULL if no empty magazine is available and cannot be allocated
472 *
473 * We have 2 magazines bound to processor.
474 * First try the current.
475 * If full, try the last.
476 * If full, put to magazines list.
477 *
478 */
479NO_TRACE static slab_magazine_t *make_empty_current_mag(slab_cache_t *cache)
480{
481 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
482 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
483
484 ASSERT(irq_spinlock_locked(&cache->mag_cache[CPU->id].lock));
485
486 if (cmag) {
487 if (cmag->busy < cmag->size)
488 return cmag;
489
490 if ((lastmag) && (lastmag->busy < lastmag->size)) {
491 cache->mag_cache[CPU->id].last = cmag;
492 cache->mag_cache[CPU->id].current = lastmag;
493 return lastmag;
494 }
495 }
496
497 /* current | last are full | nonexistent, allocate new */
498
499 /*
500 * We do not want to sleep just because of caching,
501 * especially we do not want reclaiming to start, as
502 * this would deadlock.
503 *
504 */
505 slab_magazine_t *newmag = slab_alloc(&mag_cache,
506 FRAME_ATOMIC | FRAME_NO_RECLAIM);
507 if (!newmag)
508 return NULL;
509
510 newmag->size = SLAB_MAG_SIZE;
511 newmag->busy = 0;
512
513 /* Flush last to magazine list */
514 if (lastmag)
515 put_mag_to_cache(cache, lastmag);
516
517 /* Move current as last, save new as current */
518 cache->mag_cache[CPU->id].last = cmag;
519 cache->mag_cache[CPU->id].current = newmag;
520
521 return newmag;
522}
523
524/** Put object into CPU-cache magazine
525 *
526 * @return 0 on success, -1 on no memory
527 *
528 */
529NO_TRACE static int magazine_obj_put(slab_cache_t *cache, void *obj)
530{
531 if (!CPU)
532 return -1;
533
534 irq_spinlock_lock(&cache->mag_cache[CPU->id].lock, true);
535
536 slab_magazine_t *mag = make_empty_current_mag(cache);
537 if (!mag) {
538 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
539 return -1;
540 }
541
542 mag->objs[mag->busy++] = obj;
543
544 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
545
546 atomic_inc(&cache->cached_objs);
547
548 return 0;
549}
550
551/************************/
552/* Slab cache functions */
553/************************/
554
555/** Return number of objects that fit in certain cache size
556 *
557 */
558NO_TRACE static size_t comp_objects(slab_cache_t *cache)
559{
560 if (cache->flags & SLAB_CACHE_SLINSIDE)
561 return ((PAGE_SIZE << cache->order)
562 - sizeof(slab_t)) / cache->size;
563 else
564 return (PAGE_SIZE << cache->order) / cache->size;
565}
566
567/** Return wasted space in slab
568 *
569 */
570NO_TRACE static size_t badness(slab_cache_t *cache)
571{
572 size_t objects = comp_objects(cache);
573 size_t ssize = PAGE_SIZE << cache->order;
574
575 if (cache->flags & SLAB_CACHE_SLINSIDE)
576 ssize -= sizeof(slab_t);
577
578 return ssize - objects * cache->size;
579}
580
581/** Initialize mag_cache structure in slab cache
582 *
583 */
584NO_TRACE static bool make_magcache(slab_cache_t *cache)
585{
586 ASSERT(_slab_initialized >= 2);
587
588 cache->mag_cache = malloc(sizeof(slab_mag_cache_t) * config.cpu_count,
589 FRAME_ATOMIC);
590 if (!cache->mag_cache)
591 return false;
592
593 size_t i;
594 for (i = 0; i < config.cpu_count; i++) {
595 memsetb(&cache->mag_cache[i], sizeof(cache->mag_cache[i]), 0);
596 irq_spinlock_initialize(&cache->mag_cache[i].lock,
597 "slab.cache.mag_cache[].lock");
598 }
599
600 return true;
601}
602
603/** Initialize allocated memory as a slab cache
604 *
605 */
606NO_TRACE static void _slab_cache_create(slab_cache_t *cache, const char *name,
607 size_t size, size_t align, int (*constructor)(void *obj,
608 unsigned int kmflag), size_t (*destructor)(void *obj), unsigned int flags)
609{
610 memsetb(cache, sizeof(*cache), 0);
611 cache->name = name;
612
613 if (align < sizeof(sysarg_t))
614 align = sizeof(sysarg_t);
615
616 size = ALIGN_UP(size, align);
617
618 cache->size = size;
619 cache->constructor = constructor;
620 cache->destructor = destructor;
621 cache->flags = flags;
622
623 list_initialize(&cache->full_slabs);
624 list_initialize(&cache->partial_slabs);
625 list_initialize(&cache->magazines);
626
627 irq_spinlock_initialize(&cache->slablock, "slab.cache.slablock");
628 irq_spinlock_initialize(&cache->maglock, "slab.cache.maglock");
629
630 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
631 (void) make_magcache(cache);
632
633 /* Compute slab sizes, object counts in slabs etc. */
634 if (cache->size < SLAB_INSIDE_SIZE)
635 cache->flags |= SLAB_CACHE_SLINSIDE;
636
637 /* Minimum slab order */
638 size_t pages = SIZE2FRAMES(cache->size);
639
640 /* We need the 2^order >= pages */
641 if (pages == 1)
642 cache->order = 0;
643 else
644 cache->order = fnzb(pages - 1) + 1;
645
646 while (badness(cache) > SLAB_MAX_BADNESS(cache))
647 cache->order += 1;
648
649 cache->objects = comp_objects(cache);
650
651 /* If info fits in, put it inside */
652 if (badness(cache) > sizeof(slab_t))
653 cache->flags |= SLAB_CACHE_SLINSIDE;
654
655 /* Add cache to cache list */
656 irq_spinlock_lock(&slab_cache_lock, true);
657 list_append(&cache->link, &slab_cache_list);
658 irq_spinlock_unlock(&slab_cache_lock, true);
659}
660
661/** Create slab cache
662 *
663 */
664slab_cache_t *slab_cache_create(const char *name, size_t size, size_t align,
665 int (*constructor)(void *obj, unsigned int kmflag),
666 size_t (*destructor)(void *obj), unsigned int flags)
667{
668 slab_cache_t *cache = slab_alloc(&slab_cache_cache, 0);
669 _slab_cache_create(cache, name, size, align, constructor, destructor,
670 flags);
671
672 return cache;
673}
674
675/** Reclaim space occupied by objects that are already free
676 *
677 * @param flags If contains SLAB_RECLAIM_ALL, do aggressive freeing
678 *
679 * @return Number of freed pages
680 *
681 */
682NO_TRACE static size_t _slab_reclaim(slab_cache_t *cache, unsigned int flags)
683{
684 if (cache->flags & SLAB_CACHE_NOMAGAZINE)
685 return 0; /* Nothing to do */
686
687 /*
688 * We count up to original magazine count to avoid
689 * endless loop
690 */
691 atomic_count_t magcount = atomic_get(&cache->magazine_counter);
692
693 slab_magazine_t *mag;
694 size_t frames = 0;
695
696 while ((magcount--) && (mag = get_mag_from_cache(cache, 0))) {
697 frames += magazine_destroy(cache, mag);
698 if ((!(flags & SLAB_RECLAIM_ALL)) && (frames))
699 break;
700 }
701
702 if (flags & SLAB_RECLAIM_ALL) {
703 /* Free cpu-bound magazines */
704 /* Destroy CPU magazines */
705 size_t i;
706 for (i = 0; i < config.cpu_count; i++) {
707 irq_spinlock_lock(&cache->mag_cache[i].lock, true);
708
709 mag = cache->mag_cache[i].current;
710 if (mag)
711 frames += magazine_destroy(cache, mag);
712 cache->mag_cache[i].current = NULL;
713
714 mag = cache->mag_cache[i].last;
715 if (mag)
716 frames += magazine_destroy(cache, mag);
717 cache->mag_cache[i].last = NULL;
718
719 irq_spinlock_unlock(&cache->mag_cache[i].lock, true);
720 }
721 }
722
723 return frames;
724}
725
726/** Check that there are no slabs and remove cache from system
727 *
728 */
729void slab_cache_destroy(slab_cache_t *cache)
730{
731 /*
732 * First remove cache from link, so that we don't need
733 * to disable interrupts later
734 *
735 */
736 irq_spinlock_lock(&slab_cache_lock, true);
737 list_remove(&cache->link);
738 irq_spinlock_unlock(&slab_cache_lock, true);
739
740 /*
741 * Do not lock anything, we assume the software is correct and
742 * does not touch the cache when it decides to destroy it
743 *
744 */
745
746 /* Destroy all magazines */
747 _slab_reclaim(cache, SLAB_RECLAIM_ALL);
748
749 /* All slabs must be empty */
750 if ((!list_empty(&cache->full_slabs)) ||
751 (!list_empty(&cache->partial_slabs)))
752 panic("Destroying cache that is not empty.");
753
754 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
755 free(cache->mag_cache);
756
757 slab_free(&slab_cache_cache, cache);
758}
759
760/** Allocate new object from cache - if no flags given, always returns memory
761 *
762 */
763void *slab_alloc(slab_cache_t *cache, unsigned int flags)
764{
765 /* Disable interrupts to avoid deadlocks with interrupt handlers */
766 ipl_t ipl = interrupts_disable();
767
768 void *result = NULL;
769
770 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
771 result = magazine_obj_get(cache);
772
773 if (!result)
774 result = slab_obj_create(cache, flags);
775
776 interrupts_restore(ipl);
777
778 if (result)
779 atomic_inc(&cache->allocated_objs);
780
781 return result;
782}
783
784/** Return object to cache, use slab if known
785 *
786 */
787NO_TRACE static void _slab_free(slab_cache_t *cache, void *obj, slab_t *slab)
788{
789 ipl_t ipl = interrupts_disable();
790
791 if ((cache->flags & SLAB_CACHE_NOMAGAZINE) ||
792 (magazine_obj_put(cache, obj)))
793 slab_obj_destroy(cache, obj, slab);
794
795 interrupts_restore(ipl);
796 atomic_dec(&cache->allocated_objs);
797}
798
799/** Return slab object to cache
800 *
801 */
802void slab_free(slab_cache_t *cache, void *obj)
803{
804 _slab_free(cache, obj, NULL);
805}
806
807/** Go through all caches and reclaim what is possible */
808size_t slab_reclaim(unsigned int flags)
809{
810 irq_spinlock_lock(&slab_cache_lock, true);
811
812 size_t frames = 0;
813 list_foreach(slab_cache_list, cur) {
814 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
815 frames += _slab_reclaim(cache, flags);
816 }
817
818 irq_spinlock_unlock(&slab_cache_lock, true);
819
820 return frames;
821}
822
823/* Print list of slabs
824 *
825 */
826void slab_print_list(void)
827{
828 printf("[slab name ] [size ] [pages ] [obj/pg] [slabs ]"
829 " [cached] [alloc ] [ctl]\n");
830
831 size_t skip = 0;
832 while (true) {
833 /*
834 * We must not hold the slab_cache_lock spinlock when printing
835 * the statistics. Otherwise we can easily deadlock if the print
836 * needs to allocate memory.
837 *
838 * Therefore, we walk through the slab cache list, skipping some
839 * amount of already processed caches during each iteration and
840 * gathering statistics about the first unprocessed cache. For
841 * the sake of printing the statistics, we realese the
842 * slab_cache_lock and reacquire it afterwards. Then the walk
843 * starts again.
844 *
845 * This limits both the efficiency and also accuracy of the
846 * obtained statistics. The efficiency is decreased because the
847 * time complexity of the algorithm is quadratic instead of
848 * linear. The accuracy is impacted because we drop the lock
849 * after processing one cache. If there is someone else
850 * manipulating the cache list, we might omit an arbitrary
851 * number of caches or process one cache multiple times.
852 * However, we don't bleed for this algorithm for it is only
853 * statistics.
854 */
855
856 irq_spinlock_lock(&slab_cache_lock, true);
857
858 link_t *cur;
859 size_t i;
860 for (i = 0, cur = slab_cache_list.head.next;
861 (i < skip) && (cur != &slab_cache_list.head);
862 i++, cur = cur->next);
863
864 if (cur == &slab_cache_list.head) {
865 irq_spinlock_unlock(&slab_cache_lock, true);
866 break;
867 }
868
869 skip++;
870
871 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
872
873 const char *name = cache->name;
874 uint8_t order = cache->order;
875 size_t size = cache->size;
876 size_t objects = cache->objects;
877 long allocated_slabs = atomic_get(&cache->allocated_slabs);
878 long cached_objs = atomic_get(&cache->cached_objs);
879 long allocated_objs = atomic_get(&cache->allocated_objs);
880 unsigned int flags = cache->flags;
881
882 irq_spinlock_unlock(&slab_cache_lock, true);
883
884 printf("%-18s %8zu %8u %8zu %8ld %8ld %8ld %-5s\n",
885 name, size, (1 << order), objects, allocated_slabs,
886 cached_objs, allocated_objs,
887 flags & SLAB_CACHE_SLINSIDE ? "in" : "out");
888 }
889}
890
891void slab_cache_init(void)
892{
893 /* Initialize magazine cache */
894 _slab_cache_create(&mag_cache, "slab_magazine_t",
895 sizeof(slab_magazine_t) + SLAB_MAG_SIZE * sizeof(void*),
896 sizeof(uintptr_t), NULL, NULL, SLAB_CACHE_NOMAGAZINE |
897 SLAB_CACHE_SLINSIDE);
898
899 /* Initialize slab_cache cache */
900 _slab_cache_create(&slab_cache_cache, "slab_cache_cache",
901 sizeof(slab_cache_cache), sizeof(uintptr_t), NULL, NULL,
902 SLAB_CACHE_NOMAGAZINE | SLAB_CACHE_SLINSIDE);
903
904 /* Initialize external slab cache */
905 slab_extern_cache = slab_cache_create("slab_t", sizeof(slab_t), 0,
906 NULL, NULL, SLAB_CACHE_SLINSIDE | SLAB_CACHE_MAGDEFERRED);
907
908 /* Initialize structures for malloc */
909 size_t i;
910 size_t size;
911
912 for (i = 0, size = (1 << SLAB_MIN_MALLOC_W);
913 i < (SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1);
914 i++, size <<= 1) {
915 malloc_caches[i] = slab_cache_create(malloc_names[i], size, 0,
916 NULL, NULL, SLAB_CACHE_MAGDEFERRED);
917 }
918
919#ifdef CONFIG_DEBUG
920 _slab_initialized = 1;
921#endif
922}
923
924/** Enable cpu_cache
925 *
926 * Kernel calls this function, when it knows the real number of
927 * processors. Allocate slab for cpucache and enable it on all
928 * existing slabs that are SLAB_CACHE_MAGDEFERRED
929 *
930 */
931void slab_enable_cpucache(void)
932{
933#ifdef CONFIG_DEBUG
934 _slab_initialized = 2;
935#endif
936
937 irq_spinlock_lock(&slab_cache_lock, false);
938
939 list_foreach(slab_cache_list, cur) {
940 slab_cache_t *slab = list_get_instance(cur, slab_cache_t, link);
941 if ((slab->flags & SLAB_CACHE_MAGDEFERRED) !=
942 SLAB_CACHE_MAGDEFERRED)
943 continue;
944
945 (void) make_magcache(slab);
946 slab->flags &= ~SLAB_CACHE_MAGDEFERRED;
947 }
948
949 irq_spinlock_unlock(&slab_cache_lock, false);
950}
951
952void *malloc(size_t size, unsigned int flags)
953{
954 ASSERT(_slab_initialized);
955 ASSERT(size <= (1 << SLAB_MAX_MALLOC_W));
956
957 if (size < (1 << SLAB_MIN_MALLOC_W))
958 size = (1 << SLAB_MIN_MALLOC_W);
959
960 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
961
962 return slab_alloc(malloc_caches[idx], flags);
963}
964
965void *realloc(void *ptr, size_t size, unsigned int flags)
966{
967 ASSERT(_slab_initialized);
968 ASSERT(size <= (1 << SLAB_MAX_MALLOC_W));
969
970 void *new_ptr;
971
972 if (size > 0) {
973 if (size < (1 << SLAB_MIN_MALLOC_W))
974 size = (1 << SLAB_MIN_MALLOC_W);
975 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
976
977 new_ptr = slab_alloc(malloc_caches[idx], flags);
978 } else
979 new_ptr = NULL;
980
981 if ((new_ptr != NULL) && (ptr != NULL)) {
982 slab_t *slab = obj2slab(ptr);
983 memcpy(new_ptr, ptr, min(size, slab->cache->size));
984 }
985
986 if (ptr != NULL)
987 free(ptr);
988
989 return new_ptr;
990}
991
992void free(void *ptr)
993{
994 if (!ptr)
995 return;
996
997 slab_t *slab = obj2slab(ptr);
998 _slab_free(slab->cache, ptr, slab);
999}
1000
1001/** @}
1002 */
Note: See TracBrowser for help on using the repository browser.