Merge "Revert "GAP: Connection state change check for multiple devices"" into q-keystone-qcom-dev
diff --git a/src/com/android/bluetooth/a2dp/A2dpService.java b/src/com/android/bluetooth/a2dp/A2dpService.java
index 6751a14..63d4181 100644
--- a/src/com/android/bluetooth/a2dp/A2dpService.java
+++ b/src/com/android/bluetooth/a2dp/A2dpService.java
@@ -56,6 +56,7 @@
 import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 /**
  * Provides Bluetooth A2DP profile, as a service in the Bluetooth application.
@@ -76,6 +77,7 @@
     private final Object mBtAvrcpLock = new Object();
     private final Object mActiveDeviceLock = new Object();
     private final Object mVariableLock = new Object();
+    private final ReentrantReadWriteLock mA2dpNativeInterfaceLock = new ReentrantReadWriteLock();
 
     @VisibleForTesting
     A2dpNativeInterface mA2dpNativeInterface;
@@ -174,8 +176,16 @@
         synchronized (mVariableLock) {
             mAdapterService = Objects.requireNonNull(AdapterService.getAdapterService(),
                 "AdapterService cannot be null when A2dpService starts");
+        }
+        try {
+            mA2dpNativeInterfaceLock.writeLock().lock();
             mA2dpNativeInterface = Objects.requireNonNull(A2dpNativeInterface.getInstance(),
                 "A2dpNativeInterface cannot be null when A2dpService starts");
+        } finally {
+            mA2dpNativeInterfaceLock.writeLock().unlock();
+        }
+        BluetoothCodecConfig[] OffloadCodecConfig;
+        synchronized (mVariableLock) {
             mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
             Objects.requireNonNull(mAudioManager,
                                "AudioManager cannot be null when A2dpService starts");
@@ -228,10 +238,20 @@
             // Step 6: Initialize native interface
             List<BluetoothCodecConfig> mCodecConfigOffload;
             mCodecConfigOffload = mAudioManager.getHwOffloadEncodingFormatsSupportedForA2DP();
-            BluetoothCodecConfig[] OffloadCodecConfig  = new BluetoothCodecConfig[mCodecConfigOffload.size()];
+            OffloadCodecConfig  = new BluetoothCodecConfig[mCodecConfigOffload.size()];
             OffloadCodecConfig  = mCodecConfigOffload.toArray(OffloadCodecConfig);
-             mA2dpNativeInterface.init(mMaxConnectedAudioDevices,
-                           mA2dpCodecConfig.codecConfigPriorities(),OffloadCodecConfig);
+        }
+
+        try {
+            mA2dpNativeInterfaceLock.writeLock().lock();
+            if (mA2dpNativeInterface != null)
+                mA2dpNativeInterface.init(mMaxConnectedAudioDevices,
+                        mA2dpCodecConfig.codecConfigPriorities(),OffloadCodecConfig);
+        } finally {
+            mA2dpNativeInterfaceLock.writeLock().unlock();
+        }
+
+        synchronized (mVariableLock) {
 
             // Step 7: Check if A2DP is in offload mode
             mA2dpOffloadEnabled = mAdapterService.isA2dpOffloadEnabled();
@@ -277,10 +297,14 @@
         unregisterReceiver(mBondStateChangedReceiver);
         mBondStateChangedReceiver = null;
         // Step 6: Cleanup native interface
-        synchronized (mVariableLock) {
+        try {
+            mA2dpNativeInterfaceLock.writeLock().lock();
             if (mA2dpNativeInterface != null)
                 mA2dpNativeInterface.cleanup();
+        } finally {
+            mA2dpNativeInterfaceLock.writeLock().unlock();
         }
+
         // Step 5: Clear codec config
         mA2dpCodecConfig = null;
 
@@ -323,10 +347,16 @@
             mSetMaxConnectedAudioDevices = 1;
             // Step 1: Clear AdapterService, A2dpNativeInterface, AudioManager
             mAudioManager = null;
-            mA2dpNativeInterface = null;
             mAdapterService = null;
         }
 
+        try {
+            mA2dpNativeInterfaceLock.writeLock().lock();
+            mA2dpNativeInterface = null;
+        } finally {
+            mA2dpNativeInterfaceLock.writeLock().unlock();
+        }
+
         return true;
     }
 
@@ -720,11 +750,14 @@
            }
         }
         // Make sure the Active device in native layer is set to null and audio is off
-        synchronized (mVariableLock ) {
+        try {
+            mA2dpNativeInterfaceLock.readLock().lock();
             if (mA2dpNativeInterface != null && !mA2dpNativeInterface.setActiveDevice(null)) {
                  Log.w(TAG, "setActiveDevice(null): Cannot remove active device in native "
                         + "layer");
             }
+        } finally {
+            mA2dpNativeInterfaceLock.readLock().unlock();
         }
     }
 
@@ -746,13 +779,18 @@
             // Set the device as the active device if currently no active device.
             setActiveDevice(device);
         }
-        synchronized (mVariableLock) {
+
+        try {
+            mA2dpNativeInterfaceLock.readLock().lock();
             if (mA2dpNativeInterface != null &&
                !mA2dpNativeInterface.setSilenceDevice(device, silence)) {
                 Log.e(TAG, "Cannot set " + device + " silence mode " + silence + " in native layer");
                 return false;
             }
+        } finally {
+            mA2dpNativeInterfaceLock.readLock().unlock();
         }
+
         return true;
     }
 
@@ -802,19 +840,21 @@
         boolean tws_switch = false;
         Log.w(TAG, "setActiveDevice(" + device + "): previous is " + previousActiveDevice);
 
+        if (device == null) {
+            // Remove active device and continue playing audio only if necessary.
+            removeActiveDevice(false);
+            synchronized(mBtAvrcpLock) {
+                if(mAvrcp_ext != null)
+                    mAvrcp_ext.setActiveDevice(device);
+            }
+            return true;
+        }
+
         synchronized (mBtA2dpLock) {
             BATService mBatService = BATService.getBATService();
             isBAActive = (mBatService != null) && (mBatService.isBATActive());
             Log.d(TAG," setActiveDevice: BA active " + isBAActive);
 
-            if (device == null) {
-                // Remove active device and continue playing audio only if necessary.
-                removeActiveDevice(false);
-                if(mAvrcp_ext != null)
-                    mAvrcp_ext.setActiveDevice(device);
-                return true;
-            }
-
             A2dpStateMachine sm = mStateMachines.get(device);
             deviceChanged = !Objects.equals(device, mActiveDevice);
             if (!deviceChanged) {
@@ -856,13 +896,18 @@
             Log.w(TAG, "setActiveDevice coming out of mutex lock");
         }
 
-        synchronized (mVariableLock) {
+        try {
+            mA2dpNativeInterfaceLock.readLock().lock();
             if (mA2dpNativeInterface != null && !mA2dpNativeInterface.setActiveDevice(device)) {
                 Log.e(TAG, "setActiveDevice(" + device + "): Cannot set as active in native layer");
                 return false;
             }
+
+        } finally {
+            mA2dpNativeInterfaceLock.readLock().unlock();
         }
 
+
         updateAndBroadcastActiveDevice(device);
         Log.d(TAG, "setActiveDevice(" + device + "): completed");
 
@@ -1299,7 +1344,8 @@
                 if (stackEvent.type == A2dpStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED) {
                     switch (stackEvent.valueInt) {
                         case A2dpStackEvent.CONNECTION_STATE_CONNECTED:
-                        case A2dpStackEvent.CONNECTION_STATE_CONNECTING:
+                        case A2dpStackEvent.CONNECTION_STATE_CONNECTING: {
+                            boolean connectionAllowed;
                             synchronized (mVariableLock) {
                                 // Create a new state machine only when connecting to a device
                                 if (mAdapterService != null && mAdapterService.isVendorIntfEnabled())
@@ -1308,15 +1354,24 @@
                                     sm = getOrCreateStateMachine(device);
                                     break;
                                 }
-                                if (!connectionAllowedCheckMaxDevices(device) && mA2dpNativeInterface != null) {
-                                    Log.e(TAG, "Cannot connect to " + device
-                                            + " : too many connected devices");
-                                    mA2dpNativeInterface.disconnectA2dp(device);
-                                    return;
+                                connectionAllowed = connectionAllowedCheckMaxDevices(device);
+                            }
+                            if (!connectionAllowed) {
+                                Log.e(TAG, "Cannot connect to " + device
+                                        + " : too many connected devices");
+                                try {
+                                    mA2dpNativeInterfaceLock.readLock().lock();
+                                    if (mA2dpNativeInterface != null) {
+                                        mA2dpNativeInterface.disconnectA2dp(device);
+                                        return;
+                                    }
+                                } finally {
+                                    mA2dpNativeInterfaceLock.readLock().unlock();
                                 }
                             }
                             sm = getOrCreateStateMachine(device);
                             break;
+                        }
                         default:
                             synchronized (mVariableLock) {
                                 if (mAdapterService!= null && mAdapterService.isVendorIntfEnabled() &&
@@ -1591,6 +1646,9 @@
             if (mFactory.getAvrcpTargetService() != null) {
                 mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device);
             }
+            if (mAvrcp_ext != null) {
+                mAvrcp_ext.removeVolumeForDevice(device);
+            }
 
             removeStateMachine(device);
         }
@@ -1687,7 +1745,9 @@
                     if (mFactory.getAvrcpTargetService() != null) {
                         mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device);
                     }
-
+                    if (mAvrcp_ext != null) {
+                        mAvrcp_ext.removeVolumeForDevice(device);
+                    }
                     removeStateMachine(device);
                 }
             }
diff --git a/src/com/android/bluetooth/btservice/AdapterService.java b/src/com/android/bluetooth/btservice/AdapterService.java
index 277eb8c..5bec2d0 100644
--- a/src/com/android/bluetooth/btservice/AdapterService.java
+++ b/src/com/android/bluetooth/btservice/AdapterService.java
@@ -2620,6 +2620,12 @@
             return false;
         }
 
+        if (pinCode.length != len) {
+            android.util.EventLog.writeEvent(0x534e4554, "139287605", -1,
+                    "PIN code length mismatch");
+            return false;
+        }
+
         StatsLog.write(StatsLog.BLUETOOTH_BOND_STATE_CHANGED,
                 obfuscateAddress(device), 0, device.getType(),
                 BluetoothDevice.BOND_BONDING,
@@ -2636,6 +2642,12 @@
             return false;
         }
 
+        if (passkey.length != len) {
+            android.util.EventLog.writeEvent(0x534e4554, "139287605", -1,
+                    "Passkey length mismatch");
+            return false;
+        }
+
         StatsLog.write(StatsLog.BLUETOOTH_BOND_STATE_CHANGED,
                 obfuscateAddress(device), 0, device.getType(),
                 BluetoothDevice.BOND_BONDING,
diff --git a/src/com/android/bluetooth/btservice/PhonePolicy.java b/src/com/android/bluetooth/btservice/PhonePolicy.java
index f3097fe..529decf 100644
--- a/src/com/android/bluetooth/btservice/PhonePolicy.java
+++ b/src/com/android/bluetooth/btservice/PhonePolicy.java
@@ -326,6 +326,9 @@
                 + prevState + " -> " + nextState);
         if ((profileId == BluetoothProfile.A2DP) || (profileId == BluetoothProfile.HEADSET)
                 || profileId == BluetoothProfile.A2DP_SINK) {
+            BluetoothDevice peerTwsDevice =
+                    (mAdapterService != null && mAdapterService.isTwsPlusDevice(device)) ?
+                    mAdapterService.getTwsPlusPeerDevice(device):null;
             if (nextState == BluetoothProfile.STATE_CONNECTED) {
                 debugLog("processProfileStateChanged: isTwsDevice: " + mAdapterService.isTwsPlusDevice(device));
                 switch (profileId) {
@@ -333,12 +336,16 @@
                         mA2dpRetrySet.remove(device);
                         if (mAdapterService.isTwsPlusDevice(device)) {
                              setAutoConnectForA2dpSink(device);
+                             if (peerTwsDevice != null)
+                                 setAutoConnectForA2dpSink(peerTwsDevice);
                         }
                         break;
                     case BluetoothProfile.HEADSET:
                         mHeadsetRetrySet.remove(device);
                         if (mAdapterService.isTwsPlusDevice(device)) {
                              setAutoConnectForHeadset(device);
+                             if (peerTwsDevice != null)
+                                 setAutoConnectForHeadset(peerTwsDevice);
                         }
                         break;
                     case BluetoothProfile.A2DP_SINK:
@@ -348,24 +355,45 @@
                 connectOtherProfile(device);
             }
             if (nextState == BluetoothProfile.STATE_DISCONNECTED) {
+                HeadsetService hsService = mFactory.getHeadsetService();
+                A2dpService a2dpService = mFactory.getA2dpService();
                 handleAllProfilesDisconnected(device);
                 if (prevState == BluetoothProfile.STATE_CONNECTING) {
-                    HeadsetService hsService = mFactory.getHeadsetService();
                     boolean hsDisconnected = hsService == null
                             || hsService.getConnectionState(device)
                             == BluetoothProfile.STATE_DISCONNECTED;
-                    A2dpService a2dpService = mFactory.getA2dpService();
                     boolean a2dpDisconnected = a2dpService == null
                             || a2dpService.getConnectionState(device)
                             == BluetoothProfile.STATE_DISCONNECTED;
+                    boolean isAnyTwsPairConnected = (peerTwsDevice != null) && ((a2dpService != null) &&
+                            (a2dpService.getConnectionState(peerTwsDevice) == BluetoothProfile.STATE_CONNECTED))
+                            || ((hsService != null) &&
+                            (hsService.getConnectionState(peerTwsDevice) == BluetoothProfile.STATE_CONNECTED));
                     debugLog("processProfileStateChanged, device=" + device + ", a2dpDisconnected="
-                            + a2dpDisconnected + ", hsDisconnected=" + hsDisconnected);
+                            + a2dpDisconnected + ", hsDisconnected=" + hsDisconnected
+                            + ", TwsPairConnected=" + isAnyTwsPairConnected);
                     if (hsDisconnected && a2dpDisconnected) {
                         //remove a2dp and headset retry set.
                         mA2dpRetrySet.remove(device);
                         mHeadsetRetrySet.remove(device);
-                        removeAutoConnectFromA2dpSink(device);
-                        removeAutoConnectFromHeadset(device);
+                        if (!isAnyTwsPairConnected) {
+                            removeAutoConnectFromA2dpSink(device);
+                            removeAutoConnectFromHeadset(device);
+                        }
+                    }
+                } else if (prevState == BluetoothProfile.STATE_DISCONNECTING) {
+                    if (peerTwsDevice != null) {
+                        int autoConnect = BluetoothProfile.PRIORITY_AUTO_CONNECT;
+                        if (((a2dpService.getPriority(peerTwsDevice) == autoConnect) &&
+                                (hsService.getPriority(peerTwsDevice) == autoConnect)) ||
+                                ((a2dpService.getPriority(device) == autoConnect) &&
+                                (hsService.getPriority(device) == autoConnect))) {
+                            debugLog("User triggered disconnect reset priority ON to both EBs");
+                            removeAutoConnectFromA2dpSink(device);
+                            removeAutoConnectFromHeadset(device);
+                            removeAutoConnectFromA2dpSink(peerTwsDevice);
+                            removeAutoConnectFromHeadset(peerTwsDevice);
+                        }
                     }
                 }
             }
@@ -394,21 +422,13 @@
 
                 setAutoConnectForA2dpSink(activeDevice);
                 setAutoConnectForHeadset(activeDevice);
-                if (mAdapterService.isTwsPlusDevice(activeDevice)) {
-                    BluetoothDevice peerTwsDevice = hsService.getTwsPlusConnectedPeer(activeDevice);
+                if (mAdapterService != null && mAdapterService.isTwsPlusDevice(activeDevice)) {
+                    BluetoothDevice peerTwsDevice = mAdapterService.getTwsPlusPeerDevice(activeDevice);
                     if (peerTwsDevice != null) {
-                        if (a2dpService != null &&
-                            a2dpService.getConnectionState(peerTwsDevice) !=
-                            BluetoothProfile.STATE_DISCONNECTED) {
-                            debugLog("A2DP: Set Autoconnect for Peer TWS+ as well");
-                            setAutoConnectForA2dpSink(peerTwsDevice);
-                        }
-                        if (hsService != null &&
-                            hsService.getConnectionState(peerTwsDevice) !=
-                            BluetoothProfile.STATE_DISCONNECTED) {
-                            debugLog("HFP: Set Autoconnect for Peer TWS+ as well");
-                            setAutoConnectForHeadset(peerTwsDevice);
-                        }
+                        debugLog("A2DP: Set Autoconnect for Peer TWS+ as well");
+                        setAutoConnectForA2dpSink(peerTwsDevice);
+                        debugLog("HFP: Set Autoconnect for Peer TWS+ as well");
+                        setAutoConnectForHeadset(peerTwsDevice);
                     }
                 }
                 break;
diff --git a/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java b/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
index 349951c..ada8ab4 100644
--- a/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
+++ b/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
@@ -32,6 +32,7 @@
 
 package com.android.bluetooth.opp;
 
+import android.bluetooth.BluetoothAdapter;
 import android.content.ContentValues;
 import android.content.Context;
 import android.net.Uri;
@@ -80,12 +81,15 @@
 
     private int mNumFilesAttemptedToSend;
 
+    private BluetoothAdapter mAdapter;
+
     public BluetoothOppObexClientSession(Context context, ObexTransport transport) {
         if (transport == null) {
             throw new NullPointerException("transport is null");
         }
         mContext = context;
         mTransport = transport;
+        mAdapter = BluetoothAdapter.getDefaultAdapter();
     }
 
     @Override
@@ -99,7 +103,7 @@
     }
 
     @Override
-    public void stop() {
+    public synchronized void stop() {
         if (D) {
             Log.d(TAG, "Stop!");
         }
@@ -110,7 +114,23 @@
                 if (V) {
                     Log.v(TAG, "waiting for thread to terminate");
                 }
-                mThread.join();
+                if (mAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
+                    Log.d(TAG, "stop, bt is turning off");
+                    mThread.join(1500);
+                    if (mThread.isAlive()) {
+                        Log.d(TAG, "stop, close the transport");
+                        mThread.interrupt();
+                        try {
+                            mTransport.close();
+                        } catch (IOException e) {
+                            Log.e(TAG, "mTransport.close error");
+                        }
+                        Log.d(TAG, "stop, close the transport, done");
+                        mThread.join();
+                    }
+                } else {
+                    mThread.join();
+                }
                 mThread = null;
             } catch (InterruptedException e) {
                 if (V) {