KBuffer.h 2.3 KB

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