USBHub.cpp 14 KB

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