From 186b9e447b5bbe8997f15f3878875fc05bd0589b Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Fri, 3 Jun 2022 22:18:42 +0000 Subject: [PATCH] USB MIDI: Reset counter after unique codes full Some tests continously plug and unplug MIDI devices. After 1000 operations, there is an infinite while loop. This CL clears up the hashset if it is nearly full. Bug: 234688233 Test: Plug and unplug MIDI devices Change-Id: Ie0c6359c07694e3f6cc4a3011fd39a525314ab94 --- .../usb/java/com/android/server/usb/UsbHostManager.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/services/usb/java/com/android/server/usb/UsbHostManager.java b/services/usb/java/com/android/server/usb/UsbHostManager.java index b1c85fe043ecd..f3892768921ce 100644 --- a/services/usb/java/com/android/server/usb/UsbHostManager.java +++ b/services/usb/java/com/android/server/usb/UsbHostManager.java @@ -102,6 +102,7 @@ public class UsbHostManager { private final HashMap> mMidiDevices = new HashMap>(); private final HashSet mMidiUniqueCodes = new HashSet(); + private static final int MAX_UNIQUE_CODE_GENERATION_ATTEMPTS = 10; private final Random mRandom = new Random(); private final boolean mHasMidiFeature; @@ -645,11 +646,18 @@ public class UsbHostManager { // Generate a 3 digit code. private String generateNewUsbDeviceIdentifier() { String code; + int numberOfAttempts = 0; do { + if (numberOfAttempts > MAX_UNIQUE_CODE_GENERATION_ATTEMPTS) { + Slog.w(TAG, "MIDI unique code array resetting"); + mMidiUniqueCodes.clear(); + numberOfAttempts = 0; + } code = ""; for (int i = 0; i < 3; i++) { code += mRandom.nextInt(10); } + numberOfAttempts++; } while (mMidiUniqueCodes.contains(code)); mMidiUniqueCodes.add(code); return code;