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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since c8d0f9e5 was c8d0f9e5, checked in by Jakub Jermar <jakub@…>, 13 years ago

Add assertions to stress the fact that the slab allocator spinlocks are
always taken with interrupts disabled.

  • 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
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 */
179NO_TRACE static slab_t *slab_space_alloc(slab_cache_t *cache,
180 unsigned int flags)
181{
182 size_t zone = 0;
183
184 void *data = frame_alloc_generic(cache->order, FRAME_KA | flags, &zone);
185 if (!data) {
186 return NULL;
187 }
188
189 slab_t *slab;
190 size_t fsize;
191
192 if (!(cache->flags & SLAB_CACHE_SLINSIDE)) {
193 slab = slab_alloc(slab_extern_cache, flags);
194 if (!slab) {
195 frame_free(KA2PA(data));
196 return NULL;
197 }
198 } else {
199 fsize = (PAGE_SIZE << cache->order);
200 slab = data + fsize - sizeof(*slab);
201 }
202
203 /* Fill in slab structures */
204 size_t i;
205 for (i = 0; i < ((size_t) 1 << cache->order); i++)
206 frame_set_parent(ADDR2PFN(KA2PA(data)) + i, slab, zone);
207
208 slab->start = data;
209 slab->available = cache->objects;
210 slab->nextavail = 0;
211 slab->cache = cache;
212
213 for (i = 0; i < cache->objects; i++)
214 *((size_t *) (slab->start + i * cache->size)) = i + 1;
215
216 atomic_inc(&cache->allocated_slabs);
217 return slab;
218}
219
220/** Deallocate space associated with slab
221 *
222 * @return number of freed frames
223 *
224 */
225NO_TRACE static size_t slab_space_free(slab_cache_t *cache, slab_t *slab)
226{
227 frame_free(KA2PA(slab->start));
228 if (!(cache->flags & SLAB_CACHE_SLINSIDE))
229 slab_free(slab_extern_cache, slab);
230
231 atomic_dec(&cache->allocated_slabs);
232
233 return (1 << cache->order);
234}
235
236/** Map object to slab structure */
237NO_TRACE static slab_t *obj2slab(void *obj)
238{
239 return (slab_t *) frame_get_parent(ADDR2PFN(KA2PA(obj)), 0);
240}
241
242/******************/
243/* Slab functions */
244/******************/
245
246/** Return object to slab and call a destructor
247 *
248 * @param slab If the caller knows directly slab of the object, otherwise NULL
249 *
250 * @return Number of freed pages
251 *
252 */
253NO_TRACE static size_t slab_obj_destroy(slab_cache_t *cache, void *obj,
254 slab_t *slab)
255{
256 ASSERT(interrupts_disabled());
257
258 if (!slab)
259 slab = obj2slab(obj);
260
261 ASSERT(slab->cache == cache);
262
263 size_t freed = 0;
264
265 if (cache->destructor)
266 freed = cache->destructor(obj);
267
268 spinlock_lock(&cache->slablock);
269 ASSERT(slab->available < cache->objects);
270
271 *((size_t *) obj) = slab->nextavail;
272 slab->nextavail = (obj - slab->start) / cache->size;
273 slab->available++;
274
275 /* Move it to correct list */
276 if (slab->available == cache->objects) {
277 /* Free associated memory */
278 list_remove(&slab->link);
279 spinlock_unlock(&cache->slablock);
280
281 return freed + slab_space_free(cache, slab);
282 } else if (slab->available == 1) {
283 /* It was in full, move to partial */
284 list_remove(&slab->link);
285 list_prepend(&slab->link, &cache->partial_slabs);
286 }
287
288 spinlock_unlock(&cache->slablock);
289 return freed;
290}
291
292/** Take new object from slab or create new if needed
293 *
294 * @return Object address or null
295 *
296 */
297NO_TRACE static void *slab_obj_create(slab_cache_t *cache, unsigned int flags)
298{
299 ASSERT(interrupts_disabled());
300
301 spinlock_lock(&cache->slablock);
302
303 slab_t *slab;
304
305 if (list_empty(&cache->partial_slabs)) {
306 /*
307 * Allow recursion and reclaiming
308 * - this should work, as the slab control structures
309 * are small and do not need to allocate with anything
310 * other than frame_alloc when they are allocating,
311 * that's why we should get recursion at most 1-level deep
312 *
313 */
314 spinlock_unlock(&cache->slablock);
315 slab = slab_space_alloc(cache, flags);
316 if (!slab)
317 return NULL;
318
319 spinlock_lock(&cache->slablock);
320 } else {
321 slab = list_get_instance(list_first(&cache->partial_slabs),
322 slab_t, link);
323 list_remove(&slab->link);
324 }
325
326 void *obj = slab->start + slab->nextavail * cache->size;
327 slab->nextavail = *((size_t *) obj);
328 slab->available--;
329
330 if (!slab->available)
331 list_prepend(&slab->link, &cache->full_slabs);
332 else
333 list_prepend(&slab->link, &cache->partial_slabs);
334
335 spinlock_unlock(&cache->slablock);
336
337 if ((cache->constructor) && (cache->constructor(obj, flags))) {
338 /* Bad, bad, construction failed */
339 slab_obj_destroy(cache, obj, slab);
340 return NULL;
341 }
342
343 return obj;
344}
345
346/****************************/
347/* CPU-Cache slab functions */
348/****************************/
349
350/** Find a full magazine in cache, take it from list and return it
351 *
352 * @param first If true, return first, else last mag.
353 *
354 */
355NO_TRACE static slab_magazine_t *get_mag_from_cache(slab_cache_t *cache,
356 bool first)
357{
358 slab_magazine_t *mag = NULL;
359 link_t *cur;
360
361 ASSERT(interrupts_disabled());
362
363 spinlock_lock(&cache->maglock);
364 if (!list_empty(&cache->magazines)) {
365 if (first)
366 cur = list_first(&cache->magazines);
367 else
368 cur = list_last(&cache->magazines);
369
370 mag = list_get_instance(cur, slab_magazine_t, link);
371 list_remove(&mag->link);
372 atomic_dec(&cache->magazine_counter);
373 }
374 spinlock_unlock(&cache->maglock);
375
376 return mag;
377}
378
379/** Prepend magazine to magazine list in cache
380 *
381 */
382NO_TRACE static void put_mag_to_cache(slab_cache_t *cache,
383 slab_magazine_t *mag)
384{
385 ASSERT(interrupts_disabled());
386
387 spinlock_lock(&cache->maglock);
388
389 list_prepend(&mag->link, &cache->magazines);
390 atomic_inc(&cache->magazine_counter);
391
392 spinlock_unlock(&cache->maglock);
393}
394
395/** Free all objects in magazine and free memory associated with magazine
396 *
397 * @return Number of freed pages
398 *
399 */
400NO_TRACE static size_t magazine_destroy(slab_cache_t *cache,
401 slab_magazine_t *mag)
402{
403 size_t i;
404 size_t frames = 0;
405
406 for (i = 0; i < mag->busy; i++) {
407 frames += slab_obj_destroy(cache, mag->objs[i], NULL);
408 atomic_dec(&cache->cached_objs);
409 }
410
411 slab_free(&mag_cache, mag);
412
413 return frames;
414}
415
416/** Find full magazine, set it as current and return it
417 *
418 */
419NO_TRACE static slab_magazine_t *get_full_current_mag(slab_cache_t *cache)
420{
421 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
422 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
423
424 ASSERT(irq_spinlock_locked(&cache->mag_cache[CPU->id].lock));
425
426 if (cmag) { /* First try local CPU magazines */
427 if (cmag->busy)
428 return cmag;
429
430 if ((lastmag) && (lastmag->busy)) {
431 cache->mag_cache[CPU->id].current = lastmag;
432 cache->mag_cache[CPU->id].last = cmag;
433 return lastmag;
434 }
435 }
436
437 /* Local magazines are empty, import one from magazine list */
438 slab_magazine_t *newmag = get_mag_from_cache(cache, 1);
439 if (!newmag)
440 return NULL;
441
442 if (lastmag)
443 magazine_destroy(cache, lastmag);
444
445 cache->mag_cache[CPU->id].last = cmag;
446 cache->mag_cache[CPU->id].current = newmag;
447
448 return newmag;
449}
450
451/** Try to find object in CPU-cache magazines
452 *
453 * @return Pointer to object or NULL if not available
454 *
455 */
456NO_TRACE static void *magazine_obj_get(slab_cache_t *cache)
457{
458 if (!CPU)
459 return NULL;
460
461 irq_spinlock_lock(&cache->mag_cache[CPU->id].lock, true);
462
463 slab_magazine_t *mag = get_full_current_mag(cache);
464 if (!mag) {
465 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
466 return NULL;
467 }
468
469 void *obj = mag->objs[--mag->busy];
470 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
471
472 atomic_dec(&cache->cached_objs);
473
474 return obj;
475}
476
477/** Assure that the current magazine is empty, return pointer to it,
478 * or NULL if no empty magazine is available and cannot be allocated
479 *
480 * We have 2 magazines bound to processor.
481 * First try the current.
482 * If full, try the last.
483 * If full, put to magazines list.
484 *
485 */
486NO_TRACE static slab_magazine_t *make_empty_current_mag(slab_cache_t *cache)
487{
488 slab_magazine_t *cmag = cache->mag_cache[CPU->id].current;
489 slab_magazine_t *lastmag = cache->mag_cache[CPU->id].last;
490
491 ASSERT(irq_spinlock_locked(&cache->mag_cache[CPU->id].lock));
492
493 if (cmag) {
494 if (cmag->busy < cmag->size)
495 return cmag;
496
497 if ((lastmag) && (lastmag->busy < lastmag->size)) {
498 cache->mag_cache[CPU->id].last = cmag;
499 cache->mag_cache[CPU->id].current = lastmag;
500 return lastmag;
501 }
502 }
503
504 /* current | last are full | nonexistent, allocate new */
505
506 /*
507 * We do not want to sleep just because of caching,
508 * especially we do not want reclaiming to start, as
509 * this would deadlock.
510 *
511 */
512 slab_magazine_t *newmag = slab_alloc(&mag_cache,
513 FRAME_ATOMIC | FRAME_NO_RECLAIM);
514 if (!newmag)
515 return NULL;
516
517 newmag->size = SLAB_MAG_SIZE;
518 newmag->busy = 0;
519
520 /* Flush last to magazine list */
521 if (lastmag)
522 put_mag_to_cache(cache, lastmag);
523
524 /* Move current as last, save new as current */
525 cache->mag_cache[CPU->id].last = cmag;
526 cache->mag_cache[CPU->id].current = newmag;
527
528 return newmag;
529}
530
531/** Put object into CPU-cache magazine
532 *
533 * @return 0 on success, -1 on no memory
534 *
535 */
536NO_TRACE static int magazine_obj_put(slab_cache_t *cache, void *obj)
537{
538 if (!CPU)
539 return -1;
540
541 irq_spinlock_lock(&cache->mag_cache[CPU->id].lock, true);
542
543 slab_magazine_t *mag = make_empty_current_mag(cache);
544 if (!mag) {
545 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
546 return -1;
547 }
548
549 mag->objs[mag->busy++] = obj;
550
551 irq_spinlock_unlock(&cache->mag_cache[CPU->id].lock, true);
552
553 atomic_inc(&cache->cached_objs);
554
555 return 0;
556}
557
558/************************/
559/* Slab cache functions */
560/************************/
561
562/** Return number of objects that fit in certain cache size
563 *
564 */
565NO_TRACE static size_t comp_objects(slab_cache_t *cache)
566{
567 if (cache->flags & SLAB_CACHE_SLINSIDE)
568 return ((PAGE_SIZE << cache->order)
569 - sizeof(slab_t)) / cache->size;
570 else
571 return (PAGE_SIZE << cache->order) / cache->size;
572}
573
574/** Return wasted space in slab
575 *
576 */
577NO_TRACE static size_t badness(slab_cache_t *cache)
578{
579 size_t objects = comp_objects(cache);
580 size_t ssize = PAGE_SIZE << cache->order;
581
582 if (cache->flags & SLAB_CACHE_SLINSIDE)
583 ssize -= sizeof(slab_t);
584
585 return ssize - objects * cache->size;
586}
587
588/** Initialize mag_cache structure in slab cache
589 *
590 */
591NO_TRACE static bool make_magcache(slab_cache_t *cache)
592{
593 ASSERT(_slab_initialized >= 2);
594
595 cache->mag_cache = malloc(sizeof(slab_mag_cache_t) * config.cpu_count,
596 FRAME_ATOMIC);
597 if (!cache->mag_cache)
598 return false;
599
600 size_t i;
601 for (i = 0; i < config.cpu_count; i++) {
602 memsetb(&cache->mag_cache[i], sizeof(cache->mag_cache[i]), 0);
603 irq_spinlock_initialize(&cache->mag_cache[i].lock,
604 "slab.cache.mag_cache[].lock");
605 }
606
607 return true;
608}
609
610/** Initialize allocated memory as a slab cache
611 *
612 */
613NO_TRACE static void _slab_cache_create(slab_cache_t *cache, const char *name,
614 size_t size, size_t align, int (*constructor)(void *obj,
615 unsigned int kmflag), size_t (*destructor)(void *obj), unsigned int flags)
616{
617 memsetb(cache, sizeof(*cache), 0);
618 cache->name = name;
619
620 if (align < sizeof(sysarg_t))
621 align = sizeof(sysarg_t);
622
623 size = ALIGN_UP(size, align);
624
625 cache->size = size;
626 cache->constructor = constructor;
627 cache->destructor = destructor;
628 cache->flags = flags;
629
630 list_initialize(&cache->full_slabs);
631 list_initialize(&cache->partial_slabs);
632 list_initialize(&cache->magazines);
633
634 spinlock_initialize(&cache->slablock, "slab.cache.slablock");
635 spinlock_initialize(&cache->maglock, "slab.cache.maglock");
636
637 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
638 (void) make_magcache(cache);
639
640 /* Compute slab sizes, object counts in slabs etc. */
641 if (cache->size < SLAB_INSIDE_SIZE)
642 cache->flags |= SLAB_CACHE_SLINSIDE;
643
644 /* Minimum slab order */
645 size_t pages = SIZE2FRAMES(cache->size);
646
647 /* We need the 2^order >= pages */
648 if (pages == 1)
649 cache->order = 0;
650 else
651 cache->order = fnzb(pages - 1) + 1;
652
653 while (badness(cache) > SLAB_MAX_BADNESS(cache))
654 cache->order += 1;
655
656 cache->objects = comp_objects(cache);
657
658 /* If info fits in, put it inside */
659 if (badness(cache) > sizeof(slab_t))
660 cache->flags |= SLAB_CACHE_SLINSIDE;
661
662 /* Add cache to cache list */
663 irq_spinlock_lock(&slab_cache_lock, true);
664 list_append(&cache->link, &slab_cache_list);
665 irq_spinlock_unlock(&slab_cache_lock, true);
666}
667
668/** Create slab cache
669 *
670 */
671slab_cache_t *slab_cache_create(const char *name, size_t size, size_t align,
672 int (*constructor)(void *obj, unsigned int kmflag),
673 size_t (*destructor)(void *obj), unsigned int flags)
674{
675 slab_cache_t *cache = slab_alloc(&slab_cache_cache, 0);
676 _slab_cache_create(cache, name, size, align, constructor, destructor,
677 flags);
678
679 return cache;
680}
681
682/** Reclaim space occupied by objects that are already free
683 *
684 * @param flags If contains SLAB_RECLAIM_ALL, do aggressive freeing
685 *
686 * @return Number of freed pages
687 *
688 */
689NO_TRACE static size_t _slab_reclaim(slab_cache_t *cache, unsigned int flags)
690{
691 if (cache->flags & SLAB_CACHE_NOMAGAZINE)
692 return 0; /* Nothing to do */
693
694 /*
695 * We count up to original magazine count to avoid
696 * endless loop
697 */
698 atomic_count_t magcount = atomic_get(&cache->magazine_counter);
699
700 slab_magazine_t *mag;
701 size_t frames = 0;
702
703 while ((magcount--) && (mag = get_mag_from_cache(cache, 0))) {
704 frames += magazine_destroy(cache, mag);
705 if ((!(flags & SLAB_RECLAIM_ALL)) && (frames))
706 break;
707 }
708
709 if (flags & SLAB_RECLAIM_ALL) {
710 /* Free cpu-bound magazines */
711 /* Destroy CPU magazines */
712 size_t i;
713 for (i = 0; i < config.cpu_count; i++) {
714 irq_spinlock_lock(&cache->mag_cache[i].lock, true);
715
716 mag = cache->mag_cache[i].current;
717 if (mag)
718 frames += magazine_destroy(cache, mag);
719 cache->mag_cache[i].current = NULL;
720
721 mag = cache->mag_cache[i].last;
722 if (mag)
723 frames += magazine_destroy(cache, mag);
724 cache->mag_cache[i].last = NULL;
725
726 irq_spinlock_unlock(&cache->mag_cache[i].lock, true);
727 }
728 }
729
730 return frames;
731}
732
733/** Check that there are no slabs and remove cache from system
734 *
735 */
736void slab_cache_destroy(slab_cache_t *cache)
737{
738 /*
739 * First remove cache from link, so that we don't need
740 * to disable interrupts later
741 *
742 */
743 irq_spinlock_lock(&slab_cache_lock, true);
744 list_remove(&cache->link);
745 irq_spinlock_unlock(&slab_cache_lock, true);
746
747 /*
748 * Do not lock anything, we assume the software is correct and
749 * does not touch the cache when it decides to destroy it
750 *
751 */
752
753 /* Destroy all magazines */
754 _slab_reclaim(cache, SLAB_RECLAIM_ALL);
755
756 /* All slabs must be empty */
757 if ((!list_empty(&cache->full_slabs)) ||
758 (!list_empty(&cache->partial_slabs)))
759 panic("Destroying cache that is not empty.");
760
761 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
762 free(cache->mag_cache);
763
764 slab_free(&slab_cache_cache, cache);
765}
766
767/** Allocate new object from cache - if no flags given, always returns memory
768 *
769 */
770void *slab_alloc(slab_cache_t *cache, unsigned int flags)
771{
772 /* Disable interrupts to avoid deadlocks with interrupt handlers */
773 ipl_t ipl = interrupts_disable();
774
775 void *result = NULL;
776
777 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
778 result = magazine_obj_get(cache);
779
780 if (!result)
781 result = slab_obj_create(cache, flags);
782
783 interrupts_restore(ipl);
784
785 if (result)
786 atomic_inc(&cache->allocated_objs);
787
788 return result;
789}
790
791/** Return object to cache, use slab if known
792 *
793 */
794NO_TRACE static void _slab_free(slab_cache_t *cache, void *obj, slab_t *slab)
795{
796 ipl_t ipl = interrupts_disable();
797
798 if ((cache->flags & SLAB_CACHE_NOMAGAZINE) ||
799 (magazine_obj_put(cache, obj)))
800 slab_obj_destroy(cache, obj, slab);
801
802 interrupts_restore(ipl);
803 atomic_dec(&cache->allocated_objs);
804}
805
806/** Return slab object to cache
807 *
808 */
809void slab_free(slab_cache_t *cache, void *obj)
810{
811 _slab_free(cache, obj, NULL);
812}
813
814/** Go through all caches and reclaim what is possible */
815size_t slab_reclaim(unsigned int flags)
816{
817 irq_spinlock_lock(&slab_cache_lock, true);
818
819 size_t frames = 0;
820 list_foreach(slab_cache_list, cur) {
821 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
822 frames += _slab_reclaim(cache, flags);
823 }
824
825 irq_spinlock_unlock(&slab_cache_lock, true);
826
827 return frames;
828}
829
830/* Print list of slabs
831 *
832 */
833void slab_print_list(void)
834{
835 printf("[slab name ] [size ] [pages ] [obj/pg] [slabs ]"
836 " [cached] [alloc ] [ctl]\n");
837
838 size_t skip = 0;
839 while (true) {
840 /*
841 * We must not hold the slab_cache_lock spinlock when printing
842 * the statistics. Otherwise we can easily deadlock if the print
843 * needs to allocate memory.
844 *
845 * Therefore, we walk through the slab cache list, skipping some
846 * amount of already processed caches during each iteration and
847 * gathering statistics about the first unprocessed cache. For
848 * the sake of printing the statistics, we realese the
849 * slab_cache_lock and reacquire it afterwards. Then the walk
850 * starts again.
851 *
852 * This limits both the efficiency and also accuracy of the
853 * obtained statistics. The efficiency is decreased because the
854 * time complexity of the algorithm is quadratic instead of
855 * linear. The accuracy is impacted because we drop the lock
856 * after processing one cache. If there is someone else
857 * manipulating the cache list, we might omit an arbitrary
858 * number of caches or process one cache multiple times.
859 * However, we don't bleed for this algorithm for it is only
860 * statistics.
861 */
862
863 irq_spinlock_lock(&slab_cache_lock, true);
864
865 link_t *cur;
866 size_t i;
867 for (i = 0, cur = slab_cache_list.head.next;
868 (i < skip) && (cur != &slab_cache_list.head);
869 i++, cur = cur->next);
870
871 if (cur == &slab_cache_list.head) {
872 irq_spinlock_unlock(&slab_cache_lock, true);
873 break;
874 }
875
876 skip++;
877
878 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
879
880 const char *name = cache->name;
881 uint8_t order = cache->order;
882 size_t size = cache->size;
883 size_t objects = cache->objects;
884 long allocated_slabs = atomic_get(&cache->allocated_slabs);
885 long cached_objs = atomic_get(&cache->cached_objs);
886 long allocated_objs = atomic_get(&cache->allocated_objs);
887 unsigned int flags = cache->flags;
888
889 irq_spinlock_unlock(&slab_cache_lock, true);
890
891 printf("%-18s %8zu %8u %8zu %8ld %8ld %8ld %-5s\n",
892 name, size, (1 << order), objects, allocated_slabs,
893 cached_objs, allocated_objs,
894 flags & SLAB_CACHE_SLINSIDE ? "in" : "out");
895 }
896}
897
898void slab_cache_init(void)
899{
900 /* Initialize magazine cache */
901 _slab_cache_create(&mag_cache, "slab_magazine",
902 sizeof(slab_magazine_t) + SLAB_MAG_SIZE * sizeof(void*),
903 sizeof(uintptr_t), NULL, NULL, SLAB_CACHE_NOMAGAZINE |
904 SLAB_CACHE_SLINSIDE);
905
906 /* Initialize slab_cache cache */
907 _slab_cache_create(&slab_cache_cache, "slab_cache",
908 sizeof(slab_cache_cache), sizeof(uintptr_t), NULL, NULL,
909 SLAB_CACHE_NOMAGAZINE | SLAB_CACHE_SLINSIDE);
910
911 /* Initialize external slab cache */
912 slab_extern_cache = slab_cache_create("slab_extern", sizeof(slab_t), 0,
913 NULL, NULL, SLAB_CACHE_SLINSIDE | SLAB_CACHE_MAGDEFERRED);
914
915 /* Initialize structures for malloc */
916 size_t i;
917 size_t size;
918
919 for (i = 0, size = (1 << SLAB_MIN_MALLOC_W);
920 i < (SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1);
921 i++, size <<= 1) {
922 malloc_caches[i] = slab_cache_create(malloc_names[i], size, 0,
923 NULL, NULL, SLAB_CACHE_MAGDEFERRED);
924 }
925
926#ifdef CONFIG_DEBUG
927 _slab_initialized = 1;
928#endif
929}
930
931/** Enable cpu_cache
932 *
933 * Kernel calls this function, when it knows the real number of
934 * processors. Allocate slab for cpucache and enable it on all
935 * existing slabs that are SLAB_CACHE_MAGDEFERRED
936 *
937 */
938void slab_enable_cpucache(void)
939{
940#ifdef CONFIG_DEBUG
941 _slab_initialized = 2;
942#endif
943
944 irq_spinlock_lock(&slab_cache_lock, false);
945
946 list_foreach(slab_cache_list, cur) {
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.