RingBuffer.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2021, Sahan Fernando <sahan.h.fernando@gmail.com>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/Memory/MemoryManager.h>
  7. #include <Kernel/Memory/RingBuffer.h>
  8. #include <Kernel/UserOrKernelBuffer.h>
  9. namespace Kernel::Memory {
  10. RingBuffer::RingBuffer(String region_name, size_t capacity)
  11. : m_region(MM.allocate_contiguous_kernel_region(page_round_up(capacity).release_value_but_fixme_should_propagate_errors(), move(region_name), Region::Access::Read | Region::Access::Write).release_value())
  12. , m_capacity_in_bytes(capacity)
  13. {
  14. }
  15. bool RingBuffer::copy_data_in(const UserOrKernelBuffer& buffer, size_t offset, size_t length, PhysicalAddress& start_of_copied_data, size_t& bytes_copied)
  16. {
  17. size_t start_of_free_area = (m_start_of_used + m_num_used_bytes) % m_capacity_in_bytes;
  18. bytes_copied = min(m_capacity_in_bytes - m_num_used_bytes, min(m_capacity_in_bytes - start_of_free_area, length));
  19. if (bytes_copied == 0)
  20. return false;
  21. if (auto result = buffer.read(m_region->vaddr().offset(start_of_free_area).as_ptr(), offset, bytes_copied); result.is_error())
  22. return false;
  23. m_num_used_bytes += bytes_copied;
  24. start_of_copied_data = m_region->physical_page(start_of_free_area / PAGE_SIZE)->paddr().offset(start_of_free_area % PAGE_SIZE);
  25. return true;
  26. }
  27. ErrorOr<size_t> RingBuffer::copy_data_out(size_t size, UserOrKernelBuffer& buffer) const
  28. {
  29. auto start = m_start_of_used % m_capacity_in_bytes;
  30. auto num_bytes = min(min(m_num_used_bytes, size), m_capacity_in_bytes - start);
  31. TRY(buffer.write(m_region->vaddr().offset(start).as_ptr(), num_bytes));
  32. return num_bytes;
  33. }
  34. ErrorOr<PhysicalAddress> RingBuffer::reserve_space(size_t size)
  35. {
  36. if (m_capacity_in_bytes < m_num_used_bytes + size)
  37. return ENOSPC;
  38. size_t start_of_free_area = (m_start_of_used + m_num_used_bytes) % m_capacity_in_bytes;
  39. m_num_used_bytes += size;
  40. PhysicalAddress start_of_reserved_space = m_region->physical_page(start_of_free_area / PAGE_SIZE)->paddr().offset(start_of_free_area % PAGE_SIZE);
  41. return start_of_reserved_space;
  42. }
  43. void RingBuffer::reclaim_space(PhysicalAddress chunk_start, size_t chunk_size)
  44. {
  45. VERIFY(start_of_used() == chunk_start);
  46. VERIFY(m_num_used_bytes >= chunk_size);
  47. m_num_used_bytes -= chunk_size;
  48. m_start_of_used += chunk_size;
  49. }
  50. PhysicalAddress RingBuffer::start_of_used() const
  51. {
  52. size_t start = m_start_of_used % m_capacity_in_bytes;
  53. return m_region->physical_page(start / PAGE_SIZE)->paddr().offset(start % PAGE_SIZE);
  54. }
  55. }