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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since aafed15 was aafed15, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

Declare malloc() etc in standard <stdlib.h> rather than <mm/slab.h>

  • Property mode set to 100644
File size: 26.5 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 kernel_generic_mm
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 <assert.h>
104#include <errno.h>
105#include <synch/spinlock.h>
106#include <mm/slab.h>
107#include <adt/list.h>
108#include <mem.h>
109#include <align.h>
110#include <mm/frame.h>
111#include <config.h>
112#include <stdio.h>
113#include <arch.h>
114#include <panic.h>
115#include <bitops.h>
116#include <macros.h>
117#include <cpu.h>
118#include <stdlib.h>
119
120IRQ_SPINLOCK_STATIC_INITIALIZE(slab_cache_lock);
121static LIST_INITIALIZE(slab_cache_list);
122
123/** Magazine cache */
124static slab_cache_t mag_cache;
125
126/** Cache for cache descriptors */
127static slab_cache_t slab_cache_cache;
128
129/** Cache for per-CPU magazines of caches */
130static slab_cache_t slab_mag_cache;
131
132/** Cache for external slab descriptors
133 * This time we want per-cpu cache, so do not make it static
134 * - using slab for internal slab structures will not deadlock,
135 * as all slab structures are 'small' - control structures of
136 * their caches do not require further allocation
137 */
138static slab_cache_t *slab_extern_cache;
139
140/** Caches for malloc */
141static slab_cache_t *malloc_caches[SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1];
142
143static const char *malloc_names[] = {
144 "malloc-16",
145 "malloc-32",
146 "malloc-64",
147 "malloc-128",
148 "malloc-256",
149 "malloc-512",
150 "malloc-1K",
151 "malloc-2K",
152 "malloc-4K",
153 "malloc-8K",
154 "malloc-16K",
155 "malloc-32K",
156 "malloc-64K",
157 "malloc-128K",
158 "malloc-256K",
159 "malloc-512K",
160 "malloc-1M",
161 "malloc-2M",
162 "malloc-4M"
163};
164
165/** Slab descriptor */
166typedef struct {
167 slab_cache_t *cache; /**< Pointer to parent cache. */
168 link_t link; /**< List of full/partial slabs. */
169 void *start; /**< Start address of first available item. */
170 size_t available; /**< Count of available items in this slab. */
171 size_t nextavail; /**< The index of next available item. */
172} slab_t;
173
174#ifdef CONFIG_DEBUG
175static unsigned int _slab_initialized = 0;
176#endif
177
178/**************************************/
179/* Slab allocation functions */
180/**************************************/
181
182/** Allocate frames for slab space and initialize
183 *
184 */
185NO_TRACE static slab_t *slab_space_alloc(slab_cache_t *cache,
186 unsigned int flags)
187{
188 size_t zone = 0;
189
190 uintptr_t data_phys =
191 frame_alloc_generic(cache->frames, FRAME_LOWMEM | flags, 0, &zone);
192 if (!data_phys)
193 return NULL;
194
195 void *data = (void *) PA2KA(data_phys);
196
197 slab_t *slab;
198 size_t fsize;
199
200 if (!(cache->flags & SLAB_CACHE_SLINSIDE)) {
201 slab = slab_alloc(slab_extern_cache, flags);
202 if (!slab) {
203 frame_free(KA2PA(data), cache->frames);
204 return NULL;
205 }
206 } else {
207 fsize = FRAMES2SIZE(cache->frames);
208 slab = data + fsize - sizeof(*slab);
209 }
210
211 /* Fill in slab structures */
212 size_t i;
213 for (i = 0; i < cache->frames; i++)
214 frame_set_parent(ADDR2PFN(KA2PA(data)) + i, slab, zone);
215
216 slab->start = data;
217 slab->available = cache->objects;
218 slab->nextavail = 0;
219 slab->cache = cache;
220
221 for (i = 0; i < cache->objects; i++)
222 *((size_t *) (slab->start + i * cache->size)) = i + 1;
223
224 atomic_inc(&cache->allocated_slabs);
225 return slab;
226}
227
228/** Deallocate space associated with slab
229 *
230 * @return number of freed frames
231 *
232 */
233NO_TRACE static size_t slab_space_free(slab_cache_t *cache, slab_t *slab)
234{
235 frame_free(KA2PA(slab->start), slab->cache->frames);
236 if (!(cache->flags & SLAB_CACHE_SLINSIDE))
237 slab_free(slab_extern_cache, slab);
238
239 atomic_dec(&cache->allocated_slabs);
240
241 return cache->frames;
242}
243
244/** Map object to slab structure */
245NO_TRACE static slab_t *obj2slab(void *obj)
246{
247 return (slab_t *) frame_get_parent(ADDR2PFN(KA2PA(obj)), 0);
248}
249
250/******************/
251/* Slab functions */
252/******************/
253
254/** Return object to slab and call a destructor
255 *
256 * @param slab If the caller knows directly slab of the object, otherwise NULL
257 *
258 * @return Number of freed pages
259 *
260 */
261NO_TRACE static size_t slab_obj_destroy(slab_cache_t *cache, void *obj,
262 slab_t *slab)
263{
264 if (!slab)
265 slab = obj2slab(obj);
266
267 assert(slab->cache == cache);
268
269 size_t freed = 0;
270
271 if (cache->destructor)
272 freed = cache->destructor(obj);
273
274 irq_spinlock_lock(&cache->slablock, true);
275 assert(slab->available < cache->objects);
276
277 *((size_t *) obj) = slab->nextavail;
278 slab->nextavail = (obj - slab->start) / cache->size;
279 slab->available++;
280
281 /* Move it to correct list */
282 if (slab->available == cache->objects) {
283 /* Free associated memory */
284 list_remove(&slab->link);
285 irq_spinlock_unlock(&cache->slablock, true);
286
287 return freed + slab_space_free(cache, slab);
288 } else if (slab->available == 1) {
289 /* It was in full, move to partial */
290 list_remove(&slab->link);
291 list_prepend(&slab->link, &cache->partial_slabs);
292 }
293
294 irq_spinlock_unlock(&cache->slablock, true);
295 return freed;
296}
297
298/** Take new object from slab or create new if needed
299 *
300 * @return Object address or null
301 *
302 */
303NO_TRACE static void *slab_obj_create(slab_cache_t *cache, unsigned int flags)
304{
305 irq_spinlock_lock(&cache->slablock, true);
306
307 slab_t *slab;
308
309 if (list_empty(&cache->partial_slabs)) {
310 /*
311 * Allow recursion and reclaiming
312 * - this should work, as the slab control structures
313 * are small and do not need to allocate with anything
314 * other than frame_alloc when they are allocating,
315 * that's why we should get recursion at most 1-level deep
316 *
317 */
318 irq_spinlock_unlock(&cache->slablock, true);
319 slab = slab_space_alloc(cache, flags);
320 if (!slab)
321 return NULL;
322
323 irq_spinlock_lock(&cache->slablock, true);
324 } else {
325 slab = list_get_instance(list_first(&cache->partial_slabs),
326 slab_t, link);
327 list_remove(&slab->link);
328 }
329
330 void *obj = slab->start + slab->nextavail * cache->size;
331 slab->nextavail = *((size_t *) obj);
332 slab->available--;
333
334 if (!slab->available)
335 list_prepend(&slab->link, &cache->full_slabs);
336 else
337 list_prepend(&slab->link, &cache->partial_slabs);
338
339 irq_spinlock_unlock(&cache->slablock, true);
340
341 if ((cache->constructor) && (cache->constructor(obj, flags) != EOK)) {
342 /* Bad, bad, construction failed */
343 slab_obj_destroy(cache, obj, slab);
344 return NULL;
345 }
346
347 return obj;
348}
349
350/****************************/
351/* CPU-Cache slab functions */
352/****************************/
353
354/** Find a full magazine in cache, take it from list and return it
355 *
356 * @param first If true, return first, else last mag.
357 *
358 */
359NO_TRACE static slab_magazine_t *get_mag_from_cache(slab_cache_t *cache,
360 bool first)
361{
362 slab_magazine_t *mag = NULL;
363 link_t *cur;
364
365 irq_spinlock_lock(&cache->maglock, true);
366 if (!list_empty(&cache->magazines)) {
367 if (first)
368 cur = list_first(&cache->magazines);
369 else
370 cur = list_last(&cache->magazines);
371
372 mag = list_get_instance(cur, slab_magazine_t, link);
373 list_remove(&mag->link);
374 atomic_dec(&cache->magazine_counter);
375 }
376 irq_spinlock_unlock(&cache->maglock, true);
377
378 return mag;
379}
380
381/** Prepend magazine to magazine list in cache
382 *
383 */
384NO_TRACE static void put_mag_to_cache(slab_cache_t *cache,
385 slab_magazine_t *mag)
386{
387 irq_spinlock_lock(&cache->maglock, true);
388
389 list_prepend(&mag->link, &cache->magazines);
390 atomic_inc(&cache->magazine_counter);
391
392 irq_spinlock_unlock(&cache->maglock, true);
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 (FRAMES2SIZE(cache->frames) - sizeof(slab_t)) /
569 cache->size;
570 else
571 return FRAMES2SIZE(cache->frames) / 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 = FRAMES2SIZE(cache->frames);
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 = slab_alloc(&slab_mag_cache, FRAME_ATOMIC);
596 if (!cache->mag_cache)
597 return false;
598
599 size_t i;
600 for (i = 0; i < config.cpu_count; i++) {
601 memsetb(&cache->mag_cache[i], sizeof(cache->mag_cache[i]), 0);
602 irq_spinlock_initialize(&cache->mag_cache[i].lock,
603 "slab.cache.mag_cache[].lock");
604 }
605
606 return true;
607}
608
609/** Initialize allocated memory as a slab cache
610 *
611 */
612NO_TRACE static void _slab_cache_create(slab_cache_t *cache, const char *name,
613 size_t size, size_t align, errno_t (*constructor)(void *obj,
614 unsigned int kmflag), size_t (*destructor)(void *obj), unsigned int flags)
615{
616 assert(size > 0);
617
618 memsetb(cache, sizeof(*cache), 0);
619 cache->name = name;
620
621 if (align < sizeof(sysarg_t))
622 align = sizeof(sysarg_t);
623
624 size = ALIGN_UP(size, align);
625
626 cache->size = size;
627 cache->constructor = constructor;
628 cache->destructor = destructor;
629 cache->flags = flags;
630
631 list_initialize(&cache->full_slabs);
632 list_initialize(&cache->partial_slabs);
633 list_initialize(&cache->magazines);
634
635 irq_spinlock_initialize(&cache->slablock, "slab.cache.slablock");
636 irq_spinlock_initialize(&cache->maglock, "slab.cache.maglock");
637
638 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
639 (void) make_magcache(cache);
640
641 /* Compute slab sizes, object counts in slabs etc. */
642 if (cache->size < SLAB_INSIDE_SIZE)
643 cache->flags |= SLAB_CACHE_SLINSIDE;
644
645 /* Minimum slab frames */
646 cache->frames = SIZE2FRAMES(cache->size);
647
648 while (badness(cache) > SLAB_MAX_BADNESS(cache))
649 cache->frames <<= 1;
650
651 cache->objects = comp_objects(cache);
652
653 /* If info fits in, put it inside */
654 if (badness(cache) > sizeof(slab_t))
655 cache->flags |= SLAB_CACHE_SLINSIDE;
656
657 /* Add cache to cache list */
658 irq_spinlock_lock(&slab_cache_lock, true);
659 list_append(&cache->link, &slab_cache_list);
660 irq_spinlock_unlock(&slab_cache_lock, true);
661}
662
663/** Create slab cache
664 *
665 */
666slab_cache_t *slab_cache_create(const char *name, size_t size, size_t align,
667 errno_t (*constructor)(void *obj, unsigned int kmflag),
668 size_t (*destructor)(void *obj), unsigned int flags)
669{
670 slab_cache_t *cache = slab_alloc(&slab_cache_cache, FRAME_ATOMIC);
671 if (!cache)
672 panic("Not enough memory to allocate slab cache %s.", name);
673
674 _slab_cache_create(cache, name, size, align, constructor, destructor,
675 flags);
676
677 return cache;
678}
679
680/** Reclaim space occupied by objects that are already free
681 *
682 * @param flags If contains SLAB_RECLAIM_ALL, do aggressive freeing
683 *
684 * @return Number of freed pages
685 *
686 */
687NO_TRACE static size_t _slab_reclaim(slab_cache_t *cache, unsigned int flags)
688{
689 if (cache->flags & SLAB_CACHE_NOMAGAZINE)
690 return 0; /* Nothing to do */
691
692 /*
693 * We count up to original magazine count to avoid
694 * endless loop
695 */
696 size_t magcount = atomic_load(&cache->magazine_counter);
697
698 slab_magazine_t *mag;
699 size_t frames = 0;
700
701 while ((magcount--) && (mag = get_mag_from_cache(cache, 0))) {
702 frames += magazine_destroy(cache, mag);
703 if ((!(flags & SLAB_RECLAIM_ALL)) && (frames))
704 break;
705 }
706
707 if (flags & SLAB_RECLAIM_ALL) {
708 /* Free cpu-bound magazines */
709 /* Destroy CPU magazines */
710 size_t i;
711 for (i = 0; i < config.cpu_count; i++) {
712 irq_spinlock_lock(&cache->mag_cache[i].lock, true);
713
714 mag = cache->mag_cache[i].current;
715 if (mag)
716 frames += magazine_destroy(cache, mag);
717 cache->mag_cache[i].current = NULL;
718
719 mag = cache->mag_cache[i].last;
720 if (mag)
721 frames += magazine_destroy(cache, mag);
722 cache->mag_cache[i].last = NULL;
723
724 irq_spinlock_unlock(&cache->mag_cache[i].lock, true);
725 }
726 }
727
728 return frames;
729}
730
731/** Return object to cache, use slab if known
732 *
733 */
734NO_TRACE static void _slab_free(slab_cache_t *cache, void *obj, slab_t *slab)
735{
736 if (!obj)
737 return;
738
739 ipl_t ipl = interrupts_disable();
740
741 if ((cache->flags & SLAB_CACHE_NOMAGAZINE) ||
742 (magazine_obj_put(cache, obj)))
743 slab_obj_destroy(cache, obj, slab);
744
745 interrupts_restore(ipl);
746 atomic_dec(&cache->allocated_objs);
747}
748
749/** Check that there are no slabs and remove cache from system
750 *
751 */
752void slab_cache_destroy(slab_cache_t *cache)
753{
754 /*
755 * First remove cache from link, so that we don't need
756 * to disable interrupts later
757 *
758 */
759 irq_spinlock_lock(&slab_cache_lock, true);
760 list_remove(&cache->link);
761 irq_spinlock_unlock(&slab_cache_lock, true);
762
763 /*
764 * Do not lock anything, we assume the software is correct and
765 * does not touch the cache when it decides to destroy it
766 *
767 */
768
769 /* Destroy all magazines */
770 _slab_reclaim(cache, SLAB_RECLAIM_ALL);
771
772 /* All slabs must be empty */
773 if ((!list_empty(&cache->full_slabs)) ||
774 (!list_empty(&cache->partial_slabs)))
775 panic("Destroying cache that is not empty.");
776
777 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE)) {
778 slab_t *mag_slab = obj2slab(cache->mag_cache);
779 _slab_free(mag_slab->cache, cache->mag_cache, mag_slab);
780 }
781
782 slab_free(&slab_cache_cache, cache);
783}
784
785/** Allocate new object from cache - if no flags given, always returns memory
786 *
787 */
788void *slab_alloc(slab_cache_t *cache, unsigned int flags)
789{
790 /* Disable interrupts to avoid deadlocks with interrupt handlers */
791 ipl_t ipl = interrupts_disable();
792
793 void *result = NULL;
794
795 if (!(cache->flags & SLAB_CACHE_NOMAGAZINE))
796 result = magazine_obj_get(cache);
797
798 if (!result)
799 result = slab_obj_create(cache, flags);
800
801 interrupts_restore(ipl);
802
803 if (result)
804 atomic_inc(&cache->allocated_objs);
805
806 return result;
807}
808
809/** Return slab object to cache
810 *
811 */
812void slab_free(slab_cache_t *cache, void *obj)
813{
814 _slab_free(cache, obj, NULL);
815}
816
817/** Go through all caches and reclaim what is possible */
818size_t slab_reclaim(unsigned int flags)
819{
820 irq_spinlock_lock(&slab_cache_lock, true);
821
822 size_t frames = 0;
823 list_foreach(slab_cache_list, link, slab_cache_t, cache) {
824 frames += _slab_reclaim(cache, flags);
825 }
826
827 irq_spinlock_unlock(&slab_cache_lock, true);
828
829 return frames;
830}
831
832/* Print list of caches */
833void slab_print_list(void)
834{
835 printf("[cache 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 = slab_cache_list.head.next;
866 size_t i = 0;
867 while (i < skip && cur != &slab_cache_list.head) {
868 i++;
869 cur = cur->next;
870 }
871
872 if (cur == &slab_cache_list.head) {
873 irq_spinlock_unlock(&slab_cache_lock, true);
874 break;
875 }
876
877 skip++;
878
879 slab_cache_t *cache = list_get_instance(cur, slab_cache_t, link);
880
881 const char *name = cache->name;
882 size_t frames = cache->frames;
883 size_t size = cache->size;
884 size_t objects = cache->objects;
885 long allocated_slabs = atomic_load(&cache->allocated_slabs);
886 long cached_objs = atomic_load(&cache->cached_objs);
887 long allocated_objs = atomic_load(&cache->allocated_objs);
888 unsigned int flags = cache->flags;
889
890 irq_spinlock_unlock(&slab_cache_lock, true);
891
892 printf("%-18s %8zu %8zu %8zu %8ld %8ld %8ld %-5s\n",
893 name, size, frames, objects, allocated_slabs,
894 cached_objs, allocated_objs,
895 flags & SLAB_CACHE_SLINSIDE ? "in" : "out");
896 }
897}
898
899void slab_cache_init(void)
900{
901 /* Initialize magazine cache */
902 _slab_cache_create(&mag_cache, "slab_magazine_t",
903 sizeof(slab_magazine_t) + SLAB_MAG_SIZE * sizeof(void *),
904 sizeof(uintptr_t), NULL, NULL, SLAB_CACHE_NOMAGAZINE |
905 SLAB_CACHE_SLINSIDE);
906
907 /* Initialize slab_cache cache */
908 _slab_cache_create(&slab_cache_cache, "slab_cache_cache",
909 sizeof(slab_cache_cache), sizeof(uintptr_t), NULL, NULL,
910 SLAB_CACHE_NOMAGAZINE | SLAB_CACHE_SLINSIDE);
911
912 /* Initialize external slab cache */
913 slab_extern_cache = slab_cache_create("slab_t", sizeof(slab_t), 0,
914 NULL, NULL, SLAB_CACHE_SLINSIDE | SLAB_CACHE_MAGDEFERRED);
915
916 /* Initialize structures for malloc */
917 size_t i;
918 size_t size;
919
920 for (i = 0, size = (1 << SLAB_MIN_MALLOC_W);
921 i < (SLAB_MAX_MALLOC_W - SLAB_MIN_MALLOC_W + 1);
922 i++, size <<= 1) {
923 malloc_caches[i] = slab_cache_create(malloc_names[i], size, 0,
924 NULL, NULL, SLAB_CACHE_MAGDEFERRED);
925 }
926
927#ifdef CONFIG_DEBUG
928 _slab_initialized = 1;
929#endif
930}
931
932/** Enable cpu_cache
933 *
934 * Kernel calls this function, when it knows the real number of
935 * processors. Allocate slab for cpucache and enable it on all
936 * existing slabs that are SLAB_CACHE_MAGDEFERRED
937 *
938 */
939void slab_enable_cpucache(void)
940{
941#ifdef CONFIG_DEBUG
942 _slab_initialized = 2;
943#endif
944
945 _slab_cache_create(&slab_mag_cache, "slab_mag_cache",
946 sizeof(slab_mag_cache_t) * config.cpu_count, sizeof(uintptr_t),
947 NULL, NULL, SLAB_CACHE_NOMAGAZINE | SLAB_CACHE_SLINSIDE);
948
949 irq_spinlock_lock(&slab_cache_lock, false);
950
951 list_foreach(slab_cache_list, link, slab_cache_t, slab) {
952 if ((slab->flags & SLAB_CACHE_MAGDEFERRED) !=
953 SLAB_CACHE_MAGDEFERRED)
954 continue;
955
956 (void) make_magcache(slab);
957 slab->flags &= ~SLAB_CACHE_MAGDEFERRED;
958 }
959
960 irq_spinlock_unlock(&slab_cache_lock, false);
961}
962
963void *malloc(size_t size)
964{
965 assert(_slab_initialized);
966 assert(size <= (1 << SLAB_MAX_MALLOC_W));
967
968 if (size < (1 << SLAB_MIN_MALLOC_W))
969 size = (1 << SLAB_MIN_MALLOC_W);
970
971 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
972
973 return slab_alloc(malloc_caches[idx], FRAME_ATOMIC);
974}
975
976void *realloc(void *ptr, size_t size)
977{
978 assert(_slab_initialized);
979 assert(size <= (1 << SLAB_MAX_MALLOC_W));
980
981 void *new_ptr;
982
983 if (size > 0) {
984 if (size < (1 << SLAB_MIN_MALLOC_W))
985 size = (1 << SLAB_MIN_MALLOC_W);
986 uint8_t idx = fnzb(size - 1) - SLAB_MIN_MALLOC_W + 1;
987
988 new_ptr = slab_alloc(malloc_caches[idx], FRAME_ATOMIC);
989 } else
990 new_ptr = NULL;
991
992 if ((new_ptr != NULL) && (ptr != NULL)) {
993 slab_t *slab = obj2slab(ptr);
994 memcpy(new_ptr, ptr, min(size, slab->cache->size));
995 }
996
997 if (ptr != NULL)
998 free(ptr);
999
1000 return new_ptr;
1001}
1002
1003void free(void *ptr)
1004{
1005 if (!ptr)
1006 return;
1007
1008 slab_t *slab = obj2slab(ptr);
1009 _slab_free(slab->cache, ptr, slab);
1010}
1011
1012/** @}
1013 */
Note: See TracBrowser for help on using the repository browser.