KBuffer.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 KResultOr<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 region = TRY(MM.allocate_kernel_region(Memory::page_round_up(size), name, access, strategy));
  25. return TRY(adopt_nonnull_own_or_enomem(new (nothrow) KBuffer { size, move(region) }));
  26. }
  27. static KResultOr<NonnullOwnPtr<KBuffer>> try_create_with_bytes(ReadonlyBytes bytes, Memory::Region::Access access = Memory::Region::Access::ReadWrite, StringView name = "KBuffer", AllocationStrategy strategy = AllocationStrategy::Reserve)
  28. {
  29. auto buffer = TRY(try_create_with_size(bytes.size(), access, name, strategy));
  30. memcpy(buffer->data(), bytes.data(), bytes.size());
  31. return buffer;
  32. }
  33. static KResultOr<NonnullOwnPtr<KBuffer>> try_copy(const void* data, size_t size, Memory::Region::Access access = Memory::Region::Access::ReadWrite, StringView name = "KBuffer")
  34. {
  35. return try_create_with_bytes(ReadonlyBytes { data, size }, access, name);
  36. }
  37. [[nodiscard]] u8* data() { return m_region->vaddr().as_ptr(); }
  38. [[nodiscard]] u8 const* data() const { return m_region->vaddr().as_ptr(); }
  39. [[nodiscard]] size_t size() const { return m_size; }
  40. [[nodiscard]] size_t capacity() const { return m_region->size(); }
  41. void set_size(size_t size)
  42. {
  43. VERIFY(size <= capacity());
  44. m_size = size;
  45. }
  46. private:
  47. explicit KBuffer(size_t size, NonnullOwnPtr<Memory::Region> region)
  48. : m_size(size)
  49. , m_region(move(region))
  50. {
  51. }
  52. size_t m_size { 0 };
  53. NonnullOwnPtr<Memory::Region> m_region;
  54. };
  55. }