Serenity Operating System
at master 66 lines 2.7 kB view raw
1/* 2 * Copyright (c) 2021, Liav A. <liavalb@hotmail.co.il> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <Kernel/Devices/DeviceManagement.h> 8#include <Kernel/Devices/MemoryDevice.h> 9#include <Kernel/Memory/AnonymousVMObject.h> 10#include <Kernel/Memory/TypedMapping.h> 11#include <Kernel/Sections.h> 12 13namespace Kernel { 14 15UNMAP_AFTER_INIT NonnullLockRefPtr<MemoryDevice> MemoryDevice::must_create() 16{ 17 auto memory_device_or_error = DeviceManagement::try_create_device<MemoryDevice>(); 18 // FIXME: Find a way to propagate errors 19 VERIFY(!memory_device_or_error.is_error()); 20 return memory_device_or_error.release_value(); 21} 22 23UNMAP_AFTER_INIT MemoryDevice::MemoryDevice() 24 : CharacterDevice(1, 1) 25{ 26} 27 28UNMAP_AFTER_INIT MemoryDevice::~MemoryDevice() = default; 29 30ErrorOr<size_t> MemoryDevice::read(OpenFileDescription&, u64 offset, UserOrKernelBuffer& buffer, size_t length) 31{ 32 if (!MM.is_allowed_to_read_physical_memory_for_userspace(PhysicalAddress(offset), length)) { 33 dbgln_if(MEMORY_DEVICE_DEBUG, "MemoryDevice: Trying to read physical memory at {} for range of {} bytes failed due to violation of access", PhysicalAddress(offset), length); 34 return EINVAL; 35 } 36 auto mapping = TRY(Memory::map_typed<u8>(PhysicalAddress(offset), length)); 37 38 auto bytes = ReadonlyBytes { mapping.ptr(), length }; 39 TRY(buffer.write(bytes)); 40 return length; 41} 42 43ErrorOr<NonnullLockRefPtr<Memory::VMObject>> MemoryDevice::vmobject_for_mmap(Process&, Memory::VirtualRange const& range, u64& offset, bool) 44{ 45 auto viewed_address = PhysicalAddress(offset); 46 47 // Note: This check happens to guard against possible memory leak. 48 // For example, if we try to mmap physical memory from 0x1000 to 0x2000 and you 49 // can actually mmap only from 0x1001, then we would fail as usual. 50 // However, in such case if we mmap from 0x1002, we are technically not violating 51 // any rules, besides the fact that we mapped an entire page with two bytes which we 52 // were not supposed to see. To prevent that, if we use mmap(2) syscall, we should 53 // always consider the start page to be aligned on PAGE_SIZE, or to be more precise 54 // is to be set to the page base of that start address. 55 VERIFY(viewed_address == viewed_address.page_base()); 56 57 if (!MM.is_allowed_to_read_physical_memory_for_userspace(viewed_address, range.size())) { 58 dbgln_if(MEMORY_DEVICE_DEBUG, "MemoryDevice: Trying to mmap physical memory at {} for range of {} bytes failed due to violation of access", viewed_address, range.size()); 59 return EINVAL; 60 } 61 62 offset = 0; 63 return TRY(Memory::AnonymousVMObject::try_create_for_physical_range(viewed_address, range.size())); 64} 65 66}