2020-01-18 11:38:21 +03:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 11:24:48 +03:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 11:38:21 +03:00
|
|
|
*/
|
|
|
|
|
2018-10-16 12:01:38 +03:00
|
|
|
#pragma once
|
|
|
|
|
2019-02-15 14:30:48 +03:00
|
|
|
#include <AK/Types.h>
|
2021-01-25 18:07:10 +03:00
|
|
|
#include <Kernel/Debug.h>
|
2019-02-15 14:30:48 +03:00
|
|
|
|
2020-02-01 12:26:05 +03:00
|
|
|
#define KMALLOC_SCRUB_BYTE 0xbb
|
|
|
|
#define KFREE_SCRUB_BYTE 0xaa
|
|
|
|
|
2021-03-11 15:11:59 +03:00
|
|
|
#define MAKE_ALIGNED_ALLOCATED(type, alignment) \
|
|
|
|
public: \
|
|
|
|
void* operator new(size_t) { return kmalloc_aligned<alignment>(sizeof(type)); } \
|
|
|
|
void operator delete(void* ptr) { kfree_aligned(ptr); } \
|
|
|
|
\
|
|
|
|
private:
|
|
|
|
|
2018-10-16 12:01:38 +03:00
|
|
|
void kmalloc_init();
|
2019-02-15 14:30:48 +03:00
|
|
|
[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_impl(size_t);
|
|
|
|
[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_eternal(size_t);
|
2020-08-30 01:41:30 +03:00
|
|
|
|
2019-11-27 16:06:24 +03:00
|
|
|
void* krealloc(void*, size_t);
|
2018-10-16 12:01:38 +03:00
|
|
|
void kfree(void*);
|
|
|
|
|
2020-08-30 01:41:30 +03:00
|
|
|
struct kmalloc_stats {
|
|
|
|
size_t bytes_allocated;
|
|
|
|
size_t bytes_free;
|
|
|
|
size_t bytes_eternal;
|
|
|
|
size_t kmalloc_call_count;
|
|
|
|
size_t kfree_call_count;
|
|
|
|
};
|
|
|
|
void get_kmalloc_stats(kmalloc_stats&);
|
|
|
|
|
2019-04-16 00:58:48 +03:00
|
|
|
extern bool g_dump_kmalloc_stacks;
|
2018-10-16 12:01:38 +03:00
|
|
|
|
|
|
|
inline void* operator new(size_t, void* p) { return p; }
|
|
|
|
inline void* operator new[](size_t, void* p) { return p; }
|
2019-01-13 01:23:35 +03:00
|
|
|
|
2021-03-04 13:13:17 +03:00
|
|
|
[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc(size_t);
|
2020-08-25 01:38:20 +03:00
|
|
|
|
2020-08-30 01:41:30 +03:00
|
|
|
template<size_t ALIGNMENT>
|
|
|
|
[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] inline void* kmalloc_aligned(size_t size)
|
|
|
|
{
|
2021-03-11 15:02:01 +03:00
|
|
|
static_assert(ALIGNMENT > sizeof(ptrdiff_t));
|
|
|
|
static_assert(ALIGNMENT <= 4096);
|
|
|
|
void* ptr = kmalloc(size + ALIGNMENT + sizeof(ptrdiff_t));
|
2020-08-30 01:41:30 +03:00
|
|
|
size_t max_addr = (size_t)ptr + ALIGNMENT;
|
|
|
|
void* aligned_ptr = (void*)(max_addr - (max_addr % ALIGNMENT));
|
2021-03-11 15:02:01 +03:00
|
|
|
((ptrdiff_t*)aligned_ptr)[-1] = (ptrdiff_t)((u8*)aligned_ptr - (u8*)ptr);
|
2020-08-30 01:41:30 +03:00
|
|
|
return aligned_ptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
inline void kfree_aligned(void* ptr)
|
|
|
|
{
|
2021-03-11 15:02:01 +03:00
|
|
|
kfree((u8*)ptr - ((const ptrdiff_t*)ptr)[-1]);
|
2020-08-30 01:41:30 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
void kmalloc_enable_expand();
|