Controller.cpp 15 KB

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