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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since da1bafb was da1bafb, checked in by Martin Decky <martin@…>, 15 years ago

major code revision

  • replace spinlocks taken with interrupts disabled with irq_spinlocks
  • change spacing (not indendation) to be tab-size independent
  • use unsigned integer types where appropriate (especially bit flags)
  • visual separation
  • remove argument names in function prototypes
  • string changes
  • correct some formating directives
  • replace various cryptic single-character variables (t, a, m, c, b, etc.) with proper identifiers (thread, task, timeout, as, itm, itc, etc.)
  • unify some assembler constructs
  • unused page table levels are now optimized out in compile time
  • replace several ints (with boolean semantics) with bools
  • use specifically sized types instead of generic types where appropriate (size_t, uint32_t, btree_key_t)
  • improve comments
  • split asserts with conjuction into multiple independent asserts
  • Property mode set to 100644
File size: 26.1 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
117IRQ_SPINLOCK_STATIC_INITIALIZE(slab_cache_lock);
118static LIST_INITIALIZE(slab_cache_list);
119
120/** Magazine cache */
121static slab_cache_t mag_cache;
122
123/** Cache for cache descriptors */
124static slab_cache_t slab_cache_cache;
125
126/** Cache for external slab descriptors
127 * This time we want per-cpu cache, so do not make it static
128 * - using slab for internal slab structures will not deadlock,
129 * as all slab structures are 'small' - control structures of
130 * their caches do not require further allocation
131 */
132static slab_cache_t *slab_extern_cache;
133
134/** Caches for malloc */
135static slab_cache_t *malloc_caches[SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1];
136
137static const char *malloc_names[] = {
138 "malloc-16",
139 "malloc-32",
140 "malloc-64",
141 "malloc-128",
142 "malloc-256",
143 "malloc-512",
144 "malloc-1K",
145 "malloc-2K",
146 "malloc-4K",
147 "malloc-8K",
148 "malloc-16K",
149 "malloc-32K",
150 "malloc-64K",
151 "malloc-128K",
152 "malloc-256K",
153 "malloc-512K",
154 "malloc-1M",
155 "malloc-2M",
156 "malloc-4M"
157};
158
159/** Slab descriptor */
160typedef struct {
161 slab_cache_t *cache; /**< Pointer to parent cache. */
162 link_t link; /**< List of full/partial slabs. */
163 void *start; /**< Start address of first available item. */
164 size_t available; /**< Count of available items in this slab. */
165 size_t nextavail; /**< The index of next available item. */
166} slab_t;
167
168#ifdef CONFIG_DEBUG
169static unsigned int _slab_initialized = 0;
170#endif
171
172/**************************************/
173/* Slab allocation functions */
174/**************************************/
175
176/** Allocate frames for slab space and initialize
177 *
178 */
179static slab_t *slab_space_alloc(slab_cache_t *cache, unsigned int flags)
180{
181
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 */
226static 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 */
238static 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 */
254static size_t slab_obj_destroy(slab_cache_t *cache, void *obj, slab_t *slab)
255{
256 if (!slab)
257 slab = obj2slab(obj);
258
259 ASSERT(slab->cache == cache);
260
261 size_t freed = 0;
262
263 if (cache->destructor)
264 freed = cache->destructor(obj);
265
266 spinlock_lock(&cache->slablock);
267 ASSERT(slab->available < cache->objects);
268
269 *((size_t *) obj) = slab->nextavail;
270 slab->nextavail = (obj - slab->start) / cache->size;
271 slab->available++;
272
273 /* Move it to correct list */
274 if (slab->available == cache->objects) {
275 /* Free associated memory */
276 list_remove(&slab->link);
277 spinlock_unlock(&cache->slablock);
278
279 return freed + slab_space_free(cache, slab);
280 } else if (slab->available == 1) {
281 /* It was in full, move to partial */
282 list_remove(&slab->link);
283 list_prepend(&slab->link, &cache->partial_slabs);
284 }
285
286 spinlock_unlock(&cache->slablock);
287 return freed;
288}
289
290/** Take new object from slab or create new if needed
291 *
292 * @return Object address or null
293 *
294 */
295static void *slab_obj_create(slab_cache_t *cache, int flags)
296{
297 spinlock_lock(&cache->slablock);
298
299 slab_t *slab;
300
301 if (list_empty(&cache->partial_slabs)) {
302 /*
303 * Allow recursion and reclaiming
304 * - this should work, as the slab control structures
305 * are small and do not need to allocate with anything
306 * other than frame_alloc when they are allocating,
307 * that's why we should get recursion at most 1-level deep
308 *
309 */
310 spinlock_unlock(&cache->slablock);
311 slab = slab_space_alloc(cache, flags);
312 if (!slab)
313 return NULL;
314
315 spinlock_lock(&cache->slablock);
316 } else {
317 slab = list_get_instance(cache->partial_slabs.next, slab_t,
318 link);
319 list_remove(&slab->link);
320 }
321
322 void *obj = slab->start + slab->nextavail * cache->size;
323 slab->nextavail = *((size_t *) obj);
324 slab->available--;
325
326 if (!slab->available)
327 list_prepend(&slab->link, &cache->full_slabs);
328 else
329 list_prepend(&slab->link, &cache->partial_slabs);
330
331 spinlock_unlock(&cache->slablock);
332
333 if ((cache->constructor) && (cache->constructor(obj, flags))) {
334 /* Bad, bad, construction failed */
335 slab_obj_destroy(cache, obj, slab);
336 return NULL;
337 }
338
339 return obj;
340}
341
342/****************************/
343/* CPU-Cache slab functions */
344/****************************/
345
346/** Find a full magazine in cache, take it from list and return it
347 *
348 * @param first If true, return first, else last mag.
349 *
350 */
351static slab_magazine_t *get_mag_from_cache(slab_cache_t *cache, bool first)
352{
353 slab_magazine_t *mag = NULL;
354 link_t *cur;
355
356 spinlock_lock(&cache->maglock);
357 if (!list_empty(&cache->magazines)) {
358 if (first)
359 cur = cache->magazines.next;
360 else
361 cur = cache->magazines.prev;
362
363 mag = list_get_instance(cur, slab_magazine_t, link);
364 list_remove(&mag->link);
365 atomic_dec(&cache->magazine_counter);
366 }
367
368 spinlock_unlock(&cache->maglock);
369 return mag;
370}
371
372/** Prepend magazine to magazine list in cache
373 *
374 */
375static void put_mag_to_cache(slab_cache_t *cache, slab_magazine_t *mag)
376{
377 spinlock_lock(&cache->maglock);
378
379 list_prepend(&mag->link, &cache->magazines);
380 atomic_inc(&cache->magazine_counter);
381
382 spinlock_unlock(&cache->maglock);
383}
384
385/** Free all objects in magazine and free memory associated with magazine
386 *
387 * @return Number of freed pages
388 *
389 */
390static size_t magazine_destroy(slab_cache_t *cache, slab_magazine_t *mag)
391{
392 size_t i;
393 size_t frames = 0;
394
395 for (i = 0; i < mag->busy; i++) {
396 frames += slab_obj_destroy(cache, mag->objs[i], NULL);
397 atomic_dec(&cache->cached_objs);
398 }
399
400 slab_free(&mag_cache, mag);
401
402 return frames;
403}
404
405/** Find full magazine, set it as current and return it
406 *
407 * Assume cpu_magazine lock is held
408 *
409 */
410static slab_magazine_t *get_full_current_mag(slab_cache_t *cache)
411{
412 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
413 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
414
415 if (cmag) { /* First try local CPU magazines */
416 if (cmag->busy)
417 return cmag;
418
419 if ((lastmag) && (lastmag->busy)) {
420 cache->mag_cache[CPU->id].current = lastmag;
421 cache->mag_cache[CPU->id].last = cmag;
422 return lastmag;
423 }
424 }
425
426 /* Local magazines are empty, import one from magazine list */
427 slab_magazine_t *newmag = get_mag_from_cache(cache, 1);
428 if (!newmag)
429 return NULL;
430
431 if (lastmag)
432 magazine_destroy(cache, lastmag);
433
434 cache->mag_cache[CPU->id].last = cmag;
435 cache->mag_cache[CPU->id].current = newmag;
436
437 return newmag;
438}
439
440/** Try to find object in CPU-cache magazines
441 *
442 * @return Pointer to object or NULL if not available
443 *
444 */
445static void *magazine_obj_get(slab_cache_t *cache)
446{
447 if (!CPU)
448 return NULL;
449
450 spinlock_lock(&cache->mag_cache[CPU->id].lock);
451
452 slab_magazine_t *mag = get_full_current_mag(cache);
453 if (!mag) {
454 spinlock_unlock(&cache->mag_cache[CPU->id].lock);
455 return NULL;
456 }
457
458 void *obj = mag->objs[--mag->busy];
459 spinlock_unlock(&cache->mag_cache[CPU->id].lock);
460
461 atomic_dec(&cache->cached_objs);
462
463 return obj;
464}
465
466/** Assure that the current magazine is empty, return pointer to it,
467 * or NULL if no empty magazine is available and cannot be allocated
468 *
469 * Assume mag_cache[CPU->id].lock is held
470 *
471 * We have 2 magazines bound to processor.
472 * First try the current.
473 * If full, try the last.
474 * If full, put to magazines list.
475 *
476 */
477static slab_magazine_t *make_empty_current_mag(slab_cache_t *cache)
478{
479 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
480 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
481
482 if (cmag) {
483 if (cmag->busy < cmag->size)
484 return cmag;
485
486 if ((lastmag) && (lastmag->busy < lastmag->size)) {
487 cache->mag_cache[CPU->id].last = cmag;
488 cache->mag_cache[CPU->id].current = lastmag;
489 return lastmag;
490 }
491 }
492
493 /* current | last are full | nonexistent, allocate new */
494
495 /*
496 * We do not want to sleep just because of caching,
497 * especially we do not want reclaiming to start, as
498 * this would deadlock.
499 *
500 */
501 slab_magazine_t *newmag = slab_alloc(&mag_cache,
502 FRAME_ATOMIC | FRAME_NO_RECLAIM);
503 if (!newmag)
504 return NULL;
505
506 newmag->size = SLAB_MAG_SIZE;
507 newmag->busy = 0;
508
509 /* Flush last to magazine list */
510 if (lastmag)
511 put_mag_to_cache(cache, lastmag);
512
513 /* Move current as last, save new as current */
514 cache->mag_cache[CPU->id].last = cmag;
515 cache->mag_cache[CPU->id].current = newmag;
516
517 return newmag;
518}
519
520/** Put object into CPU-cache magazine
521 *
522 * @return 0 on success, -1 on no memory
523 *
524 */
525static int magazine_obj_put(slab_cache_t *cache, void *obj)
526{
527 if (!CPU)
528 return -1;
529
530 spinlock_lock(&cache->mag_cache[CPU->id].lock);
531
532 slab_magazine_t *mag = make_empty_current_mag(cache);
533 if (!mag) {
534 spinlock_unlock(&cache->mag_cache[CPU->id].lock);
535 return -1;
536 }
537
538 mag->objs[mag->busy++] = obj;
539
540 spinlock_unlock(&cache->mag_cache[CPU->id].lock);
541
542 atomic_inc(&cache->cached_objs);
543
544 return 0;
545}
546
547/************************/
548/* Slab cache functions */
549/************************/
550
551/** Return number of objects that fit in certain cache size
552 *
553 */
554static size_t comp_objects(slab_cache_t *cache)
555{
556 if (cache->flags & SLAB_CACHE_SLINSIDE)
557 return ((PAGE_SIZE << cache->order)
558 - sizeof(slab_t)) / cache->size;
559 else
560 return (PAGE_SIZE << cache->order) / cache->size;
561}
562
563/** Return wasted space in slab
564 *
565 */
566static size_t badness(slab_cache_t *cache)
567{
568 size_t objects = comp_objects(cache);
569 size_t ssize = PAGE_SIZE << cache->order;
570
571 if (cache->flags & SLAB_CACHE_SLINSIDE)
572 ssize -= sizeof(slab_t);
573
574 return ssize - objects * cache->size;
575}
576
577/** Initialize mag_cache structure in slab cache
578 *
579 */
580static bool make_magcache(slab_cache_t *cache)
581{
582 ASSERT(_slab_initialized >= 2);
583
584 cache->mag_cache = malloc(sizeof(slab_mag_cache_t) * config.cpu_count,
585 FRAME_ATOMIC);
586 if (!cache->mag_cache)
587 return false;
588
589 size_t i;
590 for (i = 0; i < config.cpu_count; i++) {
591 memsetb(&cache->mag_cache[i], sizeof(cache->mag_cache[i]), 0);
592 spinlock_initialize(&cache->mag_cache[i].lock,
593 "slab.cache.mag_cache[].lock");
594 }
595
596 return true;
597}
598
599/** Initialize allocated memory as a slab cache
600 *
601 */
602static void _slab_cache_create(slab_cache_t *cache, const char *name,
603 size_t size, size_t align, int (*constructor)(void *obj,
604 unsigned int kmflag), size_t (*destructor)(void *obj), unsigned int flags)
605{
606 memsetb(cache, sizeof(*cache), 0);
607 cache->name = name;
608
609 if (align < sizeof(unative_t))
610 align = sizeof(unative_t);
611
612 size = ALIGN_UP(size, align);
613
614 cache->size = size;
615 cache->constructor = constructor;
616 cache->destructor = destructor;
617 cache->flags = flags;
618
619 list_initialize(&cache->full_slabs);
620 list_initialize(&cache->partial_slabs);
621 list_initialize(&cache->magazines);
622
623 spinlock_initialize(&cache->slablock, "slab.cache.slablock");
624 spinlock_initialize(&cache->maglock, "slab.cache.maglock");
625
626 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
627 (void) make_magcache(cache);
628
629 /* Compute slab sizes, object counts in slabs etc. */
630 if (cache->size < SLAB_INSIDE_SIZE)
631 cache->flags |= SLAB_CACHE_SLINSIDE;
632
633 /* Minimum slab order */
634 size_t pages = SIZE2FRAMES(cache->size);
635
636 /* We need the 2^order >= pages */
637 if (pages == 1)
638 cache->order = 0;
639 else
640 cache->order = fnzb(pages - 1) + 1;
641
642 while (badness(cache) > SLAB_MAX_BADNESS(cache))
643 cache->order += 1;
644
645 cache->objects = comp_objects(cache);
646
647 /* If info fits in, put it inside */
648 if (badness(cache) > sizeof(slab_t))
649 cache->flags |= SLAB_CACHE_SLINSIDE;
650
651 /* Add cache to cache list */
652 irq_spinlock_lock(&slab_cache_lock, true);
653 list_append(&cache->link, &slab_cache_list);
654 irq_spinlock_unlock(&slab_cache_lock, true);
655}
656
657/** Create slab cache
658 *
659 */
660slab_cache_t *slab_cache_create(const char *name, size_t size, size_t align,
661 int (*constructor)(void *obj, unsigned int kmflag),
662 size_t (*destructor)(void *obj), unsigned int flags)
663{
664 slab_cache_t *cache = slab_alloc(&slab_cache_cache, 0);
665 _slab_cache_create(cache, name, size, align, constructor, destructor,
666 flags);
667
668 return cache;
669}
670
671/** Reclaim space occupied by objects that are already free
672 *
673 * @param flags If contains SLAB_RECLAIM_ALL, do aggressive freeing
674 *
675 * @return Number of freed pages
676 *
677 */
678static size_t _slab_reclaim(slab_cache_t *cache, unsigned int flags)
679{
680 if (cache->flags & SLAB_CACHE_NOMAGAZINE)
681 return 0; /* Nothing to do */
682
683 /*
684 * We count up to original magazine count to avoid
685 * endless loop
686 */
687 atomic_count_t magcount = atomic_get(&cache->magazine_counter);
688
689 slab_magazine_t *mag;
690 size_t frames = 0;
691
692 while ((magcount--) && (mag = get_mag_from_cache(cache, 0))) {
693 frames += magazine_destroy(cache, mag);
694 if ((!(flags & SLAB_RECLAIM_ALL)) && (frames))
695 break;
696 }
697
698 if (flags & SLAB_RECLAIM_ALL) {
699 /* Free cpu-bound magazines */
700 /* Destroy CPU magazines */
701 size_t i;
702 for (i = 0; i < config.cpu_count; i++) {
703 spinlock_lock(&cache->mag_cache[i].lock);
704
705 mag = cache->mag_cache[i].current;
706 if (mag)
707 frames += magazine_destroy(cache, mag);
708 cache->mag_cache[i].current = NULL;
709
710 mag = cache->mag_cache[i].last;
711 if (mag)
712 frames += magazine_destroy(cache, mag);
713 cache->mag_cache[i].last = NULL;
714
715 spinlock_unlock(&cache->mag_cache[i].lock);
716 }
717 }
718
719 return frames;
720}
721
722/** Check that there are no slabs and remove cache from system
723 *
724 */
725void slab_cache_destroy(slab_cache_t *cache)
726{
727 /*
728 * First remove cache from link, so that we don't need
729 * to disable interrupts later
730 *
731 */
732 irq_spinlock_lock(&slab_cache_lock, true);
733 list_remove(&cache->link);
734 irq_spinlock_unlock(&slab_cache_lock, true);
735
736 /*
737 * Do not lock anything, we assume the software is correct and
738 * does not touch the cache when it decides to destroy it
739 *
740 */
741
742 /* Destroy all magazines */
743 _slab_reclaim(cache, SLAB_RECLAIM_ALL);
744
745 /* All slabs must be empty */
746 if ((!list_empty(&cache->full_slabs)) ||
747 (!list_empty(&cache->partial_slabs)))
748 panic("Destroying cache that is not empty.");
749
750 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
751 free(cache->mag_cache);
752
753 slab_free(&slab_cache_cache, cache);
754}
755
756/** Allocate new object from cache - if no flags given, always returns memory
757 *
758 */
759void *slab_alloc(slab_cache_t *cache, unsigned int flags)
760{
761 /* Disable interrupts to avoid deadlocks with interrupt handlers */
762 ipl_t ipl = interrupts_disable();
763
764 void *result = NULL;
765
766 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
767 result = magazine_obj_get(cache);
768
769 if (!result)
770 result = slab_obj_create(cache, flags);
771
772 interrupts_restore(ipl);
773
774 if (result)
775 atomic_inc(&cache->allocated_objs);
776
777 return result;
778}
779
780/** Return object to cache, use slab if known
781 *
782 */
783static void _slab_free(slab_cache_t *cache, void *obj, slab_t *slab)
784{
785 ipl_t ipl = interrupts_disable();
786
787 if ((cache->flags & SLAB_CACHE_NOMAGAZINE) ||
788 (magazine_obj_put(cache, obj)))
789 slab_obj_destroy(cache, obj, slab);
790
791 interrupts_restore(ipl);
792 atomic_dec(&cache->allocated_objs);
793}
794
795/** Return slab object to cache
796 *
797 */
798void slab_free(slab_cache_t *cache, void *obj)
799{
800 _slab_free(cache, obj, NULL);
801}
802
803/** Go through all caches and reclaim what is possible
804 *
805 * Interrupts must be disabled before calling this function,
806 * otherwise memory allocation from interrupts can deadlock.
807 *
808 */
809size_t slab_reclaim(unsigned int flags)
810{
811 irq_spinlock_lock(&slab_cache_lock, false);
812
813 size_t frames = 0;
814 link_t *cur;
815 for (cur = slab_cache_list.next; cur != &slab_cache_list;
816 cur = cur->next) {
817 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
818 frames += _slab_reclaim(cache, flags);
819 }
820
821 irq_spinlock_unlock(&slab_cache_lock, false);
822
823 return frames;
824}
825
826/* Print list of slabs
827 *
828 */
829void slab_print_list(void)
830{
831 printf("slab name size pages obj/pg slabs cached allocated"
832 " ctl\n");
833 printf("---------------- -------- ------ -------- ------ ------ ---------"
834 " ---\n");
835
836 size_t skip = 0;
837 while (true) {
838 /*
839 * We must not hold the slab_cache_lock spinlock when printing
840 * the statistics. Otherwise we can easily deadlock if the print
841 * needs to allocate memory.
842 *
843 * Therefore, we walk through the slab cache list, skipping some
844 * amount of already processed caches during each iteration and
845 * gathering statistics about the first unprocessed cache. For
846 * the sake of printing the statistics, we realese the
847 * slab_cache_lock and reacquire it afterwards. Then the walk
848 * starts again.
849 *
850 * This limits both the efficiency and also accuracy of the
851 * obtained statistics. The efficiency is decreased because the
852 * time complexity of the algorithm is quadratic instead of
853 * linear. The accuracy is impacted because we drop the lock
854 * after processing one cache. If there is someone else
855 * manipulating the cache list, we might omit an arbitrary
856 * number of caches or process one cache multiple times.
857 * However, we don't bleed for this algorithm for it is only
858 * statistics.
859 */
860
861 irq_spinlock_lock(&slab_cache_lock, true);
862
863 link_t *cur;
864 size_t i;
865 for (i = 0, cur = slab_cache_list.next;
866 (i < skip) && (cur != &slab_cache_list);
867 i++, cur = cur->next);
868
869 if (cur == &slab_cache_list) {
870 irq_spinlock_unlock(&slab_cache_lock, true);
871 break;
872 }
873
874 skip++;
875
876 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
877
878 const char *name = cache->name;
879 uint8_t order = cache->order;
880 size_t size = cache->size;
881 size_t objects = cache->objects;
882 long allocated_slabs = atomic_get(&cache->allocated_slabs);
883 long cached_objs = atomic_get(&cache->cached_objs);
884 long allocated_objs = atomic_get(&cache->allocated_objs);
885 unsigned int flags = cache->flags;
886
887 irq_spinlock_unlock(&slab_cache_lock, true);
888
889 printf("%-16s %8" PRIs " %6u %8" PRIs " %6ld %6ld %9ld %-3s\n",
890 name, size, (1 << order), objects, allocated_slabs,
891 cached_objs, allocated_objs,
892 flags & SLAB_CACHE_SLINSIDE ? "in" : "out");
893 }
894}
895
896void slab_cache_init(void)
897{
898 /* Initialize magazine cache */
899 _slab_cache_create(&mag_cache, "slab_magazine",
900 sizeof(slab_magazine_t) + SLAB_MAG_SIZE * sizeof(void*),
901 sizeof(uintptr_t), NULL, NULL, SLAB_CACHE_NOMAGAZINE |
902 SLAB_CACHE_SLINSIDE);
903
904 /* Initialize slab_cache cache */
905 _slab_cache_create(&slab_cache_cache, "slab_cache",
906 sizeof(slab_cache_cache), sizeof(uintptr_t), NULL, NULL,
907 SLAB_CACHE_NOMAGAZINE | SLAB_CACHE_SLINSIDE);
908
909 /* Initialize external slab cache */
910 slab_extern_cache = slab_cache_create("slab_extern", sizeof(slab_t), 0,
911 NULL, NULL, SLAB_CACHE_SLINSIDE | SLAB_CACHE_MAGDEFERRED);
912
913 /* Initialize structures for malloc */
914 size_t i;
915 size_t size;
916
917 for (i = 0, size = (1 << SLAB_MIN_MALLOC_W);
918 i < (SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1);
919 i++, size <<= 1) {
920 malloc_caches[i] = slab_cache_create(malloc_names[i], size, 0,
921 NULL, NULL, SLAB_CACHE_MAGDEFERRED);
922 }
923
924#ifdef CONFIG_DEBUG
925 _slab_initialized = 1;
926#endif
927}
928
929/** Enable cpu_cache
930 *
931 * Kernel calls this function, when it knows the real number of
932 * processors. Allocate slab for cpucache and enable it on all
933 * existing slabs that are SLAB_CACHE_MAGDEFERRED
934 *
935 */
936void slab_enable_cpucache(void)
937{
938#ifdef CONFIG_DEBUG
939 _slab_initialized = 2;
940#endif
941
942 irq_spinlock_lock(&slab_cache_lock, false);
943
944 link_t *cur;
945 for (cur = slab_cache_list.next; cur != &slab_cache_list;
946 cur = cur->next) {
947 slab_cache_t *slab = list_get_instance(cur, slab_cache_t, link);
948 if ((slab->flags & SLAB_CACHE_MAGDEFERRED) !=
949 SLAB_CACHE_MAGDEFERRED)
950 continue;
951
952 (void) make_magcache(slab);
953 slab->flags &= ~SLAB_CACHE_MAGDEFERRED;
954 }
955
956 irq_spinlock_unlock(&slab_cache_lock, false);
957}
958
959void *malloc(size_t size, unsigned int flags)
960{
961 ASSERT(_slab_initialized);
962 ASSERT(size <= (1 << SLAB_MAX_MALLOC_W));
963
964 if (size < (1 << SLAB_MIN_MALLOC_W))
965 size = (1 << SLAB_MIN_MALLOC_W);
966
967 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
968
969 return slab_alloc(malloc_caches[idx], flags);
970}
971
972void *realloc(void *ptr, size_t size, unsigned int flags)
973{
974 ASSERT(_slab_initialized);
975 ASSERT(size <= (1 << SLAB_MAX_MALLOC_W));
976
977 void *new_ptr;
978
979 if (size > 0) {
980 if (size < (1 << SLAB_MIN_MALLOC_W))
981 size = (1 << SLAB_MIN_MALLOC_W);
982 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
983
984 new_ptr = slab_alloc(malloc_caches[idx], flags);
985 } else
986 new_ptr = NULL;
987
988 if ((new_ptr != NULL) && (ptr != NULL)) {
989 slab_t *slab = obj2slab(ptr);
990 memcpy(new_ptr, ptr, min(size, slab->cache->size));
991 }
992
993 if (ptr != NULL)
994 free(ptr);
995
996 return new_ptr;
997}
998
999void free(void *ptr)
1000{
1001 if (!ptr)
1002 return;
1003
1004 slab_t *slab = obj2slab(ptr);
1005 _slab_free(slab->cache, ptr, slab);
1006}
1007
1008/** @}
1009 */
Note: See TracBrowser for help on using the repository browser.