Console.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. * Copyright (c) 2021, Kyle Pereira <hey@xylepereira.me>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <Kernel/Bus/VirtIO/Console.h>
  8. #include <Kernel/Devices/DeviceManagement.h>
  9. #include <Kernel/Sections.h>
  10. #include <Kernel/WorkQueue.h>
  11. namespace Kernel::VirtIO {
  12. unsigned Console::next_device_id = 0;
  13. UNMAP_AFTER_INIT NonnullLockRefPtr<Console> Console::must_create(PCI::DeviceIdentifier const& pci_device_identifier)
  14. {
  15. return adopt_lock_ref_if_nonnull(new Console(pci_device_identifier)).release_nonnull();
  16. }
  17. UNMAP_AFTER_INIT ErrorOr<void> Console::initialize_virtio_resources()
  18. {
  19. TRY(Device::initialize_virtio_resources());
  20. auto const* cfg = TRY(get_config(VirtIO::ConfigurationType::Device));
  21. bool success = negotiate_features([&](u64 supported_features) {
  22. u64 negotiated = 0;
  23. if (is_feature_set(supported_features, VIRTIO_CONSOLE_F_SIZE))
  24. dbgln("VirtIO::Console: Console size is not yet supported!");
  25. if (is_feature_set(supported_features, VIRTIO_CONSOLE_F_MULTIPORT))
  26. negotiated |= VIRTIO_CONSOLE_F_MULTIPORT;
  27. return negotiated;
  28. });
  29. if (!success)
  30. return Error::from_errno(EIO);
  31. u32 max_nr_ports = 0;
  32. u16 cols = 0, rows = 0;
  33. read_config_atomic([&]() {
  34. if (is_feature_accepted(VIRTIO_CONSOLE_F_SIZE)) {
  35. cols = config_read16(*cfg, 0x0);
  36. rows = config_read16(*cfg, 0x2);
  37. }
  38. if (is_feature_accepted(VIRTIO_CONSOLE_F_MULTIPORT)) {
  39. max_nr_ports = config_read32(*cfg, 0x4);
  40. m_ports.resize(max_nr_ports);
  41. }
  42. });
  43. dbgln("VirtIO::Console: cols: {}, rows: {}, max nr ports {}", cols, rows, max_nr_ports);
  44. // Base receiveq/transmitq for port0 + optional control queues and 2 per every additional port
  45. success = setup_queues(2 + max_nr_ports > 0 ? 2 + 2 * max_nr_ports : 0);
  46. if (!success)
  47. return Error::from_errno(EIO);
  48. finish_init();
  49. if (is_feature_accepted(VIRTIO_CONSOLE_F_MULTIPORT)) {
  50. setup_multiport();
  51. } else {
  52. auto port = TRY(DeviceManagement::the().try_create_device<VirtIO::ConsolePort>(0u, *this));
  53. port->init_receive_buffer({});
  54. m_ports.append(port);
  55. }
  56. return {};
  57. }
  58. UNMAP_AFTER_INIT Console::Console(PCI::DeviceIdentifier const& pci_device_identifier)
  59. : VirtIO::Device(pci_device_identifier)
  60. , m_device_id(next_device_id++)
  61. {
  62. }
  63. bool Console::handle_device_config_change()
  64. {
  65. dbgln("VirtIO::Console: Handle device config change");
  66. return true;
  67. }
  68. void Console::handle_queue_update(u16 queue_index)
  69. {
  70. dbgln_if(VIRTIO_DEBUG, "VirtIO::Console: Handle queue update {}", queue_index);
  71. if (queue_index == CONTROL_RECEIVEQ) {
  72. SpinlockLocker ringbuffer_lock(m_control_receive_buffer->lock());
  73. auto& queue = get_queue(CONTROL_RECEIVEQ);
  74. SpinlockLocker queue_lock(queue.lock());
  75. size_t used;
  76. QueueChain popped_chain = queue.pop_used_buffer_chain(used);
  77. while (!popped_chain.is_empty()) {
  78. popped_chain.for_each([&](auto addr, auto) {
  79. auto offset = addr.as_ptr() - m_control_receive_buffer->start_of_region().as_ptr();
  80. auto* message = reinterpret_cast<ControlMessage*>(m_control_receive_buffer->vaddr().offset(offset).as_ptr());
  81. process_control_message(*message);
  82. });
  83. supply_chain_and_notify(CONTROL_RECEIVEQ, popped_chain);
  84. popped_chain = queue.pop_used_buffer_chain(used);
  85. }
  86. } else if (queue_index == CONTROL_TRANSMITQ) {
  87. SpinlockLocker ringbuffer_lock(m_control_transmit_buffer->lock());
  88. auto& queue = get_queue(CONTROL_TRANSMITQ);
  89. SpinlockLocker queue_lock(queue.lock());
  90. size_t used;
  91. QueueChain popped_chain = queue.pop_used_buffer_chain(used);
  92. auto number_of_messages = 0;
  93. do {
  94. popped_chain.for_each([this](PhysicalAddress address, size_t length) {
  95. m_control_transmit_buffer->reclaim_space(address, length);
  96. });
  97. popped_chain.release_buffer_slots_to_queue();
  98. popped_chain = queue.pop_used_buffer_chain(used);
  99. number_of_messages++;
  100. } while (!popped_chain.is_empty());
  101. m_control_wait_queue.wake_n(number_of_messages);
  102. } else {
  103. u32 port_index = queue_index < 2 ? 0 : (queue_index - 2) / 2;
  104. if (port_index >= m_ports.size() || !m_ports.at(port_index)) {
  105. dbgln("Invalid queue_index {}", queue_index);
  106. return;
  107. }
  108. m_ports.at(port_index)->handle_queue_update({}, queue_index);
  109. }
  110. }
  111. void Console::setup_multiport()
  112. {
  113. m_control_receive_buffer = Memory::RingBuffer::try_create("VirtIOConsole control receive queue"sv, CONTROL_BUFFER_SIZE).release_value_but_fixme_should_propagate_errors();
  114. m_control_transmit_buffer = Memory::RingBuffer::try_create("VirtIOConsole control transmit queue"sv, CONTROL_BUFFER_SIZE).release_value_but_fixme_should_propagate_errors();
  115. auto& queue = get_queue(CONTROL_RECEIVEQ);
  116. SpinlockLocker queue_lock(queue.lock());
  117. QueueChain chain(queue);
  118. auto offset = 0ul;
  119. while (offset < CONTROL_BUFFER_SIZE) {
  120. auto buffer_start = m_control_receive_buffer->start_of_region().offset(offset);
  121. auto did_add_buffer = chain.add_buffer_to_chain(buffer_start, CONTROL_MESSAGE_SIZE, BufferType::DeviceWritable);
  122. VERIFY(did_add_buffer);
  123. offset += CONTROL_MESSAGE_SIZE;
  124. supply_chain_and_notify(CONTROL_RECEIVEQ, chain);
  125. }
  126. ControlMessage ready_event {
  127. .id = 0, // Unused
  128. .event = (u16)ControlEvent::DeviceReady,
  129. .value = (u16)ControlMessage::Status::Success
  130. };
  131. write_control_message(ready_event);
  132. }
  133. void Console::process_control_message(ControlMessage message)
  134. {
  135. switch (message.event) {
  136. case (u16)ControlEvent::DeviceAdd: {
  137. // FIXME: Do something sanely here if we can't allocate a work queue?
  138. MUST(g_io_work->try_queue([message, this]() -> void {
  139. u32 id = message.id;
  140. if (id >= m_ports.size()) {
  141. dbgln("Device provided an invalid port number {}. max_nr_ports: {}", id, m_ports.size());
  142. return;
  143. }
  144. if (!m_ports.at(id).is_null()) {
  145. dbgln("Device tried to add port {} which was already added!", id);
  146. return;
  147. }
  148. auto port = MUST(DeviceManagement::the().try_create_device<VirtIO::ConsolePort>(id, *this));
  149. port->init_receive_buffer({});
  150. m_ports.at(id) = port;
  151. ControlMessage ready_event {
  152. .id = static_cast<u32>(id),
  153. .event = (u16)ControlEvent::PortReady,
  154. .value = (u16)ControlMessage::Status::Success
  155. };
  156. write_control_message(ready_event);
  157. }));
  158. break;
  159. }
  160. case (u16)ControlEvent::ConsolePort:
  161. case (u16)ControlEvent::PortOpen: {
  162. if (message.id >= m_ports.size()) {
  163. dbgln("Device provided an invalid port number {}. max_nr_ports: {}", message.id, m_ports.size());
  164. return;
  165. }
  166. if (m_ports.at(message.id).is_null()) {
  167. dbgln("Device tried to open port {} which was not added!", message.id);
  168. return;
  169. }
  170. if (message.value == (u16)ControlMessage::PortStatus::Open) {
  171. auto is_open = m_ports.at(message.id)->is_open();
  172. if (!is_open) {
  173. m_ports.at(message.id)->set_open({}, true);
  174. send_open_control_message(message.id, true);
  175. }
  176. } else if (message.value == (u16)ControlMessage::PortStatus::Close) {
  177. m_ports.at(message.id)->set_open({}, false);
  178. } else {
  179. dbgln("Device specified invalid value {}. Must be 0 or 1.", message.value);
  180. }
  181. break;
  182. }
  183. default:
  184. dbgln("Unhandled message event {}!", message.event);
  185. }
  186. }
  187. void Console::write_control_message(ControlMessage message)
  188. {
  189. SpinlockLocker ringbuffer_lock(m_control_transmit_buffer->lock());
  190. PhysicalAddress start_of_chunk;
  191. size_t length_of_chunk;
  192. auto data = UserOrKernelBuffer::for_kernel_buffer((u8*)&message);
  193. while (!m_control_transmit_buffer->copy_data_in(data, 0, sizeof(message), start_of_chunk, length_of_chunk)) {
  194. ringbuffer_lock.unlock();
  195. m_control_wait_queue.wait_forever();
  196. ringbuffer_lock.lock();
  197. }
  198. auto& queue = get_queue(CONTROL_TRANSMITQ);
  199. SpinlockLocker queue_lock(queue.lock());
  200. QueueChain chain(queue);
  201. bool did_add_buffer = chain.add_buffer_to_chain(start_of_chunk, length_of_chunk, BufferType::DeviceReadable);
  202. VERIFY(did_add_buffer);
  203. supply_chain_and_notify(CONTROL_TRANSMITQ, chain);
  204. }
  205. void Console::send_open_control_message(unsigned port_number, bool open)
  206. {
  207. ControlMessage port_open {
  208. .id = static_cast<u32>(port_number),
  209. .event = (u16)ControlEvent::PortOpen,
  210. .value = open
  211. };
  212. write_control_message(port_open);
  213. }
  214. }