Serenity Operating System
at master 66 lines 2.5 kB view raw
1/* 2 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#pragma once 8 9// KBuffer: Memory buffer backed by a kernel region. 10// 11// The memory is allocated via the global kernel-only page allocator, rather than via 12// kmalloc() which is what ByteBuffer/Vector/etc will use. 13// 14// This makes KBuffer a little heavier to allocate, but much better for large and/or 15// long-lived allocations, since they don't put all that weight and pressure on the 16// severely limited kmalloc heap. 17 18#include <AK/Assertions.h> 19#include <AK/StringView.h> 20#include <Kernel/Memory/MemoryManager.h> 21#include <Kernel/StdLib.h> // For memcpy. FIXME: Make memcpy less expensive to access a declaration of in the Kernel. 22 23namespace Kernel { 24 25class [[nodiscard]] KBuffer { 26public: 27 static ErrorOr<NonnullOwnPtr<KBuffer>> try_create_with_size(StringView name, size_t size, Memory::Region::Access access = Memory::Region::Access::ReadWrite, AllocationStrategy strategy = AllocationStrategy::Reserve) 28 { 29 auto rounded_size = TRY(Memory::page_round_up(size)); 30 auto region = TRY(MM.allocate_kernel_region(rounded_size, name, access, strategy)); 31 return TRY(adopt_nonnull_own_or_enomem(new (nothrow) KBuffer { size, move(region) })); 32 } 33 34 static ErrorOr<NonnullOwnPtr<KBuffer>> try_create_with_bytes(StringView name, ReadonlyBytes bytes, Memory::Region::Access access = Memory::Region::Access::ReadWrite, AllocationStrategy strategy = AllocationStrategy::Reserve) 35 { 36 auto buffer = TRY(try_create_with_size(name, bytes.size(), access, strategy)); 37 memcpy(buffer->data(), bytes.data(), bytes.size()); 38 return buffer; 39 } 40 41 [[nodiscard]] u8* data() { return m_region->vaddr().as_ptr(); } 42 [[nodiscard]] u8 const* data() const { return m_region->vaddr().as_ptr(); } 43 [[nodiscard]] size_t size() const { return m_size; } 44 [[nodiscard]] size_t capacity() const { return m_region->size(); } 45 46 [[nodiscard]] ReadonlyBytes bytes() const { return { data(), size() }; } 47 [[nodiscard]] Bytes bytes() { return { data(), size() }; } 48 49 void set_size(size_t size) 50 { 51 VERIFY(size <= capacity()); 52 m_size = size; 53 } 54 55private: 56 explicit KBuffer(size_t size, NonnullOwnPtr<Memory::Region> region) 57 : m_size(size) 58 , m_region(move(region)) 59 { 60 } 61 62 size_t m_size { 0 }; 63 NonnullOwnPtr<Memory::Region> m_region; 64}; 65 66}