ladybird/Kernel/Devices/RandomDevice.cpp
Liav A aee4786d8e Kernel: Introduce the DeviceManagement singleton
This singleton simplifies many aspects that we struggled with before:
1. There's no need to make derived classes of Device expose the
constructor as public anymore. The singleton is a friend of them, so he
can call the constructor. This solves the issue with try_create_device
helper neatly, hopefully for good.
2. Getting a reference of the NullDevice is now being done from this
singleton, which means that NullDevice no longer needs to use its own
singleton, and we can apply the try_create_device helper on it too :)
3. We can now defer registration completely after the Device constructor
which means the Device constructor is merely assigning the major and
minor numbers of the Device, and the try_create_device helper ensures it
calls the after_inserting method immediately after construction. This
creates a great opportunity to make registration more OOM-safe.
2021-09-17 01:02:48 +03:00

51 lines
1.2 KiB
C++

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <Kernel/Devices/DeviceManagement.h>
#include <Kernel/Devices/RandomDevice.h>
#include <Kernel/Random.h>
#include <Kernel/Sections.h>
namespace Kernel {
UNMAP_AFTER_INIT NonnullRefPtr<RandomDevice> RandomDevice::must_create()
{
auto random_device_or_error = DeviceManagement::try_create_device<RandomDevice>();
// FIXME: Find a way to propagate errors
VERIFY(!random_device_or_error.is_error());
return random_device_or_error.release_value();
}
UNMAP_AFTER_INIT RandomDevice::RandomDevice()
: CharacterDevice(1, 8)
{
}
UNMAP_AFTER_INIT RandomDevice::~RandomDevice()
{
}
bool RandomDevice::can_read(const OpenFileDescription&, size_t) const
{
return true;
}
KResultOr<size_t> RandomDevice::read(OpenFileDescription&, u64, UserOrKernelBuffer& buffer, size_t size)
{
return buffer.write_buffered<256>(size, [&](Bytes bytes) {
get_good_random_bytes(bytes);
return bytes.size();
});
}
KResultOr<size_t> RandomDevice::write(OpenFileDescription&, u64, const UserOrKernelBuffer&, size_t size)
{
// FIXME: Use input for entropy? I guess that could be a neat feature?
return size;
}
}