Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
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 are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#pragma once
28
29#include <AK/Types.h>
30
31//#define KMALLOC_DEBUG_LARGE_ALLOCATIONS
32
33#define KMALLOC_SCRUB_BYTE 0xbb
34#define KFREE_SCRUB_BYTE 0xaa
35
36void kmalloc_init();
37[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_impl(size_t);
38[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_eternal(size_t);
39[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_page_aligned(size_t);
40[[gnu::malloc, gnu::returns_nonnull, gnu::alloc_size(1)]] void* kmalloc_aligned(size_t, size_t alignment);
41void* krealloc(void*, size_t);
42void kfree(void*);
43void kfree_aligned(void*);
44
45extern volatile size_t sum_alloc;
46extern volatile size_t sum_free;
47extern volatile size_t kmalloc_sum_eternal;
48extern volatile size_t kmalloc_sum_page_aligned;
49extern u32 g_kmalloc_call_count;
50extern u32 g_kfree_call_count;
51extern bool g_dump_kmalloc_stacks;
52
53inline void* operator new(size_t, void* p) { return p; }
54inline void* operator new[](size_t, void* p) { return p; }
55
56[[gnu::always_inline]] inline void* kmalloc(size_t size)
57{
58#ifdef KMALLOC_DEBUG_LARGE_ALLOCATIONS
59 // Any kernel allocation >= 1M is 99.9% a bug.
60 if (size >= 1048576)
61 asm volatile("cli;hlt");
62#endif
63 return kmalloc_impl(size);
64}