USBHub.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. TRY(m_sysfs_device_info_node.with([&](auto& node) -> ErrorOr<void> {
  42. node = TRY(SysFSUSBDeviceInformation::create(*this));
  43. return {};
  44. }));
  45. if (m_device_descriptor.device_class != USB_CLASS_HUB) {
  46. dbgln("USB Hub: Trying to enumerate and power on a device that says it isn't a hub.");
  47. return EINVAL;
  48. }
  49. dbgln_if(USB_DEBUG, "USB Hub: Enumerating and powering on for address {}", m_address);
  50. USBHubDescriptor descriptor {};
  51. // 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.
  52. auto transfer_length = TRY(m_default_pipe->submit_control_transfer(USB_REQUEST_TRANSFER_DIRECTION_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS, HubRequest::GET_DESCRIPTOR, (DESCRIPTOR_TYPE_HUB << 8), 0, sizeof(USBHubDescriptor), &descriptor));
  53. // FIXME: This be "not equal to" instead of "less than", but control transfers report a higher transfer length than expected.
  54. if (transfer_length < sizeof(USBHubDescriptor)) {
  55. dbgln("USB Hub: Unexpected hub descriptor size. Expected {}, got {}", sizeof(USBHubDescriptor), transfer_length);
  56. return EIO;
  57. }
  58. if constexpr (USB_DEBUG) {
  59. dbgln("USB Hub Descriptor for {:04x}:{:04x}", m_vendor_id, m_product_id);
  60. dbgln("Number of Downstream Ports: {}", descriptor.number_of_downstream_ports);
  61. dbgln("Hub Characteristics: 0x{:04x}", descriptor.hub_characteristics);
  62. dbgln("Power On to Power Good Time: {} ms ({} * 2ms)", descriptor.power_on_to_power_good_time * 2, descriptor.power_on_to_power_good_time);
  63. dbgln("Hub Controller Current: {} mA", descriptor.hub_controller_current);
  64. }
  65. // FIXME: Queue the status change interrupt
  66. // Enable all the ports
  67. for (u8 port_index = 0; port_index < descriptor.number_of_downstream_ports; ++port_index) {
  68. auto result = m_default_pipe->submit_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);
  69. if (result.is_error())
  70. dbgln("USB: Failed to power on port {} on hub at address {}.", port_index + 1, m_address);
  71. }
  72. // 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.
  73. microseconds_delay(descriptor.power_on_to_power_good_time * 2000);
  74. memcpy(&m_hub_descriptor, &descriptor, sizeof(USBHubDescriptor));
  75. return {};
  76. }
  77. // USB 2.0 Specification Section 11.24.2.7
  78. ErrorOr<void> Hub::get_port_status(u8 port, HubStatus& hub_status)
  79. {
  80. // Ports are 1-based.
  81. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  82. return EINVAL;
  83. auto transfer_length = TRY(m_default_pipe->submit_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));
  84. // FIXME: This be "not equal to" instead of "less than", but control transfers report a higher transfer length than expected.
  85. if (transfer_length < sizeof(HubStatus)) {
  86. dbgln("USB Hub: Unexpected hub status size. Expected {}, got {}.", sizeof(HubStatus), transfer_length);
  87. return EIO;
  88. }
  89. return {};
  90. }
  91. // USB 2.0 Specification Section 11.24.2.2
  92. ErrorOr<void> Hub::clear_port_feature(u8 port, HubFeatureSelector feature_selector)
  93. {
  94. // Ports are 1-based.
  95. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  96. return EINVAL;
  97. TRY(m_default_pipe->submit_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));
  98. return {};
  99. }
  100. // USB 2.0 Specification Section 11.24.2.13
  101. ErrorOr<void> Hub::set_port_feature(u8 port, HubFeatureSelector feature_selector)
  102. {
  103. // Ports are 1-based.
  104. if (port == 0 || port > m_hub_descriptor.number_of_downstream_ports)
  105. return EINVAL;
  106. TRY(m_default_pipe->submit_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));
  107. return {};
  108. }
  109. void Hub::remove_children_from_sysfs()
  110. {
  111. for (auto& child : m_children) {
  112. child.sysfs_device_info_node({}).with([](auto& node) {
  113. SysFSUSBBusDirectory::the().unplug({}, *node);
  114. });
  115. }
  116. }
  117. void Hub::check_for_port_updates()
  118. {
  119. for (u8 port_number = 1; port_number < m_hub_descriptor.number_of_downstream_ports + 1; ++port_number) {
  120. dbgln_if(USB_DEBUG, "USB Hub: Checking for port updates on port {}...", port_number);
  121. HubStatus port_status {};
  122. if (auto result = get_port_status(port_number, port_status); result.is_error()) {
  123. dbgln("USB Hub: Error occurred when getting status for port {}: {}. Checking next port instead.", port_number, result.error());
  124. continue;
  125. }
  126. if (port_status.change & PORT_STATUS_CONNECT_STATUS_CHANGED) {
  127. // Clear the connection status change notification.
  128. if (auto result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_CONNECTION); result.is_error()) {
  129. dbgln("USB Hub: Error occurred when clearing port connection change for port {}: {}.", port_number, result.error());
  130. return;
  131. }
  132. if (port_status.status & PORT_STATUS_CURRENT_CONNECT_STATUS) {
  133. dbgln("USB Hub: Device attached to port {}!", port_number);
  134. // Debounce the port. USB 2.0 Specification Page 150
  135. // Debounce interval is 100 ms (100000 us). USB 2.0 Specification Page 188 Table 7-14.
  136. constexpr u32 debounce_interval = 100 * 1000;
  137. // We must check if the device disconnected every so often. If it disconnects, we must reset the debounce timer.
  138. // This doesn't seem to be specified. Let's check every 10ms (10000 us).
  139. constexpr u32 debounce_disconnect_check_interval = 10 * 1000;
  140. u32 debounce_timer = 0;
  141. dbgln_if(USB_DEBUG, "USB Hub: Debouncing...");
  142. // FIXME: Timeout
  143. while (debounce_timer < debounce_interval) {
  144. microseconds_delay(debounce_disconnect_check_interval);
  145. debounce_timer += debounce_disconnect_check_interval;
  146. if (auto result = get_port_status(port_number, port_status); result.is_error()) {
  147. dbgln("USB Hub: Error occurred when getting status while debouncing port {}: {}.", port_number, result.error());
  148. return;
  149. }
  150. if (!(port_status.change & PORT_STATUS_CONNECT_STATUS_CHANGED))
  151. continue;
  152. dbgln_if(USB_DEBUG, "USB Hub: Connection status changed while debouncing, resetting debounce timer.");
  153. debounce_timer = 0;
  154. if (auto result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_CONNECTION); result.is_error()) {
  155. dbgln("USB Hub: Error occurred when clearing port connection change while debouncing port {}: {}.", port_number, result.error());
  156. return;
  157. }
  158. }
  159. // Reset the port
  160. dbgln_if(USB_DEBUG, "USB Hub: Debounce finished. Driving reset...");
  161. if (auto result = set_port_feature(port_number, HubFeatureSelector::PORT_RESET); result.is_error()) {
  162. dbgln("USB Hub: Error occurred when resetting port {}: {}.", port_number, result.error());
  163. return;
  164. }
  165. // FIXME: Timeout
  166. for (;;) {
  167. // Wait at least 10 ms for the port to reset.
  168. // This is T DRST in the USB 2.0 Specification Page 186 Table 7-13.
  169. constexpr u16 reset_delay = 10 * 1000;
  170. microseconds_delay(reset_delay);
  171. if (auto result = get_port_status(port_number, port_status); result.is_error()) {
  172. dbgln("USB Hub: Error occurred when getting status while resetting port {}: {}.", port_number, result.error());
  173. return;
  174. }
  175. if (port_status.change & PORT_STATUS_RESET_CHANGED)
  176. break;
  177. }
  178. // Stop asserting reset. This also causes the port to become enabled.
  179. if (auto result = clear_port_feature(port_number, HubFeatureSelector::C_PORT_RESET); result.is_error()) {
  180. dbgln("USB Hub: Error occurred when resetting port {}: {}.", port_number, result.error());
  181. return;
  182. }
  183. // Wait 10 ms for the port to recover.
  184. // This is T RSTRCY in the USB 2.0 Specification Page 188 Table 7-14.
  185. constexpr u16 reset_recovery_delay = 10 * 1000;
  186. microseconds_delay(reset_recovery_delay);
  187. dbgln_if(USB_DEBUG, "USB Hub: Reset complete!");
  188. // The port is ready to go. This is where we start communicating with the device to set up a driver for it.
  189. if (auto result = get_port_status(port_number, port_status); result.is_error()) {
  190. dbgln("USB Hub: Error occurred when getting status for port {} after reset: {}.", port_number, result.error());
  191. return;
  192. }
  193. // FIXME: Check for high speed.
  194. auto speed = port_status.status & PORT_STATUS_LOW_SPEED_DEVICE_ATTACHED ? USB::Device::DeviceSpeed::LowSpeed : USB::Device::DeviceSpeed::FullSpeed;
  195. auto device_or_error = USB::Device::try_create(m_controller, port_number, speed);
  196. if (device_or_error.is_error()) {
  197. dbgln("USB Hub: Failed to create device for port {}: {}", port_number, device_or_error.error());
  198. return;
  199. }
  200. auto device = device_or_error.release_value();
  201. dbgln_if(USB_DEBUG, "USB Hub: Created device with address {}!", device->address());
  202. if (device->device_descriptor().device_class == USB_CLASS_HUB) {
  203. auto hub_or_error = Hub::try_create_from_device(*device);
  204. if (hub_or_error.is_error()) {
  205. dbgln("USB Hub: Failed to upgrade device to hub for port {}: {}", port_number, device_or_error.error());
  206. return;
  207. }
  208. dbgln_if(USB_DEBUG, "USB Hub: Upgraded device at address {} to hub!", device->address());
  209. auto hub = hub_or_error.release_value();
  210. m_children.append(hub);
  211. hub->sysfs_device_info_node({}).with([](auto& node) {
  212. SysFSUSBBusDirectory::the().plug({}, *node);
  213. });
  214. } else {
  215. m_children.append(device);
  216. device->sysfs_device_info_node({}).with([](auto& node) {
  217. SysFSUSBBusDirectory::the().plug({}, *node);
  218. });
  219. }
  220. } else {
  221. dbgln("USB Hub: Device detached on port {}!", port_number);
  222. LockRefPtr<Device> device_to_remove = nullptr;
  223. for (auto& child : m_children) {
  224. if (port_number == child.port()) {
  225. device_to_remove = &child;
  226. break;
  227. }
  228. }
  229. if (device_to_remove) {
  230. device_to_remove->sysfs_device_info_node({}).with([](auto& node) {
  231. SysFSUSBBusDirectory::the().unplug({}, *node);
  232. });
  233. if (device_to_remove->device_descriptor().device_class == USB_CLASS_HUB) {
  234. auto* hub_child = static_cast<Hub*>(device_to_remove.ptr());
  235. hub_child->remove_children_from_sysfs();
  236. }
  237. m_children.remove(*device_to_remove);
  238. } else {
  239. dbgln_if(USB_DEBUG, "USB Hub: No child set up on port {}, ignoring detachment.", port_number);
  240. }
  241. }
  242. }
  243. }
  244. for (auto& child : m_children) {
  245. if (child.device_descriptor().device_class == USB_CLASS_HUB) {
  246. auto& hub_child = static_cast<Hub&>(child);
  247. dbgln_if(USB_DEBUG, "USB Hub: Checking for port updates on child hub at address {}...", child.address());
  248. hub_child.check_for_port_updates();
  249. }
  250. }
  251. }
  252. }