USBHub.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/Bus/USB/SysFSUSB.h>
  7. #include <Kernel/Bus/USB/USBClasses.h>
  8. #include <Kernel/Bus/USB/USBController.h>
  9. #include <Kernel/Bus/USB/USBHub.h>
  10. #include <Kernel/Bus/USB/USBRequest.h>
  11. #include <Kernel/StdLib.h>
  12. namespace Kernel::USB {
  13. KResultOr<NonnullRefPtr<Hub>> Hub::try_create_root_hub(NonnullRefPtr<USBController> controller, DeviceSpeed device_speed)
  14. {
  15. // NOTE: Enumeration does not happen here, as the controller must know what the device address is at all times during enumeration to intercept requests.
  16. auto pipe = TRY(Pipe::try_create_pipe(controller, Pipe::Type::Control, Pipe::Direction::Bidirectional, 0, 8, 0));
  17. auto hub = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Hub(controller, device_speed, move(pipe))));
  18. return hub;
  19. }
  20. KResultOr<NonnullRefPtr<Hub>> Hub::try_create_from_device(Device const& device)
  21. {
  22. auto pipe = TRY(Pipe::try_create_pipe(device.controller(), Pipe::Type::Control, Pipe::Direction::Bidirectional, 0, device.device_descriptor().max_packet_size, device.address()));
  23. auto hub = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Hub(device, move(pipe))));
  24. TRY(hub->enumerate_and_power_on_hub());
  25. return hub;
  26. }
  27. Hub::Hub(NonnullRefPtr<USBController> controller, DeviceSpeed device_speed, NonnullOwnPtr<Pipe> default_pipe)
  28. : Device(move(controller), 1 /* Port 1 */, device_speed, move(default_pipe))
  29. {
  30. }
  31. Hub::Hub(Device const& device, NonnullOwnPtr<Pipe> default_pipe)
  32. : Device(device, move(default_pipe))
  33. {
  34. }
  35. KResult Hub::enumerate_and_power_on_hub()
  36. {
  37. // USBDevice::enumerate_device must be called before this.
  38. VERIFY(m_address > 0);
  39. if (m_device_descriptor.device_class != USB_CLASS_HUB) {
  40. dbgln("USB Hub: Trying to enumerate and power on a device that says it isn't a hub.");
  41. return EINVAL;
  42. }
  43. dbgln_if(USB_DEBUG, "USB Hub: Enumerating and powering on for address {}", m_address);
  44. USBHubDescriptor descriptor {};
  45. // Get the first hub descriptor. All hubs are required to have a hub descriptor at index 0. USB 2.0 Specification Section 11.24.2.5.
  46. auto transfer_length = TRY(m_default_pipe->control_transfer(USB_REQUEST_TRANSFER_DIRECTION_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS, HubRequest::GET_DESCRIPTOR, (DESCRIPTOR_TYPE_HUB << 8), 0, sizeof(USBHubDescriptor), &descriptor));
  47. // FIXME: This be "not equal to" instead of "less than", but control transfers report a higher transfer length than expected.
  48. if (transfer_length < sizeof(USBHubDescriptor)) {
  49. dbgln("USB Hub: Unexpected hub descriptor size. Expected {}, got {}", sizeof(USBHubDescriptor), transfer_length);
  50. return EIO;
  51. }
  52. if constexpr (USB_DEBUG) {
  53. dbgln("USB Hub Descriptor for {:04x}:{:04x}", m_vendor_id, m_product_id);
  54. dbgln("Number of Downstream Ports: {}", descriptor.number_of_downstream_ports);
  55. dbgln("Hub Characteristics: 0x{:04x}", descriptor.hub_characteristics);
  56. dbgln("Power On to Power Good Time: {} ms ({} * 2ms)", descriptor.power_on_to_power_good_time * 2, descriptor.power_on_to_power_good_time);
  57. dbgln("Hub Controller Current: {} mA", descriptor.hub_controller_current);
  58. }
  59. // FIXME: Queue the status change interrupt
  60. // Enable all the ports
  61. for (u8 port_index = 0; port_index < descriptor.number_of_downstream_ports; ++port_index) {
  62. auto result = m_default_pipe->control_transfer(USB_REQUEST_TRANSFER_DIRECTION_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_REQUEST_RECIPIENT_OTHER, HubRequest::SET_FEATURE, HubFeatureSelector::PORT_POWER, port_index + 1, 0, nullptr);
  63. if (result.is_error())
  64. dbgln("USB: Failed to power on port {} on hub at address {}.", port_index + 1, m_address);
  65. }
  66. // Wait for the ports to power up. power_on_to_power_good_time is in units of 2 ms and we want in us, so multiply by 2000.
  67. IO::delay(descriptor.power_on_to_power_good_time * 2000);
  68. memcpy(&m_hub_descriptor, &descriptor, sizeof(USBHubDescriptor));
  69. return KSuccess;
  70. }
  71. // USB 2.0 Specification Section 11.24.2.7
  72. KResult Hub::get_port_status(u8 port, HubStatus& hub_status)
  73. {
  74. // Ports are 1-based.
  75. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  76. return EINVAL;
  77. auto transfer_length = TRY(m_default_pipe->control_transfer(USB_REQUEST_TRANSFER_DIRECTION_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS | USB_REQUEST_RECIPIENT_OTHER, HubRequest::GET_STATUS, 0, port, sizeof(HubStatus), &hub_status));
  78. // FIXME: This be "not equal to" instead of "less than", but control transfers report a higher transfer length than expected.
  79. if (transfer_length < sizeof(HubStatus)) {
  80. dbgln("USB Hub: Unexpected hub status size. Expected {}, got {}.", sizeof(HubStatus), transfer_length);
  81. return EIO;
  82. }
  83. return KSuccess;
  84. }
  85. // USB 2.0 Specification Section 11.24.2.2
  86. KResult Hub::clear_port_feature(u8 port, HubFeatureSelector feature_selector)
  87. {
  88. // Ports are 1-based.
  89. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  90. return EINVAL;
  91. TRY(m_default_pipe->control_transfer(USB_REQUEST_TRANSFER_DIRECTION_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_REQUEST_RECIPIENT_OTHER, HubRequest::CLEAR_FEATURE, feature_selector, port, 0, nullptr));
  92. return KSuccess;
  93. }
  94. // USB 2.0 Specification Section 11.24.2.13
  95. KResult Hub::set_port_feature(u8 port, HubFeatureSelector feature_selector)
  96. {
  97. // Ports are 1-based.
  98. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  99. return EINVAL;
  100. TRY(m_default_pipe->control_transfer(USB_REQUEST_TRANSFER_DIRECTION_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_REQUEST_RECIPIENT_OTHER, HubRequest::SET_FEATURE, feature_selector, port, 0, nullptr));
  101. return KSuccess;
  102. }
  103. void Hub::remove_children_from_sysfs()
  104. {
  105. for (auto& child : m_children)
  106. SysFSUSBBusDirectory::the().unplug(child);
  107. }
  108. void Hub::check_for_port_updates()
  109. {
  110. for (u8 port_number = 1; port_number < m_hub_descriptor.number_of_downstream_ports + 1; ++port_number) {
  111. dbgln_if(USB_DEBUG, "USB Hub: Checking for port updates on port {}...", port_number);
  112. HubStatus port_status {};
  113. auto result = get_port_status(port_number, port_status);
  114. if (result.is_error()) {
  115. dbgln("USB Hub: Error occurred when getting status for port {}: {}. Checking next port instead.", port_number, result.error());
  116. continue;
  117. }
  118. if (port_status.change & PORT_STATUS_CONNECT_STATUS_CHANGED) {
  119. // Clear the connection status change notification.
  120. result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_CONNECTION);
  121. if (result.is_error()) {
  122. dbgln("USB Hub: Error occurred when clearing port connection change for port {}: {}.", port_number, result.error());
  123. return;
  124. }
  125. if (port_status.status & PORT_STATUS_CURRENT_CONNECT_STATUS) {
  126. dbgln("USB Hub: Device attached to port {}!", port_number);
  127. // Debounce the port. USB 2.0 Specification Page 150
  128. // Debounce interval is 100 ms (100000 us). USB 2.0 Specification Page 188 Table 7-14.
  129. constexpr u32 debounce_interval = 100 * 1000;
  130. // We must check if the device disconnected every so often. If it disconnects, we must reset the debounce timer.
  131. // This doesn't seem to be specified. Let's check every 10ms (10000 us).
  132. constexpr u32 debounce_disconnect_check_interval = 10 * 1000;
  133. u32 debounce_timer = 0;
  134. dbgln_if(USB_DEBUG, "USB Hub: Debouncing...");
  135. // FIXME: Timeout
  136. while (debounce_timer < debounce_interval) {
  137. IO::delay(debounce_disconnect_check_interval);
  138. debounce_timer += debounce_disconnect_check_interval;
  139. result = get_port_status(port_number, port_status);
  140. if (result.is_error()) {
  141. dbgln("USB Hub: Error occurred when getting status while debouncing port {}: {}.", port_number, result.error());
  142. return;
  143. }
  144. if (!(port_status.change & PORT_STATUS_CONNECT_STATUS_CHANGED))
  145. continue;
  146. dbgln_if(USB_DEBUG, "USB Hub: Connection status changed while debouncing, resetting debounce timer.");
  147. debounce_timer = 0;
  148. result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_CONNECTION);
  149. if (result.is_error()) {
  150. dbgln("USB Hub: Error occurred when clearing port connection change while debouncing port {}: {}.", port_number, result.error());
  151. return;
  152. }
  153. }
  154. // Reset the port
  155. dbgln_if(USB_DEBUG, "USB Hub: Debounce finished. Driving reset...");
  156. result = set_port_feature(port_number, HubFeatureSelector::PORT_RESET);
  157. if (result.is_error()) {
  158. dbgln("USB Hub: Error occurred when resetting port {}: {}.", port_number, result.error());
  159. return;
  160. }
  161. // FIXME: Timeout
  162. for (;;) {
  163. // Wait at least 10 ms for the port to reset.
  164. // This is T DRST in the USB 2.0 Specification Page 186 Table 7-13.
  165. constexpr u16 reset_delay = 10 * 1000;
  166. IO::delay(reset_delay);
  167. result = get_port_status(port_number, port_status);
  168. if (result.is_error()) {
  169. dbgln("USB Hub: Error occurred when getting status while resetting port {}: {}.", port_number, result.error());
  170. return;
  171. }
  172. if (port_status.change & PORT_STATUS_RESET_CHANGED)
  173. break;
  174. }
  175. // Stop asserting reset. This also causes the port to become enabled.
  176. result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_RESET);
  177. if (result.is_error()) {
  178. dbgln("USB Hub: Error occurred when resetting port {}: {}.", port_number, result.error());
  179. return;
  180. }
  181. // Wait 10 ms for the port to recover.
  182. // This is T RSTRCY in the USB 2.0 Specification Page 188 Table 7-14.
  183. constexpr u16 reset_recovery_delay = 10 * 1000;
  184. IO::delay(reset_recovery_delay);
  185. dbgln_if(USB_DEBUG, "USB Hub: Reset complete!");
  186. // The port is ready to go. This is where we start communicating with the device to set up a driver for it.
  187. result = get_port_status(port_number, port_status);
  188. if (result.is_error()) {
  189. dbgln("USB Hub: Error occurred when getting status for port {} after reset: {}.", port_number, result.error());
  190. return;
  191. }
  192. // FIXME: Check for high speed.
  193. auto speed = port_status.status & PORT_STATUS_LOW_SPEED_DEVICE_ATTACHED ? USB::Device::DeviceSpeed::LowSpeed : USB::Device::DeviceSpeed::FullSpeed;
  194. auto device_or_error = USB::Device::try_create(m_controller, port_number, speed);
  195. if (device_or_error.is_error()) {
  196. dbgln("USB Hub: Failed to create device for port {}: {}", port_number, device_or_error.error());
  197. return;
  198. }
  199. auto device = device_or_error.release_value();
  200. dbgln_if(USB_DEBUG, "USB Hub: Created device with address {}!", device->address());
  201. if (device->device_descriptor().device_class == USB_CLASS_HUB) {
  202. auto hub_or_error = Hub::try_create_from_device(*device);
  203. if (hub_or_error.is_error()) {
  204. dbgln("USB Hub: Failed to upgrade device to hub for port {}: {}", port_number, device_or_error.error());
  205. return;
  206. }
  207. dbgln_if(USB_DEBUG, "USB Hub: Upgraded device at address {} to hub!", device->address());
  208. auto hub = hub_or_error.release_value();
  209. m_children.append(hub);
  210. SysFSUSBBusDirectory::the().plug(hub);
  211. } else {
  212. m_children.append(device);
  213. SysFSUSBBusDirectory::the().plug(device);
  214. }
  215. } else {
  216. dbgln("USB Hub: Device detached on port {}!", port_number);
  217. RefPtr<Device> device_to_remove = nullptr;
  218. for (auto& child : m_children) {
  219. if (port_number == child.port()) {
  220. device_to_remove = &child;
  221. break;
  222. }
  223. }
  224. if (device_to_remove) {
  225. m_children.remove(*device_to_remove);
  226. SysFSUSBBusDirectory::the().unplug(*device_to_remove);
  227. if (device_to_remove->device_descriptor().device_class == USB_CLASS_HUB) {
  228. auto* hub_child = static_cast<Hub*>(device_to_remove.ptr());
  229. hub_child->remove_children_from_sysfs();
  230. }
  231. } else {
  232. dbgln_if(USB_DEBUG, "USB Hub: No child set up on port {}, ignoring detachment.", port_number);
  233. }
  234. }
  235. }
  236. }
  237. for (auto& child : m_children) {
  238. if (child.device_descriptor().device_class == USB_CLASS_HUB) {
  239. auto& hub_child = static_cast<Hub&>(child);
  240. dbgln_if(USB_DEBUG, "USB Hub: Checking for port updates on child hub at address {}...", child.address());
  241. hub_child.check_for_port_updates();
  242. }
  243. }
  244. }
  245. }