My Kernel v0.1.0
kmalloc.h
Go to the documentation of this file.
1
50#pragma once
51
52#include <kernel/types.h>
53
54#include <utils/compiler.h>
55
60typedef enum kmalloc_flags {
61 KMALLOC_KERNEL = 0, /* Default allocation flags. */
62} kmalloc_flags_t;
63
64#define KMALLOC_CACHE_MIN_SIZE 16
65#define KMALLOC_CACHE_MAX_SIZE 16384
66#define KMALLOC_CACHE_COUNT 11
67
68/*
69 * @return The index of the smallest cache that can contain a @size bytes object
70 *
71 * This function is inlined and marked 'const' so that it is optimized out by
72 * the compiler when passing a value known at compile time.
73 */
74static ALWAYS_INLINE __attribute__((const)) int kmalloc_cache_index(size_t size)
75{
76 if (size <= 16) return 0;
77 if (size <= 32) return 1;
78 if (size <= 64) return 2;
79 if (size <= 128) return 3;
80 if (size <= 256) return 4;
81 if (size <= 512) return 5;
82 if (size <= 1024) return 6;
83 if (size <= 2048) return 7;
84 if (size <= 4096) return 8;
85 if (size <= 8192) return 9;
86 if (size <= 16384) return 10;
87
88 return -1;
89}
90
98void *kmalloc_from_cache(int cache_index, int flags);
99
101void *kmalloc_large(size_t size, int flags);
102
103/*
104 *
105 */
106static ALWAYS_INLINE void *kmalloc(size_t size, int flags)
107{
108 int cache_index;
109
110 cache_index = kmalloc_cache_index(size);
111 if (cache_index < 0)
112 return kmalloc_large(size, flags);
113
114 return kmalloc_from_cache(cache_index, flags);
115}
116
117
127void *kcalloc(size_t nmemb, size_t size, int flags);
128
130void kfree(void *ptr);
131
149void *krealloc(void *ptr, size_t size, int flags);
150
158void *krealloc_array(void *ptr, size_t nmemb, size_t size, int flags);
159
169void *kmalloc_dma(size_t size);
170
172void kfree_dma(void *dma_ptr);
173
174void kmalloc_api_init(void);
175
void kfree(void *ptr)
Free a pointer allocated through Kernel dynamic allocator.
Definition: kmalloc.c:73
void * krealloc_array(void *ptr, size_t nmemb, size_t size, int flags)
Change the size of the given memory block.
Definition: kmalloc.c:131
void * kmalloc_from_cache(int cache_index, int flags)
Allocate kernel memory from one of the global memory caches.
Definition: kmalloc.c:33
void * kcalloc(size_t nmemb, size_t size, int flags)
Allocate nmemb members of size bytes and initialize its content to 0.
Definition: kmalloc.c:90
void * kmalloc_dma(size_t size)
Allocate an addressable memory buffer suitable for DMA operations.
Definition: kmalloc.c:139
kmalloc_flags
Feature flags passed to the kmalloc function family.
Definition: kmalloc.h:60
void * krealloc(void *ptr, size_t size, int flags)
Change the size of the given memory block.
Definition: kmalloc.c:102
void kfree_dma(void *dma_ptr)
Free a buffer allocated through kmalloc_dma.
Definition: kmalloc.c:157
void * kmalloc_large(size_t size, int flags)
Allocate a memory buffer too large to fit inside the default caches.
Definition: kmalloc.c:39