USBHub.cpp 14 KB

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