From 979f4507e40300a0890a9b42c068ae3eb3dee5f6 Mon Sep 17 00:00:00 2001 From: Andrey Tolstoy Date: Thu, 30 Dec 2021 12:32:59 +0700 Subject: [PATCH] [rtl872x] hal: avoid initializing USB driver twice which causes enumeration issues --- hal/src/rtl872x/usbd_device.cpp | 10 ++++++---- hal/src/rtl872x/usbd_driver.cpp | 17 +++++++++++++++-- hal/src/rtl872x/usbd_driver.h | 2 ++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/hal/src/rtl872x/usbd_device.cpp b/hal/src/rtl872x/usbd_device.cpp index 3dba6c0202..6813fa9271 100644 --- a/hal/src/rtl872x/usbd_device.cpp +++ b/hal/src/rtl872x/usbd_device.cpp @@ -399,11 +399,13 @@ int Device::clearConfig(unsigned index) { int lastError = 0; for (auto& cls: classDrivers_) { if (cls && cls->isEnabled()) { - int r = cls->deinit(index); - if (r < 0) { - lastError = r; + if (cls->isConfigured()) { + int r = cls->deinit(index); + if (r < 0) { + lastError = r; + } + cls->configured(false); } - cls->configured(false); } } return lastError; diff --git a/hal/src/rtl872x/usbd_driver.cpp b/hal/src/rtl872x/usbd_driver.cpp index 4885b0ccd9..4f03787814 100644 --- a/hal/src/rtl872x/usbd_driver.cpp +++ b/hal/src/rtl872x/usbd_driver.cpp @@ -130,15 +130,28 @@ RtlUsbDriver::~RtlUsbDriver() { } int RtlUsbDriver::attach() { + if (initialized_) { + // Ignore + return 0; + } + initialized_ = true; // NOTE: these calls may fail - usbd_init(&usbdCfg_); - usbd_register_class(&classDrv_); + auto r = usbd_init(&usbdCfg_); + if (r) { + // LOG(ERROR, "usbd_init failed: %d", r); + initialized_ = false; + CHECK_RTL_USB_TO_SYSTEM(r); + } else { + usbd_register_class(&classDrv_); + } + return 0; } int RtlUsbDriver::detach() { usbd_unregister_class(); usbd_deinit(); + initialized_ = true; return 0; } diff --git a/hal/src/rtl872x/usbd_driver.h b/hal/src/rtl872x/usbd_driver.h index 5906e071e5..5f6ece78d7 100644 --- a/hal/src/rtl872x/usbd_driver.h +++ b/hal/src/rtl872x/usbd_driver.h @@ -129,6 +129,8 @@ class RtlUsbDriver : public DeviceDriver { #if MODULE_FUNCTION != MOD_FUNC_BOOTLOADER RecursiveMutex mutex_; #endif // MODULE_FUNCTION != MOD_FUNC_BOOTLOADER + + volatile bool initialized_ = false; }; } // namespace usbd