Controller.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Copyright (c) 2023, Jelle Raaijmakers <jelle@gmta.nl>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Controller.h"
  7. #include <AK/Optional.h>
  8. #include <AK/Vector.h>
  9. #include <Kernel/Arch/Delay.h>
  10. #include <Kernel/Bus/PCI/API.h>
  11. #include <Kernel/Devices/Audio/IntelHDA/Codec.h>
  12. #include <Kernel/Devices/Audio/IntelHDA/InterruptHandler.h>
  13. #include <Kernel/Devices/Audio/IntelHDA/Stream.h>
  14. #include <Kernel/Devices/Audio/IntelHDA/Timing.h>
  15. #include <Kernel/Time/TimeManagement.h>
  16. namespace Kernel::Audio::IntelHDA {
  17. UNMAP_AFTER_INIT ErrorOr<bool> Controller::probe(PCI::DeviceIdentifier const& device_identifier)
  18. {
  19. VERIFY(device_identifier.class_code() == PCI::ClassID::Multimedia);
  20. return device_identifier.subclass_code() == PCI::Multimedia::SubclassID::HDACompatible;
  21. }
  22. UNMAP_AFTER_INIT ErrorOr<NonnullRefPtr<AudioController>> Controller::create(PCI::DeviceIdentifier const& pci_device_identifier)
  23. {
  24. auto controller_io_window = TRY(IOWindow::create_for_pci_device_bar(pci_device_identifier, PCI::HeaderType0BaseRegister::BAR0));
  25. return TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Controller(pci_device_identifier, move(controller_io_window))));
  26. }
  27. UNMAP_AFTER_INIT Controller::Controller(PCI::DeviceIdentifier const& pci_device_identifier, NonnullOwnPtr<IOWindow> controller_io_window)
  28. : PCI::Device(const_cast<PCI::DeviceIdentifier&>(pci_device_identifier))
  29. , m_controller_io_window(move(controller_io_window))
  30. {
  31. }
  32. UNMAP_AFTER_INIT ErrorOr<void> Controller::initialize(Badge<AudioManagement>)
  33. {
  34. // Enable DMA and interrupts
  35. PCI::enable_bus_mastering(device_identifier());
  36. m_interrupt_handler = TRY(InterruptHandler::create(*this));
  37. // 3.3.3, 3.3.4: Controller version
  38. auto version_minor = m_controller_io_window->read8(ControllerRegister::VersionMinor);
  39. auto version_major = m_controller_io_window->read8(ControllerRegister::VersionMajor);
  40. dmesgln_pci(*this, "Intel High Definition Audio specification v{}.{}", version_major, version_minor);
  41. if (version_major != 1 || version_minor != 0)
  42. return ENOTSUP;
  43. // 3.3.2: Read capabilities
  44. u16 capabilities = m_controller_io_window->read16(ControllerRegister::GlobalCapabilities);
  45. dbgln_if(INTEL_HDA_DEBUG, "Controller capabilities:");
  46. m_number_of_output_streams = capabilities >> 12;
  47. m_number_of_input_streams = (capabilities >> 8) & 0xf;
  48. m_number_of_bidirectional_streams = (capabilities >> 3) & 0x1f;
  49. bool is_64_bit_addressing_supported = (capabilities & 0x1) > 0;
  50. dbgln_if(INTEL_HDA_DEBUG, "├ Number of output streams: {}", m_number_of_output_streams);
  51. dbgln_if(INTEL_HDA_DEBUG, "├ Number of input streams: {}", m_number_of_input_streams);
  52. dbgln_if(INTEL_HDA_DEBUG, "├ Number of bidirectional streams: {}", m_number_of_bidirectional_streams);
  53. dbgln_if(INTEL_HDA_DEBUG, "└ 64-bit addressing supported: {}", is_64_bit_addressing_supported ? "yes" : "no");
  54. if (m_number_of_output_streams == 0)
  55. return ENOTSUP;
  56. if (!is_64_bit_addressing_supported && sizeof(FlatPtr) == 8)
  57. return ENOTSUP;
  58. // Reset the controller
  59. TRY(reset());
  60. // Register CORB and RIRB
  61. auto command_io_window = TRY(m_controller_io_window->create_from_io_window_with_offset(ControllerRegister::CommandOutboundRingBufferOffset));
  62. m_command_buffer = TRY(CommandOutboundRingBuffer::create("IntelHDA CORB"sv, move(command_io_window)));
  63. TRY(m_command_buffer->register_with_controller());
  64. auto response_io_window = TRY(m_controller_io_window->create_from_io_window_with_offset(ControllerRegister::ResponseInboundRingBufferOffset));
  65. m_response_buffer = TRY(ResponseInboundRingBuffer::create("IntelHDA RIRB"sv, move(response_io_window)));
  66. TRY(m_response_buffer->register_with_controller());
  67. dbgln_if(INTEL_HDA_DEBUG, "CORB ({} entries) and RIRB ({} entries) registered", m_command_buffer->capacity(), m_response_buffer->capacity());
  68. // Initialize all codecs
  69. // 3.3.9: State Change Status
  70. u16 state_change_status = m_controller_io_window->read16(ControllerRegister::StateChangeStatus);
  71. for (u8 codec_address = 0; codec_address < 14; ++codec_address) {
  72. if ((state_change_status & (1 << codec_address)) > 0) {
  73. dmesgln_pci(*this, "Found codec on address #{}", codec_address);
  74. TRY(initialize_codec(codec_address));
  75. }
  76. }
  77. auto result = configure_output_route();
  78. if (result.is_error()) {
  79. dmesgln_pci(*this, "Failed to set up an output audio channel: {}", result.error());
  80. return result.release_error();
  81. }
  82. m_audio_channel = TRY(AudioChannel::create(*this, fixed_audio_channel_index));
  83. return {};
  84. }
  85. UNMAP_AFTER_INIT ErrorOr<void> Controller::initialize_codec(u8 codec_address)
  86. {
  87. auto codec = TRY(Codec::create(*this, codec_address));
  88. auto root_node = TRY(Node::create<RootNode>(codec));
  89. if constexpr (INTEL_HDA_DEBUG)
  90. root_node->debug_dump();
  91. codec->set_root_node(root_node);
  92. TRY(m_codecs.try_append(codec));
  93. return {};
  94. }
  95. ErrorOr<u32> Controller::send_command(u8 codec_address, u8 node_id, CodecControlVerb verb, u16 payload)
  96. {
  97. // Construct command
  98. // 7.3: If the most significant 4 bits of 12-bits verb are 0xf or 0x7, extended mode is selected
  99. u32 command_value = codec_address << 28 | (node_id << 20);
  100. if (((verb & 0x700) > 0) || ((verb & 0xf00) > 0))
  101. command_value |= ((verb & 0xfff) << 8) | (payload & 0xff);
  102. else
  103. command_value |= ((verb & 0xf) << 16) | payload;
  104. dbgln_if(INTEL_HDA_DEBUG, "Controller::{}: codec {} node {} verb {:#x} payload {:#b}",
  105. __FUNCTION__, codec_address, node_id, to_underlying(verb), payload);
  106. TRY(m_command_buffer->write_value(command_value));
  107. // Read response
  108. Optional<u64> full_response;
  109. TRY(wait_until(frame_delay_in_microseconds(1), controller_timeout_in_microseconds, [&]() -> ErrorOr<bool> {
  110. full_response = TRY(m_response_buffer->read_value());
  111. return full_response.has_value();
  112. }));
  113. u32 response = full_response.value() & 0xffffffffu;
  114. dbgln_if(INTEL_HDA_DEBUG, "Controller::{}: response {:#032b}", __FUNCTION__, response);
  115. return response;
  116. }
  117. UNMAP_AFTER_INIT ErrorOr<void> Controller::configure_output_route()
  118. {
  119. Vector<NonnullRefPtr<WidgetNode>> queued_nodes;
  120. Vector<WidgetNode*> visited_nodes;
  121. HashMap<WidgetNode*, WidgetNode*> parents;
  122. auto create_output_path = [&](RefPtr<WidgetNode> found_node) -> ErrorOr<NonnullOwnPtr<OutputPath>> {
  123. // Reconstruct path by traversing parent nodes
  124. Vector<NonnullRefPtr<WidgetNode>> path;
  125. auto path_node = found_node;
  126. while (path_node) {
  127. TRY(path.try_append(*path_node));
  128. path_node = parents.get(path_node).value_or(nullptr);
  129. }
  130. path.reverse();
  131. // Create output stream
  132. constexpr u8 output_stream_index = 0;
  133. constexpr u8 output_stream_number = 1;
  134. u64 output_stream_offset = ControllerRegister::StreamsOffset
  135. + m_number_of_input_streams * 0x20
  136. + output_stream_index * 0x20;
  137. auto stream_io_window = TRY(m_controller_io_window->create_from_io_window_with_offset(output_stream_offset));
  138. auto output_stream = TRY(OutputStream::create(move(stream_io_window), output_stream_number));
  139. // Create output path
  140. auto output_path = TRY(OutputPath::create(move(path), move(output_stream)));
  141. TRY(output_path->activate());
  142. // Enable controller and stream interrupts for this output stream
  143. auto interrupt_control = m_controller_io_window->read32(ControllerRegister::InterruptControl);
  144. interrupt_control |= InterruptControlFlag::GlobalInterruptEnable;
  145. interrupt_control |= 1u << (m_number_of_input_streams + output_stream_index);
  146. m_controller_io_window->write32(ControllerRegister::InterruptControl, interrupt_control);
  147. return output_path;
  148. };
  149. for (auto codec : m_codecs) {
  150. // Start off by finding all candidate pin complexes
  151. auto pin_widgets = TRY(codec->nodes_matching<WidgetNode>([](NonnullRefPtr<WidgetNode> node) {
  152. // Find pin complexes that support output.
  153. if (node->widget_type() != WidgetNode::WidgetType::PinComplex
  154. || !node->pin_complex_output_supported())
  155. return false;
  156. // Only consider pin complexes that have:
  157. // - a physical connection (jack or fixed function)
  158. // - and a default device that is line out, speakers or headphones.
  159. auto configuration_default = node->pin_configuration_default();
  160. auto port_connectivity = configuration_default.port_connectivity;
  161. auto default_device = configuration_default.default_device;
  162. bool is_physically_connected = port_connectivity == WidgetNode::PinPortConnectivity::Jack
  163. || port_connectivity == WidgetNode::PinPortConnectivity::FixedFunction
  164. || port_connectivity == WidgetNode::PinPortConnectivity::JackAndFixedFunction;
  165. bool is_output_device = default_device == WidgetNode::PinDefaultDevice::LineOut
  166. || default_device == WidgetNode::PinDefaultDevice::Speaker
  167. || default_device == WidgetNode::PinDefaultDevice::HPOut;
  168. return is_physically_connected && is_output_device;
  169. }));
  170. // Perform a breadth-first search to find a path to an audio output widget
  171. for (auto pin_widget : pin_widgets) {
  172. VERIFY(queued_nodes.is_empty() && visited_nodes.is_empty() && parents.is_empty());
  173. TRY(queued_nodes.try_append(pin_widget));
  174. Optional<NonnullRefPtr<WidgetNode>> found_node = {};
  175. while (!queued_nodes.is_empty()) {
  176. auto current_node = queued_nodes.take_first();
  177. if (current_node->widget_type() == WidgetNode::AudioOutput) {
  178. found_node = current_node;
  179. break;
  180. }
  181. TRY(visited_nodes.try_append(current_node.ptr()));
  182. for (u8 connection_node_id : current_node->connection_list()) {
  183. auto connection_node = codec->node_by_node_id(connection_node_id);
  184. if (!connection_node.has_value() || connection_node.value()->node_type() != Node::NodeType::Widget) {
  185. dmesgln_pci(*this, "Warning: connection node {} does not exist or is the wrong type", connection_node_id);
  186. continue;
  187. }
  188. auto connection_widget = NonnullRefPtr<WidgetNode> { *reinterpret_cast<WidgetNode*>(connection_node.release_value()) };
  189. if (visited_nodes.contains_slow(connection_widget))
  190. continue;
  191. TRY(queued_nodes.try_append(connection_widget));
  192. TRY(parents.try_set(connection_widget, current_node.ptr()));
  193. }
  194. }
  195. if (found_node.has_value()) {
  196. m_output_path = TRY(create_output_path(found_node.release_value()));
  197. break;
  198. }
  199. queued_nodes.clear_with_capacity();
  200. visited_nodes.clear_with_capacity();
  201. parents.clear_with_capacity();
  202. }
  203. if (m_output_path)
  204. break;
  205. }
  206. if (!m_output_path) {
  207. dmesgln_pci(*this, "Failed to find an audio output path");
  208. return ENODEV;
  209. }
  210. // We are ready to go!
  211. dmesgln_pci(*this, "Successfully configured an audio output path");
  212. dbgln_if(INTEL_HDA_DEBUG, "{}", TRY(m_output_path->to_string()));
  213. return {};
  214. }
  215. ErrorOr<void> Controller::reset()
  216. {
  217. // 3.3.7: "Controller Reset (CRST): Writing a 0 to this bit causes the High Definition Audio
  218. // controller to transition to the Reset state."
  219. u32 global_control = m_controller_io_window->read32(ControllerRegister::GlobalControl);
  220. global_control &= ~GlobalControlFlag::ControllerReset;
  221. global_control &= ~GlobalControlFlag::AcceptUnsolicitedResponseEnable;
  222. m_controller_io_window->write32(ControllerRegister::GlobalControl, global_control);
  223. // 3.3.7: "After the hardware has completed sequencing into the reset state, it will report
  224. // a 0 in this bit. Software must read a 0 from this bit to verify that the
  225. // controller is in reset."
  226. TRY(wait_until(frame_delay_in_microseconds(1), controller_timeout_in_microseconds, [&]() {
  227. global_control = m_controller_io_window->read32(ControllerRegister::GlobalControl);
  228. return (global_control & GlobalControlFlag::ControllerReset) == 0;
  229. }));
  230. // 3.3.7: "Writing a 1 to this bit causes the controller to exit its Reset state and
  231. // de-assert the link RESET# signal. Software is responsible for
  232. // setting/clearing this bit such that the minimum link RESET# signal assertion
  233. // pulse width specification is met (see Section 5.5)."
  234. microseconds_delay(100);
  235. global_control |= GlobalControlFlag::ControllerReset;
  236. m_controller_io_window->write32(ControllerRegister::GlobalControl, global_control);
  237. // 3.3.7: "When the controller hardware is ready to begin operation, it will report a 1 in
  238. // this bit. Software must read a 1 from this bit before accessing any controller
  239. // registers."
  240. TRY(wait_until(frame_delay_in_microseconds(1), controller_timeout_in_microseconds, [&]() {
  241. global_control = m_controller_io_window->read32(ControllerRegister::GlobalControl);
  242. return (global_control & GlobalControlFlag::ControllerReset) > 0;
  243. }));
  244. // 4.3 Codec Discovery:
  245. // "The software must wait at least 521 us (25 frames) after reading CRST as a 1 before
  246. // assuming that codecs have all made status change requests and have been registered
  247. // by the controller."
  248. microseconds_delay(frame_delay_in_microseconds(25));
  249. dbgln_if(INTEL_HDA_DEBUG, "Controller reset");
  250. return {};
  251. }
  252. ErrorOr<bool> Controller::handle_interrupt(Badge<InterruptHandler>)
  253. {
  254. // Check if any interrupt status bit is set
  255. auto interrupt_status = m_controller_io_window->read32(ControllerRegister::InterruptStatus);
  256. if ((interrupt_status & InterruptStatusFlag::GlobalInterruptStatus) == 0)
  257. return false;
  258. // FIXME: Actually look at interrupt_status and iterate over streams as soon as
  259. // we support multiple streams.
  260. if (m_output_path)
  261. TRY(m_output_path->output_stream().handle_interrupt({}));
  262. return true;
  263. }
  264. RefPtr<AudioChannel> Controller::audio_channel(u32 index) const
  265. {
  266. if (index != fixed_audio_channel_index)
  267. return {};
  268. return m_audio_channel;
  269. }
  270. ErrorOr<size_t> Controller::write(size_t channel_index, UserOrKernelBuffer const& data, size_t length)
  271. {
  272. if (channel_index != fixed_audio_channel_index || !m_output_path)
  273. return ENODEV;
  274. return m_output_path->output_stream().write(data, length);
  275. }
  276. ErrorOr<void> Controller::set_pcm_output_sample_rate(size_t channel_index, u32 samples_per_second_rate)
  277. {
  278. if (channel_index != fixed_audio_channel_index || !m_output_path)
  279. return ENODEV;
  280. TRY(m_output_path->set_format({
  281. .sample_rate = samples_per_second_rate,
  282. .pcm_bits = OutputPath::fixed_pcm_bits,
  283. .number_of_channels = OutputPath::fixed_channel_count,
  284. }));
  285. dmesgln_pci(*this, "Set output channel #{} PCM rate: {} Hz", channel_index, samples_per_second_rate);
  286. return {};
  287. }
  288. ErrorOr<u32> Controller::get_pcm_output_sample_rate(size_t channel_index)
  289. {
  290. if (channel_index != fixed_audio_channel_index || !m_output_path)
  291. return ENODEV;
  292. return m_output_path->output_stream().sample_rate();
  293. }
  294. ErrorOr<void> wait_until(size_t delay_in_microseconds, size_t timeout_in_microseconds, Function<ErrorOr<bool>()> condition)
  295. {
  296. auto const timeout = Duration::from_microseconds(static_cast<i64>(timeout_in_microseconds));
  297. auto const& time_management = TimeManagement::the();
  298. auto start = time_management.monotonic_time(TimePrecision::Precise);
  299. while (!TRY(condition())) {
  300. microseconds_delay(delay_in_microseconds);
  301. if (time_management.monotonic_time(TimePrecision::Precise) - start >= timeout)
  302. return ETIMEDOUT;
  303. }
  304. return {};
  305. }
  306. }