Controller.cpp 15 KB

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