VirtIORNG.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/Bus/VirtIO/VirtIORNG.h>
  7. #include <Kernel/Sections.h>
  8. namespace Kernel {
  9. UNMAP_AFTER_INIT VirtIORNG::VirtIORNG(PCI::Address address)
  10. : CharacterDevice(10, 183)
  11. , VirtIODevice(address, "VirtIORNG")
  12. {
  13. bool success = negotiate_features([&](auto) {
  14. return 0;
  15. });
  16. if (success) {
  17. success = setup_queues(1);
  18. }
  19. if (success) {
  20. finish_init();
  21. m_entropy_buffer = MM.allocate_contiguous_kernel_region(PAGE_SIZE, "VirtIORNG", Memory::Region::Access::ReadWrite);
  22. if (m_entropy_buffer) {
  23. memset(m_entropy_buffer->vaddr().as_ptr(), 0, m_entropy_buffer->size());
  24. request_entropy_from_host();
  25. }
  26. }
  27. }
  28. VirtIORNG::~VirtIORNG()
  29. {
  30. }
  31. bool VirtIORNG::handle_device_config_change()
  32. {
  33. VERIFY_NOT_REACHED(); // Device has no config
  34. }
  35. void VirtIORNG::handle_queue_update(u16 queue_index)
  36. {
  37. VERIFY(queue_index == REQUESTQ);
  38. size_t available_entropy = 0, used;
  39. auto& queue = get_queue(REQUESTQ);
  40. {
  41. SpinlockLocker lock(queue.lock());
  42. auto chain = queue.pop_used_buffer_chain(used);
  43. if (chain.is_empty())
  44. return;
  45. VERIFY(chain.length() == 1);
  46. chain.for_each([&available_entropy](PhysicalAddress, size_t length) {
  47. available_entropy = length;
  48. });
  49. chain.release_buffer_slots_to_queue();
  50. }
  51. dbgln_if(VIRTIO_DEBUG, "VirtIORNG: received {} bytes of entropy!", available_entropy);
  52. for (auto i = 0u; i < available_entropy; i++) {
  53. m_entropy_source.add_random_event(m_entropy_buffer->vaddr().as_ptr()[i]);
  54. }
  55. // TODO: When should we get some more entropy?
  56. }
  57. void VirtIORNG::request_entropy_from_host()
  58. {
  59. auto& queue = get_queue(REQUESTQ);
  60. SpinlockLocker lock(queue.lock());
  61. VirtIOQueueChain chain(queue);
  62. chain.add_buffer_to_chain(m_entropy_buffer->physical_page(0)->paddr(), PAGE_SIZE, BufferType::DeviceWritable);
  63. supply_chain_and_notify(REQUESTQ, chain);
  64. }
  65. }