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