Handle a condition when the result of getting configured networks returns null am: 3abc7f0561 am: 3b17189719 am: 1e779938f2 am: fb9027f897
am: fb77c3dc21

Change-Id: Iac98eee54bc8f30646d6043986359f094033a1dc
diff --git a/libwifi_system/Android.bp b/libwifi_system/Android.bp
index 877d05f..f5ea184 100644
--- a/libwifi_system/Android.bp
+++ b/libwifi_system/Android.bp
@@ -29,7 +29,7 @@
 
 // Device independent wifi system logic.
 // ============================================================
-cc_library_shared {
+cc_library {
     name: "libwifi-system",
     defaults: ["libwifi-system-defaults"],
     export_include_dirs: ["include"],
diff --git a/libwifi_system/tests/hostapd_manager_unittest.cpp b/libwifi_system/tests/hostapd_manager_unittest.cpp
index 048d473..b25dd8e 100644
--- a/libwifi_system/tests/hostapd_manager_unittest.cpp
+++ b/libwifi_system/tests/hostapd_manager_unittest.cpp
@@ -24,6 +24,8 @@
 
 using std::string;
 using std::vector;
+using testing::HasSubstr;
+using testing::Not;
 
 namespace android {
 namespace wifi_system {
@@ -34,46 +36,10 @@
 const char kTestPassphraseStr[] = "yourelookingfor";
 const int kTestChannel = 2;
 
-#define CONFIG_COMMON_PREFIX \
-    "interface=foobar0\n" \
-    "driver=nl80211\n" \
-    "ctrl_interface=/data/misc/wifi/hostapd/ctrl\n" \
-    "ssid2=68656c6c6f" "6973" "6974" "6d65\n" \
-    "channel=2\n" \
-    "ieee80211n=1\n" \
-    "hw_mode=g\n"
-
 // If you generate your config file with both the test ssid
 // and the test passphrase, you'll get this line in the config.
-#define CONFIG_PSK_LINE \
-    "wpa_psk=dffa36815281e5a6eca1910f254717fa2528681335e3bbec5966d2aa9221a66e\n"
-
-#define CONFIG_WPA_SUFFIX \
-    "wpa=3\n" \
-    "wpa_pairwise=TKIP CCMP\n" \
-    CONFIG_PSK_LINE
-
-#define CONFIG_WPA2_SUFFIX \
-    "wpa=2\n" \
-    "rsn_pairwise=CCMP\n" \
-    CONFIG_PSK_LINE
-
-const char kExpectedOpenConfig[] =
-  CONFIG_COMMON_PREFIX
-  "ignore_broadcast_ssid=0\n"
-  "wowlan_triggers=any\n";
-
-const char kExpectedWpaConfig[] =
-    CONFIG_COMMON_PREFIX
-    "ignore_broadcast_ssid=0\n"
-    "wowlan_triggers=any\n"
-    CONFIG_WPA_SUFFIX;
-
-const char kExpectedWpa2Config[] =
-    CONFIG_COMMON_PREFIX
-    "ignore_broadcast_ssid=0\n"
-    "wowlan_triggers=any\n"
-    CONFIG_WPA2_SUFFIX;
+const char kConfigPskLine[] =
+    "wpa_psk=dffa36815281e5a6eca1910f254717fa2528681335e3bbec5966d2aa9221a66e\n";
 
 class HostapdManagerTest : public ::testing::Test {
  protected:
@@ -93,27 +59,44 @@
   }
 };  // class HostapdManagerTest
 
+// This is used to verify config string generated by test helper function
+// |GetConfigForEncryptionType|.
+void VerifyCommonConfigs(const string& config) {
+  EXPECT_THAT(config, HasSubstr("interface=foobar0\n"));
+  EXPECT_THAT(config, HasSubstr("driver=nl80211\n"));
+  EXPECT_THAT(config, HasSubstr("ctrl_interface=/data/misc/wifi/hostapd/ctrl\n"));
+  EXPECT_THAT(config, HasSubstr("ssid2=68656c6c6f" "6973" "6974" "6d65\n"));
+  EXPECT_THAT(config, HasSubstr("channel=2\n"));
+  EXPECT_THAT(config, HasSubstr("hw_mode=g\n"));
+  EXPECT_THAT(config, HasSubstr("wowlan_triggers=any\n"));
+  EXPECT_THAT(config, HasSubstr("ignore_broadcast_ssid=0\n"));
+  EXPECT_THAT(config, Not(HasSubstr("ignore_broadcast_ssid=1\n")));
+}
+
 }  // namespace
 
 TEST_F(HostapdManagerTest, GeneratesCorrectOpenConfig) {
   string config = GetConfigForEncryptionType(
       HostapdManager::EncryptionType::kOpen);
-  EXPECT_FALSE(config.empty());
-  EXPECT_EQ(kExpectedOpenConfig, config);
+  VerifyCommonConfigs(config);
 }
 
 TEST_F(HostapdManagerTest, GeneratesCorrectWpaConfig) {
   string config = GetConfigForEncryptionType(
       HostapdManager::EncryptionType::kWpa);
-  EXPECT_FALSE(config.empty());
-  EXPECT_EQ(kExpectedWpaConfig, config);
+  VerifyCommonConfigs(config);
+  EXPECT_THAT(config, HasSubstr("wpa=3\n"));
+  EXPECT_THAT(config, HasSubstr("wpa_pairwise=TKIP CCMP\n"));
+  EXPECT_THAT(config, HasSubstr(kConfigPskLine));
 }
 
 TEST_F(HostapdManagerTest, GeneratesCorrectWpa2Config) {
   string config = GetConfigForEncryptionType(
       HostapdManager::EncryptionType::kWpa2);
-  EXPECT_FALSE(config.empty());
-  EXPECT_EQ(kExpectedWpa2Config, config);
+  VerifyCommonConfigs(config);
+  EXPECT_THAT(config, HasSubstr("wpa=2\n"));
+  EXPECT_THAT(config, HasSubstr("rsn_pairwise=CCMP\n"));
+  EXPECT_THAT(config, HasSubstr(kConfigPskLine));
 }
 
 TEST_F(HostapdManagerTest, RespectsHiddenSetting) {
@@ -124,8 +107,8 @@
         kTestChannel,
         HostapdManager::EncryptionType::kOpen,
         vector<uint8_t>());
-  EXPECT_FALSE(config.find("ignore_broadcast_ssid=1\n") == string::npos);
-  EXPECT_TRUE(config.find("ignore_broadcast_ssid=0\n") == string::npos);
+  EXPECT_THAT(config, HasSubstr("ignore_broadcast_ssid=1\n"));
+  EXPECT_THAT(config, Not(HasSubstr("ignore_broadcast_ssid=0\n")));
 }
 
 TEST_F(HostapdManagerTest, CorrectlyInfersHwMode) {
@@ -136,8 +119,8 @@
         44,
         HostapdManager::EncryptionType::kOpen,
         vector<uint8_t>());
-  EXPECT_FALSE(config.find("hw_mode=a\n") == string::npos);
-  EXPECT_TRUE(config.find("hw_mode=g\n") == string::npos);
+  EXPECT_THAT(config, HasSubstr("hw_mode=a\n"));
+  EXPECT_THAT(config, Not(HasSubstr("hw_mode=g\n")));
 }
 
 
diff --git a/libwifi_system_iface/Android.bp b/libwifi_system_iface/Android.bp
index 4be0aa0..80249ef 100644
--- a/libwifi_system_iface/Android.bp
+++ b/libwifi_system_iface/Android.bp
@@ -26,9 +26,12 @@
 
 // Device independent wifi system logic.
 // ============================================================
-cc_library_shared {
+cc_library {
     name: "libwifi-system-iface",
     vendor_available: true,
+    vndk: {
+        enabled: true,
+    },
     cflags: wifi_system_iface_cflags,
     local_include_dirs: ["include"],
     export_include_dirs: ["include"],
diff --git a/service/Android.mk b/service/Android.mk
index 155f5b2..5b539e5 100644
--- a/service/Android.mk
+++ b/service/Android.mk
@@ -70,6 +70,11 @@
 LOCAL_MODULE := wifi-service
 LOCAL_INIT_RC := wifi-events.rc
 
+LOCAL_DEX_PREOPT_APP_IMAGE := false
+LOCAL_DEX_PREOPT_GENERATE_PROFILE := true
+LOCAL_DEX_PREOPT_PROFILE_CLASS_LISTING := frameworks/base/services/art-profile
+
+
 include $(BUILD_JAVA_LIBRARY)
 
 endif  # !TARGET_BUILD_PDK
diff --git a/service/java/com/android/server/wifi/CarrierNetworkConfig.java b/service/java/com/android/server/wifi/CarrierNetworkConfig.java
new file mode 100644
index 0000000..c23213e
--- /dev/null
+++ b/service/java/com/android/server/wifi/CarrierNetworkConfig.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.wifi.EAPConstants;
+import android.net.wifi.WifiEnterpriseConfig;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.util.Base64;
+import android.util.Log;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Class for maintaining/caching carrier Wi-Fi network configurations.
+ */
+public class CarrierNetworkConfig {
+    private static final String TAG = "CarrierNetworkConfig";
+
+    private static final String NETWORK_CONFIG_SEPARATOR = ",";
+    private static final int ENCODED_SSID_INDEX = 0;
+    private static final int EAP_TYPE_INDEX = 1;
+    private static final int CONFIG_ELEMENT_SIZE = 2;
+
+    private final Map<String, NetworkInfo> mCarrierNetworkMap;
+
+    public CarrierNetworkConfig(Context context) {
+        mCarrierNetworkMap = new HashMap<>();
+        updateNetworkConfig(context);
+
+        // Monitor for carrier config changes.
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
+        context.registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                updateNetworkConfig(context);
+            }
+        }, filter);
+    }
+
+    /**
+     * @return true if the given SSID is associated with a carrier network
+     */
+    public boolean isCarrierNetwork(String ssid) {
+        return mCarrierNetworkMap.containsKey(ssid);
+    }
+
+    /**
+     * @return the EAP type associated with a carrier AP, or -1 if the specified AP
+     * is not associated with a carrier network
+     */
+    public int getNetworkEapType(String ssid) {
+        NetworkInfo info = mCarrierNetworkMap.get(ssid);
+        return info == null ? -1 : info.mEapType;
+    }
+
+    /**
+     * @return the name of carrier associated with a carrier AP, or null if the specified AP
+     * is not associated with a carrier network.
+     */
+    public String getCarrierName(String ssid) {
+        NetworkInfo info = mCarrierNetworkMap.get(ssid);
+        return info == null ? null : info.mCarrierName;
+    }
+
+    /**
+     * Utility class for storing carrier network information.
+     */
+    private static class NetworkInfo {
+        final int mEapType;
+        final String mCarrierName;
+
+        NetworkInfo(int eapType, String carrierName) {
+            mEapType = eapType;
+            mCarrierName = carrierName;
+        }
+    }
+
+    /**
+     * Update the carrier network map based on the current carrier configuration of the active
+     * subscriptions.
+     *
+     * @param context Current application context
+     */
+    private void updateNetworkConfig(Context context) {
+        // Reset network map.
+        mCarrierNetworkMap.clear();
+
+        CarrierConfigManager carrierConfigManager =
+                (CarrierConfigManager) context.getSystemService(Context.CARRIER_CONFIG_SERVICE);
+        if (carrierConfigManager == null) {
+            return;
+        }
+
+        SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(
+                Context.TELEPHONY_SUBSCRIPTION_SERVICE);
+        if (subscriptionManager == null) {
+            return;
+        }
+        List<SubscriptionInfo> subInfoList = subscriptionManager.getActiveSubscriptionInfoList();
+        if (subInfoList == null) {
+            return;
+        }
+
+        // Process the carrier config for each active subscription.
+        for (SubscriptionInfo subInfo : subInfoList) {
+            processNetworkConfig(
+                    carrierConfigManager.getConfigForSubId(subInfo.getSubscriptionId()),
+                    subInfo.getDisplayName().toString());
+        }
+    }
+
+    /**
+     * Process the carrier network config, the network config string is formatted as follow:
+     *
+     * "[Base64 Encoded SSID],[EAP Type]"
+     * Where EAP Type is the standard EAP method number, refer to
+     * http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml for more info.
+
+     * @param carrierConfig The bundle containing the carrier configuration
+     * @param carrierName The display name of the associated carrier
+     */
+    private void processNetworkConfig(PersistableBundle carrierConfig, String carrierName) {
+        if (carrierConfig == null) {
+            return;
+        }
+        String[] networkConfigs = carrierConfig.getStringArray(
+                CarrierConfigManager.KEY_CARRIER_WIFI_STRING_ARRAY);
+        if (networkConfigs == null) {
+            return;
+        }
+
+        for (String networkConfig : networkConfigs) {
+            String[] configArr = networkConfig.split(NETWORK_CONFIG_SEPARATOR);
+            if (configArr.length != CONFIG_ELEMENT_SIZE) {
+                Log.e(TAG, "Ignore invalid config: " + networkConfig);
+                continue;
+            }
+            try {
+                String ssid = new String(Base64.decode(
+                        configArr[ENCODED_SSID_INDEX], Base64.DEFAULT));
+                int eapType = parseEapType(Integer.parseInt(configArr[EAP_TYPE_INDEX]));
+                // Verify EAP type, must be a SIM based EAP type.
+                if (eapType == -1) {
+                    Log.e(TAG, "Invalid EAP type: " + configArr[EAP_TYPE_INDEX]);
+                    continue;
+                }
+                mCarrierNetworkMap.put(ssid, new NetworkInfo(eapType, carrierName));
+            } catch (NumberFormatException e) {
+                Log.e(TAG, "Failed to parse EAP type: " + e.getMessage());
+            } catch (IllegalArgumentException e) {
+                Log.e(TAG, "Failed to decode SSID: " + e.getMessage());
+            }
+        }
+    }
+
+    /**
+     * Convert a standard SIM-based EAP type (SIM, AKA, AKA') to the internal EAP type as defined in
+     * {@link WifiEnterpriseConfig.Eap}. -1 will be returned if the given EAP type is not
+     * SIM-based.
+     *
+     * @return SIM-based EAP type as defined in {@link WifiEnterpriseConfig.Eap}, or -1 if not
+     * SIM-based EAP type
+     */
+    private static int parseEapType(int eapType) {
+        if (eapType == EAPConstants.EAP_SIM) {
+            return WifiEnterpriseConfig.Eap.SIM;
+        } else if (eapType == EAPConstants.EAP_AKA) {
+            return WifiEnterpriseConfig.Eap.AKA;
+        } else if (eapType == EAPConstants.EAP_AKA_PRIME) {
+            return WifiEnterpriseConfig.Eap.AKA_PRIME;
+        }
+        return -1;
+    }
+}
diff --git a/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java b/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java
new file mode 100644
index 0000000..5963b57
--- /dev/null
+++ b/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static com.android.server.wifi.OpenNetworkNotifier.ACTION_USER_DISMISSED_NOTIFICATION;
+import static com.android.server.wifi.OpenNetworkNotifier.ACTION_USER_TAPPED_CONTENT;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+
+import com.android.internal.R;
+import com.android.internal.notification.SystemNotificationChannels;
+
+/**
+ * Helper to create notifications for {@link OpenNetworkNotifier}.
+ */
+public class OpenNetworkNotificationBuilder {
+
+    private Context mContext;
+    private Resources mResources;
+    private FrameworkFacade mFrameworkFacade;
+
+    public OpenNetworkNotificationBuilder(
+            Context context,
+            FrameworkFacade framework) {
+        mContext = context;
+        mResources = context.getResources();
+        mFrameworkFacade = framework;
+    }
+
+    /**
+     * Creates the open network available notification that alerts users there are open networks
+     * nearby.
+     */
+    public Notification createOpenNetworkAvailableNotification(int numNetworks) {
+
+        CharSequence title = mResources.getQuantityText(
+                com.android.internal.R.plurals.wifi_available, numNetworks);
+        CharSequence content = mResources.getQuantityText(
+                com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
+
+        PendingIntent contentIntent =
+                mFrameworkFacade.getBroadcast(
+                        mContext,
+                        0,
+                        new Intent(ACTION_USER_TAPPED_CONTENT),
+                        PendingIntent.FLAG_UPDATE_CURRENT);
+        return createNotificationBuilder(title, content)
+                .setContentIntent(contentIntent)
+                .build();
+    }
+
+    private Notification.Builder createNotificationBuilder(
+            CharSequence title, CharSequence content) {
+        PendingIntent deleteIntent =
+                mFrameworkFacade.getBroadcast(
+                        mContext,
+                        0,
+                        new Intent(ACTION_USER_DISMISSED_NOTIFICATION),
+                        PendingIntent.FLAG_UPDATE_CURRENT);
+        return mFrameworkFacade.makeNotificationBuilder(mContext,
+                SystemNotificationChannels.NETWORK_AVAILABLE)
+                .setSmallIcon(R.drawable.stat_notify_wifi_in_range)
+                .setAutoCancel(true)
+                .setTicker(title)
+                .setContentTitle(title)
+                .setContentText(content)
+                .setDeleteIntent(deleteIntent)
+                .setShowWhen(false)
+                .setLocalOnly(true)
+                .setColor(mResources.getColor(R.color.system_notification_accent_color,
+                        mContext.getTheme()));
+    }
+}
diff --git a/service/java/com/android/server/wifi/OpenNetworkNotifier.java b/service/java/com/android/server/wifi/OpenNetworkNotifier.java
new file mode 100644
index 0000000..fc144c1
--- /dev/null
+++ b/service/java/com/android/server/wifi/OpenNetworkNotifier.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import android.annotation.NonNull;
+import android.app.NotificationManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.ContentObserver;
+import android.net.wifi.ScanResult;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.provider.Settings;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.List;
+
+/**
+ * Takes care of handling the "open wi-fi network available" notification
+ * @hide
+ */
+public class OpenNetworkNotifier {
+
+    static final String ACTION_USER_DISMISSED_NOTIFICATION =
+            "com.android.server.wifi.OpenNetworkNotifier.USER_DISMISSED_NOTIFICATION";
+    static final String ACTION_USER_TAPPED_CONTENT =
+            "com.android.server.wifi.OpenNetworkNotifier.USER_TAPPED_CONTENT";
+
+    /**
+     * The {@link Clock#getWallClockMillis()} must be at least this value for us
+     * to show the notification again.
+     */
+    private long mNotificationRepeatTime;
+    /**
+     * When a notification is shown, we wait this amount before possibly showing it again.
+     */
+    private final long mNotificationRepeatDelay;
+    /** Default repeat delay in seconds. */
+    @VisibleForTesting
+    static final int DEFAULT_REPEAT_DELAY_SEC = 900;
+
+    /** Whether the user has set the setting to show the 'available networks' notification. */
+    private boolean mSettingEnabled;
+    /** Whether the notification is being shown. */
+    private boolean mNotificationShown;
+    /** Whether the screen is on or not. */
+    private boolean mScreenOn;
+
+    private final Context mContext;
+    private final Handler mHandler;
+    private final FrameworkFacade mFrameworkFacade;
+    private final Clock mClock;
+    private final OpenNetworkRecommender mOpenNetworkRecommender;
+    private final OpenNetworkNotificationBuilder mOpenNetworkNotificationBuilder;
+
+    private ScanResult mRecommendedNetwork;
+
+    OpenNetworkNotifier(
+            Context context,
+            Looper looper,
+            FrameworkFacade framework,
+            Clock clock,
+            OpenNetworkRecommender openNetworkRecommender) {
+        mContext = context;
+        mHandler = new Handler(looper);
+        mFrameworkFacade = framework;
+        mClock = clock;
+        mOpenNetworkRecommender = openNetworkRecommender;
+        mOpenNetworkNotificationBuilder = new OpenNetworkNotificationBuilder(context, framework);
+        mScreenOn = false;
+
+        // Setting is in seconds
+        mNotificationRepeatDelay = mFrameworkFacade.getIntegerSetting(context,
+                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
+                DEFAULT_REPEAT_DELAY_SEC) * 1000L;
+        NotificationEnabledSettingObserver settingObserver = new NotificationEnabledSettingObserver(
+                mHandler);
+        settingObserver.register();
+
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(ACTION_USER_DISMISSED_NOTIFICATION);
+        filter.addAction(ACTION_USER_TAPPED_CONTENT);
+        mContext.registerReceiver(
+                mBroadcastReceiver, filter, null /* broadcastPermission */, mHandler);
+    }
+
+    private final BroadcastReceiver mBroadcastReceiver =
+            new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    if (ACTION_USER_TAPPED_CONTENT.equals(intent.getAction())) {
+                        handleUserClickedContentAction();
+                    } else if (ACTION_USER_DISMISSED_NOTIFICATION.equals(intent.getAction())) {
+                        handleUserDismissedAction();
+                    }
+                }
+            };
+
+    /**
+     * Clears the pending notification. This is called by {@link WifiConnectivityManager} on stop.
+     *
+     * @param resetRepeatDelay resets the time delay for repeated notification if true.
+     */
+    public void clearPendingNotification(boolean resetRepeatDelay) {
+        if (resetRepeatDelay) {
+            mNotificationRepeatTime = 0;
+        }
+
+        if (mNotificationShown) {
+            getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_AVAILABLE);
+            mRecommendedNetwork = null;
+            mNotificationShown = false;
+        }
+    }
+
+    private boolean isControllerEnabled() {
+        return mSettingEnabled && !UserManager.get(mContext)
+                .hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT);
+    }
+
+    /**
+     * If there are open networks, attempt to post an open network notification.
+     *
+     * @param availableNetworks Available networks from
+     * {@link WifiNetworkSelector.NetworkEvaluator#getFilteredScanDetailsForOpenUnsavedNetworks()}.
+     */
+    public void handleScanResults(@NonNull List<ScanDetail> availableNetworks) {
+        if (!isControllerEnabled()) {
+            clearPendingNotification(true /* resetRepeatDelay */);
+            return;
+        }
+        if (availableNetworks.isEmpty()) {
+            clearPendingNotification(false /* resetRepeatDelay */);
+            return;
+        }
+
+        // Do not show or update the notification if screen is off. We want to avoid a race that
+        // could occur between a user picking a network in settings and a network candidate picked
+        // through network selection, which will happen because screen on triggers a new
+        // connectivity scan.
+        if (mNotificationShown || !mScreenOn) {
+            return;
+        }
+
+        mRecommendedNetwork = mOpenNetworkRecommender.recommendNetwork(
+                availableNetworks, mRecommendedNetwork);
+
+        postNotification(availableNetworks.size());
+    }
+
+    /** Handles screen state changes. */
+    public void handleScreenStateChanged(boolean screenOn) {
+        mScreenOn = screenOn;
+    }
+
+    private NotificationManager getNotificationManager() {
+        return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+    }
+
+    private void postNotification(int numNetworks) {
+        // Not enough time has passed to show the notification again
+        if (mClock.getWallClockMillis() < mNotificationRepeatTime) {
+            return;
+        }
+
+        getNotificationManager().notify(
+                SystemMessage.NOTE_NETWORK_AVAILABLE,
+                mOpenNetworkNotificationBuilder.createOpenNetworkAvailableNotification(
+                        numNetworks));
+        mNotificationShown = true;
+        mNotificationRepeatTime = mClock.getWallClockMillis() + mNotificationRepeatDelay;
+    }
+
+    /** Opens Wi-Fi picker. */
+    private void handleUserClickedContentAction() {
+        mNotificationShown = false;
+        mContext.startActivity(
+                new Intent(Settings.ACTION_WIFI_SETTINGS)
+                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+    }
+
+    /** A delay is set before the next shown notification after user dismissal. */
+    private void handleUserDismissedAction() {
+        mNotificationShown = false;
+    }
+
+    /** Dump ONA controller state. */
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println("OpenNetworkNotifier: ");
+        pw.println("mSettingEnabled " + mSettingEnabled);
+        pw.println("currentTime: " + mClock.getWallClockMillis());
+        pw.println("mNotificationRepeatTime: " + mNotificationRepeatTime);
+        pw.println("mNotificationShown: " + mNotificationShown);
+    }
+
+    private class NotificationEnabledSettingObserver extends ContentObserver {
+        NotificationEnabledSettingObserver(Handler handler) {
+            super(handler);
+        }
+
+        public void register() {
+            mFrameworkFacade.registerContentObserver(mContext, Settings.Global.getUriFor(
+                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
+            mSettingEnabled = getValue();
+        }
+
+        @Override
+        public void onChange(boolean selfChange) {
+            super.onChange(selfChange);
+            mSettingEnabled = getValue();
+            clearPendingNotification(true /* resetRepeatDelay */);
+        }
+
+        private boolean getValue() {
+            return mFrameworkFacade.getIntegerSetting(mContext,
+                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
+        }
+    }
+}
diff --git a/service/java/com/android/server/wifi/OpenNetworkRecommender.java b/service/java/com/android/server/wifi/OpenNetworkRecommender.java
new file mode 100644
index 0000000..cd460e5
--- /dev/null
+++ b/service/java/com/android/server/wifi/OpenNetworkRecommender.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import android.annotation.NonNull;
+import android.net.wifi.ScanResult;
+
+import java.util.List;
+
+/**
+ * Helps recommend the best available network for {@link OpenNetworkNotifier}.
+ * @hide
+ */
+public class OpenNetworkRecommender {
+
+    /**
+     * Recommends the network with the best signal strength.
+     *
+     * @param networks List of scan details to pick a recommendation. This list should not be null
+     *                 or empty.
+     * @param currentRecommendation The currently recommended network.
+     */
+    public ScanResult recommendNetwork(
+            @NonNull List<ScanDetail> networks, ScanResult currentRecommendation) {
+        ScanResult currentUpdatedRecommendation = null;
+        ScanResult result = null;
+        int highestRssi = Integer.MIN_VALUE;
+        for (ScanDetail scanDetail : networks) {
+            ScanResult scanResult = scanDetail.getScanResult();
+
+            if (currentRecommendation != null
+                    && currentRecommendation.SSID.equals(scanResult.SSID)) {
+                currentUpdatedRecommendation = scanResult;
+            }
+
+            if (scanResult.level > highestRssi) {
+                result = scanResult;
+                highestRssi = scanResult.level;
+            }
+        }
+        if (currentUpdatedRecommendation != null
+                && currentUpdatedRecommendation.level >= result.level) {
+            return currentUpdatedRecommendation;
+        } else {
+            return result;
+        }
+    }
+}
diff --git a/service/java/com/android/server/wifi/RttService.java b/service/java/com/android/server/wifi/RttService.java
index 7e4648b..bd27367 100644
--- a/service/java/com/android/server/wifi/RttService.java
+++ b/service/java/com/android/server/wifi/RttService.java
@@ -6,11 +6,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
-import android.net.wifi.IApInterface;
-import android.net.wifi.IClientInterface;
-import android.net.wifi.IInterfaceEventCallback;
 import android.net.wifi.IRttManager;
-import android.net.wifi.IWificond;
 import android.net.wifi.RttManager;
 import android.net.wifi.RttManager.ResponderConfig;
 import android.net.wifi.WifiManager;
@@ -26,6 +22,7 @@
 import android.util.ArrayMap;
 import android.util.Log;
 import android.util.Slog;
+import android.util.SparseArray;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.AsyncChannel;
@@ -40,22 +37,64 @@
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
-import java.util.List;
 import java.util.Queue;
 import java.util.Set;
 
 public final class RttService extends SystemService {
 
     public static final boolean DBG = true;
-    private static final String WIFICOND_SERVICE_NAME = "wificond";
 
     static class RttServiceImpl extends IRttManager.Stub {
+        private int mCurrentKey = 100; // increment on each usage
+        private final SparseArray<IBinder> mBinderByKey = new SparseArray<>();
 
         @Override
-        public Messenger getMessenger() {
+        public Messenger getMessenger(IBinder binder, int[] key) {
+            if (key != null && key.length != 0) {
+                final int keyToUse = mCurrentKey++;
+                if (binder != null) {
+                    try {
+                        binder.linkToDeath(() -> {
+                            // clean-up here if didn't get final registration
+                            Slog.d(TAG, "Binder death on key=" + keyToUse);
+                            mBinderByKey.delete(keyToUse);
+                        }, 0);
+                        mBinderByKey.put(keyToUse, binder);
+                    } catch (RemoteException e) {
+                        Slog.e(TAG, "getMessenger: can't link to death on binder: " + e);
+                        return null;
+                    }
+                }
+
+                key[0] = keyToUse;
+            }
             return new Messenger(mClientHandler);
         }
 
+        private class RttDeathListener implements IBinder.DeathRecipient {
+            private final IBinder mBinder;
+            private final Messenger mReplyTo;
+
+            RttDeathListener(IBinder binder, Messenger replyTo) {
+                mBinder = binder;
+                mReplyTo = replyTo;
+            }
+
+            @Override
+            public void binderDied() {
+                if (DBG) Slog.d(TAG, "binder death for client mReplyTo=" + mReplyTo);
+                synchronized (mLock) {
+                    ClientInfo ci = mClients.remove(mReplyTo);
+                    if (ci != null) {
+                        ci.cleanup();
+                    } else {
+                        Slog.w(TAG,
+                                "ClientInfo not found for terminated app -- mReplyTo=" + mReplyTo);
+                    }
+                }
+            }
+        }
+
         private class ClientHandler extends Handler {
 
             ClientHandler(android.os.Looper looper) {
@@ -86,13 +125,30 @@
                     case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION:
                         AsyncChannel ac = new AsyncChannel();
                         ac.connected(mContext, this, msg.replyTo);
-                        ClientInfo client = new ClientInfo(ac, msg.sendingUid);
+                        String packageName = msg.obj != null
+                                ? ((RttManager.RttClient) msg.obj).getPackageName() : null;
+                        ClientInfo client = new ClientInfo(ac, msg.sendingUid, packageName);
                         synchronized (mLock) {
                             mClients.put(msg.replyTo, client);
                         }
                         ac.replyToMessage(msg, AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED,
                                 AsyncChannel.STATUS_SUCCESSFUL);
                         return;
+                    case RttManager.CMD_OP_REG_BINDER: {
+                        int key = msg.arg1;
+                        IBinder binder = mBinderByKey.get(key);
+                        if (binder == null) {
+                            Slog.e(TAG, "Can't find binder registered with key=" + key + " - no "
+                                    + "death listener!");
+                            return;
+                        }
+                        try {
+                            binder.linkToDeath(new RttDeathListener(binder, msg.replyTo), 0);
+                        } catch (RemoteException e) {
+                            Slog.e(TAG, "Can't link to death for binder on key=" + key);
+                        }
+                        return;
+                    }
                 }
 
                 ClientInfo ci;
@@ -109,6 +165,12 @@
                             "Client doesn't have LOCATION_HARDWARE permission");
                     return;
                 }
+                if (!checkLocationPermission(ci)) {
+                    replyFailed(msg, RttManager.REASON_PERMISSION_DENIED,
+                            "Client doesn't have ACCESS_COARSE_LOCATION or "
+                                    + "ACCESS_FINE_LOCATION permission");
+                    return;
+                }
                 final int validCommands[] = {
                         RttManager.CMD_OP_START_RANGING,
                         RttManager.CMD_OP_STOP_RANGING,
@@ -141,9 +203,10 @@
         private final WifiNative mWifiNative;
         private final Context mContext;
         private final Looper mLooper;
+        private final WifiInjector mWifiInjector;
+
         private RttStateMachine mStateMachine;
         private ClientHandler mClientHandler;
-        private WifiInjector mWifiInjector;
 
         RttServiceImpl(Context context, Looper looper, WifiInjector wifiInjector) {
             mContext = context;
@@ -192,14 +255,16 @@
         private class ClientInfo {
             private final AsyncChannel mChannel;
             private final int mUid;
+            private final String mPackageName;
 
             ArrayMap<Integer, RttRequest> mRequests = new ArrayMap<>();
             // Client keys of all outstanding responders.
             Set<Integer> mResponderRequests = new HashSet<>();
 
-            ClientInfo(AsyncChannel channel, int uid) {
+            ClientInfo(AsyncChannel channel, int uid, String packageName) {
                 mChannel = channel;
                 mUid = uid;
+                mPackageName = packageName;
             }
 
             void addResponderRequest(int key) {
@@ -293,37 +358,11 @@
         private static final int CMD_DRIVER_UNLOADED                     = BASE + 1;
         private static final int CMD_ISSUE_NEXT_REQUEST                  = BASE + 2;
         private static final int CMD_RTT_RESPONSE                        = BASE + 3;
-        private static final int CMD_CLIENT_INTERFACE_READY              = BASE + 4;
-        private static final int CMD_CLIENT_INTERFACE_DOWN               = BASE + 5;
 
         // Maximum duration for responder role.
         private static final int MAX_RESPONDER_DURATION_SECONDS = 60 * 10;
 
-        private static class InterfaceEventHandler extends IInterfaceEventCallback.Stub {
-            InterfaceEventHandler(RttStateMachine rttStateMachine) {
-                mRttStateMachine = rttStateMachine;
-            }
-            @Override
-            public void OnClientTorndownEvent(IClientInterface networkInterface) {
-                mRttStateMachine.sendMessage(CMD_CLIENT_INTERFACE_DOWN, networkInterface);
-            }
-            @Override
-            public void OnClientInterfaceReady(IClientInterface networkInterface) {
-                mRttStateMachine.sendMessage(CMD_CLIENT_INTERFACE_READY, networkInterface);
-            }
-            @Override
-            public void OnApTorndownEvent(IApInterface networkInterface) { }
-            @Override
-            public void OnApInterfaceReady(IApInterface networkInterface) { }
-
-            private RttStateMachine mRttStateMachine;
-        }
-
         class RttStateMachine extends StateMachine {
-            private IWificond mWificond;
-            private InterfaceEventHandler mInterfaceEventHandler;
-            private IClientInterface mClientInterface;
-
             DefaultState mDefaultState = new DefaultState();
             EnabledState mEnabledState = new EnabledState();
             InitiatorEnabledState mInitiatorEnabledState = new InitiatorEnabledState();
@@ -385,39 +424,9 @@
             class EnabledState extends State {
                 @Override
                 public void enter() {
-                    // This allows us to tolerate wificond restarts.
-                    // When wificond restarts WifiStateMachine is supposed to go
-                    // back to initial state and restart.
-                    // 1) RttService watches for WIFI_STATE_ENABLED broadcasts
-                    // 2) WifiStateMachine sends these broadcasts in the SupplicantStarted state
-                    // 3) Since WSM will only be in SupplicantStarted for as long as wificond is
-                    // alive, we refresh our wificond handler here and we don't subscribe to
-                    // wificond's death explicitly.
-                    mWificond = mWifiInjector.makeWificond();
-                    if (mWificond == null) {
-                        Log.w(TAG, "Failed to get wificond binder handler");
-                        transitionTo(mDefaultState);
-                    }
-                    mInterfaceEventHandler = new InterfaceEventHandler(mStateMachine);
-                    try {
-                        mWificond.RegisterCallback(mInterfaceEventHandler);
-                        // Get the current client interface, assuming there is at most
-                        // one client interface for now.
-                        List<IBinder> interfaces = mWificond.GetClientInterfaces();
-                        if (interfaces.size() > 0) {
-                            mStateMachine.sendMessage(
-                                    CMD_CLIENT_INTERFACE_READY,
-                                    IClientInterface.Stub.asInterface(interfaces.get(0)));
-                        }
-                    } catch (RemoteException e1) { }
-
                 }
                 @Override
                 public void exit() {
-                    try {
-                        mWificond.UnregisterCallback(mInterfaceEventHandler);
-                    } catch (RemoteException e1) { }
-                    mInterfaceEventHandler = null;
                 }
                 @Override
                 public boolean processMessage(Message msg) {
@@ -481,14 +490,6 @@
                             break;
                         case RttManager.CMD_OP_DISABLE_RESPONDER:
                             break;
-                        case CMD_CLIENT_INTERFACE_DOWN:
-                            if (mClientInterface == (IClientInterface) msg.obj) {
-                                mClientInterface = null;
-                            }
-                            break;
-                        case CMD_CLIENT_INTERFACE_READY:
-                            mClientInterface = (IClientInterface) msg.obj;
-                            break;
                         default:
                             return NOT_HANDLED;
                     }
@@ -534,8 +535,10 @@
                             break;
                         case CMD_RTT_RESPONSE:
                             if (DBG) Log.d(TAG, "Received an RTT response from: " + msg.arg2);
-                            mOutstandingRequest.ci.reportResult(
-                                    mOutstandingRequest, (RttManager.RttResult[])msg.obj);
+                            if (checkLocationPermission(mOutstandingRequest.ci)) {
+                                mOutstandingRequest.ci.reportResult(
+                                        mOutstandingRequest, (RttManager.RttResult[]) msg.obj);
+                            }
                             mOutstandingRequest = null;
                             sendMessage(CMD_ISSUE_NEXT_REQUEST);
                             break;
@@ -659,7 +662,7 @@
             }
         }
 
-        boolean enforcePermissionCheck(Message msg) {
+        private boolean enforcePermissionCheck(Message msg) {
             try {
                 mContext.enforcePermission(Manifest.permission.LOCATION_HARDWARE,
                          -1, msg.sendingUid, "LocationRTT");
@@ -670,6 +673,12 @@
             return true;
         }
 
+        // Returns whether the client has location permission.
+        private boolean checkLocationPermission(ClientInfo clientInfo) {
+            return mWifiInjector.getWifiPermissionsUtil().checkCallersLocationPermission(
+                    clientInfo.mPackageName, clientInfo.mUid);
+        }
+
         @Override
         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
@@ -717,8 +726,11 @@
             if (DBG) Log.d(TAG, "No more requests left");
             return null;
         }
+
         @Override
         public RttManager.RttCapabilities getRttCapabilities() {
+            mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access rtt capabilities");
             return mWifiNative.getRttCapabilities();
         }
     }
diff --git a/service/java/com/android/server/wifi/ScanDetailCache.java b/service/java/com/android/server/wifi/ScanDetailCache.java
index 3b69a64..abb6ad8 100644
--- a/service/java/com/android/server/wifi/ScanDetailCache.java
+++ b/service/java/com/android/server/wifi/ScanDetailCache.java
@@ -16,6 +16,7 @@
 
 package com.android.server.wifi;
 
+import android.annotation.NonNull;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiConfiguration;
 import android.os.SystemClock;
@@ -73,7 +74,7 @@
      * @param bssid provided BSSID
      * @return {@code null} if no match ScanResult is found.
      */
-    public ScanResult get(String bssid) {
+    public ScanResult getScanResult(String bssid) {
         ScanDetail scanDetail = getScanDetail(bssid);
         return scanDetail == null ? null : scanDetail.getScanResult();
     }
@@ -84,11 +85,11 @@
      * @param bssid provided BSSID
      * @return {@code null} if no match ScanDetail is found.
      */
-    public ScanDetail getScanDetail(String bssid) {
+    public ScanDetail getScanDetail(@NonNull String bssid) {
         return mMap.get(bssid);
     }
 
-    void remove(String bssid) {
+    void remove(@NonNull String bssid) {
         mMap.remove(bssid);
     }
 
diff --git a/service/java/com/android/server/wifi/SupplicantStaNetworkHal.java b/service/java/com/android/server/wifi/SupplicantStaNetworkHal.java
index 61ec9b3..b359897 100644
--- a/service/java/com/android/server/wifi/SupplicantStaNetworkHal.java
+++ b/service/java/com/android/server/wifi/SupplicantStaNetworkHal.java
@@ -199,7 +199,7 @@
             for (int i = 0; i < 4; i++) {
                 config.wepKeys[i] = null;
                 if (getWepKey(i) && !ArrayUtils.isEmpty(mWepKey)) {
-                    config.wepKeys[i] = NativeUtil.bytesToHexOrQuotedAsciiString(mWepKey);
+                    config.wepKeys[i] = NativeUtil.bytesToHexOrQuotedString(mWepKey);
                 }
             }
             /** PSK pass phrase */
@@ -293,7 +293,7 @@
                 for (int i = 0; i < config.wepKeys.length; i++) {
                     if (config.wepKeys[i] != null) {
                         if (!setWepKey(
-                                i, NativeUtil.hexOrQuotedAsciiStringToBytes(config.wepKeys[i]))) {
+                                i, NativeUtil.hexOrQuotedStringToBytes(config.wepKeys[i]))) {
                             Log.e(TAG, "failed to set wep_key " + i);
                             return false;
                         }
diff --git a/service/java/com/android/server/wifi/WifiConfigManager.java b/service/java/com/android/server/wifi/WifiConfigManager.java
index d8b4237..8180ab7 100644
--- a/service/java/com/android/server/wifi/WifiConfigManager.java
+++ b/service/java/com/android/server/wifi/WifiConfigManager.java
@@ -652,6 +652,12 @@
      * @param ignoreLockdown Ignore the configuration lockdown checks for connection attempts.
      */
     private boolean canModifyNetwork(WifiConfiguration config, int uid, boolean ignoreLockdown) {
+        // System internals can always update networks; they're typically only
+        // making meteredHint or meteredOverride changes
+        if (uid == Process.SYSTEM_UID) {
+            return true;
+        }
+
         // Passpoint configurations are generated and managed by PasspointManager. They can be
         // added by either PasspointNetworkEvaluator (for auto connection) or Settings app
         // (for manual connection), and need to be removed once the connection is completed.
@@ -711,16 +717,24 @@
     }
 
     /**
-     * Method to check if the provided UID belongs to the current foreground user or some other
-     * app (only SysUI today) running on behalf of the user.
-     * This is used to prevent any background user apps from modifying network configurations.
+     * Check if the given UID belongs to the current foreground user. This is
+     * used to prevent apps running in background users from modifying network
+     * configurations.
+     * <p>
+     * UIDs belonging to system internals (such as SystemUI) are always allowed,
+     * since they always run as {@link UserHandle#USER_SYSTEM}.
      *
      * @param uid uid of the app.
-     * @return true if the UID belongs to the current foreground app or SystemUI, false otherwise.
+     * @return true if the given UID belongs to the current foreground user,
+     *         otherwise false.
      */
     private boolean doesUidBelongToCurrentUser(int uid) {
-        return (WifiConfigurationUtil.doesUidBelongToAnyProfile(
-                uid, mUserManager.getProfiles(mCurrentUserId)) || (uid == mSystemUiUid));
+        if (uid == android.os.Process.SYSTEM_UID || uid == mSystemUiUid) {
+            return true;
+        } else {
+            return WifiConfigurationUtil.doesUidBelongToAnyProfile(
+                    uid, mUserManager.getProfiles(mCurrentUserId));
+        }
     }
 
     /**
@@ -829,6 +843,10 @@
             internalConfig.enterpriseConfig.copyFromExternal(
                     externalConfig.enterpriseConfig, PASSWORD_MASK);
         }
+
+        // Copy over any metered information.
+        internalConfig.meteredHint = externalConfig.meteredHint;
+        internalConfig.meteredOverride = externalConfig.meteredOverride;
     }
 
     /**
@@ -891,7 +909,6 @@
         newInternalConfig.requirePMF = externalConfig.requirePMF;
         newInternalConfig.noInternetAccessExpected = externalConfig.noInternetAccessExpected;
         newInternalConfig.ephemeral = externalConfig.ephemeral;
-        newInternalConfig.meteredHint = externalConfig.meteredHint;
         newInternalConfig.useExternalScores = externalConfig.useExternalScores;
         newInternalConfig.shared = externalConfig.shared;
 
@@ -1910,7 +1927,7 @@
         }
 
         // Adding a new BSSID
-        ScanResult result = scanDetailCache.get(scanResult.BSSID);
+        ScanResult result = scanDetailCache.getScanResult(scanResult.BSSID);
         if (result != null) {
             // transfer the black list status
             scanResult.blackListTimestamp = result.blackListTimestamp;
@@ -2681,8 +2698,8 @@
 
     /**
      * Migrate data from legacy store files. The function performs the following operations:
-     * 1. Check if the legacy store files are present.
-     * 2. If yes, read all the data from the store files.
+     * 1. Check if the legacy store files are present and the new store files are absent on device.
+     * 2. Read all the data from the store files.
      * 3. Save it to the new store files.
      * 4. Delete the legacy store file.
      *
@@ -2693,6 +2710,12 @@
             Log.d(TAG, "Legacy store files not found. No migration needed!");
             return true;
         }
+        if (mWifiConfigStore.areStoresPresent()) {
+            Log.d(TAG, "New store files found. No migration needed!"
+                    + " Remove legacy store files");
+            mWifiConfigStoreLegacy.removeStores();
+            return true;
+        }
         WifiConfigStoreDataLegacy storeData = mWifiConfigStoreLegacy.read();
         Log.d(TAG, "Reading from legacy store completed");
         loadInternalData(storeData.getConfigurations(), new ArrayList<WifiConfiguration>(),
@@ -2908,4 +2931,29 @@
     public void setOnSavedNetworkUpdateListener(OnSavedNetworkUpdateListener listener) {
         mListener = listener;
     }
+
+    /**
+     * Set extra failure reason for given config. Used to surface extra failure details to the UI
+     * @param netId The network ID of the config to set the extra failure reason for
+     * @param reason the WifiConfiguration.ExtraFailureReason failure code representing the most
+     *               recent failure reason
+     */
+    public void setRecentFailureAssociationStatus(int netId, int reason) {
+        WifiConfiguration config = getInternalConfiguredNetwork(netId);
+        if (config == null) {
+            return;
+        }
+        config.recentFailure.setAssociationStatus(reason);
+    }
+
+    /**
+     * @param netId The network ID of the config to clear the extra failure reason from
+     */
+    public void clearRecentFailureReason(int netId) {
+        WifiConfiguration config = getInternalConfiguredNetwork(netId);
+        if (config == null) {
+            return;
+        }
+        config.recentFailure.clear();
+    }
 }
diff --git a/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java b/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java
index 8677755..39e48a5 100644
--- a/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java
+++ b/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java
@@ -301,24 +301,20 @@
         // First remove all networks from wpa_supplicant and save configuration.
         if (!mWifiNative.removeAllNetworks()) {
             Log.e(TAG, "Removing networks from wpa_supplicant failed");
-            return false;
         }
 
         // Now remove the ipconfig.txt file.
         if (!IP_CONFIG_FILE.delete()) {
             Log.e(TAG, "Removing ipconfig.txt failed");
-            return false;
         }
 
         // Now finally remove network history.txt
         if (!NETWORK_HISTORY_FILE.delete()) {
             Log.e(TAG, "Removing networkHistory.txt failed");
-            return false;
         }
 
         if (!PPS_FILE.delete()) {
             Log.e(TAG, "Removing PerProviderSubscription.conf failed");
-            return false;
         }
 
         Log.i(TAG, "All legacy stores removed!");
diff --git a/service/java/com/android/server/wifi/WifiConfigurationUtil.java b/service/java/com/android/server/wifi/WifiConfigurationUtil.java
index fef78aa..dadc8a4 100644
--- a/service/java/com/android/server/wifi/WifiConfigurationUtil.java
+++ b/service/java/com/android/server/wifi/WifiConfigurationUtil.java
@@ -345,7 +345,7 @@
             }
         }
         try {
-            NativeUtil.hexOrQuotedAsciiStringToBytes(psk);
+            NativeUtil.hexOrQuotedStringToBytes(psk);
         } catch (IllegalArgumentException e) {
             Log.e(TAG, "validatePsk failed: malformed string: " + psk);
             return false;
diff --git a/service/java/com/android/server/wifi/WifiConnectivityManager.java b/service/java/com/android/server/wifi/WifiConnectivityManager.java
index 344242a..e417fde 100644
--- a/service/java/com/android/server/wifi/WifiConnectivityManager.java
+++ b/service/java/com/android/server/wifi/WifiConnectivityManager.java
@@ -133,7 +133,7 @@
     private final WifiConnectivityHelper mConnectivityHelper;
     private final WifiNetworkSelector mNetworkSelector;
     private final WifiLastResortWatchdog mWifiLastResortWatchdog;
-    private final WifiNotificationController mWifiNotificationController;
+    private final OpenNetworkNotifier mOpenNetworkNotifier;
     private final WifiMetrics mWifiMetrics;
     private final AlarmManager mAlarmManager;
     private final Handler mEventHandler;
@@ -270,7 +270,7 @@
             return true;
         } else {
             if (mWifiState == WIFI_STATE_DISCONNECTED) {
-                mWifiNotificationController.handleScanResults(
+                mOpenNetworkNotifier.handleScanResults(
                         mNetworkSelector.getFilteredScanDetailsForOpenUnsavedNetworks());
             }
             return false;
@@ -467,6 +467,10 @@
         @Override
         public void onPnoNetworkFound(ScanResult[] results) {
             for (ScanResult result: results) {
+                if (result.informationElements == null) {
+                    localLog("Skipping scan result with null information elements");
+                    continue;
+                }
                 mScanDetails.add(ScanResultUtil.toScanDetail(result));
             }
 
@@ -508,6 +512,8 @@
         }
         @Override
         public void onSavedNetworkUpdated(int networkId) {
+            // User might have changed meteredOverride, so update capabilties
+            mStateMachine.updateCapabilities();
             updatePnoScan();
         }
         @Override
@@ -536,7 +542,7 @@
             WifiScanner scanner, WifiConfigManager configManager, WifiInfo wifiInfo,
             WifiNetworkSelector networkSelector, WifiConnectivityHelper connectivityHelper,
             WifiLastResortWatchdog wifiLastResortWatchdog,
-            WifiNotificationController wifiNotificationController, WifiMetrics wifiMetrics,
+            OpenNetworkNotifier openNetworkNotifier, WifiMetrics wifiMetrics,
             Looper looper, Clock clock, LocalLog localLog, boolean enable,
             FrameworkFacade frameworkFacade,
             SavedNetworkEvaluator savedNetworkEvaluator,
@@ -550,7 +556,7 @@
         mConnectivityHelper = connectivityHelper;
         mLocalLog = localLog;
         mWifiLastResortWatchdog = wifiLastResortWatchdog;
-        mWifiNotificationController = wifiNotificationController;
+        mOpenNetworkNotifier = openNetworkNotifier;
         mWifiMetrics = wifiMetrics;
         mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         mEventHandler = new Handler(looper);
@@ -558,9 +564,9 @@
         mConnectionAttemptTimeStamps = new LinkedList<>();
 
         mMin5GHzRssi = context.getResources().getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz);
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_5GHz);
         mMin24GHzRssi = context.getResources().getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz);
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_24GHz);
         mBand5GHzBonus = context.getResources().getInteger(
                 R.integer.config_wifi_framework_5GHz_preference_boost_factor);
         mCurrentConnectionBonus = context.getResources().getInteger(
@@ -1037,7 +1043,7 @@
 
         mScreenOn = screenOn;
 
-        mWifiNotificationController.handleScreenStateChanged(screenOn);
+        mOpenNetworkNotifier.handleScreenStateChanged(screenOn);
 
         startConnectivityScan(SCAN_ON_SCHEDULE);
     }
@@ -1067,7 +1073,7 @@
         mWifiState = state;
 
         if (mWifiState == WIFI_STATE_CONNECTED) {
-            mWifiNotificationController.clearPendingNotification(false /* resetRepeatDelay */);
+            mOpenNetworkNotifier.clearPendingNotification(false /* resetRepeatDelay */);
         }
 
         // Reset BSSID of last connection attempt and kick off
@@ -1303,7 +1309,7 @@
         stopConnectivityScan();
         clearBssidBlacklist();
         resetLastPeriodicSingleScanTimeStamp();
-        mWifiNotificationController.clearPendingNotification(true /* resetRepeatDelay */);
+        mOpenNetworkNotifier.clearPendingNotification(true /* resetRepeatDelay */);
         mLastConnectionAttemptBssid = null;
         mWaitForFullBandScanResults = false;
     }
@@ -1363,6 +1369,6 @@
         pw.println("WifiConnectivityManager - Log Begin ----");
         mLocalLog.dump(fd, pw, args);
         pw.println("WifiConnectivityManager - Log End ----");
-        mWifiNotificationController.dump(fd, pw, args);
+        mOpenNetworkNotifier.dump(fd, pw, args);
     }
 }
diff --git a/service/java/com/android/server/wifi/WifiController.java b/service/java/com/android/server/wifi/WifiController.java
index c1b1861..494ce86 100644
--- a/service/java/com/android/server/wifi/WifiController.java
+++ b/service/java/com/android/server/wifi/WifiController.java
@@ -248,9 +248,9 @@
     }
 
     private void readWifiSleepPolicy() {
-        mSleepPolicy = mFacade.getIntegerSetting(mContext,
-                Settings.Global.WIFI_SLEEP_POLICY,
-                Settings.Global.WIFI_SLEEP_POLICY_NEVER);
+        // This should always set to default value because the settings menu to toggle this
+        // has been removed now.
+        mSleepPolicy = Settings.Global.WIFI_SLEEP_POLICY_NEVER;
     }
 
     private void readWifiReEnableDelay() {
diff --git a/service/java/com/android/server/wifi/WifiInjector.java b/service/java/com/android/server/wifi/WifiInjector.java
index 80daaea..60c5d2f 100644
--- a/service/java/com/android/server/wifi/WifiInjector.java
+++ b/service/java/com/android/server/wifi/WifiInjector.java
@@ -87,7 +87,7 @@
     private final WifiStateMachine mWifiStateMachine;
     private final WifiSettingsStore mSettingsStore;
     private final WifiCertManager mCertManager;
-    private final WifiNotificationController mNotificationController;
+    private final OpenNetworkNotifier mOpenNetworkNotifier;
     private final WifiLockManager mLockManager;
     private final WifiController mWifiController;
     private final WificondControl mWificondControl;
@@ -169,7 +169,8 @@
         mWifiVendorHal =
                 new WifiVendorHal(mHalDeviceManager, mWifiStateMachineHandlerThread.getLooper());
         mSupplicantStaIfaceHal = new SupplicantStaIfaceHal(mContext, mWifiMonitor);
-        mWificondControl = new WificondControl(this, mWifiMonitor);
+        mWificondControl = new WificondControl(this, mWifiMonitor,
+                new CarrierNetworkConfig(mContext));
         mWifiNative = new WifiNative(SystemProperties.get("wifi.interface", "wlan0"),
                 mWifiVendorHal, mSupplicantStaIfaceHal, mWificondControl);
         mWifiP2pMonitor = new WifiP2pMonitor(this);
@@ -230,8 +231,9 @@
                 this, mBackupManagerProxy, mCountryCode, mWifiNative,
                 new WrongPasswordNotifier(mContext, mFrameworkFacade));
         mCertManager = new WifiCertManager(mContext);
-        mNotificationController = new WifiNotificationController(mContext,
-                mWifiStateMachineHandlerThread.getLooper(), mFrameworkFacade, null);
+        mOpenNetworkNotifier = new OpenNetworkNotifier(mContext,
+                mWifiStateMachineHandlerThread.getLooper(), mFrameworkFacade, mClock,
+                new OpenNetworkRecommender());
         mLockManager = new WifiLockManager(mContext, BatteryStatsService.getService());
         mWifiController = new WifiController(mContext, mWifiStateMachine, mSettingsStore,
                 mLockManager, mWifiServiceHandlerThread.getLooper(), mFrameworkFacade);
@@ -430,7 +432,7 @@
                                                                boolean hasConnectionRequests) {
         return new WifiConnectivityManager(mContext, mWifiStateMachine, getWifiScanner(),
                 mWifiConfigManager, wifiInfo, mWifiNetworkSelector, mWifiConnectivityHelper,
-                mWifiLastResortWatchdog, mNotificationController, mWifiMetrics,
+                mWifiLastResortWatchdog, mOpenNetworkNotifier, mWifiMetrics,
                 mWifiStateMachineHandlerThread.getLooper(), mClock, mConnectivityLocalLog,
                 hasConnectionRequests, mFrameworkFacade, mSavedNetworkEvaluator,
                 mScoredNetworkEvaluator, mPasspointNetworkEvaluator);
diff --git a/service/java/com/android/server/wifi/WifiMetrics.java b/service/java/com/android/server/wifi/WifiMetrics.java
index 7dfdb86..5db5ee6 100644
--- a/service/java/com/android/server/wifi/WifiMetrics.java
+++ b/service/java/com/android/server/wifi/WifiMetrics.java
@@ -37,6 +37,7 @@
 import com.android.server.wifi.hotspot2.PasspointMatch;
 import com.android.server.wifi.hotspot2.PasspointProvider;
 import com.android.server.wifi.nano.WifiMetricsProto;
+import com.android.server.wifi.nano.WifiMetricsProto.PnoScanMetrics;
 import com.android.server.wifi.nano.WifiMetricsProto.StaEvent;
 import com.android.server.wifi.nano.WifiMetricsProto.StaEvent.ConfigInfo;
 import com.android.server.wifi.util.InformationElementUtil;
@@ -86,6 +87,7 @@
     private boolean mScreenOn;
     private int mWifiState;
     private WifiAwareMetrics mWifiAwareMetrics;
+    private final PnoScanMetrics mPnoScanMetrics = new PnoScanMetrics();
     private Handler mHandler;
     private WifiConfigManager mWifiConfigManager;
     private WifiNetworkSelector mWifiNetworkSelector;
@@ -407,6 +409,51 @@
         mPasspointManager = passpointManager;
     }
 
+    /**
+     * Increment total number of attempts to start a pno scan
+     */
+    public void incrementPnoScanStartAttempCount() {
+        synchronized (mLock) {
+            mPnoScanMetrics.numPnoScanAttempts++;
+        }
+    }
+
+    /**
+     * Increment total number of attempts with pno scan failed
+     */
+    public void incrementPnoScanFailedCount() {
+        synchronized (mLock) {
+            mPnoScanMetrics.numPnoScanFailed++;
+        }
+    }
+
+    /**
+     * Increment number of pno scans started successfully over offload
+     */
+    public void incrementPnoScanStartedOverOffloadCount() {
+        synchronized (mLock) {
+            mPnoScanMetrics.numPnoScanStartedOverOffload++;
+        }
+    }
+
+    /**
+     * Increment number of pno scans failed over offload
+     */
+    public void incrementPnoScanFailedOverOffloadCount() {
+        synchronized (mLock) {
+            mPnoScanMetrics.numPnoScanFailedOverOffload++;
+        }
+    }
+
+    /**
+     * Increment number of times pno scan found a result
+     */
+    public void incrementPnoFoundNetworkEventCount() {
+        synchronized (mLock) {
+            mPnoScanMetrics.numPnoFoundNetworkEvents++;
+        }
+    }
+
     // Values used for indexing SystemStateEntries
     private static final int SCREEN_ON = 1;
     private static final int SCREEN_OFF = 0;
@@ -1388,8 +1435,8 @@
                 pw.println("mWifiLogProto.numWifiOnFailureDueToWificond="
                         + mWifiLogProto.numWifiOnFailureDueToWificond);
                 pw.println("StaEventList:");
-                for (StaEvent event : mStaEventList) {
-                    pw.println(staEventToString(event));
+                for (StaEventWithTime event : mStaEventList) {
+                    pw.println(event);
                 }
 
                 pw.println("mWifiLogProto.numPasspointProviders="
@@ -1430,6 +1477,17 @@
                         + mWifiLogProto.fullBandAllSingleScanListenerResults);
                 pw.println("mWifiAwareMetrics:");
                 mWifiAwareMetrics.dump(fd, pw, args);
+
+                pw.println("mPnoScanMetrics.numPnoScanAttempts="
+                        + mPnoScanMetrics.numPnoScanAttempts);
+                pw.println("mPnoScanMetrics.numPnoScanFailed="
+                        + mPnoScanMetrics.numPnoScanFailed);
+                pw.println("mPnoScanMetrics.numPnoScanStartedOverOffload="
+                        + mPnoScanMetrics.numPnoScanStartedOverOffload);
+                pw.println("mPnoScanMetrics.numPnoScanFailedOverOffload="
+                        + mPnoScanMetrics.numPnoScanFailedOverOffload);
+                pw.println("mPnoScanMetrics.numPnoFoundNetworkEvents="
+                        + mPnoScanMetrics.numPnoFoundNetworkEvents);
             }
         }
     }
@@ -1605,6 +1663,14 @@
                 mWifiLogProto.softApReturnCode[sapCode].count =
                         mSoftApManagerReturnCodeCounts.valueAt(sapCode);
             }
+
+            /**
+             * Convert StaEventList to array of StaEvents
+             */
+            mWifiLogProto.staEventList = new StaEvent[mStaEventList.size()];
+            for (int i = 0; i < mStaEventList.size(); i++) {
+                mWifiLogProto.staEventList[i] = mStaEventList.get(i).staEvent;
+            }
             mWifiLogProto.totalSsidsInScanHistogram =
                     makeNumConnectableNetworksBucketArray(mTotalSsidsInScanHistogram);
             mWifiLogProto.totalBssidsInScanHistogram =
@@ -1629,8 +1695,9 @@
             mWifiLogProto.availableSavedPasspointProviderBssidsInScanHistogram =
                     makeNumConnectableNetworksBucketArray(
                     mAvailableSavedPasspointProviderBssidsInScanHistogram);
-            mWifiLogProto.staEventList = mStaEventList.toArray(mWifiLogProto.staEventList);
             mWifiLogProto.wifiAwareLog = mWifiAwareMetrics.consolidateProto();
+
+            mWifiLogProto.pnoScanMetrics = mPnoScanMetrics;
         }
     }
 
@@ -1679,6 +1746,7 @@
             mAvailableOpenOrSavedBssidsInScanHistogram.clear();
             mAvailableSavedPasspointProviderProfilesInScanHistogram.clear();
             mAvailableSavedPasspointProviderBssidsInScanHistogram.clear();
+            mPnoScanMetrics.clear();
         }
     }
 
@@ -1826,7 +1894,7 @@
         mLastPollRssi = -127;
         mLastPollFreq = -1;
         mLastPollLinkSpeed = -1;
-        mStaEventList.add(staEvent);
+        mStaEventList.add(new StaEventWithTime(staEvent, mClock.getWallClockMillis()));
         // Prune StaEventList if it gets too long
         if (mStaEventList.size() > MAX_STA_EVENTS) mStaEventList.remove();
     }
@@ -1903,7 +1971,7 @@
 
     private static String supplicantStateChangesBitmaskToString(int mask) {
         StringBuilder sb = new StringBuilder();
-        sb.append("SUPPLICANT_STATE_CHANGE_EVENTS: {");
+        sb.append("supplicantStateChangeEvents: {");
         if ((mask & (1 << StaEvent.STATE_DISCONNECTED)) > 0) sb.append(" DISCONNECTED");
         if ((mask & (1 << StaEvent.STATE_INTERFACE_DISABLED)) > 0) sb.append(" INTERFACE_DISABLED");
         if ((mask & (1 << StaEvent.STATE_INACTIVE)) > 0) sb.append(" INACTIVE");
@@ -1928,58 +1996,56 @@
     public static String staEventToString(StaEvent event) {
         if (event == null) return "<NULL>";
         StringBuilder sb = new StringBuilder();
-        Long time = event.startTimeMillis;
-        sb.append(String.format("%9d ", time.longValue())).append(" ");
         switch (event.type) {
             case StaEvent.TYPE_ASSOCIATION_REJECTION_EVENT:
-                sb.append("ASSOCIATION_REJECTION_EVENT:")
+                sb.append("ASSOCIATION_REJECTION_EVENT")
                         .append(" timedOut=").append(event.associationTimedOut)
                         .append(" status=").append(event.status).append(":")
                         .append(ISupplicantStaIfaceCallback.StatusCode.toString(event.status));
                 break;
             case StaEvent.TYPE_AUTHENTICATION_FAILURE_EVENT:
-                sb.append("AUTHENTICATION_FAILURE_EVENT: reason=").append(event.authFailureReason)
+                sb.append("AUTHENTICATION_FAILURE_EVENT reason=").append(event.authFailureReason)
                         .append(":").append(authFailureReasonToString(event.authFailureReason));
                 break;
             case StaEvent.TYPE_NETWORK_CONNECTION_EVENT:
-                sb.append("NETWORK_CONNECTION_EVENT:");
+                sb.append("NETWORK_CONNECTION_EVENT");
                 break;
             case StaEvent.TYPE_NETWORK_DISCONNECTION_EVENT:
-                sb.append("NETWORK_DISCONNECTION_EVENT:")
+                sb.append("NETWORK_DISCONNECTION_EVENT")
                         .append(" local_gen=").append(event.localGen)
                         .append(" reason=").append(event.reason).append(":")
                         .append(ISupplicantStaIfaceCallback.ReasonCode.toString(
                                 (event.reason >= 0 ? event.reason : -1 * event.reason)));
                 break;
             case StaEvent.TYPE_CMD_ASSOCIATED_BSSID:
-                sb.append("CMD_ASSOCIATED_BSSID:");
+                sb.append("CMD_ASSOCIATED_BSSID");
                 break;
             case StaEvent.TYPE_CMD_IP_CONFIGURATION_SUCCESSFUL:
-                sb.append("CMD_IP_CONFIGURATION_SUCCESSFUL:");
+                sb.append("CMD_IP_CONFIGURATION_SUCCESSFUL");
                 break;
             case StaEvent.TYPE_CMD_IP_CONFIGURATION_LOST:
-                sb.append("CMD_IP_CONFIGURATION_LOST:");
+                sb.append("CMD_IP_CONFIGURATION_LOST");
                 break;
             case StaEvent.TYPE_CMD_IP_REACHABILITY_LOST:
-                sb.append("CMD_IP_REACHABILITY_LOST:");
+                sb.append("CMD_IP_REACHABILITY_LOST");
                 break;
             case StaEvent.TYPE_CMD_TARGET_BSSID:
-                sb.append("CMD_TARGET_BSSID:");
+                sb.append("CMD_TARGET_BSSID");
                 break;
             case StaEvent.TYPE_CMD_START_CONNECT:
-                sb.append("CMD_START_CONNECT:");
+                sb.append("CMD_START_CONNECT");
                 break;
             case StaEvent.TYPE_CMD_START_ROAM:
-                sb.append("CMD_START_ROAM:");
+                sb.append("CMD_START_ROAM");
                 break;
             case StaEvent.TYPE_CONNECT_NETWORK:
-                sb.append("CONNECT_NETWORK:");
+                sb.append("CONNECT_NETWORK");
                 break;
             case StaEvent.TYPE_NETWORK_AGENT_VALID_NETWORK:
-                sb.append("NETWORK_AGENT_VALID_NETWORK:");
+                sb.append("NETWORK_AGENT_VALID_NETWORK");
                 break;
             case StaEvent.TYPE_FRAMEWORK_DISCONNECT:
-                sb.append("FRAMEWORK_DISCONNECT:")
+                sb.append("FRAMEWORK_DISCONNECT")
                         .append(" reason=")
                         .append(frameworkDisconnectReasonToString(event.frameworkDisconnectReason));
                 break;
@@ -1991,11 +2057,11 @@
         if (event.lastFreq != -1) sb.append(" lastFreq=").append(event.lastFreq);
         if (event.lastLinkSpeed != -1) sb.append(" lastLinkSpeed=").append(event.lastLinkSpeed);
         if (event.supplicantStateChangesBitmask != 0) {
-            sb.append("\n             ").append(supplicantStateChangesBitmaskToString(
+            sb.append(", ").append(supplicantStateChangesBitmaskToString(
                     event.supplicantStateChangesBitmask));
         }
         if (event.configInfo != null) {
-            sb.append("\n             ").append(configInfoToString(event.configInfo));
+            sb.append(", ").append(configInfoToString(event.configInfo));
         }
 
         return sb.toString();
@@ -2053,7 +2119,7 @@
     }
 
     public static final int MAX_STA_EVENTS = 512;
-    private LinkedList<StaEvent> mStaEventList = new LinkedList<StaEvent>();
+    private LinkedList<StaEventWithTime> mStaEventList = new LinkedList<StaEventWithTime>();
     private int mLastPollRssi = -127;
     private int mLastPollLinkSpeed = -1;
     private int mLastPollFreq = -1;
@@ -2085,4 +2151,27 @@
         int count = sia.get(element);
         sia.put(element, count + 1);
     }
+
+    private static class StaEventWithTime {
+        public StaEvent staEvent;
+        public long wallClockMillis;
+
+        StaEventWithTime(StaEvent event, long wallClockMillis) {
+            staEvent = event;
+            this.wallClockMillis = wallClockMillis;
+        }
+
+        public String toString() {
+            StringBuilder sb = new StringBuilder();
+            Calendar c = Calendar.getInstance();
+            c.setTimeInMillis(wallClockMillis);
+            if (wallClockMillis != 0) {
+                sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
+            } else {
+                sb.append("                  ");
+            }
+            sb.append(" ").append(staEventToString(staEvent));
+            return sb.toString();
+        }
+    }
 }
diff --git a/service/java/com/android/server/wifi/WifiNative.java b/service/java/com/android/server/wifi/WifiNative.java
index 973b659..5b12a36 100644
--- a/service/java/com/android/server/wifi/WifiNative.java
+++ b/service/java/com/android/server/wifi/WifiNative.java
@@ -227,7 +227,16 @@
      * Returns an empty ArrayList on failure.
      */
     public ArrayList<ScanDetail> getScanResults() {
-        return mWificondControl.getScanResults();
+        return mWificondControl.getScanResults(WificondControl.SCAN_TYPE_SINGLE_SCAN);
+    }
+
+    /**
+     * Fetch the latest scan result from kernel via wificond.
+     * @return Returns an ArrayList of ScanDetail.
+     * Returns an empty ArrayList on failure.
+     */
+    public ArrayList<ScanDetail> getPnoScanResults() {
+        return mWificondControl.getScanResults(WificondControl.SCAN_TYPE_PNO_SCAN);
     }
 
     /**
@@ -1536,26 +1545,6 @@
     }
 
     /**
-     * Set the PNO settings & the network list in HAL to start PNO.
-     * @param settings PNO settings and network list.
-     * @param eventHandler Handler to receive notifications back during PNO scan.
-     * @return true if success, false otherwise
-     */
-    public boolean setPnoList(PnoSettings settings, PnoEventHandler eventHandler) {
-        Log.e(mTAG, "setPnoList not supported");
-        return false;
-    }
-
-    /**
-     * Reset the PNO settings in HAL to stop PNO.
-     * @return true if success, false otherwise
-     */
-    public boolean resetPnoList() {
-        Log.e(mTAG, "resetPnoList not supported");
-        return false;
-    }
-
-    /**
      * Start sending the specified keep alive packets periodically.
      *
      * @param slot Integer used to identify each request.
diff --git a/service/java/com/android/server/wifi/WifiNetworkHistory.java b/service/java/com/android/server/wifi/WifiNetworkHistory.java
index f8457cd..282f605 100644
--- a/service/java/com/android/server/wifi/WifiNetworkHistory.java
+++ b/service/java/com/android/server/wifi/WifiNetworkHistory.java
@@ -17,16 +17,13 @@
 package com.android.server.wifi;
 
 import android.content.Context;
-
 import android.net.wifi.ScanResult;
-
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
 import android.net.wifi.WifiSsid;
 import android.os.Environment;
 import android.os.Process;
 import android.text.TextUtils;
-
 import android.util.Log;
 
 import com.android.server.net.DelayedDiskWrite;
@@ -76,7 +73,6 @@
     private static final String AUTH_KEY = "AUTH";
     private static final String BSSID_STATUS_KEY = "BSSID_STATUS";
     private static final String SELF_ADDED_KEY = "SELF_ADDED";
-    private static final String FAILURE_KEY = "FAILURE";
     private static final String DID_SELF_ADD_KEY = "DID_SELF_ADD";
     private static final String PEER_CONFIGURATION_KEY = "PEER_CONFIGURATION";
     static final String CREATOR_UID_KEY = "CREATOR_UID_KEY";
@@ -91,6 +87,7 @@
     private static final String EPHEMERAL_KEY = "EPHEMERAL";
     private static final String USE_EXTERNAL_SCORES_KEY = "USE_EXTERNAL_SCORES";
     private static final String METERED_HINT_KEY = "METERED_HINT";
+    private static final String METERED_OVERRIDE_KEY = "METERED_OVERRIDE";
     private static final String NUM_ASSOCIATION_KEY = "NUM_ASSOCIATION";
     private static final String DELETED_EPHEMERAL_KEY = "DELETED_EPHEMERAL";
     private static final String CREATOR_NAME_KEY = "CREATOR_NAME";
@@ -213,6 +210,8 @@
                             + Boolean.toString(config.ephemeral) + NL);
                     out.writeUTF(METERED_HINT_KEY + SEPARATOR
                             + Boolean.toString(config.meteredHint) + NL);
+                    out.writeUTF(METERED_OVERRIDE_KEY + SEPARATOR
+                            + Integer.toString(config.meteredOverride) + NL);
                     out.writeUTF(USE_EXTERNAL_SCORES_KEY + SEPARATOR
                             + Boolean.toString(config.useExternalScores) + NL);
                     if (config.creationTime != null) {
@@ -289,9 +288,6 @@
                             out.writeUTF(BSSID_KEY_END + NL);
                         }
                     }
-                    if (config.lastFailure != null) {
-                        out.writeUTF(FAILURE_KEY + SEPARATOR + config.lastFailure + NL);
-                    }
                     out.writeUTF(HAS_EVER_CONNECTED_KEY + SEPARATOR
                             + Boolean.toString(status.getHasEverConnected()) + NL);
                     out.writeUTF(NL);
@@ -427,6 +423,9 @@
                         case METERED_HINT_KEY:
                             config.meteredHint = Boolean.parseBoolean(value);
                             break;
+                        case METERED_OVERRIDE_KEY:
+                            config.meteredOverride = Integer.parseInt(value);
+                            break;
                         case USE_EXTERNAL_SCORES_KEY:
                             config.useExternalScores = Boolean.parseBoolean(value);
                             break;
@@ -448,9 +447,6 @@
                         case UPDATE_UID_KEY:
                             config.lastUpdateUid = Integer.parseInt(value);
                             break;
-                        case FAILURE_KEY:
-                            config.lastFailure = value;
-                            break;
                         case PEER_CONFIGURATION_KEY:
                             config.peerWifiConfiguration = value;
                             break;
diff --git a/service/java/com/android/server/wifi/WifiNetworkSelector.java b/service/java/com/android/server/wifi/WifiNetworkSelector.java
index 89068a8..071fc07 100644
--- a/service/java/com/android/server/wifi/WifiNetworkSelector.java
+++ b/service/java/com/android/server/wifi/WifiNetworkSelector.java
@@ -575,15 +575,15 @@
         mLocalLog = localLog;
 
         mThresholdQualifiedRssi24 = context.getResources().getInteger(
-                            R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz);
+                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz);
         mThresholdQualifiedRssi5 = context.getResources().getInteger(
-                            R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz);
+                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz);
         mThresholdMinimumRssi24 = context.getResources().getInteger(
-                            R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz);
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_24GHz);
         mThresholdMinimumRssi5 = context.getResources().getInteger(
-                            R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz);
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_5GHz);
         mEnableAutoJoinWhenAssociated = context.getResources().getBoolean(
-                            R.bool.config_wifi_framework_enable_associated_network_selection);
+                R.bool.config_wifi_framework_enable_associated_network_selection);
         mStayOnNetworkMinimumTxRate = context.getResources().getInteger(
                 R.integer.config_wifi_framework_min_tx_rate_for_staying_on_network);
         mStayOnNetworkMinimumRxRate = context.getResources().getInteger(
diff --git a/service/java/com/android/server/wifi/WifiNotificationController.java b/service/java/com/android/server/wifi/WifiNotificationController.java
deleted file mode 100644
index 797fd43..0000000
--- a/service/java/com/android/server/wifi/WifiNotificationController.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.wifi;
-
-import android.annotation.NonNull;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.TaskStackBuilder;
-import android.content.Context;
-import android.content.Intent;
-import android.database.ContentObserver;
-import android.net.wifi.WifiManager;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.provider.Settings;
-
-import com.android.internal.notification.SystemNotificationChannels;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.List;
-
-/**
- * Takes care of handling the "open wi-fi network available" notification
- * @hide
- */
-public class WifiNotificationController {
-    /**
-     * The icon to show in the 'available networks' notification. This will also
-     * be the ID of the Notification given to the NotificationManager.
-     */
-    private static final int ICON_NETWORKS_AVAILABLE =
-            com.android.internal.R.drawable.stat_notify_wifi_in_range;
-    /**
-     * When a notification is shown, we wait this amount before possibly showing it again.
-     */
-    private final long NOTIFICATION_REPEAT_DELAY_MS;
-
-    /** Whether the user has set the setting to show the 'available networks' notification. */
-    private boolean mSettingEnabled;
-
-    /**
-     * Observes the user setting to keep {@link #mSettingEnabled} in sync.
-     */
-    private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
-
-    /**
-     * The {@link System#currentTimeMillis()} must be at least this value for us
-     * to show the notification again.
-     */
-    private long mNotificationRepeatTime;
-    /**
-     * The Notification object given to the NotificationManager.
-     */
-    private Notification.Builder mNotificationBuilder;
-    /**
-     * Whether the notification is being shown, as set by us. That is, if the
-     * user cancels the notification, we will not receive the callback so this
-     * will still be true. We only guarantee if this is false, then the
-     * notification is not showing.
-     */
-    private boolean mNotificationShown;
-    /** Whether the screen is on or not. */
-    private boolean mScreenOn;
-
-    private final Context mContext;
-    private FrameworkFacade mFrameworkFacade;
-
-    WifiNotificationController(Context context,
-                               Looper looper,
-                               FrameworkFacade framework,
-                               Notification.Builder builder) {
-        mContext = context;
-        mFrameworkFacade = framework;
-        mNotificationBuilder = builder;
-
-        mScreenOn = false;
-
-        // Setting is in seconds
-        NOTIFICATION_REPEAT_DELAY_MS = mFrameworkFacade.getIntegerSetting(context,
-                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000L;
-        mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(
-                new Handler(looper));
-        mNotificationEnabledSettingObserver.register();
-    }
-
-    /**
-     * Clears the pending notification. This is called by {@link WifiConnectivityManager} on stop.
-     *
-     * @param resetRepeatDelay resets the time delay for repeated notification if true.
-     */
-    public void clearPendingNotification(boolean resetRepeatDelay) {
-        if (resetRepeatDelay) {
-            mNotificationRepeatTime = 0;
-        }
-        setNotificationVisible(false, 0, false, 0);
-    }
-
-    private boolean isControllerEnabled() {
-        return mSettingEnabled && !UserManager.get(mContext)
-                .hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT);
-    }
-
-    /**
-     * If there are open networks, attempt to post an open network notification.
-     *
-     * @param availableNetworks Available networks from
-     * {@link WifiNetworkSelector.NetworkEvaluator#getFilteredScanDetailsForOpenUnsavedNetworks()}.
-     */
-    public void handleScanResults(@NonNull List<ScanDetail> availableNetworks) {
-        if (!isControllerEnabled()) {
-            clearPendingNotification(true /* resetRepeatDelay */);
-            return;
-        }
-        if (availableNetworks.isEmpty()) {
-            clearPendingNotification(false /* resetRepeatDelay */);
-            return;
-        }
-
-        // Do not show or update the notification if screen is off. We want to avoid a race that
-        // could occur between a user picking a network in settings and a network candidate picked
-        // through network selection, which will happen because screen on triggers a new
-        // connectivity scan.
-        if (mNotificationShown || !mScreenOn) {
-            return;
-        }
-
-        setNotificationVisible(true, availableNetworks.size(), false, 0);
-    }
-
-    /** Handles screen state changes. */
-    public void handleScreenStateChanged(boolean screenOn) {
-        mScreenOn = screenOn;
-    }
-
-    /**
-     * Display or don't display a notification that there are open Wi-Fi networks.
-     * @param visible {@code true} if notification should be visible, {@code false} otherwise
-     * @param numNetworks the number networks seen
-     * @param force {@code true} to force notification to be shown/not-shown,
-     * even if it is already shown/not-shown.
-     * @param delay time in milliseconds after which the notification should be made
-     * visible or invisible.
-     */
-    private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
-            int delay) {
-
-        // Since we use auto cancel on the notification, when the
-        // mNetworksAvailableNotificationShown is true, the notification may
-        // have actually been canceled.  However, when it is false we know
-        // for sure that it is not being shown (it will not be shown any other
-        // place than here)
-
-        // If it should be hidden and it is already hidden, then noop
-        if (!visible && !mNotificationShown && !force) {
-            return;
-        }
-
-        NotificationManager notificationManager = (NotificationManager) mContext
-                .getSystemService(Context.NOTIFICATION_SERVICE);
-
-        Message message;
-        if (visible) {
-
-            // Not enough time has passed to show the notification again
-            if (System.currentTimeMillis() < mNotificationRepeatTime) {
-                return;
-            }
-
-            if (mNotificationBuilder == null) {
-                // Cache the Notification builder object.
-                mNotificationBuilder = new Notification.Builder(mContext,
-                        SystemNotificationChannels.NETWORK_AVAILABLE)
-                        .setWhen(0)
-                        .setSmallIcon(ICON_NETWORKS_AVAILABLE)
-                        .setAutoCancel(true)
-                        .setContentIntent(TaskStackBuilder.create(mContext)
-                                .addNextIntentWithParentStack(
-                                        new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
-                                .getPendingIntent(0, 0, null, UserHandle.CURRENT))
-                        .setColor(mContext.getResources().getColor(
-                                com.android.internal.R.color.system_notification_accent_color));
-            }
-
-            CharSequence title = mContext.getResources().getQuantityText(
-                    com.android.internal.R.plurals.wifi_available, numNetworks);
-            CharSequence details = mContext.getResources().getQuantityText(
-                    com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
-            mNotificationBuilder.setTicker(title);
-            mNotificationBuilder.setContentTitle(title);
-            mNotificationBuilder.setContentText(details);
-
-            mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
-
-            notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE,
-                    mNotificationBuilder.build(), UserHandle.ALL);
-        } else {
-            notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
-        }
-
-        mNotificationShown = visible;
-    }
-
-    /** Dump ONA controller state. */
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        pw.println("WifiNotificationController: ");
-        pw.println("mSettingEnabled " + mSettingEnabled);
-        pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
-        pw.println("mNotificationShown " + mNotificationShown);
-    }
-
-    private class NotificationEnabledSettingObserver extends ContentObserver {
-        NotificationEnabledSettingObserver(Handler handler) {
-            super(handler);
-        }
-
-        public void register() {
-            mFrameworkFacade.registerContentObserver(mContext, Settings.Global.getUriFor(
-                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
-            mSettingEnabled = getValue();
-        }
-
-        @Override
-        public void onChange(boolean selfChange) {
-            super.onChange(selfChange);
-            mSettingEnabled = getValue();
-            clearPendingNotification(true /* resetRepeatDelay */);
-        }
-
-        private boolean getValue() {
-            return mFrameworkFacade.getIntegerSetting(mContext,
-                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
-        }
-    }
-}
diff --git a/service/java/com/android/server/wifi/WifiServiceImpl.java b/service/java/com/android/server/wifi/WifiServiceImpl.java
index d6faf9b..bb995b7 100644
--- a/service/java/com/android/server/wifi/WifiServiceImpl.java
+++ b/service/java/com/android/server/wifi/WifiServiceImpl.java
@@ -591,7 +591,7 @@
     public void startScan(ScanSettings settings, WorkSource workSource, String packageName) {
         enforceChangePermission();
 
-        mLog.trace("startScan uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("startScan uid=%").c(Binder.getCallingUid()).flush();
         // Check and throttle background apps for wifi scan.
         if (isRequestFromBackground(packageName)) {
             long lastScanMs = mLastScanTimestamps.getOrDefault(packageName, 0L);
@@ -683,7 +683,7 @@
     @Override
     public String getCurrentNetworkWpsNfcConfigurationToken() {
         enforceConnectivityInternalPermission();
-        mLog.trace("getCurrentNetworkWpsNfcConfigurationToken uid=%")
+        mLog.info("getCurrentNetworkWpsNfcConfigurationToken uid=%")
                 .c(Binder.getCallingUid()).flush();
         // TODO Add private logging for netId b/33807876
         return mWifiStateMachine.syncGetCurrentNetworkWpsNfcConfigurationToken();
@@ -713,6 +713,11 @@
         }
     }
 
+    private boolean checkNetworkSettingsPermission(int pid, int uid) {
+        return mContext.checkPermission(android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
+                == PackageManager.PERMISSION_GRANTED;
+    }
+
     private void enforceNetworkSettingsPermission() {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS,
                 "WifiService");
@@ -777,15 +782,15 @@
         enforceChangePermission();
         Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
                     + ", uid=" + Binder.getCallingUid() + ", package=" + packageName);
-        mLog.trace("setWifiEnabled package=% uid=% enable=%").c(packageName)
+        mLog.info("setWifiEnabled package=% uid=% enable=%").c(packageName)
                 .c(Binder.getCallingUid()).c(enable).flush();
 
-        boolean isFromSettings =
-                mWifiPermissionsUtil.checkNetworkSettingsPermission(Binder.getCallingUid());
+        boolean isFromSettings = checkNetworkSettingsPermission(
+                Binder.getCallingPid(), Binder.getCallingUid());
 
         // If Airplane mode is enabled, only Settings is allowed to toggle Wifi
         if (mSettingsStore.isAirplaneModeOn() && !isFromSettings) {
-            mLog.trace("setWifiEnabled in Airplane mode: only Settings can enable wifi").flush();
+            mLog.info("setWifiEnabled in Airplane mode: only Settings can enable wifi").flush();
             return false;
         }
 
@@ -794,7 +799,7 @@
                 mWifiStateMachine.syncGetWifiApState() != WifiManager.WIFI_AP_STATE_DISABLED;
 
         if (apEnabled && !isFromSettings) {
-            mLog.trace("setWifiEnabled SoftAp not disabled: only Settings can enable wifi").flush();
+            mLog.info("setWifiEnabled SoftAp not disabled: only Settings can enable wifi").flush();
             return false;
         }
 
@@ -847,7 +852,7 @@
     @Override
     public int getWifiEnabledState() {
         enforceAccessPermission();
-        mLog.trace("getWifiEnabledState uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getWifiEnabledState uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.syncGetWifiState();
     }
 
@@ -862,7 +867,7 @@
         enforceChangePermission();
         mWifiPermissionsUtil.enforceTetherChangePermission(mContext);
 
-        mLog.trace("setWifiApEnabled uid=% enable=%").c(Binder.getCallingUid()).c(enabled).flush();
+        mLog.info("setWifiApEnabled uid=% enable=%").c(Binder.getCallingUid()).c(enabled).flush();
 
         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
             throw new SecurityException("DISALLOW_CONFIG_TETHERING is enabled for this user.");
@@ -888,7 +893,7 @@
     @Override
     public int getWifiApEnabledState() {
         enforceAccessPermission();
-        mLog.trace("getWifiApEnabledState uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getWifiApEnabledState uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.syncGetWifiApState();
     }
 
@@ -963,7 +968,7 @@
                     }
                     break;
                 default:
-                    mLog.trace("updateInterfaceIpStateInternal: unknown mode %").c(mode).flush();
+                    mLog.warn("updateInterfaceIpStateInternal: unknown mode %").c(mode).flush();
             }
         }
     }
@@ -979,7 +984,7 @@
         // NETWORK_STACK is a signature only permission.
         enforceNetworkStackPermission();
 
-        mLog.trace("startSoftAp uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("startSoftAp uid=%").c(Binder.getCallingUid()).flush();
 
         synchronized (mLocalOnlyHotspotRequests) {
             // If a tethering request comes in while we have LOHS running (or requested), call stop
@@ -1023,7 +1028,7 @@
         // only permitted callers are allowed to this point - they must have gone through
         // connectivity service since this method is protected with the NETWORK_STACK PERMISSION
 
-        mLog.trace("stopSoftAp uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("stopSoftAp uid=%").c(Binder.getCallingUid()).flush();
 
         synchronized (mLocalOnlyHotspotRequests) {
             // If a tethering request comes in while we have LOHS running (or requested), call stop
@@ -1212,17 +1217,17 @@
                 return LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
             }
         } catch (RemoteException e) {
-            mLog.trace("RemoteException during isAppForeground when calling startLOHS");
+            mLog.warn("RemoteException during isAppForeground when calling startLOHS");
             return LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
         }
 
-        mLog.trace("startLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
+        mLog.info("startLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
 
         synchronized (mLocalOnlyHotspotRequests) {
             // check if we are currently tethering
             if (mIfaceIpModes.contains(WifiManager.IFACE_IP_MODE_TETHERED)) {
                 // Tethering is enabled, cannot start LocalOnlyHotspot
-                mLog.trace("Cannot start localOnlyHotspot when WiFi Tethering is active.");
+                mLog.info("Cannot start localOnlyHotspot when WiFi Tethering is active.");
                 return LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
             }
 
@@ -1272,7 +1277,7 @@
         final int uid = Binder.getCallingUid();
         final int pid = Binder.getCallingPid();
 
-        mLog.trace("stopLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
+        mLog.info("stopLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
 
         synchronized (mLocalOnlyHotspotRequests) {
             // was the caller already registered?  check request tracker - return false if not
@@ -1360,7 +1365,7 @@
             throw new SecurityException("App not allowed to read or update stored WiFi Ap config "
                     + "(uid = " + uid + ")");
         }
-        mLog.trace("getWifiApConfiguration uid=%").c(uid).flush();
+        mLog.info("getWifiApConfiguration uid=%").c(uid).flush();
         return mWifiStateMachine.syncGetWifiApConfiguration();
     }
 
@@ -1379,7 +1384,7 @@
             throw new SecurityException("App not allowed to read or update stored WiFi AP config "
                     + "(uid = " + uid + ")");
         }
-        mLog.trace("setWifiApConfiguration uid=%").c(uid).flush();
+        mLog.info("setWifiApConfiguration uid=%").c(uid).flush();
         if (wifiConfig == null)
             return;
         if (isValid(wifiConfig)) {
@@ -1395,7 +1400,7 @@
     @Override
     public boolean isScanAlwaysAvailable() {
         enforceAccessPermission();
-        mLog.trace("isScanAlwaysAvailable uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("isScanAlwaysAvailable uid=%").c(Binder.getCallingUid()).flush();
         return mSettingsStore.isScanAlwaysAvailable();
     }
 
@@ -1405,7 +1410,7 @@
     @Override
     public void disconnect() {
         enforceChangePermission();
-        mLog.trace("disconnect uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("disconnect uid=%").c(Binder.getCallingUid()).flush();
         mWifiStateMachine.disconnectCommand();
     }
 
@@ -1415,7 +1420,7 @@
     @Override
     public void reconnect() {
         enforceChangePermission();
-        mLog.trace("reconnect uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("reconnect uid=%").c(Binder.getCallingUid()).flush();
         mWifiStateMachine.reconnectCommand();
     }
 
@@ -1425,7 +1430,7 @@
     @Override
     public void reassociate() {
         enforceChangePermission();
-        mLog.trace("reassociate uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("reassociate uid=%").c(Binder.getCallingUid()).flush();
         mWifiStateMachine.reassociateCommand();
     }
 
@@ -1435,7 +1440,7 @@
     @Override
     public int getSupportedFeatures() {
         enforceAccessPermission();
-        mLog.trace("getSupportedFeatures uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getSupportedFeatures uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel != null) {
             return mWifiStateMachine.syncGetSupportedFeatures(mWifiStateMachineChannel);
         } else {
@@ -1447,7 +1452,7 @@
     @Override
     public void requestActivityInfo(ResultReceiver result) {
         Bundle bundle = new Bundle();
-        mLog.trace("requestActivityInfo uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("requestActivityInfo uid=%").c(Binder.getCallingUid()).flush();
         bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, reportActivityInfo());
         result.send(0, bundle);
     }
@@ -1458,7 +1463,7 @@
     @Override
     public WifiActivityEnergyInfo reportActivityInfo() {
         enforceAccessPermission();
-        mLog.trace("reportActivityInfo uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("reportActivityInfo uid=%").c(Binder.getCallingUid()).flush();
         if ((getSupportedFeatures() & WifiManager.WIFI_FEATURE_LINK_LAYER_STATS) == 0) {
             return null;
         }
@@ -1531,7 +1536,7 @@
     @Override
     public ParceledListSlice<WifiConfiguration> getConfiguredNetworks() {
         enforceAccessPermission();
-        mLog.trace("getConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel != null) {
             List<WifiConfiguration> configs = mWifiStateMachine.syncGetConfiguredNetworks(
                     Binder.getCallingUid(), mWifiStateMachineChannel);
@@ -1552,7 +1557,7 @@
     public ParceledListSlice<WifiConfiguration> getPrivilegedConfiguredNetworks() {
         enforceReadCredentialPermission();
         enforceAccessPermission();
-        mLog.trace("getPrivilegedConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getPrivilegedConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel != null) {
             List<WifiConfiguration> configs =
                     mWifiStateMachine.syncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel);
@@ -1574,7 +1579,7 @@
     @Override
     public WifiConfiguration getMatchingWifiConfig(ScanResult scanResult) {
         enforceAccessPermission();
-        mLog.trace("getMatchingWifiConfig uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getMatchingWifiConfig uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1591,7 +1596,7 @@
     @Override
     public List<OsuProvider> getMatchingOsuProviders(ScanResult scanResult) {
         enforceAccessPermission();
-        mLog.trace("getMatchingOsuProviders uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getMatchingOsuProviders uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1607,7 +1612,7 @@
     @Override
     public int addOrUpdateNetwork(WifiConfiguration config) {
         enforceChangePermission();
-        mLog.trace("addOrUpdateNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("addOrUpdateNetwork uid=%").c(Binder.getCallingUid()).flush();
 
         // Previously, this API is overloaded for installing Passpoint profiles.  Now
         // that we have a dedicated API for doing it, redirect the call to the dedicated API.
@@ -1678,7 +1683,7 @@
     @Override
     public boolean removeNetwork(int netId) {
         enforceChangePermission();
-        mLog.trace("removeNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("removeNetwork uid=%").c(Binder.getCallingUid()).flush();
         // TODO Add private logging for netId b/33807876
         if (mWifiStateMachineChannel != null) {
             return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
@@ -1699,7 +1704,7 @@
     public boolean enableNetwork(int netId, boolean disableOthers) {
         enforceChangePermission();
         // TODO b/33807876 Log netId
-        mLog.trace("enableNetwork uid=% disableOthers=%")
+        mLog.info("enableNetwork uid=% disableOthers=%")
                 .c(Binder.getCallingUid())
                 .c(disableOthers).flush();
 
@@ -1722,7 +1727,7 @@
     public boolean disableNetwork(int netId) {
         enforceChangePermission();
         // TODO b/33807876 Log netId
-        mLog.trace("disableNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("disableNetwork uid=%").c(Binder.getCallingUid()).flush();
 
         if (mWifiStateMachineChannel != null) {
             return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
@@ -1737,14 +1742,14 @@
      * @return the Wi-Fi information, contained in {@link WifiInfo}.
      */
     @Override
-    public WifiInfo getConnectionInfo() {
+    public WifiInfo getConnectionInfo(String callingPackage) {
         enforceAccessPermission();
-        mLog.trace("getConnectionInfo uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getConnectionInfo uid=%").c(Binder.getCallingUid()).flush();
         /*
          * Make sure we have the latest information, by sending
          * a status request to the supplicant.
          */
-        return mWifiStateMachine.syncRequestConnectionInfo();
+        return mWifiStateMachine.syncRequestConnectionInfo(callingPackage);
     }
 
     /**
@@ -1780,7 +1785,7 @@
     @Override
     public boolean addOrUpdatePasspointConfiguration(PasspointConfiguration config) {
         enforceChangePermission();
-        mLog.trace("addorUpdatePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("addorUpdatePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1798,7 +1803,7 @@
     @Override
     public boolean removePasspointConfiguration(String fqdn) {
         enforceChangePermission();
-        mLog.trace("removePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("removePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1816,7 +1821,7 @@
     @Override
     public List<PasspointConfiguration> getPasspointConfigurations() {
         enforceAccessPermission();
-        mLog.trace("getPasspointConfigurations uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getPasspointConfigurations uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1832,7 +1837,7 @@
     @Override
     public void queryPasspointIcon(long bssid, String fileName) {
         enforceAccessPermission();
-        mLog.trace("queryPasspointIcon uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("queryPasspointIcon uid=%").c(Binder.getCallingUid()).flush();
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_WIFI_PASSPOINT)) {
             throw new UnsupportedOperationException("Passpoint not enabled");
@@ -1847,7 +1852,7 @@
      */
     @Override
     public int matchProviderWithCurrentNetwork(String fqdn) {
-        mLog.trace("matchProviderWithCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("matchProviderWithCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.matchProviderWithCurrentNetwork(mWifiStateMachineChannel, fqdn);
     }
 
@@ -1858,7 +1863,7 @@
      */
     @Override
     public void deauthenticateNetwork(long holdoff, boolean ess) {
-        mLog.trace("deauthenticateNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("deauthenticateNetwork uid=%").c(Binder.getCallingUid()).flush();
         mWifiStateMachine.deauthenticateNetwork(mWifiStateMachineChannel, holdoff, ess);
     }
 
@@ -1871,7 +1876,7 @@
     @Override
     public boolean saveConfiguration() {
         enforceChangePermission();
-        mLog.trace("saveConfiguration uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("saveConfiguration uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel != null) {
             return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
         } else {
@@ -1894,7 +1899,7 @@
         Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
                 " with persist set to " + persist);
         enforceConnectivityInternalPermission();
-        mLog.trace("setCountryCode uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("setCountryCode uid=%").c(Binder.getCallingUid()).flush();
         final long token = Binder.clearCallingIdentity();
         mCountryCode.setCountryCode(countryCode);
         Binder.restoreCallingIdentity(token);
@@ -1909,7 +1914,7 @@
     @Override
     public String getCountryCode() {
         enforceConnectivityInternalPermission();
-        mLog.trace("getCountryCode uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getCountryCode uid=%").c(Binder.getCallingUid()).flush();
         String country = mCountryCode.getCountryCode();
         return country;
     }
@@ -1917,7 +1922,7 @@
     @Override
     public boolean isDualBandSupported() {
         //TODO: Should move towards adding a driver API that checks at runtime
-        mLog.trace("isDualBandSupported uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("isDualBandSupported uid=%").c(Binder.getCallingUid()).flush();
         return mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_wifi_dual_band_support);
     }
@@ -1932,7 +1937,7 @@
     @Deprecated
     public DhcpInfo getDhcpInfo() {
         enforceAccessPermission();
-        mLog.trace("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush();
         DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
 
         DhcpInfo info = new DhcpInfo();
@@ -2045,7 +2050,7 @@
         if (remoteAddress == null) {
           throw new IllegalArgumentException("remoteAddress cannot be null");
         }
-        mLog.trace("enableTdls uid=% enable=%").c(Binder.getCallingUid()).c(enable).flush();
+        mLog.info("enableTdls uid=% enable=%").c(Binder.getCallingUid()).c(enable).flush();
         TdlsTaskParams params = new TdlsTaskParams();
         params.remoteIpAddress = remoteAddress;
         params.enable = enable;
@@ -2055,7 +2060,7 @@
 
     @Override
     public void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable) {
-        mLog.trace("enableTdlsWithMacAddress uid=% enable=%")
+        mLog.info("enableTdlsWithMacAddress uid=% enable=%")
                 .c(Binder.getCallingUid())
                 .c(enable)
                 .flush();
@@ -2074,7 +2079,7 @@
     public Messenger getWifiServiceMessenger() {
         enforceAccessPermission();
         enforceChangePermission();
-        mLog.trace("getWifiServiceMessenger uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getWifiServiceMessenger uid=%").c(Binder.getCallingUid()).flush();
         return new Messenger(mClientHandler);
     }
 
@@ -2085,7 +2090,7 @@
     public void disableEphemeralNetwork(String SSID) {
         enforceAccessPermission();
         enforceChangePermission();
-        mLog.trace("disableEphemeralNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("disableEphemeralNetwork uid=%").c(Binder.getCallingUid()).flush();
         mWifiStateMachine.disableEphemeralNetwork(SSID);
     }
 
@@ -2321,7 +2326,7 @@
 
     @Override
     public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
-        mLog.trace("acquireWifiLock uid=% lockMode=%")
+        mLog.info("acquireWifiLock uid=% lockMode=%")
                 .c(Binder.getCallingUid())
                 .c(lockMode).flush();
         if (mWifiLockManager.acquireWifiLock(lockMode, tag, binder, ws)) {
@@ -2333,13 +2338,13 @@
 
     @Override
     public void updateWifiLockWorkSource(IBinder binder, WorkSource ws) {
-        mLog.trace("updateWifiLockWorkSource uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("updateWifiLockWorkSource uid=%").c(Binder.getCallingUid()).flush();
         mWifiLockManager.updateWifiLockWorkSource(binder, ws);
     }
 
     @Override
     public boolean releaseWifiLock(IBinder binder) {
-        mLog.trace("releaseWifiLock uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("releaseWifiLock uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiLockManager.releaseWifiLock(binder)) {
             mWifiController.sendMessage(CMD_LOCKS_CHANGED);
             return true;
@@ -2350,35 +2355,35 @@
     @Override
     public void initializeMulticastFiltering() {
         enforceMulticastChangePermission();
-        mLog.trace("initializeMulticastFiltering uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("initializeMulticastFiltering uid=%").c(Binder.getCallingUid()).flush();
         mWifiMulticastLockManager.initializeFiltering();
     }
 
     @Override
     public void acquireMulticastLock(IBinder binder, String tag) {
         enforceMulticastChangePermission();
-        mLog.trace("acquireMulticastLock uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("acquireMulticastLock uid=%").c(Binder.getCallingUid()).flush();
         mWifiMulticastLockManager.acquireLock(binder, tag);
     }
 
     @Override
     public void releaseMulticastLock() {
         enforceMulticastChangePermission();
-        mLog.trace("releaseMulticastLock uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("releaseMulticastLock uid=%").c(Binder.getCallingUid()).flush();
         mWifiMulticastLockManager.releaseLock();
     }
 
     @Override
     public boolean isMulticastEnabled() {
         enforceAccessPermission();
-        mLog.trace("isMulticastEnabled uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("isMulticastEnabled uid=%").c(Binder.getCallingUid()).flush();
         return mWifiMulticastLockManager.isMulticastEnabled();
     }
 
     @Override
     public void enableVerboseLogging(int verbose) {
         enforceAccessPermission();
-        mLog.trace("enableVerboseLogging uid=% verbose=%")
+        mLog.info("enableVerboseLogging uid=% verbose=%")
                 .c(Binder.getCallingUid())
                 .c(verbose).flush();
         mFacade.setIntegerSetting(
@@ -2398,7 +2403,7 @@
     @Override
     public int getVerboseLoggingLevel() {
         enforceAccessPermission();
-        mLog.trace("getVerboseLoggingLevel uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getVerboseLoggingLevel uid=%").c(Binder.getCallingUid()).flush();
         return mFacade.getIntegerSetting(
                 mContext, Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, 0);
     }
@@ -2406,7 +2411,7 @@
     @Override
     public void enableAggressiveHandover(int enabled) {
         enforceAccessPermission();
-        mLog.trace("enableAggressiveHandover uid=% enabled=%")
+        mLog.info("enableAggressiveHandover uid=% enabled=%")
             .c(Binder.getCallingUid())
             .c(enabled)
             .flush();
@@ -2416,14 +2421,14 @@
     @Override
     public int getAggressiveHandover() {
         enforceAccessPermission();
-        mLog.trace("getAggressiveHandover uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getAggressiveHandover uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.getAggressiveHandover();
     }
 
     @Override
     public void setAllowScansWithTraffic(int enabled) {
         enforceAccessPermission();
-        mLog.trace("setAllowScansWithTraffic uid=% enabled=%")
+        mLog.info("setAllowScansWithTraffic uid=% enabled=%")
                 .c(Binder.getCallingUid())
                 .c(enabled).flush();
         mWifiStateMachine.setAllowScansWithTraffic(enabled);
@@ -2432,14 +2437,14 @@
     @Override
     public int getAllowScansWithTraffic() {
         enforceAccessPermission();
-        mLog.trace("getAllowScansWithTraffic uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getAllowScansWithTraffic uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.getAllowScansWithTraffic();
     }
 
     @Override
     public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
         enforceChangePermission();
-        mLog.trace("setEnableAutoJoinWhenAssociated uid=% enabled=%")
+        mLog.info("setEnableAutoJoinWhenAssociated uid=% enabled=%")
                 .c(Binder.getCallingUid())
                 .c(enabled).flush();
         return mWifiStateMachine.setEnableAutoJoinWhenAssociated(enabled);
@@ -2448,7 +2453,7 @@
     @Override
     public boolean getEnableAutoJoinWhenAssociated() {
         enforceAccessPermission();
-        mLog.trace("getEnableAutoJoinWhenAssociated uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getEnableAutoJoinWhenAssociated uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.getEnableAutoJoinWhenAssociated();
     }
 
@@ -2457,7 +2462,7 @@
     public WifiConnectionStatistics getConnectionStatistics() {
         enforceAccessPermission();
         enforceReadCredentialPermission();
-        mLog.trace("getConnectionStatistics uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getConnectionStatistics uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel != null) {
             return mWifiStateMachine.syncGetConnectionStatistics(mWifiStateMachineChannel);
         } else {
@@ -2469,7 +2474,7 @@
     @Override
     public void factoryReset() {
         enforceConnectivityInternalPermission();
-        mLog.trace("factoryReset uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("factoryReset uid=%").c(Binder.getCallingUid()).flush();
         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
             return;
         }
@@ -2543,7 +2548,7 @@
     @Override
     public Network getCurrentNetwork() {
         enforceAccessPermission();
-        mLog.trace("getCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("getCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
         return mWifiStateMachine.getCurrentNetwork();
     }
 
@@ -2575,9 +2580,9 @@
     @Override
     public void enableWifiConnectivityManager(boolean enabled) {
         enforceConnectivityInternalPermission();
-        mLog.trace("enableWifiConnectivityManager uid=% enabled=%")
-            .c(Binder.getCallingUid())
-            .c(enabled).flush();
+        mLog.info("enableWifiConnectivityManager uid=% enabled=%")
+                .c(Binder.getCallingUid())
+                .c(enabled).flush();
         mWifiStateMachine.enableWifiConnectivityManager(enabled);
     }
 
@@ -2589,7 +2594,7 @@
     @Override
     public byte[] retrieveBackupData() {
         enforceNetworkSettingsPermission();
-        mLog.trace("retrieveBackupData uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("retrieveBackupData uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel == null) {
             Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
             return null;
@@ -2634,7 +2639,7 @@
     @Override
     public void restoreBackupData(byte[] data) {
         enforceNetworkSettingsPermission();
-        mLog.trace("restoreBackupData uid=%").c(Binder.getCallingUid()).flush();
+        mLog.info("restoreBackupData uid=%").c(Binder.getCallingUid()).flush();
         if (mWifiStateMachineChannel == null) {
             Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
             return;
diff --git a/service/java/com/android/server/wifi/WifiStateMachine.java b/service/java/com/android/server/wifi/WifiStateMachine.java
index bf5d08b..1d26f04 100644
--- a/service/java/com/android/server/wifi/WifiStateMachine.java
+++ b/service/java/com/android/server/wifi/WifiStateMachine.java
@@ -31,6 +31,7 @@
 
 import android.Manifest;
 import android.app.ActivityManager;
+import android.app.AppGlobals;
 import android.app.PendingIntent;
 import android.bluetooth.BluetoothAdapter;
 import android.content.BroadcastReceiver;
@@ -82,6 +83,7 @@
 import android.net.wifi.p2p.IWifiP2pManager;
 import android.os.BatteryStats;
 import android.os.Binder;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.INetworkManagementService;
@@ -260,7 +262,7 @@
         if (mVerboseLoggingEnabled) {
             Log.e(TAG, "onRssiThresholdBreach event. Cur Rssi = " + curRssi);
         }
-        sendMessage(CMD_RSSI_THRESHOLD_BREACH, curRssi);
+        sendMessage(CMD_RSSI_THRESHOLD_BREACHED, curRssi);
     }
 
     public void processRssiThreshold(byte curRssi, int reason) {
@@ -278,7 +280,7 @@
                 // the rssi thresholds and raised event to host. This would be eggregious if this
                 // value is invalid
                 mWifiInfo.setRssi(curRssi);
-                updateCapabilities(getCurrentWifiConfiguration());
+                updateCapabilities();
                 int ret = startRssiMonitoringOffload(maxRssi, minRssi);
                 Log.d(TAG, "Re-program RSSI thresholds for " + smToString(reason) +
                         ": [" + minRssi + ", " + maxRssi + "], curRssi=" + curRssi + " ret=" + ret);
@@ -364,7 +366,7 @@
     private final Object mDhcpResultsLock = new Object();
     private DhcpResults mDhcpResults;
 
-    // NOTE: Do not return to clients - use #getWiFiInfoForUid(int)
+    // NOTE: Do not return to clients - see syncRequestConnectionInfo()
     private final WifiInfo mWifiInfo;
     private NetworkInfo mNetworkInfo;
     private final NetworkCapabilities mDfltNetworkCapabilities;
@@ -691,7 +693,7 @@
     static final int CMD_STOP_RSSI_MONITORING_OFFLOAD                   = BASE + 163;
 
     /* used to indicated RSSI threshold breach in hw */
-    static final int CMD_RSSI_THRESHOLD_BREACH                          = BASE + 164;
+    static final int CMD_RSSI_THRESHOLD_BREACHED                        = BASE + 164;
 
     /* Enable/Disable WifiConnectivityManager */
     static final int CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER               = BASE + 166;
@@ -1754,8 +1756,36 @@
      *
      * @return a {@link WifiInfo} object containing information about the current connection
      */
-    public WifiInfo syncRequestConnectionInfo() {
-        return getWiFiInfoForUid(Binder.getCallingUid());
+    public WifiInfo syncRequestConnectionInfo(String callingPackage) {
+        int uid = Binder.getCallingUid();
+        WifiInfo result = new WifiInfo(mWifiInfo);
+        if (uid == Process.myUid()) return result;
+        boolean hideBssidAndSsid = true;
+        result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS);
+
+        IPackageManager packageManager = AppGlobals.getPackageManager();
+
+        try {
+            if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS,
+                    uid) == PackageManager.PERMISSION_GRANTED) {
+                result.setMacAddress(mWifiInfo.getMacAddress());
+            }
+            if (mWifiPermissionsUtil.canAccessScanResults(
+                    callingPackage,
+                    uid,
+                    Build.VERSION_CODES.O)) {
+                hideBssidAndSsid = false;
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error checking receiver permission", e);
+        } catch (SecurityException e) {
+            Log.e(TAG, "Security exception checking receiver permission", e);
+        }
+        if (hideBssidAndSsid) {
+            result.setBSSID(WifiInfo.DEFAULT_MAC_ADDRESS);
+            result.setSSID(WifiSsid.createFromHex(null));
+        }
+        return result;
     }
 
     public WifiInfo getWifiInfo() {
@@ -2719,7 +2749,7 @@
                 break;
             case CMD_START_RSSI_MONITORING_OFFLOAD:
             case CMD_STOP_RSSI_MONITORING_OFFLOAD:
-            case CMD_RSSI_THRESHOLD_BREACH:
+            case CMD_RSSI_THRESHOLD_BREACHED:
                 sb.append(" rssi=");
                 sb.append(Integer.toString(msg.arg1));
                 sb.append(" thresholds=");
@@ -2980,13 +3010,13 @@
              */
             int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS);
             if (newSignalLevel != mLastSignalLevel) {
-                updateCapabilities(getCurrentWifiConfiguration());
+                updateCapabilities();
                 sendRssiChangeBroadcast(newRssi);
             }
             mLastSignalLevel = newSignalLevel;
         } else {
             mWifiInfo.setRssi(WifiInfo.INVALID_RSSI);
-            updateCapabilities(getCurrentWifiConfiguration());
+            updateCapabilities();
         }
 
         if (newLinkSpeed != null) {
@@ -3142,29 +3172,6 @@
         mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
     }
 
-    private WifiInfo getWiFiInfoForUid(int uid) {
-        WifiInfo result = new WifiInfo(mWifiInfo);
-        if (Binder.getCallingUid() == Process.myUid()) {
-            return result;
-        }
-
-        result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS);
-
-        IBinder binder = mFacade.getService("package");
-        IPackageManager packageManager = IPackageManager.Stub.asInterface(binder);
-
-        try {
-            if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS,
-                    uid) == PackageManager.PERMISSION_GRANTED) {
-                result.setMacAddress(mWifiInfo.getMacAddress());
-            }
-        } catch (RemoteException e) {
-            Log.e(TAG, "Error checking receiver permission", e);
-        }
-
-        return result;
-    }
-
     private void sendLinkConfigurationChangedBroadcast() {
         Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
@@ -3260,12 +3267,13 @@
         }
 
         mWifiInfo.setBSSID(stateChangeResult.BSSID);
-
         mWifiInfo.setSSID(stateChangeResult.wifiSsid);
-        WifiConfiguration config = getCurrentWifiConfiguration();
+
+        final WifiConfiguration config = getCurrentWifiConfiguration();
         if (config != null) {
-            // Set meteredHint to true if the access network type of the connecting/connected AP
-            // is a chargeable public network.
+            mWifiInfo.setEphemeral(config.ephemeral);
+
+            // Set meteredHint if scan result says network is expensive
             ScanDetailCache scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(
                     config.networkId);
             if (scanDetailCache != null) {
@@ -3279,15 +3287,9 @@
                     }
                 }
             }
-
-            mWifiInfo.setEphemeral(config.ephemeral);
-            if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set.
-                mWifiInfo.setMeteredHint(config.meteredHint);
-            }
         }
 
         mSupplicantStateTracker.sendMessage(Message.obtain(message));
-
         return state;
     }
 
@@ -3478,11 +3480,20 @@
                         mWifiInfo + " got: " + addr);
             }
         }
+
         mWifiInfo.setInetAddress(addr);
-        if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set.
-            mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint());
-            updateCapabilities(getCurrentWifiConfiguration());
+
+        final WifiConfiguration config = getCurrentWifiConfiguration();
+        if (config != null) {
+            mWifiInfo.setEphemeral(config.ephemeral);
         }
+
+        // Set meteredHint if DHCP result says network is metered
+        if (dhcpResults.hasMeteredHint()) {
+            mWifiInfo.setMeteredHint(true);
+        }
+
+        updateCapabilities(config);
     }
 
     private void handleSuccessfulIpConfiguration() {
@@ -4854,7 +4865,7 @@
             return null;
         }
 
-        return scanDetailCache.get(BSSID);
+        return scanDetailCache.getScanResult(BSSID);
     }
 
     String getCurrentBSSID() {
@@ -4944,8 +4955,10 @@
                     mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId,
                             WifiConfiguration.NetworkSelectionStatus
                             .DISABLED_ASSOCIATION_REJECTION);
+                    mWifiConfigManager.setRecentFailureAssociationStatus(mTargetNetworkId,
+                            reasonCode);
                     mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT);
-                    //If rejection occurred while Metrics is tracking a ConnnectionEvent, end it.
+                    // If rejection occurred while Metrics is tracking a ConnnectionEvent, end it.
                     reportConnectionAttemptEnd(
                             WifiMetrics.ConnectionEvent.FAILURE_ASSOCIATION_REJECTION,
                             WifiMetricsProto.ConnectionEvent.HLF_NONE);
@@ -4973,6 +4986,7 @@
                     }
                     mWifiConfigManager.updateNetworkSelectionStatus(
                             mTargetNetworkId, disableReason);
+                    mWifiConfigManager.clearRecentFailureReason(mTargetNetworkId);
                     //If failure occurred while Metrics is tracking a ConnnectionEvent, end it.
                     reportConnectionAttemptEnd(
                             WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE,
@@ -5392,6 +5406,7 @@
                 case WifiMonitor.NETWORK_CONNECTION_EVENT:
                     if (mVerboseLoggingEnabled) log("Network connection established");
                     mLastNetworkId = lookupFrameworkNetworkId(message.arg1);
+                    mWifiConfigManager.clearRecentFailureReason(mLastNetworkId);
                     mLastBssid = (String) message.obj;
                     reasonCode = message.arg2;
                     // TODO: This check should not be needed after WifiStateMachinePrime refactor.
@@ -5408,7 +5423,7 @@
                         ScanDetailCache scanDetailCache =
                                 mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId);
                         if (scanDetailCache != null && mLastBssid != null) {
-                            ScanResult scanResult = scanDetailCache.get(mLastBssid);
+                            ScanResult scanResult = scanDetailCache.getScanResult(mLastBssid);
                             if (scanResult != null) {
                                 mWifiInfo.setFrequency(scanResult.frequency);
                             }
@@ -5496,28 +5511,34 @@
         }
     }
 
+    public void updateCapabilities() {
+        updateCapabilities(getCurrentWifiConfiguration());
+    }
+
     private void updateCapabilities(WifiConfiguration config) {
-        NetworkCapabilities networkCapabilities = new NetworkCapabilities(mDfltNetworkCapabilities);
-        if (config != null) {
-            if (config.ephemeral) {
-                networkCapabilities.removeCapability(
-                        NetworkCapabilities.NET_CAPABILITY_TRUSTED);
-            } else {
-                networkCapabilities.addCapability(
-                        NetworkCapabilities.NET_CAPABILITY_TRUSTED);
-            }
+        final NetworkCapabilities result = new NetworkCapabilities(mDfltNetworkCapabilities);
 
-            networkCapabilities.setSignalStrength(
-                    (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI)
-                    ? mWifiInfo.getRssi()
-                    : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED);
+        if (mWifiInfo != null && !mWifiInfo.isEphemeral()) {
+            result.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
+        } else {
+            result.removeCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
         }
 
-        if (mWifiInfo.getMeteredHint()) {
-            networkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
+        if (mWifiInfo != null && !WifiConfiguration.isMetered(config, mWifiInfo)) {
+            result.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
+        } else {
+            result.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
         }
 
-        mNetworkAgent.sendNetworkCapabilities(networkCapabilities);
+        if (mWifiInfo != null && mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI) {
+            result.setSignalStrength(mWifiInfo.getRssi());
+        } else {
+            result.setSignalStrength(NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED);
+        }
+
+        if (mNetworkAgent != null) {
+            mNetworkAgent.sendNetworkCapabilities(result);
+        }
     }
 
     /**
@@ -5961,7 +5982,7 @@
                             ScanDetailCache scanDetailCache = mWifiConfigManager
                                     .getScanDetailCacheForNetwork(config.networkId);
                             if (scanDetailCache != null) {
-                                ScanResult scanResult = scanDetailCache.get(mLastBssid);
+                                ScanResult scanResult = scanDetailCache.getScanResult(mLastBssid);
                                 if (scanResult != null) {
                                     mWifiInfo.setFrequency(scanResult.frequency);
                                 }
@@ -5971,7 +5992,7 @@
                     }
                     break;
                 case CMD_START_RSSI_MONITORING_OFFLOAD:
-                case CMD_RSSI_THRESHOLD_BREACH:
+                case CMD_RSSI_THRESHOLD_BREACHED:
                     byte currRssi = (byte) message.arg1;
                     processRssiThreshold(currRssi, message.what);
                     break;
@@ -6132,7 +6153,9 @@
                 if (mVerboseLoggingEnabled) {
                     log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected);
                 }
-                mNetworkAgent.explicitlySelected(config.noInternetAccessExpected);
+                if (mNetworkAgent != null) {
+                    mNetworkAgent.explicitlySelected(config.noInternetAccessExpected);
+                }
             }
         }
 
@@ -6504,13 +6527,17 @@
                         dstMac = NativeUtil.macAddressToByteArray(dstMacStr);
                     } catch (NullPointerException | IllegalArgumentException e) {
                         loge("Can't find MAC address for next hop to " + pkt.dstAddress);
-                        mNetworkAgent.onPacketKeepaliveEvent(slot,
-                                ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS);
+                        if (mNetworkAgent != null) {
+                            mNetworkAgent.onPacketKeepaliveEvent(slot,
+                                    ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS);
+                        }
                         break;
                     }
                     pkt.dstMac = dstMac;
                     int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds);
-                    mNetworkAgent.onPacketKeepaliveEvent(slot, result);
+                    if (mNetworkAgent != null) {
+                        mNetworkAgent.onPacketKeepaliveEvent(slot, result);
+                    }
                     break;
                 }
                 default:
@@ -6763,7 +6790,11 @@
                     // Ignore intermediate success, wait for full connection
                     break;
                 case WifiMonitor.NETWORK_CONNECTION_EVENT:
-                    if (loadNetworksFromSupplicantAfterWps()) {
+                    Pair<Boolean, Integer> loadResult = loadNetworksFromSupplicantAfterWps();
+                    boolean success = loadResult.first;
+                    int netId = loadResult.second;
+                    if (success) {
+                        message.arg1 = netId;
                         replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED);
                     } else {
                         replyToMessage(mSourceMessage, WifiManager.WPS_FAILED,
@@ -6859,13 +6890,17 @@
 
         /**
          * Load network config from wpa_supplicant after WPS is complete.
+         * @return a boolean (true if load was successful) and integer (Network Id of currently
+         *          connected network, can be {@link WifiConfiguration#INVALID_NETWORK_ID} despite
+         *          successful loading, if multiple networks in supplicant) pair.
          */
-        private boolean loadNetworksFromSupplicantAfterWps() {
+        private Pair<Boolean, Integer> loadNetworksFromSupplicantAfterWps() {
             Map<String, WifiConfiguration> configs = new HashMap<>();
             SparseArray<Map<String, String>> extras = new SparseArray<>();
+            int netId = WifiConfiguration.INVALID_NETWORK_ID;
             if (!mWifiNative.migrateNetworksFromSupplicant(configs, extras)) {
                 loge("Failed to load networks from wpa_supplicant after Wps");
-                return false;
+                return Pair.create(false, WifiConfiguration.INVALID_NETWORK_ID);
             }
             for (Map.Entry<String, WifiConfiguration> entry : configs.entrySet()) {
                 WifiConfiguration config = entry.getValue();
@@ -6876,15 +6911,17 @@
                         config, mSourceMessage.sendingUid);
                 if (!result.isSuccess()) {
                     loge("Failed to add network after WPS: " + entry.getValue());
-                    return false;
+                    return Pair.create(false, WifiConfiguration.INVALID_NETWORK_ID);
                 }
                 if (!mWifiConfigManager.enableNetwork(
                         result.getNetworkId(), true, mSourceMessage.sendingUid)) {
-                    loge("Failed to enable network after WPS: " + entry.getValue());
-                    return false;
+                    Log.wtf(TAG, "Failed to enable network after WPS: " + entry.getValue());
+                    return Pair.create(false, WifiConfiguration.INVALID_NETWORK_ID);
                 }
+                netId = result.getNetworkId();
             }
-            return true;
+            return Pair.create(true,
+                    configs.size() == 1 ? netId : WifiConfiguration.INVALID_NETWORK_ID);
         }
     }
 
diff --git a/service/java/com/android/server/wifi/WificondControl.java b/service/java/com/android/server/wifi/WificondControl.java
index a877c09..056777f 100644
--- a/service/java/com/android/server/wifi/WificondControl.java
+++ b/service/java/com/android/server/wifi/WificondControl.java
@@ -32,6 +32,7 @@
 import com.android.server.wifi.hotspot2.NetworkDetail;
 import com.android.server.wifi.util.InformationElementUtil;
 import com.android.server.wifi.util.NativeUtil;
+import com.android.server.wifi.util.ScanResultUtil;
 import com.android.server.wifi.wificond.ChannelSettings;
 import com.android.server.wifi.wificond.HiddenNetwork;
 import com.android.server.wifi.wificond.NativeScanResult;
@@ -50,8 +51,16 @@
     private boolean mVerboseLoggingEnabled = false;
 
     private static final String TAG = "WificondControl";
+
+    /* Get scan results for a single scan */
+    public static final int SCAN_TYPE_SINGLE_SCAN = 0;
+
+    /* Get scan results for Pno Scan */
+    public static final int SCAN_TYPE_PNO_SCAN = 1;
+
     private WifiInjector mWifiInjector;
     private WifiMonitor mWifiMonitor;
+    private final CarrierNetworkConfig mCarrierNetworkConfig;
 
     // Cached wificond binder handlers.
     private IWificond mWificond;
@@ -78,9 +87,11 @@
         }
     }
 
-    WificondControl(WifiInjector wifiInjector, WifiMonitor wifiMonitor) {
+    WificondControl(WifiInjector wifiInjector, WifiMonitor wifiMonitor,
+            CarrierNetworkConfig carrierNetworkConfig) {
         mWifiInjector = wifiInjector;
         mWifiMonitor = wifiMonitor;
+        mCarrierNetworkConfig = carrierNetworkConfig;
     }
 
     private class PnoScanEventHandler extends IPnoScanEvent.Stub {
@@ -88,12 +99,25 @@
         public void OnPnoNetworkFound() {
             Log.d(TAG, "Pno scan result event");
             mWifiMonitor.broadcastPnoScanResultEvent(mClientInterfaceName);
+            mWifiInjector.getWifiMetrics().incrementPnoFoundNetworkEventCount();
         }
 
         @Override
         public void OnPnoScanFailed() {
             Log.d(TAG, "Pno Scan failed event");
-            // Nothing to do for now.
+            mWifiInjector.getWifiMetrics().incrementPnoScanFailedCount();
+        }
+
+        @Override
+        public void OnPnoScanOverOffloadStarted() {
+            Log.d(TAG, "Pno scan over offload started");
+            mWifiInjector.getWifiMetrics().incrementPnoScanStartedOverOffloadCount();
+        }
+
+        @Override
+        public void OnPnoScanOverOffloadFailed(int reason) {
+            Log.d(TAG, "Pno scan over offload failed");
+            mWifiInjector.getWifiMetrics().incrementPnoScanFailedOverOffloadCount();
         }
     }
 
@@ -318,14 +342,19 @@
     * @return Returns an ArrayList of ScanDetail.
     * Returns an empty ArrayList on failure.
     */
-    public ArrayList<ScanDetail> getScanResults() {
+    public ArrayList<ScanDetail> getScanResults(int scanType) {
         ArrayList<ScanDetail> results = new ArrayList<>();
         if (mWificondScanner == null) {
             Log.e(TAG, "No valid wificond scanner interface handler");
             return results;
         }
         try {
-            NativeScanResult[] nativeResults = mWificondScanner.getScanResults();
+            NativeScanResult[] nativeResults;
+            if (scanType == SCAN_TYPE_SINGLE_SCAN) {
+                nativeResults = mWificondScanner.getScanResults();
+            } else {
+                nativeResults = mWificondScanner.getPnoScanResults();
+            }
             for (NativeScanResult result : nativeResults) {
                 WifiSsid wifiSsid = WifiSsid.createFromByteArray(result.ssid);
                 String bssid;
@@ -348,12 +377,18 @@
                 NetworkDetail networkDetail =
                         new NetworkDetail(bssid, ies, null, result.frequency);
 
-                if (!wifiSsid.toString().equals(networkDetail.getTrimmedSSID())) {
-                    Log.e(TAG, "Inconsistent SSID on BSSID: " + bssid);
-                    continue;
-                }
                 ScanDetail scanDetail = new ScanDetail(networkDetail, wifiSsid, bssid, flags,
                         result.signalMbm / 100, result.frequency, result.tsf, ies, null);
+                // Update carrier network info if this AP's SSID is associated with a carrier Wi-Fi
+                // network and it uses EAP.
+                if (ScanResultUtil.isScanResultForEapNetwork(scanDetail.getScanResult())
+                        && mCarrierNetworkConfig.isCarrierNetwork(wifiSsid.toString())) {
+                    scanDetail.getScanResult().isCarrierAp = true;
+                    scanDetail.getScanResult().carrierApEapType =
+                            mCarrierNetworkConfig.getNetworkEapType(wifiSsid.toString());
+                    scanDetail.getScanResult().carrierName =
+                            mCarrierNetworkConfig.getCarrierName(wifiSsid.toString());
+                }
                 results.add(scanDetail);
             }
         } catch (RemoteException e1) {
@@ -441,9 +476,14 @@
         }
 
         try {
-            return mWificondScanner.startPnoScan(settings);
+            boolean success = mWificondScanner.startPnoScan(settings);
+            mWifiInjector.getWifiMetrics().incrementPnoScanStartAttempCount();
+            if (!success) {
+                mWifiInjector.getWifiMetrics().incrementPnoScanFailedCount();
+            }
+            return success;
         } catch (RemoteException e1) {
-            Log.e(TAG, "Failed to stop pno scan due to remote exception");
+            Log.e(TAG, "Failed to start pno scan due to remote exception");
         }
         return false;
     }
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareDataPathStateManager.java b/service/java/com/android/server/wifi/aware/WifiAwareDataPathStateManager.java
index 04bf2e0..16888c8 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareDataPathStateManager.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareDataPathStateManager.java
@@ -33,6 +33,7 @@
 import android.net.NetworkRequest;
 import android.net.NetworkSpecifier;
 import android.net.RouteInfo;
+import android.net.wifi.aware.WifiAwareAgentNetworkSpecifier;
 import android.net.wifi.aware.WifiAwareManager;
 import android.net.wifi.aware.WifiAwareNetworkSpecifier;
 import android.net.wifi.aware.WifiAwareUtils;
@@ -61,6 +62,7 @@
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -85,8 +87,8 @@
     private static final int NETWORK_FACTORY_SIGNAL_STRENGTH_AVAIL = 1;
 
     private final WifiAwareStateManager mMgr;
-    private final NetworkInterfaceWrapper mNiWrapper = new NetworkInterfaceWrapper();
-    private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities();
+    public NetworkInterfaceWrapper mNiWrapper = new NetworkInterfaceWrapper();
+    private static final NetworkCapabilities sNetworkCapabilitiesFilter = new NetworkCapabilities();
     private final Set<String> mInterfaces = new HashSet<>();
     private final Map<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
             mNetworkRequestsCache = new ArrayMap<>();
@@ -95,7 +97,7 @@
     private WifiPermissionsWrapper mPermissionsWrapper;
     private Looper mLooper;
     private WifiAwareNetworkFactory mNetworkFactory;
-    private INetworkManagementService mNwService;
+    public INetworkManagementService mNwService;
 
     public WifiAwareDataPathStateManager(WifiAwareStateManager mgr) {
         mMgr = mgr;
@@ -114,19 +116,19 @@
         mPermissionsWrapper = permissionsWrapper;
         mLooper = looper;
 
-        mNetworkCapabilitiesFilter.clearAll();
-        mNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE);
-        mNetworkCapabilitiesFilter
+        sNetworkCapabilitiesFilter.clearAll();
+        sNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE);
+        sNetworkCapabilitiesFilter
                 .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
                 .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
                 .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
                 .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
-        mNetworkCapabilitiesFilter.setNetworkSpecifier(new MatchAllNetworkSpecifier());
-        mNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
-        mNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
-        mNetworkCapabilitiesFilter.setSignalStrength(NETWORK_FACTORY_SIGNAL_STRENGTH_AVAIL);
+        sNetworkCapabilitiesFilter.setNetworkSpecifier(new MatchAllNetworkSpecifier());
+        sNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
+        sNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
+        sNetworkCapabilitiesFilter.setSignalStrength(NETWORK_FACTORY_SIGNAL_STRENGTH_AVAIL);
 
-        mNetworkFactory = new WifiAwareNetworkFactory(looper, context, mNetworkCapabilitiesFilter);
+        mNetworkFactory = new WifiAwareNetworkFactory(looper, context, sNetworkCapabilitiesFilter);
         mNetworkFactory.setScoreFilter(NETWORK_FACTORY_SCORE_AVAIL);
         mNetworkFactory.register();
 
@@ -146,6 +148,18 @@
         return null;
     }
 
+    private Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
+                getNetworkRequestByCanonicalDescriptor(CanonicalConnectionInfo cci) {
+        for (Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> entry :
+                mNetworkRequestsCache.entrySet()) {
+            if (entry.getValue().getCanonicalDescriptor().equals(cci)) {
+                return entry;
+            }
+        }
+
+        return null;
+    }
+
     /**
      * Create all Aware data-path interfaces which are possible on the device - based on the
      * capabilities of the firmware.
@@ -247,7 +261,7 @@
             return;
         }
 
-        nnri.state = AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_CONFIRM;
+        nnri.state = AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM;
         nnri.ndpId = ndpId;
     }
 
@@ -411,7 +425,7 @@
             return;
         }
 
-        nnri.state = AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_CONFIRM;
+        nnri.state = AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM;
     }
 
     /**
@@ -452,18 +466,8 @@
         AwareNetworkRequestInformation nnri = nnriE.getValue();
 
         // validate state
-        if (nnri.networkSpecifier.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
-                && nnri.state != AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_CONFIRM) {
-            Log.w(TAG, "onDataPathConfirm: INITIATOR in invalid state=" + nnri.state);
-            mNetworkRequestsCache.remove(networkSpecifier);
-            if (accept) {
-                mMgr.endDataPath(ndpId);
-            }
-            return networkSpecifier;
-        }
-        if (nnri.networkSpecifier.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER
-                && nnri.state != AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_CONFIRM) {
-            Log.w(TAG, "onDataPathConfirm: RESPONDER in invalid state=" + nnri.state);
+        if (nnri.state != AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM) {
+            Log.w(TAG, "onDataPathConfirm: invalid state=" + nnri.state);
             mNetworkRequestsCache.remove(networkSpecifier);
             if (accept) {
                 mMgr.endDataPath(ndpId);
@@ -472,38 +476,45 @@
         }
 
         if (accept) {
-            nnri.state = (nnri.networkSpecifier.role
-                    == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR)
-                    ? AwareNetworkRequestInformation.STATE_INITIATOR_CONFIRMED
-                    : AwareNetworkRequestInformation.STATE_RESPONDER_CONFIRMED;
+            nnri.state = AwareNetworkRequestInformation.STATE_CONFIRMED;
             nnri.peerDataMac = mac;
 
-            NetworkInfo networkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0,
+            NetworkInfo networkInfo = new NetworkInfo(ConnectivityManager.TYPE_NONE, 0,
                     NETWORK_TAG, "");
             NetworkCapabilities networkCapabilities = new NetworkCapabilities(
-                    mNetworkCapabilitiesFilter);
+                    sNetworkCapabilitiesFilter);
             LinkProperties linkProperties = new LinkProperties();
 
-            try {
-                mNwService.setInterfaceUp(nnri.interfaceName);
-                mNwService.enableIpv6(nnri.interfaceName);
-            } catch (Exception e) { // NwService throws runtime exceptions for errors
-                Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri + ": can't configure network - "
-                        + e);
-                mMgr.endDataPath(ndpId);
-                return networkSpecifier;
+            boolean interfaceUsedByAnotherNdp = isInterfaceUpAndUsedByAnotherNdp(nnri);
+            if (!interfaceUsedByAnotherNdp) {
+                try {
+                    mNwService.setInterfaceUp(nnri.interfaceName);
+                    mNwService.enableIpv6(nnri.interfaceName);
+                } catch (Exception e) { // NwService throws runtime exceptions for errors
+                    Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
+                            + ": can't configure network - "
+                            + e);
+                    mMgr.endDataPath(ndpId);
+                    nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
+                    return networkSpecifier;
+                }
+            } else {
+                if (VDBG) {
+                    Log.v(TAG, "onDataPathConfirm: interface already configured: "
+                            + nnri.interfaceName);
+                }
             }
 
-            if (!mNiWrapper.configureAgentProperties(nnri, networkSpecifier, ndpId, networkInfo,
-                    networkCapabilities, linkProperties)) {
+            if (!mNiWrapper.configureAgentProperties(nnri, nnri.equivalentSpecifiers, ndpId,
+                    networkInfo, networkCapabilities, linkProperties)) {
                 return networkSpecifier;
             }
 
             nnri.networkAgent = new WifiAwareNetworkAgent(mLooper, mContext,
                     AGENT_TAG_PREFIX + nnri.ndpId,
-                    new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, NETWORK_TAG, ""),
+                    new NetworkInfo(ConnectivityManager.TYPE_NONE, 0, NETWORK_TAG, ""),
                     networkCapabilities, linkProperties, NETWORK_FACTORY_SCORE_AVAIL,
-                    networkSpecifier, ndpId);
+                    nnri);
             nnri.networkAgent.sendNetworkInfo(networkInfo);
 
             mAwareMetrics.recordNdpStatus(NanStatusType.SUCCESS, networkSpecifier.isOutOfBand(),
@@ -541,13 +552,14 @@
             return;
         }
 
-        tearDownInterface(nnriE.getValue());
-        if (nnriE.getValue().state == AwareNetworkRequestInformation.STATE_RESPONDER_CONFIRMED
-                || nnriE.getValue().state
-                == AwareNetworkRequestInformation.STATE_INITIATOR_CONFIRMED) {
+        tearDownInterfaceIfPossible(nnriE.getValue());
+        if (nnriE.getValue().state == AwareNetworkRequestInformation.STATE_CONFIRMED
+                || nnriE.getValue().state == AwareNetworkRequestInformation.STATE_TERMINATING) {
             mAwareMetrics.recordNdpSessionDuration(nnriE.getValue().startTimestamp);
         }
         mNetworkRequestsCache.remove(nnriE.getKey());
+
+        mNetworkFactory.tickleConnectivityIfWaiting();
     }
 
     /**
@@ -557,7 +569,7 @@
         if (VDBG) Log.v(TAG, "onAwareDownCleanupDataPaths");
 
         for (AwareNetworkRequestInformation nnri : mNetworkRequestsCache.values()) {
-            tearDownInterface(nnri);
+            tearDownInterfaceIfPossible(nnri);
         }
         mNetworkRequestsCache.clear();
     }
@@ -584,13 +596,26 @@
                 nnri.networkSpecifier.isOutOfBand(), nnri.startTimestamp);
 
         mMgr.endDataPath(nnri.ndpId);
+        nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
     }
 
     private class WifiAwareNetworkFactory extends NetworkFactory {
+        // Request received while waiting for confirmation that a canonically identical data-path
+        // (NDP) is in the process of being terminated
+        private boolean mWaitingForTermination = false;
+
         WifiAwareNetworkFactory(Looper looper, Context context, NetworkCapabilities filter) {
             super(looper, context, NETWORK_TAG, filter);
         }
 
+        public void tickleConnectivityIfWaiting() {
+            if (mWaitingForTermination) {
+                if (VDBG) Log.v(TAG, "tickleConnectivityIfWaiting: was waiting!");
+                mWaitingForTermination = false;
+                reevaluateAllRequests();
+            }
+        }
+
         @Override
         public boolean acceptRequest(NetworkRequest request, int score) {
             if (VDBG) {
@@ -628,7 +653,12 @@
             if (nnri != null) {
                 if (DBG) {
                     Log.d(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
-                            + " - already in cache!?");
+                            + " - already in cache with state=" + nnri.state);
+                }
+
+                if (nnri.state == AwareNetworkRequestInformation.STATE_TERMINATING) {
+                    mWaitingForTermination = true;
+                    return false;
                 }
 
                 // seems to happen after a network agent is created - trying to rematch all
@@ -644,10 +674,22 @@
                 return false;
             }
 
-            // TODO (b/63635780) support more then a single concurrent NDP
-            if (mNetworkRequestsCache.size() > 0) {
-                Log.e(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
-                        + " - >1 concurrent NDPs aren't supported (yet).");
+            // check to see if a canonical version exists
+            Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> primaryRequest =
+                    getNetworkRequestByCanonicalDescriptor(nnri.getCanonicalDescriptor());
+            if (primaryRequest != null) {
+                if (VDBG) {
+                    Log.v(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
+                            + ", already has a primary request=" + primaryRequest.getKey()
+                            + " with state=" + primaryRequest.getValue().state);
+                }
+
+                if (primaryRequest.getValue().state
+                        == AwareNetworkRequestInformation.STATE_TERMINATING) {
+                    mWaitingForTermination = true;
+                } else {
+                    primaryRequest.getValue().updateToSupportNewRequest(networkSpecifier);
+                }
                 return false;
             }
 
@@ -676,18 +718,17 @@
                 return;
             }
 
+            if (nnri.state != AwareNetworkRequestInformation.STATE_IDLE) {
+                if (DBG) {
+                    Log.d(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
+                            + networkRequest + " - already in progress");
+                    // TODO: understand how/when can be called again/while in progress (seems
+                    // to be related to score re-calculation after a network agent is created)
+                }
+                return;
+            }
             if (nnri.networkSpecifier.role
                     == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR) {
-                if (nnri.state != AwareNetworkRequestInformation.STATE_INITIATOR_IDLE) {
-                    if (DBG) {
-                        Log.d(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
-                                + networkRequest + " - already in progress");
-                        // TODO: understand how/when can be called again/while in progress (seems
-                        // to be related to score re-calculation after a network agent is created)
-                    }
-                    return;
-                }
-
                 nnri.interfaceName = selectInterfaceForRequest(nnri);
                 if (nnri.interfaceName == null) {
                     Log.w(TAG, "needNetworkFor: request " + networkSpecifier
@@ -704,16 +745,6 @@
                         AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE;
                 nnri.startTimestamp = SystemClock.elapsedRealtime();
             } else {
-                if (nnri.state != AwareNetworkRequestInformation.STATE_RESPONDER_IDLE) {
-                    if (DBG) {
-                        Log.d(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
-                                + networkRequest + " - already in progress");
-                        // TODO: understand how/when can be called again/while in progress (seems
-                        // to be related to score re-calculation after a network agent is created)
-                    }
-                    return;
-                }
-
                 nnri.state = AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_REQUEST;
             }
         }
@@ -749,45 +780,52 @@
                 return;
             }
 
-            if (nnri.networkSpecifier.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
-                    && nnri.state
-                    > AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE) {
-                mMgr.endDataPath(nnri.ndpId);
+            /*
+             * Since there's no agent it means we're in the process of setting up the NDP.
+             * However, it is possible that there were other equivalent requests for this NDP. We
+             * should keep going in that case.
+             */
+            nnri.removeSupportForRequest(networkSpecifier);
+            if (nnri.equivalentSpecifiers.isEmpty()) {
+                if (VDBG) {
+                    Log.v(TAG, "releaseNetworkFor: there are no further requests, networkRequest="
+                            + networkRequest);
+                }
+                if (nnri.ndpId != 0) { // 0 is never a valid ID!
+                    if (VDBG) Log.v(TAG, "releaseNetworkFor: in progress NDP being terminated");
+                    mMgr.endDataPath(nnri.ndpId);
+                    nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
+                }
+            } else {
+                if (VDBG) {
+                    Log.v(TAG, "releaseNetworkFor: equivalent requests exist - not terminating "
+                            + "networkRequest=" + networkRequest);
+                }
             }
-            if (nnri.networkSpecifier.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER
-                    && nnri.state
-                    > AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_REQUEST) {
-                mMgr.endDataPath(nnri.ndpId);
-            }
-
-            // Will get a callback (on both initiator and responder) when data-path actually
-            // terminated. At that point will inform the agent and will clear the cache.
         }
     }
 
     private class WifiAwareNetworkAgent extends NetworkAgent {
         private NetworkInfo mNetworkInfo;
-        private WifiAwareNetworkSpecifier mNetworkSpecifier;
-        private int mNdpId;
+        private AwareNetworkRequestInformation mAwareNetworkRequestInfo;
 
         WifiAwareNetworkAgent(Looper looper, Context context, String logTag, NetworkInfo ni,
                 NetworkCapabilities nc, LinkProperties lp, int score,
-                WifiAwareNetworkSpecifier networkSpecifier, int ndpId) {
+                AwareNetworkRequestInformation anri) {
             super(looper, context, logTag, ni, nc, lp, score);
 
             mNetworkInfo = ni;
-            mNetworkSpecifier = networkSpecifier;
-            mNdpId = ndpId;
+            mAwareNetworkRequestInfo = anri;
         }
 
         @Override
         protected void unwanted() {
             if (VDBG) {
-                Log.v(TAG, "WifiAwareNetworkAgent.unwanted: networkSpecifier=" + mNetworkSpecifier
-                        + ", ndpId=" + mNdpId);
+                Log.v(TAG, "WifiAwareNetworkAgent.unwanted: request=" + mAwareNetworkRequestInfo);
             }
 
-            mMgr.endDataPath(mNdpId);
+            mMgr.endDataPath(mAwareNetworkRequestInfo.ndpId);
+            mAwareNetworkRequestInfo.state = AwareNetworkRequestInformation.STATE_TERMINATING;
 
             // Will get a callback (on both initiator and responder) when data-path actually
             // terminated. At that point will inform the agent and will clear the cache.
@@ -795,8 +833,8 @@
 
         void reconfigureAgentAsDisconnected() {
             if (VDBG) {
-                Log.v(TAG, "WifiAwareNetworkAgent.reconfigureAgentAsDisconnected: networkSpecifier="
-                        + mNetworkSpecifier + ", ndpId=" + mNdpId);
+                Log.v(TAG, "WifiAwareNetworkAgent.reconfigureAgentAsDisconnected: request="
+                        + mAwareNetworkRequestInfo);
             }
 
             mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, "");
@@ -804,15 +842,23 @@
         }
     }
 
-    private void tearDownInterface(AwareNetworkRequestInformation nnri) {
-        if (VDBG) Log.v(TAG, "tearDownInterface: nnri=" + nnri);
+    private void tearDownInterfaceIfPossible(AwareNetworkRequestInformation nnri) {
+        if (VDBG) Log.v(TAG, "tearDownInterfaceIfPossible: nnri=" + nnri);
 
-        if (nnri.interfaceName != null && !nnri.interfaceName.isEmpty()) {
-            try {
-                mNwService.setInterfaceDown(nnri.interfaceName);
-            } catch (Exception e) { // NwService throws runtime exceptions for errors
-                Log.e(TAG,
-                        "tearDownInterface: nnri=" + nnri + ": can't bring interface down - " + e);
+        if (!TextUtils.isEmpty(nnri.interfaceName)) {
+            boolean interfaceUsedByAnotherNdp = isInterfaceUpAndUsedByAnotherNdp(nnri);
+            if (interfaceUsedByAnotherNdp) {
+                if (VDBG) {
+                    Log.v(TAG, "tearDownInterfaceIfPossible: interfaceName=" + nnri.interfaceName
+                            + ", still in use - not turning down");
+                }
+            } else {
+                try {
+                    mNwService.setInterfaceDown(nnri.interfaceName);
+                } catch (Exception e) { // NwService throws runtime exceptions for errors
+                    Log.e(TAG, "tearDownInterfaceIfPossible: nnri=" + nnri
+                            + ": can't bring interface down - " + e);
+                }
             }
         }
 
@@ -821,6 +867,22 @@
         }
     }
 
+    private boolean isInterfaceUpAndUsedByAnotherNdp(AwareNetworkRequestInformation nri) {
+        for (AwareNetworkRequestInformation lnri : mNetworkRequestsCache.values()) {
+            if (lnri == nri) {
+                continue;
+            }
+
+            if (nri.interfaceName.equals(lnri.interfaceName) && (
+                    lnri.state == AwareNetworkRequestInformation.STATE_CONFIRMED
+                            || lnri.state == AwareNetworkRequestInformation.STATE_TERMINATING)) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
     /**
      * Select one of the existing interfaces for the new network request.
      *
@@ -853,16 +915,13 @@
      */
     @VisibleForTesting
     public static class AwareNetworkRequestInformation {
-        static final int STATE_INITIATOR_IDLE = 100;
-        static final int STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE = 101;
-        static final int STATE_INITIATOR_WAIT_FOR_CONFIRM = 102;
-        static final int STATE_INITIATOR_CONFIRMED = 103;
-
-        static final int STATE_RESPONDER_IDLE = 200;
-        static final int STATE_RESPONDER_WAIT_FOR_REQUEST = 201;
-        static final int STATE_RESPONDER_WAIT_FOR_RESPOND_RESPONSE = 202;
-        static final int STATE_RESPONDER_WAIT_FOR_CONFIRM = 203;
-        static final int STATE_RESPONDER_CONFIRMED = 204;
+        static final int STATE_IDLE = 100;
+        static final int STATE_WAIT_FOR_CONFIRM = 101;
+        static final int STATE_CONFIRMED = 102;
+        static final int STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE = 103;
+        static final int STATE_RESPONDER_WAIT_FOR_REQUEST = 104;
+        static final int STATE_RESPONDER_WAIT_FOR_RESPOND_RESPONSE = 105;
+        static final int STATE_TERMINATING = 106;
 
         public int state;
 
@@ -871,13 +930,55 @@
         public int pubSubId = 0;
         public int peerInstanceId = 0;
         public byte[] peerDiscoveryMac = null;
-        public int ndpId;
+        public int ndpId = 0; // 0 is never a valid ID!
         public byte[] peerDataMac;
         public WifiAwareNetworkSpecifier networkSpecifier;
         public long startTimestamp = 0; // request is made (initiator) / get request (responder)
 
         public WifiAwareNetworkAgent networkAgent;
 
+        /* A collection of specifiers which are equivalent to the current request and are
+         * supported by it's agent. This list DOES include the original (first) network specifier
+         * (which is stored separately above).
+         */
+        public Set<WifiAwareNetworkSpecifier> equivalentSpecifiers = new HashSet<>();
+
+        void updateToSupportNewRequest(WifiAwareNetworkSpecifier ns) {
+            if (VDBG) Log.v(TAG, "updateToSupportNewRequest: ns=" + ns);
+            if (equivalentSpecifiers.add(ns) && state == STATE_CONFIRMED) {
+                if (networkAgent == null) {
+                    Log.wtf(TAG, "updateToSupportNewRequest: null agent in CONFIRMED state!?");
+                    return;
+                }
+
+                networkAgent.sendNetworkCapabilities(getNetworkCapabilities());
+            }
+        }
+
+        void removeSupportForRequest(WifiAwareNetworkSpecifier ns) {
+            if (VDBG) Log.v(TAG, "removeSupportForRequest: ns=" + ns);
+            equivalentSpecifiers.remove(ns);
+
+            // we will not update the agent:
+            // 1. this will only get called before the agent is created
+            // 2. connectivity service does not allow (WTF) updates with reduced capabilities
+        }
+
+        private NetworkCapabilities getNetworkCapabilities() {
+            NetworkCapabilities nc = new NetworkCapabilities(sNetworkCapabilitiesFilter);
+            nc.setNetworkSpecifier(new WifiAwareAgentNetworkSpecifier(equivalentSpecifiers.toArray(
+                    new WifiAwareNetworkSpecifier[equivalentSpecifiers.size()])));
+            return nc;
+        }
+
+        /**
+         * Returns a canonical descriptor for the network request.
+         */
+        CanonicalConnectionInfo getCanonicalDescriptor() {
+            return new CanonicalConnectionInfo(peerDiscoveryMac, networkSpecifier.pmk,
+                    networkSpecifier.sessionId, networkSpecifier.passphrase);
+        }
+
         static AwareNetworkRequestInformation processNetworkSpecifier(WifiAwareNetworkSpecifier ns,
                 WifiAwareStateManager mgr, WifiPermissionsWrapper permissionWrapper) {
             int uid, pubSubId = 0;
@@ -1001,14 +1102,13 @@
 
             // create container and populate
             AwareNetworkRequestInformation nnri = new AwareNetworkRequestInformation();
-            nnri.state = (ns.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR)
-                    ? AwareNetworkRequestInformation.STATE_INITIATOR_IDLE
-                    : AwareNetworkRequestInformation.STATE_RESPONDER_IDLE;
+            nnri.state = AwareNetworkRequestInformation.STATE_IDLE;
             nnri.uid = uid;
             nnri.pubSubId = pubSubId;
             nnri.peerInstanceId = peerInstanceId;
             nnri.peerDiscoveryMac = peerMac;
             nnri.networkSpecifier = ns;
+            nnri.equivalentSpecifiers.add(ns);
 
             return nnri;
         }
@@ -1025,7 +1125,69 @@
                     ", ndpId=").append(ndpId).append(", peerDataMac=").append(
                     peerDataMac == null ? ""
                             : String.valueOf(HexEncoding.encode(peerDataMac))).append(
-                    ", startTimestamp=").append(startTimestamp);
+                    ", startTimestamp=").append(startTimestamp).append(", equivalentSpecifiers=[");
+            for (WifiAwareNetworkSpecifier ns: equivalentSpecifiers) {
+                sb.append(ns.toString()).append(", ");
+            }
+            return sb.append("]").toString();
+        }
+    }
+
+    /**
+     * A canonical (unique) descriptor of the peer connection.
+     */
+    static class CanonicalConnectionInfo {
+        CanonicalConnectionInfo(byte[] peerDiscoveryMac, byte[] pmk, int sessionId,
+                String passphrase) {
+            this.peerDiscoveryMac = peerDiscoveryMac;
+            this.pmk = pmk;
+            this.sessionId = sessionId;
+            this.passphrase = passphrase;
+        }
+
+        public final byte[] peerDiscoveryMac;
+
+        /*
+         * Security configuration matching:
+         * - open: pmk/passphrase = null
+         * - pmk: pmk != null, passphrase = null
+         * - passphrase: passphrase != null, sessionId used (==0 for OOB), pmk=null
+         */
+        public final byte[] pmk;
+
+        public final int sessionId;
+        public final String passphrase;
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(Arrays.hashCode(peerDiscoveryMac), Arrays.hashCode(pmk), sessionId,
+                passphrase);
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+
+            if (!(obj instanceof CanonicalConnectionInfo)) {
+                return false;
+            }
+
+            CanonicalConnectionInfo lhs = (CanonicalConnectionInfo) obj;
+
+            return Arrays.equals(peerDiscoveryMac, lhs.peerDiscoveryMac) && Arrays.equals(pmk,
+                    lhs.pmk) && TextUtils.equals(passphrase, lhs.passphrase)
+                    && sessionId == lhs.sessionId;
+        }
+
+        @Override
+        public String toString() {
+            StringBuilder sb = new StringBuilder("CanonicalConnectionInfo: [");
+            sb.append("peerDiscoveryMac=").append(peerDiscoveryMac == null ? ""
+                    : String.valueOf(HexEncoding.encode(peerDiscoveryMac))).append("pmk=").append(
+                    pmk == null ? "" : "*").append("sessionId=").append(sessionId).append(
+                    "passphrase=").append(passphrase == null ? "" : "*").append("]");
             return sb.toString();
         }
     }
@@ -1040,8 +1202,9 @@
          * name. Delegated to enable mocking.
          */
         public boolean configureAgentProperties(AwareNetworkRequestInformation nnri,
-                WifiAwareNetworkSpecifier networkSpecifier, int ndpId, NetworkInfo networkInfo,
-                NetworkCapabilities networkCapabilities, LinkProperties linkProperties) {
+                Set<WifiAwareNetworkSpecifier> networkSpecifiers, int ndpId,
+                NetworkInfo networkInfo, NetworkCapabilities networkCapabilities,
+                LinkProperties linkProperties) {
             // find link-local address
             InetAddress linkLocal = null;
             NetworkInterface ni;
@@ -1051,12 +1214,14 @@
                 Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
                         + ": can't get network interface - " + e);
                 mMgr.endDataPath(ndpId);
+                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                 return false;
             }
             if (ni == null) {
                 Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
                         + ": can't get network interface (null)");
                 mMgr.endDataPath(ndpId);
+                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                 return false;
             }
             Enumeration<InetAddress> addresses = ni.getInetAddresses();
@@ -1071,6 +1236,7 @@
             if (linkLocal == null) {
                 Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri + ": no link local addresses");
                 mMgr.endDataPath(ndpId);
+                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                 return false;
             }
 
@@ -1078,7 +1244,8 @@
             networkInfo.setIsAvailable(true);
             networkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
 
-            networkCapabilities.setNetworkSpecifier(networkSpecifier);
+            networkCapabilities.setNetworkSpecifier(new WifiAwareAgentNetworkSpecifier(
+                    networkSpecifiers.toArray(new WifiAwareNetworkSpecifier[0])));
 
             linkProperties.setInterfaceName(nnri.interfaceName);
             linkProperties.addLinkAddress(new LinkAddress(linkLocal, 64));
@@ -1095,7 +1262,7 @@
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.println("WifiAwareDataPathStateManager:");
         pw.println("  mInterfaces: " + mInterfaces);
-        pw.println("  mNetworkCapabilitiesFilter: " + mNetworkCapabilitiesFilter);
+        pw.println("  sNetworkCapabilitiesFilter: " + sNetworkCapabilitiesFilter);
         pw.println("  mNetworkRequestsCache: " + mNetworkRequestsCache);
         pw.println("  mNetworkFactory:");
         mNetworkFactory.dump(fd, pw, args);
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareMetrics.java b/service/java/com/android/server/wifi/aware/WifiAwareMetrics.java
index 02eaf5d..c45c6dc 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareMetrics.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareMetrics.java
@@ -320,10 +320,7 @@
                 networkRequestCache.values()) {
             if (anri.state
                     != WifiAwareDataPathStateManager.AwareNetworkRequestInformation
-                    .STATE_INITIATOR_CONFIRMED
-                    && anri.state
-                    != WifiAwareDataPathStateManager.AwareNetworkRequestInformation
-                    .STATE_RESPONDER_CONFIRMED) {
+                    .STATE_CONFIRMED) {
                 continue; // only count completed (up-and-running) NDPs
             }
 
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareNativeCallback.java b/service/java/com/android/server/wifi/aware/WifiAwareNativeCallback.java
index 05721af..2f424db 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareNativeCallback.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareNativeCallback.java
@@ -167,10 +167,9 @@
                     capabilities.maxSubscribeInterfaceAddresses;
             frameworkCapabilities.supportedCipherSuites = capabilities.supportedCipherSuites;
 
-            // TODO (b/63635780, b/63635857): enable framework support of >1 NDI and >1 NDP per NDI
-            // Until then: force corresponding capabilities to 1.
+            // TODO (b/63635857): enable framework support of >1 NDI
+            // Until then: force corresponding capability to 1.
             frameworkCapabilities.maxNdiInterfaces = 1;
-            frameworkCapabilities.maxNdpSessions = 1;
 
             mWifiAwareStateManager.onCapabilitiesUpdateResponse(id, frameworkCapabilities);
         } else {
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareRttStateManager.java b/service/java/com/android/server/wifi/aware/WifiAwareRttStateManager.java
index 74f34b3..9d0441f 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareRttStateManager.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareRttStateManager.java
@@ -50,6 +50,7 @@
 
     private final SparseArray<WifiAwareClientState> mPendingOperations = new SparseArray<>();
     private AsyncChannel mAsyncChannel;
+    private Context mContext;
 
     /**
      * Initializes the connection to the RTT service.
@@ -74,7 +75,7 @@
     public void startWithRttService(Context context, Looper looper, IRttManager service) {
         Messenger messenger;
         try {
-            messenger = service.getMessenger();
+            messenger = service.getMessenger(null, new int[1]);
         } catch (RemoteException e) {
             Log.e(TAG, "start(): not able to getMessenger() of WIFI_RTT_SERVICE");
             return;
@@ -82,6 +83,7 @@
 
         mAsyncChannel = new AsyncChannel();
         mAsyncChannel.connect(context, new AwareRttHandler(looper), messenger);
+        mContext = context;
     }
 
     private WifiAwareClientState getAndRemovePendingOperationClient(int rangingId) {
@@ -125,7 +127,8 @@
             switch (msg.what) {
                 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
                     if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
-                        mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
+                        mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION,
+                                new RttManager.RttClient(mContext.getPackageName()));
                     } else {
                         Log.e(TAG, "Failed to set up channel connection to RTT service");
                         mAsyncChannel = null;
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java b/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
index 30aa42a..6ced948 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
@@ -204,7 +204,7 @@
     private volatile Characteristics mCharacteristics = null;
     private WifiAwareStateMachine mSm;
     private WifiAwareRttStateManager mRtt;
-    private WifiAwareDataPathStateManager mDataPathMgr;
+    public WifiAwareDataPathStateManager mDataPathMgr;
     private PowerManager mPowerManager;
 
     private final SparseArray<WifiAwareClientState> mClients = new SparseArray<>();
diff --git a/service/java/com/android/server/wifi/hotspot2/PasspointNetworkEvaluator.java b/service/java/com/android/server/wifi/hotspot2/PasspointNetworkEvaluator.java
index 6ff5ee9..fb81316 100644
--- a/service/java/com/android/server/wifi/hotspot2/PasspointNetworkEvaluator.java
+++ b/service/java/com/android/server/wifi/hotspot2/PasspointNetworkEvaluator.java
@@ -115,6 +115,13 @@
         if (currentNetwork != null && TextUtils.equals(currentNetwork.SSID,
                 ScanResultUtil.createQuotedSSID(bestNetwork.mScanDetail.getSSID()))) {
             localLog("Staying with current Passpoint network " + currentNetwork.SSID);
+
+            // Update current network with the latest scan info.
+            mWifiConfigManager.setNetworkCandidateScanResult(currentNetwork.networkId,
+                    bestNetwork.mScanDetail.getScanResult(), 0);
+            mWifiConfigManager.updateScanDetailForNetwork(currentNetwork.networkId,
+                    bestNetwork.mScanDetail);
+
             connectableNetworks.add(Pair.create(bestNetwork.mScanDetail, currentNetwork));
             return currentNetwork;
         }
diff --git a/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallback.java b/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallback.java
index 802f643..b7a4b3b 100644
--- a/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallback.java
+++ b/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallback.java
@@ -30,8 +30,6 @@
 import com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus;
 import com.android.server.wifi.util.NativeUtil;
 
-import libcore.util.HexEncoding;
-
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -97,7 +95,6 @@
             byte[] wfdDeviceInfo) {
         WifiP2pDevice device = new WifiP2pDevice();
         device.deviceName = deviceName;
-
         if (deviceName == null) {
             Log.e(TAG, "Missing device name.");
             return;
@@ -111,8 +108,7 @@
         }
 
         try {
-            device.primaryDeviceType = new String(HexEncoding.encode(
-                    primaryDeviceType, 0, primaryDeviceType.length));
+            device.primaryDeviceType = NativeUtil.wpsDevTypeStringFromByteArray(primaryDeviceType);
         } catch (Exception e) {
             Log.e(TAG, "Could not encode device primary type.", e);
             return;
@@ -134,7 +130,6 @@
         mMonitor.broadcastP2pDeviceFound(mInterface, device);
     }
 
-
     /**
      * Used to indicate that a P2P device has been lost.
      *
diff --git a/service/java/com/android/server/wifi/scanner/HalWifiScannerImpl.java b/service/java/com/android/server/wifi/scanner/HalWifiScannerImpl.java
index 0fadd80..7d0ccba 100644
--- a/service/java/com/android/server/wifi/scanner/HalWifiScannerImpl.java
+++ b/service/java/com/android/server/wifi/scanner/HalWifiScannerImpl.java
@@ -42,7 +42,6 @@
     private final WifiNative mWifiNative;
     private final ChannelHelper mChannelHelper;
     private final WificondScannerImpl mWificondScannerDelegate;
-    private final boolean mHalBasedPnoSupported;
 
     public HalWifiScannerImpl(Context context, WifiNative wifiNative, WifiMonitor wifiMonitor,
                               Looper looper, Clock clock) {
@@ -51,9 +50,6 @@
         mWificondScannerDelegate =
                 new WificondScannerImpl(context, wifiNative, wifiMonitor, mChannelHelper,
                         looper, clock);
-
-        // We are not going to support HAL ePNO currently.
-        mHalBasedPnoSupported = false;
     }
 
     @Override
@@ -121,38 +117,22 @@
     @Override
     public boolean setHwPnoList(WifiNative.PnoSettings settings,
             WifiNative.PnoEventHandler eventHandler) {
-        if (mHalBasedPnoSupported) {
-            return mWifiNative.setPnoList(settings, eventHandler);
-        } else {
-            return mWificondScannerDelegate.setHwPnoList(settings, eventHandler);
-        }
+        return mWificondScannerDelegate.setHwPnoList(settings, eventHandler);
     }
 
     @Override
     public boolean resetHwPnoList() {
-        if (mHalBasedPnoSupported) {
-            return mWifiNative.resetPnoList();
-        } else {
-            return mWificondScannerDelegate.resetHwPnoList();
-        }
+        return mWificondScannerDelegate.resetHwPnoList();
     }
 
     @Override
     public boolean isHwPnoSupported(boolean isConnectedPno) {
-        if (mHalBasedPnoSupported) {
-            return true;
-        } else {
-            return mWificondScannerDelegate.isHwPnoSupported(isConnectedPno);
-        }
+        return mWificondScannerDelegate.isHwPnoSupported(isConnectedPno);
     }
 
     @Override
     public boolean shouldScheduleBackgroundScanForHwPno() {
-        if (mHalBasedPnoSupported) {
-            return true;
-        } else {
-            return mWificondScannerDelegate.shouldScheduleBackgroundScanForHwPno();
-        }
+        return mWificondScannerDelegate.shouldScheduleBackgroundScanForHwPno();
     }
 
     @Override
diff --git a/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java b/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
index ab2a5dc..4b8e284 100644
--- a/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
+++ b/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
@@ -2129,20 +2129,21 @@
             pw.println();
             pw.println("Latest scan results:");
             List<ScanResult> scanResults = mSingleScanStateMachine.getCachedScanResultsAsList();
-            long nowMs = System.currentTimeMillis();
+            long nowMs = mClock.getElapsedSinceBootMillis();
             if (scanResults != null && scanResults.size() != 0) {
                 pw.println("    BSSID              Frequency  RSSI  Age(sec)   SSID "
                         + "                                Flags");
                 for (ScanResult r : scanResults) {
+                    long timeStampMs = r.timestamp / 1000;
                     String age;
-                    if (r.seen <= 0) {
+                    if (timeStampMs <= 0) {
                         age = "___?___";
-                    } else if (nowMs < r.seen) {
+                    } else if (nowMs < timeStampMs) {
                         age = "  0.000";
-                    } else if (r.seen < nowMs - 1000000) {
+                    } else if (timeStampMs < nowMs - 1000000) {
                         age = ">1000.0";
                     } else {
-                        age = String.format("%3.3f", (nowMs - r.seen) / 1000.0);
+                        age = String.format("%3.3f", (nowMs - timeStampMs) / 1000.0);
                     }
                     String ssid = r.SSID == null ? "" : r.SSID;
                     pw.printf("  %17s  %9d  %5d   %7s    %-32s  %s\n",
diff --git a/service/java/com/android/server/wifi/scanner/WificondScannerImpl.java b/service/java/com/android/server/wifi/scanner/WificondScannerImpl.java
index 84105ee..12a0bde 100644
--- a/service/java/com/android/server/wifi/scanner/WificondScannerImpl.java
+++ b/service/java/com/android/server/wifi/scanner/WificondScannerImpl.java
@@ -538,7 +538,7 @@
                  // got a scan before we started scanning or after scan was canceled
                 return;
             }
-            mNativeScanResults = mWifiNative.getScanResults();
+            mNativeScanResults = mWifiNative.getPnoScanResults();
             List<ScanResult> hwPnoScanResults = new ArrayList<>();
             int numFilteredScanResults = 0;
             for (int i = 0; i < mNativeScanResults.size(); ++i) {
diff --git a/service/java/com/android/server/wifi/util/Matrix.java b/service/java/com/android/server/wifi/util/Matrix.java
new file mode 100644
index 0000000..bdf147e
--- /dev/null
+++ b/service/java/com/android/server/wifi/util/Matrix.java
@@ -0,0 +1,340 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi.util;
+
+/**
+ * Utility for doing basic matix calculations
+ */
+public class Matrix {
+    public final int n;
+    public final int m;
+    public final double[] mem;
+
+    /**
+     * Creates a new matrix, initialized to zeros
+     *
+     * @param rows - number of rows (n)
+     * @param cols - number of columns (m)
+     */
+    public Matrix(int rows, int cols) {
+        n = rows;
+        m = cols;
+        mem = new double[rows * cols];
+    }
+
+    /**
+     * Creates a new matrix using the provided array of values
+     * <p>
+     * Values are in row-major order.
+     *
+     * @param stride is the number of columns.
+     * @param values is the array of values.
+     * @throws IllegalArgumentException if length of values array not a multiple of stride
+     */
+    public Matrix(int stride, double[] values) {
+        n = (values.length + stride - 1) / stride;
+        m = stride;
+        mem = values;
+        if (mem.length != n * m) throw new IllegalArgumentException();
+    }
+
+    /**
+     * Creates a new matrix duplicating the given one
+     *
+     * @param that is the source Matrix.
+     */
+    public Matrix(Matrix that) {
+        n = that.n;
+        m = that.m;
+        mem = new double[that.mem.length];
+        for (int i = 0; i < mem.length; i++) {
+            mem[i] = that.mem[i];
+        }
+    }
+
+    /**
+     * Gets the matrix coefficient from row i, column j
+     *
+     * @param i row number
+     * @param j column number
+     * @return Coefficient at i,j
+     * @throws IndexOutOfBoundsException if an index is out of bounds
+     */
+    public double get(int i, int j) {
+        if (!(0 <= i && i < n && 0 <= j && j < m)) throw new IndexOutOfBoundsException();
+        return mem[i * m + j];
+    }
+
+    /**
+     * Store a matrix coefficient in row i, column j
+     *
+     * @param i row number
+     * @param j column number
+     * @param v Coefficient to store at i,j
+     * @throws IndexOutOfBoundsException if an index is out of bounds
+     */
+    public void put(int i, int j, double v) {
+        if (!(0 <= i && i < n && 0 <= j && j < m)) throw new IndexOutOfBoundsException();
+        mem[i * m + j] = v;
+    }
+
+    /**
+     * Forms the sum of two matrices, this and that
+     *
+     * @param that is the other matrix
+     * @return newly allocated matrix representing the sum of this and that
+     * @throws IllegalArgumentException if shapes differ
+     */
+    public Matrix plus(Matrix that) {
+        return plus(that, new Matrix(n, m));
+
+    }
+
+    /**
+     * Forms the sum of two matrices, this and that
+     *
+     * @param that   is the other matrix
+     * @param result is space to hold the result
+     * @return result, filled with the matrix sum
+     * @throws IllegalArgumentException if shapes differ
+     */
+    public Matrix plus(Matrix that, Matrix result) {
+        if (!(this.n == that.n && this.m == that.m && this.n == result.n && this.m == result.m)) {
+            throw new IllegalArgumentException();
+        }
+        for (int i = 0; i < mem.length; i++) {
+            result.mem[i] = this.mem[i] + that.mem[i];
+        }
+        return result;
+    }
+
+    /**
+     * Forms the difference of two matrices, this and that
+     *
+     * @param that is the other matrix
+     * @return newly allocated matrix representing the difference of this and that
+     * @throws IllegalArgumentException if shapes differ
+     */
+    public Matrix minus(Matrix that) {
+        return minus(that, new Matrix(n, m));
+    }
+
+    /**
+     * Forms the difference of two matrices, this and that
+     *
+     * @param that   is the other matrix
+     * @param result is space to hold the result
+     * @return result, filled with the matrix difference
+     * @throws IllegalArgumentException if shapes differ
+     */
+    public Matrix minus(Matrix that, Matrix result) {
+        if (!(this.n == that.n && this.m == that.m && this.n == result.n && this.m == result.m)) {
+            throw new IllegalArgumentException();
+        }
+        for (int i = 0; i < mem.length; i++) {
+            result.mem[i] = this.mem[i] - that.mem[i];
+        }
+        return result;
+    }
+
+    /**
+     * Forms the matrix product of two matrices, this and that
+     *
+     * @param that is the other matrix
+     * @return newly allocated matrix representing the matrix product of this and that
+     * @throws IllegalArgumentException if shapes are not conformant
+     */
+    public Matrix dot(Matrix that) {
+        return dot(that, new Matrix(this.n, that.m));
+    }
+
+    /**
+     * Forms the matrix product of two matrices, this and that
+     * <p>
+     * Caller supplies an object to contain the result, as well as scratch space
+     *
+     * @param that   is the other matrix
+     * @param result is space to hold the result
+     * @return result, filled with the matrix product
+     * @throws IllegalArgumentException if shapes are not conformant
+     */
+    public Matrix dot(Matrix that, Matrix result) {
+        if (!(this.n == result.n && this.m == that.n && that.m == result.m)) {
+            throw new IllegalArgumentException();
+        }
+        for (int i = 0; i < n; i++) {
+            for (int j = 0; j < that.m; j++) {
+                double s = 0.0;
+                for (int k = 0; k < m; k++) {
+                    s += this.get(i, k) * that.get(k, j);
+                }
+                result.put(i, j, s);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Forms the matrix transpose
+     *
+     * @return newly allocated transpose matrix
+     */
+    public Matrix transpose() {
+        return transpose(new Matrix(m, n));
+    }
+
+    /**
+     * Forms the matrix transpose
+     * <p>
+     * Caller supplies an object to contain the result
+     *
+     * @param result is space to hold the result
+     * @return result, filled with the matrix transpose
+     * @throws IllegalArgumentException if result shape is wrong
+     */
+    public Matrix transpose(Matrix result) {
+        if (!(this.n == result.m && this.m == result.n)) throw new IllegalArgumentException();
+        for (int i = 0; i < n; i++) {
+            for (int j = 0; j < m; j++) {
+                result.put(j, i, get(i, j));
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Forms the inverse of a square matrix
+     *
+     * @return newly allocated matrix representing the matrix inverse
+     * @throws ArithmeticException if the matrix is not invertible
+     */
+    public Matrix inverse() {
+        return inverse(new Matrix(n, m), new Matrix(n, 2 * m));
+    }
+
+    /**
+     * Forms the inverse of a square matrix
+     *
+     * @param result  is space to hold the result
+     * @param scratch is workspace of dimension n by 2*n
+     * @return result, filled with the matrix inverse
+     * @throws ArithmeticException if the matrix is not invertible
+     * @throws IllegalArgumentException if shape of scratch or result is wrong
+     */
+    public Matrix inverse(Matrix result, Matrix scratch) {
+        if (!(n == m && n == result.n && m == result.m && n == scratch.n && 2 * m == scratch.m)) {
+            throw new IllegalArgumentException();
+        }
+
+        for (int i = 0; i < n; i++) {
+            for (int j = 0; j < m; j++) {
+                scratch.put(i, j, get(i, j));
+                scratch.put(i, m + j, i == j ? 1.0 : 0.0);
+            }
+        }
+
+        for (int i = 0; i < n; i++) {
+            int ibest = i;
+            double vbest = Math.abs(scratch.get(ibest, ibest));
+            for (int ii = i + 1; ii < n; ii++) {
+                double v = Math.abs(scratch.get(ii, i));
+                if (v > vbest) {
+                    ibest = ii;
+                    vbest = v;
+                }
+            }
+            if (ibest != i) {
+                for (int j = 0; j < scratch.m; j++) {
+                    double t = scratch.get(i, j);
+                    scratch.put(i, j, scratch.get(ibest, j));
+                    scratch.put(ibest, j, t);
+                }
+            }
+            double d = scratch.get(i, i);
+            if (d == 0.0) throw new ArithmeticException("Singular matrix");
+            for (int j = 0; j < scratch.m; j++) {
+                scratch.put(i, j, scratch.get(i, j) / d);
+            }
+            for (int ii = i + 1; ii < n; ii++) {
+                d = scratch.get(ii, i);
+                for (int j = 0; j < scratch.m; j++) {
+                    scratch.put(ii, j, scratch.get(ii, j) - d * scratch.get(i, j));
+                }
+            }
+        }
+        for (int i = n - 1; i >= 0; i--) {
+            for (int ii = 0; ii < i; ii++) {
+                double d = scratch.get(ii, i);
+                for (int j = 0; j < scratch.m; j++) {
+                    scratch.put(ii, j, scratch.get(ii, j) - d * scratch.get(i, j));
+                }
+            }
+        }
+        for (int i = 0; i < result.n; i++) {
+            for (int j = 0; j < result.m; j++) {
+                result.put(i, j, scratch.get(i, m + j));
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Tests for equality
+     */
+    @Override
+    public boolean equals(Object that) {
+        if (this == that) return true;
+        if (!(that instanceof Matrix)) return false;
+        Matrix other = (Matrix) that;
+        if (n != other.n) return false;
+        if (m != other.m) return false;
+        for (int i = 0; i < mem.length; i++) {
+            if (mem[i] != other.mem[i]) return false;
+        }
+        return true;
+    }
+
+    /**
+     * Calculates a hash code
+     */
+    @Override
+    public int hashCode() {
+        int h = n * 101 + m;
+        for (int i = 0; i < mem.length; i++) {
+            h = h * 37 + Double.hashCode(mem[i]);
+        }
+        return h;
+    }
+
+    /**
+     * Makes a string representation
+     *
+     * @return string like "[a, b; c, d]"
+     */
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder(n * m * 8);
+        sb.append("[");
+        for (int i = 0; i < mem.length; i++) {
+            if (i > 0) sb.append(i % m == 0 ? "; " : ", ");
+            sb.append(mem[i]);
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+}
diff --git a/service/java/com/android/server/wifi/util/NativeUtil.java b/service/java/com/android/server/wifi/util/NativeUtil.java
index 07c3f9b..84f9351 100644
--- a/service/java/com/android/server/wifi/util/NativeUtil.java
+++ b/service/java/com/android/server/wifi/util/NativeUtil.java
@@ -30,6 +30,7 @@
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Arrays;
 
 /**
  * Provide utility functions for native interfacing modules.
@@ -209,13 +210,13 @@
     /**
      * Converts an string to an arraylist of UTF_8 byte values.
      * These forms are acceptable:
-     * a) ASCII String encapsulated in quotes, or
+     * a) UTF-8 String encapsulated in quotes, or
      * b) Hex string with no delimiters.
      *
      * @param str String to be converted.
      * @throws IllegalArgumentException for null string.
      */
-    public static ArrayList<Byte> hexOrQuotedAsciiStringToBytes(String str) {
+    public static ArrayList<Byte> hexOrQuotedStringToBytes(String str) {
         if (str == null) {
             throw new IllegalArgumentException("null string");
         }
@@ -231,21 +232,21 @@
     /**
      * Converts an ArrayList<Byte> of UTF_8 byte values to string.
      * The string will either be:
-     * a) ASCII String encapsulated in quotes (if all the bytes are ASCII encodeable and non null),
+     * a) UTF-8 String encapsulated in quotes (if all the bytes are UTF-8 encodeable and non null),
      * or
      * b) Hex string with no delimiters.
      *
      * @param bytes List of bytes for ssid.
      * @throws IllegalArgumentException for null bytes.
      */
-    public static String bytesToHexOrQuotedAsciiString(ArrayList<Byte> bytes) {
+    public static String bytesToHexOrQuotedString(ArrayList<Byte> bytes) {
         if (bytes == null) {
             throw new IllegalArgumentException("null ssid bytes");
         }
         byte[] byteArray = byteArrayFromArrayList(bytes);
         // Check for 0's in the byte stream in which case we cannot convert this into a string.
         if (!bytes.contains(Byte.valueOf((byte) 0))) {
-            CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
+            CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
             try {
                 CharBuffer decoded = decoder.decode(ByteBuffer.wrap(byteArray));
                 return "\"" + decoded.toString() + "\"";
@@ -258,20 +259,20 @@
     /**
      * Converts an ssid string to an arraylist of UTF_8 byte values.
      * These forms are acceptable:
-     * a) ASCII String encapsulated in quotes, or
+     * a) UTF-8 String encapsulated in quotes, or
      * b) Hex string with no delimiters.
      *
      * @param ssidStr String to be converted.
      * @throws IllegalArgumentException for null string.
      */
     public static ArrayList<Byte> decodeSsid(String ssidStr) {
-        return hexOrQuotedAsciiStringToBytes(ssidStr);
+        return hexOrQuotedStringToBytes(ssidStr);
     }
 
     /**
      * Converts an ArrayList<Byte> of UTF_8 byte values to ssid string.
      * The string will either be:
-     * a) ASCII String encapsulated in quotes (if all the bytes are ASCII encodeable and non null),
+     * a) UTF-8 String encapsulated in quotes (if all the bytes are UTF-8 encodeable and non null),
      * or
      * b) Hex string with no delimiters.
      *
@@ -279,7 +280,7 @@
      * @throws IllegalArgumentException for null bytes.
      */
     public static String encodeSsid(ArrayList<Byte> ssidBytes) {
-        return bytesToHexOrQuotedAsciiString(ssidBytes);
+        return bytesToHexOrQuotedString(ssidBytes);
     }
 
     /**
@@ -330,4 +331,16 @@
         }
         return new String(HexEncoding.encode(bytes)).toLowerCase();
     }
+
+    /**
+     * Converts an 8 byte array to a WPS device type string
+     * { 0, 1, 2, -1, 4, 5, 6, 7 } --> "1-02FF0405-1543";
+     */
+    public static String wpsDevTypeStringFromByteArray(byte[] devType) {
+        byte[] a = devType;
+        int x = ((a[0] & 0xFF) << 8) | (a[1] & 0xFF);
+        String y = new String(HexEncoding.encode(Arrays.copyOfRange(devType, 2, 6)));
+        int z = ((a[6] & 0xFF) << 8) | (a[7] & 0xFF);
+        return String.format("%d-%s-%d", x, y, z);
+    }
 }
diff --git a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
index c5eea7d..069e5a8 100644
--- a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
+++ b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
@@ -23,6 +23,7 @@
 import android.content.pm.UserInfo;
 import android.net.ConnectivityManager;
 import android.net.NetworkScoreManager;
+import android.os.Binder;
 import android.os.RemoteException;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -113,10 +114,29 @@
         }
     }
 
+
+    /**
+     * Checks that calling process has android.Manifest.permission.ACCESS_COARSE_LOCATION
+     * and a corresponding app op is allowed for this package and uid.
+     *
+     * @param pkgName PackageName of the application requesting access
+     * @param uid The uid of the package
+     */
+    public boolean checkCallersLocationPermission(String pkgName, int uid) {
+        // Coarse Permission implies Fine permission
+        if ((mWifiPermissionsWrapper.getUidPermission(
+                Manifest.permission.ACCESS_COARSE_LOCATION, uid)
+                == PackageManager.PERMISSION_GRANTED)
+                && checkAppOpAllowed(AppOpsManager.OP_COARSE_LOCATION, pkgName, uid)) {
+            return true;
+        }
+        return false;
+    }
+
     /**
      * API to determine if the caller has permissions to get
      * scan results.
-     * @param pkgName Packagename of the application requesting access
+     * @param pkgName package name of the application requesting access
      * @param uid The uid of the package
      * @param minVersion Minimum app API Version number to enforce location permission
      * @return boolean true or false if permissions is granted
@@ -193,19 +213,24 @@
      * current user.
      */
     private boolean isCurrentProfile(int uid) {
-        int currentUser = mWifiPermissionsWrapper.getCurrentUser();
-        int callingUserId = mWifiPermissionsWrapper.getCallingUserId(uid);
-        if (callingUserId == currentUser) {
-            return true;
-        } else {
-            List<UserInfo> userProfiles = mUserManager.getProfiles(currentUser);
-            for (UserInfo user: userProfiles) {
-                if (user.id == callingUserId) {
-                    return true;
+        final long token = Binder.clearCallingIdentity();
+        try {
+            int currentUser = mWifiPermissionsWrapper.getCurrentUser();
+            int callingUserId = mWifiPermissionsWrapper.getCallingUserId(uid);
+            if (callingUserId == currentUser) {
+                return true;
+            } else {
+                List<UserInfo> userProfiles = mUserManager.getProfiles(currentUser);
+                for (UserInfo user : userProfiles) {
+                    if (user.id == callingUserId) {
+                        return true;
+                    }
                 }
             }
+            return false;
+        } finally {
+            Binder.restoreCallingIdentity(token);
         }
-        return false;
     }
 
     /**
@@ -237,20 +262,6 @@
         return pkgName.equals(mWifiPermissionsWrapper.getTopPkgName());
     }
 
-    /**
-     * Checks that calling process has android.Manifest.permission.ACCESS_COARSE_LOCATION
-     * and a corresponding app op is allowed for this package and uid.
-     */
-    private boolean checkCallersLocationPermission(String pkgName, int uid) {
-        // Coarse Permission implies Fine permission
-        if ((mWifiPermissionsWrapper.getUidPermission(
-                Manifest.permission.ACCESS_COARSE_LOCATION, uid)
-                == PackageManager.PERMISSION_GRANTED)
-                && checkAppOpAllowed(AppOpsManager.OP_COARSE_LOCATION, pkgName, uid)) {
-            return true;
-        }
-        return false;
-    }
     private boolean isLocationModeEnabled(String pkgName) {
         // Location mode check on applications that are later than version.
         return (mSettingsStore.getLocationModeSetting(mContext)
diff --git a/service/java/com/android/server/wifi/util/XmlUtil.java b/service/java/com/android/server/wifi/util/XmlUtil.java
index 853136b..f4c3ab1 100644
--- a/service/java/com/android/server/wifi/util/XmlUtil.java
+++ b/service/java/com/android/server/wifi/util/XmlUtil.java
@@ -332,6 +332,7 @@
         public static final String XML_TAG_NO_INTERNET_ACCESS_EXPECTED = "NoInternetAccessExpected";
         public static final String XML_TAG_USER_APPROVED = "UserApproved";
         public static final String XML_TAG_METERED_HINT = "MeteredHint";
+        public static final String XML_TAG_METERED_OVERRIDE = "MeteredOverride";
         public static final String XML_TAG_USE_EXTERNAL_SCORES = "UseExternalScores";
         public static final String XML_TAG_NUM_ASSOCIATION = "NumAssociation";
         public static final String XML_TAG_CREATOR_UID = "CreatorUid";
@@ -445,6 +446,7 @@
                     configuration.noInternetAccessExpected);
             XmlUtil.writeNextValue(out, XML_TAG_USER_APPROVED, configuration.userApproved);
             XmlUtil.writeNextValue(out, XML_TAG_METERED_HINT, configuration.meteredHint);
+            XmlUtil.writeNextValue(out, XML_TAG_METERED_OVERRIDE, configuration.meteredOverride);
             XmlUtil.writeNextValue(
                     out, XML_TAG_USE_EXTERNAL_SCORES, configuration.useExternalScores);
             XmlUtil.writeNextValue(out, XML_TAG_NUM_ASSOCIATION, configuration.numAssociation);
@@ -591,6 +593,9 @@
                     case XML_TAG_METERED_HINT:
                         configuration.meteredHint = (boolean) value;
                         break;
+                    case XML_TAG_METERED_OVERRIDE:
+                        configuration.meteredOverride = (int) value;
+                        break;
                     case XML_TAG_USE_EXTERNAL_SCORES:
                         configuration.useExternalScores = (boolean) value;
                         break;
diff --git a/tests/wifitests/src/com/android/server/wifi/CarrierNetworkConfigTest.java b/tests/wifitests/src/com/android/server/wifi/CarrierNetworkConfigTest.java
new file mode 100644
index 0000000..f8d2e52
--- /dev/null
+++ b/tests/wifitests/src/com/android/server/wifi/CarrierNetworkConfigTest.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.wifi.EAPConstants;
+import android.net.wifi.WifiEnterpriseConfig;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.util.Base64;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Arrays;
+
+/**
+ * Unit tests for {@link com.android.server.wifi.CarrierNetworkConfig}.
+ */
+@SmallTest
+public class CarrierNetworkConfigTest {
+    private static final String TEST_SSID = "Test SSID";
+    private static final int TEST_STANDARD_EAP_TYPE = EAPConstants.EAP_SIM;
+    private static final int TEST_INTERNAL_EAP_TYPE = WifiEnterpriseConfig.Eap.SIM;
+    private static final int TEST_SUBSCRIPTION_ID = 1;
+    private static final String TEST_CARRIER_NAME = "Test Carrier";
+    private static final SubscriptionInfo TEST_SUBSCRIPTION_INFO =
+            new SubscriptionInfo(TEST_SUBSCRIPTION_ID, null, 0, TEST_CARRIER_NAME, null, 0, 0,
+                    null, 0, null, 0, 0, null);
+
+    @Mock Context mContext;
+    @Mock CarrierConfigManager mCarrierConfigManager;
+    @Mock SubscriptionManager mSubscriptionManager;
+    BroadcastReceiver mBroadcastReceiver;
+    CarrierNetworkConfig mCarrierNetworkConfig;
+
+    /**
+     * Generate and return a carrier config for testing
+     *
+     * @param ssid The SSID of the carrier network
+     * @param eapType The EAP type of the carrier network
+     * @return {@link PersistableBundle} containing carrier config
+     */
+    private PersistableBundle generateTestConfig(String ssid, int eapType) {
+        PersistableBundle bundle = new PersistableBundle();
+        String networkConfig =
+                new String(Base64.encode(ssid.getBytes(), Base64.DEFAULT)) + "," + eapType;
+        bundle.putStringArray(CarrierConfigManager.KEY_CARRIER_WIFI_STRING_ARRAY,
+                new String[] {networkConfig});
+        return bundle;
+    }
+
+    /**
+     * Method to initialize mocks for tests.
+     */
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE))
+                .thenReturn(mCarrierConfigManager);
+        when(mContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE))
+                .thenReturn(mSubscriptionManager);
+        when(mCarrierConfigManager.getConfigForSubId(TEST_SUBSCRIPTION_ID))
+                .thenReturn(generateTestConfig(TEST_SSID, TEST_STANDARD_EAP_TYPE));
+        when(mSubscriptionManager.getActiveSubscriptionInfoList())
+                .thenReturn(Arrays.asList(new SubscriptionInfo[] {TEST_SUBSCRIPTION_INFO}));
+        mCarrierNetworkConfig = new CarrierNetworkConfig(mContext);
+        ArgumentCaptor<BroadcastReceiver> receiver =
+                ArgumentCaptor.forClass(BroadcastReceiver.class);
+        verify(mContext).registerReceiver(receiver.capture(), any(IntentFilter.class));
+        mBroadcastReceiver = receiver.getValue();
+        reset(mCarrierConfigManager);
+    }
+
+    /**
+     * Verify that {@link CarrierNetworkConfig#isCarrierNetwork} will return true and
+     * {@link CarrierNetworkConfig#getNetworkEapType} will return the corresponding EAP type
+     * when the given SSID is associated with a carrier network.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void getExistingCarrierNetworkInfo() throws Exception {
+        assertTrue(mCarrierNetworkConfig.isCarrierNetwork(TEST_SSID));
+        assertEquals(TEST_INTERNAL_EAP_TYPE, mCarrierNetworkConfig.getNetworkEapType(TEST_SSID));
+        assertEquals(TEST_CARRIER_NAME, mCarrierNetworkConfig.getCarrierName(TEST_SSID));
+    }
+
+    /**
+     * Verify that {@link CarrierNetworkConfig#isCarrierNetwork} will return false and
+     * {@link CarrierNetworkConfig#getNetworkEapType} will return -1 when the given SSID is not
+     * associated with any carrier network.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void getNonCarrierNetworkInfo() throws Exception {
+        String dummySsid = "Dummy SSID";
+        assertFalse(mCarrierNetworkConfig.isCarrierNetwork(dummySsid));
+        assertEquals(-1, mCarrierNetworkConfig.getNetworkEapType(dummySsid));
+    }
+
+    /**
+     * Verify that the carrier network config is updated when
+     * {@link CarrierConfigManager#ACTION_CARRIER_CONFIG_CHANGED} intent is received.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void receivedCarrierConfigChangedIntent() throws Exception {
+        String updatedSsid = "Updated SSID";
+        int updatedStandardEapType = EAPConstants.EAP_AKA;
+        int updatedInternalEapType = WifiEnterpriseConfig.Eap.AKA;
+        String updatedCarrierName = "Updated Carrier";
+        SubscriptionInfo updatedSubscriptionInfo = new SubscriptionInfo(TEST_SUBSCRIPTION_ID,
+                null, 0, updatedCarrierName, null, 0, 0, null, 0, null, 0, 0, null);
+        when(mSubscriptionManager.getActiveSubscriptionInfoList())
+                .thenReturn(Arrays.asList(new SubscriptionInfo[] {updatedSubscriptionInfo}));
+        when(mCarrierConfigManager.getConfigForSubId(TEST_SUBSCRIPTION_ID))
+                .thenReturn(generateTestConfig(updatedSsid, updatedStandardEapType));
+        mBroadcastReceiver.onReceive(mContext,
+                new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
+
+        // Verify that original SSID no longer associated with a carrier network.
+        assertFalse(mCarrierNetworkConfig.isCarrierNetwork(TEST_SSID));
+        assertEquals(-1, mCarrierNetworkConfig.getNetworkEapType(TEST_SSID));
+        assertEquals(null, mCarrierNetworkConfig.getCarrierName(TEST_SSID));
+
+        // Verify that updated SSID is associated with a carrier network.
+        assertTrue(mCarrierNetworkConfig.isCarrierNetwork(updatedSsid));
+        assertEquals(updatedInternalEapType, mCarrierNetworkConfig.getNetworkEapType(updatedSsid));
+        assertEquals(updatedCarrierName, mCarrierNetworkConfig.getCarrierName(updatedSsid));
+    }
+
+    /**
+     * Verify that the carrier network config is not updated when non
+     * {@link CarrierConfigManager#ACTION_CARRIER_CONFIG_CHANGED} intent is received.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void receivedNonCarrierConfigChangedIntent() throws Exception {
+        mBroadcastReceiver.onReceive(mContext, new Intent("dummyIntent"));
+        verify(mCarrierConfigManager, never()).getConfig();
+    }
+}
diff --git a/tests/wifitests/src/com/android/server/wifi/NetworkListStoreDataTest.java b/tests/wifitests/src/com/android/server/wifi/NetworkListStoreDataTest.java
index 01257c1..cbad3bb 100644
--- a/tests/wifitests/src/com/android/server/wifi/NetworkListStoreDataTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/NetworkListStoreDataTest.java
@@ -75,6 +75,7 @@
                     + "<boolean name=\"NoInternetAccessExpected\" value=\"false\" />\n"
                     + "<int name=\"UserApproved\" value=\"0\" />\n"
                     + "<boolean name=\"MeteredHint\" value=\"false\" />\n"
+                    + "<int name=\"MeteredOverride\" value=\"0\" />\n"
                     + "<boolean name=\"UseExternalScores\" value=\"false\" />\n"
                     + "<int name=\"NumAssociation\" value=\"0\" />\n"
                     + "<int name=\"CreatorUid\" value=\"%d\" />\n"
@@ -125,6 +126,7 @@
                     + "<boolean name=\"NoInternetAccessExpected\" value=\"false\" />\n"
                     + "<int name=\"UserApproved\" value=\"0\" />\n"
                     + "<boolean name=\"MeteredHint\" value=\"false\" />\n"
+                    + "<int name=\"MeteredOverride\" value=\"0\" />\n"
                     + "<boolean name=\"UseExternalScores\" value=\"false\" />\n"
                     + "<int name=\"NumAssociation\" value=\"0\" />\n"
                     + "<int name=\"CreatorUid\" value=\"%d\" />\n"
diff --git a/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java b/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
new file mode 100644
index 0000000..29c068d
--- /dev/null
+++ b/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
@@ -0,0 +1,322 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static com.android.server.wifi.OpenNetworkNotifier.DEFAULT_REPEAT_DELAY_SEC;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.net.wifi.ScanResult;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.os.test.TestLooper;
+import android.provider.Settings;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Answers;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Unit tests for {@link OpenNetworkNotifier}.
+ */
+public class OpenNetworkNotifierTest {
+
+    private static final String TEST_SSID_1 = "Test SSID 1";
+    private static final int MIN_RSSI_LEVEL = -127;
+
+    @Mock private Context mContext;
+    @Mock private Resources mResources;
+    @Mock private FrameworkFacade mFrameworkFacade;
+    @Mock private Clock mClock;
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Notification.Builder mNotificationBuilder;
+    @Mock private NotificationManager mNotificationManager;
+    @Mock private OpenNetworkRecommender mOpenNetworkRecommender;
+    @Mock private UserManager mUserManager;
+    private OpenNetworkNotifier mNotificationController;
+    private BroadcastReceiver mBroadcastReceiver;
+    private ScanResult mDummyNetwork;
+
+
+    /** Initialize objects before each test run. */
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        when(mContext.getSystemService(Context.NOTIFICATION_SERVICE))
+                .thenReturn(mNotificationManager);
+        when(mFrameworkFacade.getIntegerSetting(mContext,
+                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1)).thenReturn(1);
+        when(mFrameworkFacade.getIntegerSetting(mContext,
+                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, DEFAULT_REPEAT_DELAY_SEC))
+                .thenReturn(DEFAULT_REPEAT_DELAY_SEC);
+        when(mFrameworkFacade.makeNotificationBuilder(any(), anyString()))
+                .thenReturn(mNotificationBuilder);
+        when(mContext.getSystemService(Context.USER_SERVICE))
+                .thenReturn(mUserManager);
+        when(mContext.getResources()).thenReturn(mResources);
+        mDummyNetwork = new ScanResult();
+        mDummyNetwork.SSID = TEST_SSID_1;
+        mDummyNetwork.capabilities = "[ESS]";
+        mDummyNetwork.level = MIN_RSSI_LEVEL;
+        when(mOpenNetworkRecommender.recommendNetwork(any(), any())).thenReturn(mDummyNetwork);
+
+        TestLooper mock_looper = new TestLooper();
+        mNotificationController = new OpenNetworkNotifier(
+                mContext, mock_looper.getLooper(), mFrameworkFacade,
+                mClock, mOpenNetworkRecommender);
+        ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
+                ArgumentCaptor.forClass(BroadcastReceiver.class);
+        verify(mContext).registerReceiver(broadcastReceiverCaptor.capture(), any(), any(), any());
+        mBroadcastReceiver = broadcastReceiverCaptor.getValue();
+        mNotificationController.handleScreenStateChanged(true);
+    }
+
+    private List<ScanDetail> createOpenScanResults() {
+        List<ScanDetail> scanResults = new ArrayList<>();
+        scanResults.add(new ScanDetail(mDummyNetwork, null /* networkDetail */));
+        return scanResults;
+    }
+
+    /**
+     * When scan results with open networks are handled, a notification is posted.
+     */
+    @Test
+    public void handleScanResults_hasOpenNetworks_notificationDisplayed() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+    }
+
+    /**
+     * When scan results with no open networks are handled, a notification is not posted.
+     */
+    @Test
+    public void handleScanResults_emptyList_notificationNotDisplayed() {
+        mNotificationController.handleScanResults(new ArrayList<>());
+
+        verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
+    }
+
+    /**
+     * When a notification is showing and scan results with no open networks are handled, the
+     * notification is cleared.
+     */
+    @Test
+    public void handleScanResults_notificationShown_emptyList_notificationCleared() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.handleScanResults(new ArrayList<>());
+
+        verify(mNotificationManager).cancel(anyInt());
+    }
+    /**
+     * When a notification is showing, screen is off, and scan results with no open networks are
+     * handled, the notification is cleared.
+     */
+    @Test
+    public void handleScanResults_notificationShown_screenOff_emptyList_notificationCleared() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.handleScreenStateChanged(false);
+        mNotificationController.handleScanResults(new ArrayList<>());
+
+        verify(mNotificationManager).cancel(anyInt());
+    }
+
+    /**
+     * If notification is showing, do not post another notification.
+     */
+    @Test
+    public void handleScanResults_notificationShowing_doesNotRepostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+    }
+
+    /**
+     * When {@link OpenNetworkNotifier#clearPendingNotification(boolean)} is called and a
+     * notification is shown, clear the notification.
+     */
+    @Test
+    public void clearPendingNotification_clearsNotificationIfOneIsShowing() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(true);
+
+        verify(mNotificationManager).cancel(anyInt());
+    }
+
+    /**
+     * When {@link OpenNetworkNotifier#clearPendingNotification(boolean)} is called and a
+     * notification was not previously shown, do not clear the notification.
+     */
+    @Test
+    public void clearPendingNotification_doesNotClearNotificationIfNoneShowing() {
+        mNotificationController.clearPendingNotification(true);
+
+        verify(mNotificationManager, never()).cancel(anyInt());
+    }
+
+    /**
+     * When screen is off and notification is not displayed, notification is not posted on handling
+     * new scan results with open networks.
+     */
+    @Test
+    public void screenOff_handleScanResults_notificationNotDisplayed() {
+        mNotificationController.handleScreenStateChanged(false);
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, the next scan with open
+     * networks should not post another notification.
+     */
+    @Test
+    public void postNotification_clearNotificationWithoutDelayReset_shouldNotPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(false);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        // Recommendation made twice but no new notification posted.
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, the next scan with open
+     * networks should post a notification.
+     */
+    @Test
+    public void postNotification_clearNotificationWithDelayReset_shouldPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(true);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager, times(2)).notify(anyInt(), any());
+    }
+
+    /**
+     * When a notification is tapped, open Wi-Fi settings.
+     */
+    @Test
+    public void notificationTap_opensWifiSettings() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mBroadcastReceiver.onReceive(
+                mContext, new Intent(OpenNetworkNotifier.ACTION_USER_TAPPED_CONTENT));
+
+        verify(mContext).startActivity(any());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, after the delay has passed
+     * the next scan with open networks should post a notification.
+     */
+    @Test
+    public void delaySet_delayPassed_shouldPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(false);
+
+        // twice the delay time passed
+        when(mClock.getWallClockMillis()).thenReturn(DEFAULT_REPEAT_DELAY_SEC * 1000L * 2);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager, times(2)).notify(anyInt(), any());
+    }
+
+    /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} disables the feature. */
+    @Test
+    public void userHasDisallowConfigWifiRestriction_notificationNotDisplayed() {
+        when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT))
+                .thenReturn(true);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
+    }
+
+    /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} clears the showing notification. */
+    @Test
+    public void userHasDisallowConfigWifiRestriction_showingNotificationIsCleared() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT))
+                .thenReturn(true);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mNotificationManager).cancel(anyInt());
+    }
+}
diff --git a/tests/wifitests/src/com/android/server/wifi/OpenNetworkRecommenderTest.java b/tests/wifitests/src/com/android/server/wifi/OpenNetworkRecommenderTest.java
new file mode 100644
index 0000000..becc1d2
--- /dev/null
+++ b/tests/wifitests/src/com/android/server/wifi/OpenNetworkRecommenderTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static org.junit.Assert.assertEquals;
+
+import android.net.wifi.ScanResult;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Tests for {@link OpenNetworkRecommender}.
+ */
+public class OpenNetworkRecommenderTest {
+
+    private static final String TEST_SSID_1 = "Test SSID 1";
+    private static final String TEST_SSID_2 = "Test SSID 2";
+    private static final int MIN_RSSI_LEVEL = -127;
+
+    private OpenNetworkRecommender mOpenNetworkRecommender;
+
+    @Before
+    public void setUp() throws Exception {
+        mOpenNetworkRecommender = new OpenNetworkRecommender();
+    }
+
+    private List<ScanDetail> createOpenScanResults(String... ssids) {
+        List<ScanDetail> scanResults = new ArrayList<>();
+        for (String ssid : ssids) {
+            ScanResult scanResult = new ScanResult();
+            scanResult.SSID = ssid;
+            scanResult.capabilities = "[ESS]";
+            scanResults.add(new ScanDetail(scanResult, null /* networkDetail */));
+        }
+        return scanResults;
+    }
+
+    /** If list of open networks contain only one network, that network should be returned. */
+    @Test
+    public void onlyNetworkIsRecommended() {
+        List<ScanDetail> scanResults = createOpenScanResults(TEST_SSID_1);
+        scanResults.get(0).getScanResult().level = MIN_RSSI_LEVEL;
+
+        ScanResult actual = mOpenNetworkRecommender.recommendNetwork(scanResults, null);
+        ScanResult expected = scanResults.get(0).getScanResult();
+        assertEquals(expected, actual);
+    }
+
+    /** Verifies that the network with the highest rssi is recommended. */
+    @Test
+    public void networkWithHighestRssiIsRecommended() {
+        List<ScanDetail> scanResults = createOpenScanResults(TEST_SSID_1, TEST_SSID_2);
+        scanResults.get(0).getScanResult().level = MIN_RSSI_LEVEL;
+        scanResults.get(1).getScanResult().level = MIN_RSSI_LEVEL + 1;
+
+        ScanResult actual = mOpenNetworkRecommender.recommendNetwork(scanResults, null);
+        ScanResult expected = scanResults.get(1).getScanResult();
+        assertEquals(expected, actual);
+    }
+
+    /**
+     * If the current recommended network is present in the list for the next recommendation and has
+     * an equal RSSI, the recommendation should not change.
+     */
+    @Test
+    public void currentRecommendationHasEquallyHighRssi_shouldNotChangeRecommendation() {
+        List<ScanDetail> scanResults = createOpenScanResults(TEST_SSID_1, TEST_SSID_2);
+        scanResults.get(0).getScanResult().level = MIN_RSSI_LEVEL + 1;
+        scanResults.get(1).getScanResult().level = MIN_RSSI_LEVEL + 1;
+
+        ScanResult currentRecommendation = new ScanResult(scanResults.get(1).getScanResult());
+        // next recommendation does not depend on the rssi of the input recommendation.
+        currentRecommendation.level = MIN_RSSI_LEVEL;
+
+        ScanResult expected = scanResults.get(1).getScanResult();
+        ScanResult actual = mOpenNetworkRecommender.recommendNetwork(
+                scanResults, currentRecommendation);
+        assertEquals(expected, actual);
+    }
+}
diff --git a/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java b/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java
index 689ade8..7300cb2 100644
--- a/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java
@@ -41,6 +41,7 @@
 import android.test.suitebuilder.annotation.SmallTest;
 
 import com.android.internal.util.test.BidirectionalAsyncChannel;
+import com.android.server.wifi.util.WifiPermissionsUtil;
 
 import org.junit.After;
 import org.junit.Before;
@@ -69,6 +70,8 @@
     WifiInjector mWifiInjector;
     @Mock
     IWificond mWificond;
+    @Mock
+    WifiPermissionsUtil mWifiPermissionsUtil;
 
     RttService.RttServiceImpl mRttServiceImpl;
     ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverCaptor = ArgumentCaptor
@@ -80,6 +83,9 @@
         mLooper = new TestLooper();
         when(mWifiInjector.makeWificond()).thenReturn(mWificond);
         when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative);
+        when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil);
+        when(mWifiPermissionsUtil.checkCallersLocationPermission(any(), anyInt()))
+                .thenReturn(true);
         mRttServiceImpl = new RttService.RttServiceImpl(mContext, mLooper.getLooper(),
                 mWifiInjector);
         mRttServiceImpl.startService();
@@ -100,7 +106,7 @@
     // Create and connect a bi-directional async channel.
     private BidirectionalAsyncChannel connectChannel(Handler handler) {
         BidirectionalAsyncChannel channel = new BidirectionalAsyncChannel();
-        channel.connect(mLooper.getLooper(), mRttServiceImpl.getMessenger(),
+        channel.connect(mLooper.getLooper(), mRttServiceImpl.getMessenger(null, new int[1]),
                 handler);
         mLooper.dispatchAll();
         channel.assertConnected();
@@ -271,6 +277,22 @@
     }
 
     /**
+     * Test RTT fails without proper location permission
+     */
+    @Test
+    public void testEnableResponderFailureNoPermission() throws Exception {
+        when(mWifiPermissionsUtil.checkCallersLocationPermission(any(), anyInt()))
+                .thenReturn(false);
+        startWifi();
+        Handler handler = mock(Handler.class);
+        BidirectionalAsyncChannel channel = connectChannel(handler);
+        Message message = sendEnableResponder(channel, handler, CLIENT_KEY1, null);
+        // RTT operations failed without proper permission.
+        assertEquals("expected permission denied, but got " + message.what,
+                RttManager.REASON_PERMISSION_DENIED, message.arg1);
+    }
+
+    /**
      * Test RTT ranging with empty RttParams.
      */
     @Test
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java b/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
index 02064d8..a923475 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
@@ -268,7 +268,9 @@
         assertFalse(WifiApConfigStore.validateApWifiConfiguration(config));
 
         // now check a valid SSID with a random length
-        config.SSID = generateRandomString(mRandom.nextInt(WifiApConfigStore.SSID_MAX_LEN + 1));
+        int validLength = WifiApConfigStore.SSID_MAX_LEN - WifiApConfigStore.SSID_MIN_LEN;
+        config.SSID = generateRandomString(
+                mRandom.nextInt(validLength) + WifiApConfigStore.SSID_MIN_LEN);
         assertTrue(WifiApConfigStore.validateApWifiConfiguration(config));
     }
 
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java b/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
index 7509c18..70f660e 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
@@ -1144,7 +1144,7 @@
         ScanDetailCache retrievedScanDetailCache =
                 mWifiConfigManager.getScanDetailCacheForNetwork(result.getNetworkId());
         assertEquals(1, retrievedScanDetailCache.size());
-        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
+        ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID);
 
         ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
     }
@@ -2555,6 +2555,7 @@
                 new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs);
 
         when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true);
+        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
         when(mWifiConfigStoreLegacy.read()).thenReturn(storeData);
 
         // Now trigger the migration from legacy store. This should populate the in memory list with
@@ -2588,6 +2589,24 @@
     }
 
     /**
+     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
+     * does not attempt to migrate data from legacy stores when the new store files are present
+     * (i.e migration was already done once).
+     */
+    @Test
+    public void testNewStoreFilesPresentNoMigrationFromLegacyStore() throws Exception {
+        when(mWifiConfigStore.areStoresPresent()).thenReturn(true);
+        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true);
+
+        // Now trigger a migration from legacy store.
+        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
+
+        verify(mWifiConfigStoreLegacy, never()).read();
+        // Verify that we went ahead and deleted the old store files.
+        verify(mWifiConfigStoreLegacy).removeStores();
+    }
+
+    /**
      * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does
      * not attempt to read from any of the stores (new or legacy) when the store files are
      * not present.
@@ -3971,7 +3990,7 @@
         ScanDetailCache retrievedScanDetailCache =
                 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId);
         assertEquals(1, retrievedScanDetailCache.size());
-        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
+        ScanResult retrievedScanResult = retrievedScanDetailCache.getScanResult(scanResult.BSSID);
 
         ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
     }
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java b/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
index 47efed3..86d6e11 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
@@ -91,6 +91,7 @@
                     + "<boolean name=\"NoInternetAccessExpected\" value=\"false\" />\n"
                     + "<int name=\"UserApproved\" value=\"0\" />\n"
                     + "<boolean name=\"MeteredHint\" value=\"false\" />\n"
+                    + "<int name=\"MeteredOverride\" value=\"0\" />\n"
                     + "<boolean name=\"UseExternalScores\" value=\"false\" />\n"
                     + "<int name=\"NumAssociation\" value=\"0\" />\n"
                     + "<int name=\"CreatorUid\" value=\"%d\" />\n"
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java b/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
index bdb6b14..a8278d3 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
@@ -123,7 +123,7 @@
     @Mock private NetworkScoreManager mNetworkScoreManager;
     @Mock private Clock mClock;
     @Mock private WifiLastResortWatchdog mWifiLastResortWatchdog;
-    @Mock private WifiNotificationController mWifiNotificationController;
+    @Mock private OpenNetworkNotifier mOpenNetworkNotifier;
     @Mock private WifiMetrics mWifiMetrics;
     @Mock private WifiNetworkScoreCache mScoreCache;
     @Captor ArgumentCaptor<ScanResult> mCandidateScanResultCaptor;
@@ -294,7 +294,7 @@
     WifiConnectivityManager createConnectivityManager() {
         return new WifiConnectivityManager(mContext, mWifiStateMachine, mWifiScanner,
                 mWifiConfigManager, mWifiInfo, mWifiNS, mWifiConnectivityHelper,
-                mWifiLastResortWatchdog, mWifiNotificationController, mWifiMetrics,
+                mWifiLastResortWatchdog, mOpenNetworkNotifier, mWifiMetrics,
                 mLooper.getLooper(), mClock, mLocalLog, true, mFrameworkFacade, null, null, null);
     }
 
@@ -609,7 +609,7 @@
     }
 
     /**
-     * {@link WifiNotificationController} handles scan results on network selection.
+     * {@link OpenNetworkNotifier} handles scan results on network selection.
      *
      * Expected behavior: ONA handles scan results
      */
@@ -633,11 +633,11 @@
         mWifiConnectivityManager.handleConnectionStateChanged(
                 WifiConnectivityManager.WIFI_STATE_DISCONNECTED);
 
-        verify(mWifiNotificationController).handleScanResults(expectedOpenNetworks);
+        verify(mOpenNetworkNotifier).handleScanResults(expectedOpenNetworks);
     }
 
     /**
-     * When wifi is connected, {@link WifiNotificationController} tries to clear the pending
+     * When wifi is connected, {@link OpenNetworkNotifier} tries to clear the pending
      * notification and does not reset notification repeat delay.
      *
      * Expected behavior: ONA clears pending notification and does not reset repeat delay.
@@ -648,11 +648,11 @@
         mWifiConnectivityManager.handleConnectionStateChanged(
                 WifiConnectivityManager.WIFI_STATE_CONNECTED);
 
-        verify(mWifiNotificationController).clearPendingNotification(false /* isRepeatDelayReset*/);
+        verify(mOpenNetworkNotifier).clearPendingNotification(false /* isRepeatDelayReset*/);
     }
 
     /**
-     * When wifi is connected, {@link WifiNotificationController} handles connection state
+     * When wifi is connected, {@link OpenNetworkNotifier} handles connection state
      * change.
      *
      * Expected behavior: ONA does not clear pending notification.
@@ -663,7 +663,7 @@
         mWifiConnectivityManager.handleConnectionStateChanged(
                 WifiConnectivityManager.WIFI_STATE_DISCONNECTED);
 
-        verify(mWifiNotificationController, never()).clearPendingNotification(anyBoolean());
+        verify(mOpenNetworkNotifier, never()).clearPendingNotification(anyBoolean());
     }
 
     /**
@@ -675,7 +675,7 @@
     public void openNetworkNotificationControllerToggledOnWifiStateChanges() {
         mWifiConnectivityManager.setWifiEnabled(false);
 
-        verify(mWifiNotificationController).clearPendingNotification(true /* isRepeatDelayReset */);
+        verify(mOpenNetworkNotifier).clearPendingNotification(true /* isRepeatDelayReset */);
     }
 
     /**
@@ -685,11 +685,11 @@
     public void openNetworkNotificationControllerTracksScreenStateChanges() {
         mWifiConnectivityManager.handleScreenStateChanged(false);
 
-        verify(mWifiNotificationController).handleScreenStateChanged(false);
+        verify(mOpenNetworkNotifier).handleScreenStateChanged(false);
 
         mWifiConnectivityManager.handleScreenStateChanged(true);
 
-        verify(mWifiNotificationController).handleScreenStateChanged(true);
+        verify(mOpenNetworkNotifier).handleScreenStateChanged(true);
     }
 
     /**
@@ -1652,7 +1652,7 @@
     /**
      *  Dump ONA controller.
      *
-     * Expected behavior: {@link WifiNotificationController#dump(FileDescriptor, PrintWriter,
+     * Expected behavior: {@link OpenNetworkNotifier#dump(FileDescriptor, PrintWriter,
      * String[])} is invoked.
      */
     @Test
@@ -1661,6 +1661,6 @@
         PrintWriter pw = new PrintWriter(sw);
         mWifiConnectivityManager.dump(new FileDescriptor(), pw, new String[]{});
 
-        verify(mWifiNotificationController).dump(any(), any(), any());
+        verify(mOpenNetworkNotifier).dump(any(), any(), any());
     }
 }
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java b/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
index 5a13928..10ad3c6 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
@@ -16,6 +16,7 @@
 package com.android.server.wifi;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.*;
 
@@ -37,6 +38,7 @@
 import com.android.server.wifi.hotspot2.PasspointMatch;
 import com.android.server.wifi.hotspot2.PasspointProvider;
 import com.android.server.wifi.nano.WifiMetricsProto;
+import com.android.server.wifi.nano.WifiMetricsProto.PnoScanMetrics;
 import com.android.server.wifi.nano.WifiMetricsProto.StaEvent;
 
 import org.junit.Before;
@@ -252,6 +254,11 @@
     private static final int NUM_PASSPOINT_PROVIDER_UNINSTALL_SUCCESS = 2;
     private static final int NUM_PASSPOINT_PROVIDERS_SUCCESSFULLY_CONNECTED = 1;
     private static final int NUM_PARTIAL_SCAN_RESULTS = 73;
+    private static final int NUM_PNO_SCAN_ATTEMPTS = 20;
+    private static final int NUM_PNO_SCAN_FAILED = 5;
+    private static final int NUM_PNO_SCAN_STARTED_OVER_OFFLOAD = 17;
+    private static final int NUM_PNO_SCAN_FAILED_OVER_OFFLOAD = 8;
+    private static final int NUM_PNO_FOUND_NETWORK_EVENTS = 10;
 
     private ScanDetail buildMockScanDetail(boolean hidden, NetworkDetail.HSRelease hSRelease,
             String capabilities) {
@@ -474,6 +481,23 @@
         for (int i = 0; i < NUM_PASSPOINT_PROVIDER_UNINSTALL_SUCCESS; i++) {
             mWifiMetrics.incrementNumPasspointProviderUninstallSuccess();
         }
+
+        // increment pno scan metrics
+        for (int i = 0; i < NUM_PNO_SCAN_ATTEMPTS; i++) {
+            mWifiMetrics.incrementPnoScanStartAttempCount();
+        }
+        for (int i = 0; i < NUM_PNO_SCAN_FAILED; i++) {
+            mWifiMetrics.incrementPnoScanFailedCount();
+        }
+        for (int i = 0; i < NUM_PNO_SCAN_STARTED_OVER_OFFLOAD; i++) {
+            mWifiMetrics.incrementPnoScanStartedOverOffloadCount();
+        }
+        for (int i = 0; i < NUM_PNO_SCAN_FAILED_OVER_OFFLOAD; i++) {
+            mWifiMetrics.incrementPnoScanFailedOverOffloadCount();
+        }
+        for (int i = 0; i < NUM_PNO_FOUND_NETWORK_EVENTS; i++) {
+            mWifiMetrics.incrementPnoFoundNetworkEventCount();
+        }
     }
 
     /**
@@ -618,6 +642,14 @@
                 mDecodedProto.numPasspointProviderUninstallSuccess);
         assertEquals(NUM_PASSPOINT_PROVIDERS_SUCCESSFULLY_CONNECTED,
                 mDecodedProto.numPasspointProvidersSuccessfullyConnected);
+
+        PnoScanMetrics pno_metrics = mDecodedProto.pnoScanMetrics;
+        assertNotNull(pno_metrics);
+        assertEquals(NUM_PNO_SCAN_ATTEMPTS, pno_metrics.numPnoScanAttempts);
+        assertEquals(NUM_PNO_SCAN_FAILED, pno_metrics.numPnoScanFailed);
+        assertEquals(NUM_PNO_SCAN_STARTED_OVER_OFFLOAD, pno_metrics.numPnoScanStartedOverOffload);
+        assertEquals(NUM_PNO_SCAN_FAILED_OVER_OFFLOAD, pno_metrics.numPnoScanFailedOverOffload);
+        assertEquals(NUM_PNO_FOUND_NETWORK_EVENTS, pno_metrics.numPnoFoundNetworkEvents);
     }
 
     /**
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java b/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
index 4965a35..3d3af36 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
@@ -23,12 +23,12 @@
 import static org.mockito.Mockito.*;
 
 import android.content.Context;
-import android.content.res.Resources;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
 import android.net.wifi.WifiInfo;
 import android.os.SystemClock;
+import android.test.mock.MockResources;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.util.LocalLog;
 import android.util.Pair;
@@ -41,6 +41,7 @@
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
 
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -52,6 +53,8 @@
 @SmallTest
 public class WifiNetworkSelectorTest {
 
+    private static final int RSSI_BUMP = 1;
+
     /** Sets up test. */
     @Before
     public void setUp() throws Exception {
@@ -68,22 +71,6 @@
         mDummyEvaluator.setEvaluatorToSelectCandidate(true);
         when(mClock.getElapsedSinceBootMillis()).thenReturn(SystemClock.elapsedRealtime());
 
-        mThresholdMinimumRssi2G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz);
-        mThresholdMinimumRssi5G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz);
-        mThresholdQualifiedRssi2G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz);
-        mThresholdQualifiedRssi5G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz);
-        mStayOnNetworkMinimumTxRate = mResource.getInteger(
-                R.integer.config_wifi_framework_min_tx_rate_for_staying_on_network);
-        mStayOnNetworkMinimumRxRate = mResource.getInteger(
-                R.integer.config_wifi_framework_min_rx_rate_for_staying_on_network);
-        mThresholdSaturatedRssi2G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz);
-        mThresholdSaturatedRssi5G = mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz);
     }
 
     /** Cleans up test. */
@@ -145,7 +132,11 @@
     private DummyNetworkEvaluator mDummyEvaluator = new DummyNetworkEvaluator();
     @Mock private WifiConfigManager mWifiConfigManager;
     @Mock private Context mContext;
-    @Mock private Resources mResource;
+
+    // For simulating the resources, we use a Spy on a MockResource
+    // (which is really more of a stub than a mock, in spite if its name).
+    // This is so that we get errors on any calls that we have not explicitly set up.
+    @Spy private MockResources mResource = new MockResources();
     @Mock private WifiInfo mWifiInfo;
     @Mock private Clock mClock;
     private LocalLog mLocalLog;
@@ -155,40 +146,32 @@
     private int mThresholdQualifiedRssi5G;
     private int mStayOnNetworkMinimumTxRate;
     private int mStayOnNetworkMinimumRxRate;
-    private int mThresholdSaturatedRssi2G;
-    private int mThresholdSaturatedRssi5G;
 
     private void setupContext() {
         when(mContext.getResources()).thenReturn(mResource);
     }
 
+    private int setupIntegerResource(int resourceName, int value) {
+        doReturn(value).when(mResource).getInteger(resourceName);
+        return value;
+    }
+
     private void setupResources() {
-        when(mResource.getBoolean(
-                R.bool.config_wifi_framework_enable_associated_network_selection)).thenReturn(true);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz))
-                .thenReturn(-70);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz))
-                .thenReturn(-73);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz))
-                .thenReturn(-82);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz))
-                .thenReturn(-85);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_max_tx_rate_for_full_scan))
-                .thenReturn(8);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_max_rx_rate_for_full_scan))
-                .thenReturn(8);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz))
-                .thenReturn(-57);
-        when(mResource.getInteger(
-                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz))
-                .thenReturn(-60);
+        doReturn(true).when(mResource).getBoolean(
+                R.bool.config_wifi_framework_enable_associated_network_selection);
+
+        mThresholdMinimumRssi2G = setupIntegerResource(
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_24GHz, -79);
+        mThresholdMinimumRssi5G = setupIntegerResource(
+                R.integer.config_wifi_framework_wifi_score_entry_rssi_threshold_5GHz, -76);
+        mThresholdQualifiedRssi2G = setupIntegerResource(
+                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz, -73);
+        mThresholdQualifiedRssi5G = setupIntegerResource(
+                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz, -70);
+        mStayOnNetworkMinimumTxRate = setupIntegerResource(
+                R.integer.config_wifi_framework_min_tx_rate_for_staying_on_network, 16);
+        mStayOnNetworkMinimumRxRate = setupIntegerResource(
+                R.integer.config_wifi_framework_min_rx_rate_for_staying_on_network, 16);
     }
 
     private void setupWifiInfo() {
@@ -279,7 +262,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         int[] securities = {SECURITY_PSK, SECURITY_PSK};
 
         // Make a network selection.
@@ -318,7 +301,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         int[] securities = {SECURITY_PSK, SECURITY_PSK};
 
         // Make a network selection.
@@ -483,7 +466,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 2457};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 20, mThresholdMinimumRssi2G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + 20, mThresholdMinimumRssi2G + RSSI_BUMP};
         int[] securities = {SECURITY_PSK, SECURITY_PSK};
 
         // Make a network selection to connect to test1.
@@ -534,8 +517,8 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4", "6c:f3:7f:ae:8c:f5"};
         int[] freqs = {2437, 5180, 5181};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1,
-                mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP,
+                mThresholdMinimumRssi5G + RSSI_BUMP};
         int[] securities = {SECURITY_PSK, SECURITY_PSK, SECURITY_PSK};
 
         ScanDetailsAndWifiConfigs scanDetailsAndConfigs =
@@ -581,7 +564,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         int[] securities = {SECURITY_PSK, SECURITY_PSK};
 
         ScanDetailsAndWifiConfigs scanDetailsAndConfigs =
@@ -961,7 +944,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         mDummyEvaluator.setEvaluatorToSelectCandidate(false);
 
         List<ScanDetail> scanDetails = WifiNetworkSelectorTestUtil.buildScanDetails(
@@ -990,7 +973,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP};
         int[] securities = {SECURITY_NONE};
         mDummyEvaluator.setEvaluatorToSelectCandidate(false);
 
@@ -1027,7 +1010,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[ESS]", "[ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         mDummyEvaluator.setEvaluatorToSelectCandidate(false);
 
         List<ScanDetail> scanDetails = WifiNetworkSelectorTestUtil.buildScanDetails(
@@ -1055,7 +1038,7 @@
         String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
         int[] freqs = {2437, 5180};
         String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]"};
-        int[] levels = {mThresholdMinimumRssi2G + 1, mThresholdMinimumRssi5G + 1};
+        int[] levels = {mThresholdMinimumRssi2G + RSSI_BUMP, mThresholdMinimumRssi5G + RSSI_BUMP};
         mDummyEvaluator.setEvaluatorToSelectCandidate(false);
 
         List<ScanDetail> scanDetails = WifiNetworkSelectorTestUtil.buildScanDetails(
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java b/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java
deleted file mode 100644
index 27055a8..0000000
--- a/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.wifi;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.content.Context;
-import android.content.res.Resources;
-import android.net.wifi.ScanResult;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.os.test.TestLooper;
-import android.provider.Settings;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Unit tests for {@link WifiNotificationController}.
- */
-public class WifiNotificationControllerTest {
-
-    @Mock private Context mContext;
-    @Mock private Resources mResources;
-    @Mock private FrameworkFacade mFrameworkFacade;
-    @Mock private NotificationManager mNotificationManager;
-    @Mock private UserManager mUserManager;
-    private WifiNotificationController mNotificationController;
-
-
-    /** Initialize objects before each test run. */
-    @Before
-    public void setUp() throws Exception {
-        MockitoAnnotations.initMocks(this);
-        when(mContext.getSystemService(Context.NOTIFICATION_SERVICE))
-                .thenReturn(mNotificationManager);
-        when(mFrameworkFacade.getIntegerSetting(mContext,
-                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1)).thenReturn(1);
-        when(mContext.getSystemService(Context.USER_SERVICE))
-                .thenReturn(mUserManager);
-        when(mContext.getResources()).thenReturn(mResources);
-
-        TestLooper mock_looper = new TestLooper();
-        mNotificationController = new WifiNotificationController(
-                mContext, mock_looper.getLooper(), mFrameworkFacade,
-                mock(Notification.Builder.class));
-        mNotificationController.handleScreenStateChanged(true);
-    }
-
-    private List<ScanDetail> createOpenScanResults() {
-        List<ScanDetail> scanResults = new ArrayList<>();
-        ScanResult scanResult = new ScanResult();
-        scanResult.capabilities = "[ESS]";
-        scanResults.add(new ScanDetail(scanResult, null /* networkDetail */));
-        return scanResults;
-    }
-
-    /**
-     * When scan results with open networks are handled, a notification is posted.
-     */
-    @Test
-    public void handleScanResults_hasOpenNetworks_notificationDisplayed() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-    }
-
-    /**
-     * When scan results with no open networks are handled, a notification is not posted.
-     */
-    @Test
-    public void handleScanResults_emptyList_notificationNotDisplayed() {
-        mNotificationController.handleScanResults(new ArrayList<>());
-
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
-    }
-
-    /**
-     * When a notification is showing and scan results with no open networks are handled, the
-     * notification is cleared.
-     */
-    @Test
-    public void handleScanResults_notificationShown_emptyList_notificationCleared() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-
-        mNotificationController.handleScanResults(new ArrayList<>());
-
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
-    }
-    /**
-     * When a notification is showing, screen is off, and scan results with no open networks are
-     * handled, the notification is cleared.
-     */
-    @Test
-    public void handleScanResults_notificationShown_screenOff_emptyList_notificationCleared() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-
-        mNotificationController.handleScreenStateChanged(false);
-        mNotificationController.handleScanResults(new ArrayList<>());
-
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
-    }
-
-    /**
-     * If notification is showing, do not post another notification.
-     */
-    @Test
-    public void handleScanResults_notificationShowing_doesNotRepostNotification() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-    }
-
-    /**
-     * When {@link WifiNotificationController#clearPendingNotification(boolean)} is called and a
-     * notification is shown, clear the notification.
-     */
-    @Test
-    public void clearPendingNotification_clearsNotificationIfOneIsShowing() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-
-        mNotificationController.clearPendingNotification(true);
-
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
-    }
-
-    /**
-     * When {@link WifiNotificationController#clearPendingNotification(boolean)} is called and a
-     * notification was not previously shown, do not clear the notification.
-     */
-    @Test
-    public void clearPendingNotification_doesNotClearNotificationIfNoneShowing() {
-        mNotificationController.clearPendingNotification(true);
-
-        verify(mNotificationManager, never()).cancelAsUser(any(), anyInt(), any());
-    }
-
-    /**
-     * When screen is off and notification is not displayed, notification is not posted on handling
-     * new scan results with open networks.
-     */
-    @Test
-    public void screenOff_handleScanResults_notificationNotDisplayed() {
-        mNotificationController.handleScreenStateChanged(false);
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
-    }
-
-    /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} disables the feature. */
-    @Test
-    public void userHasDisallowConfigWifiRestriction_notificationNotDisplayed() {
-        when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT))
-                .thenReturn(true);
-
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
-    }
-
-    /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} clears the showing notification. */
-    @Test
-    public void userHasDisallowConfigWifiRestriction_showingNotificationIsCleared() {
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
-
-        when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT))
-                .thenReturn(true);
-
-        mNotificationController.handleScanResults(createOpenScanResults());
-
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
-    }
-}
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java b/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
index 24d3afa..6f01c8e 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
@@ -48,6 +48,18 @@
 
     private static final int CELLULAR_THRESHOLD_SCORE = 50;
 
+    class FakeClock extends Clock {
+        long mWallClockMillis = 1500000000000L;
+        int mStepMillis = 1001;
+
+        @Override
+        public long getWallClockMillis() {
+            mWallClockMillis += mStepMillis;
+            return mWallClockMillis;
+        }
+    }
+
+    FakeClock mClock;
     WifiConfiguration mWifiConfiguration;
     WifiScoreReport mWifiScoreReport;
     ScanDetailCache mScanDetailCache;
@@ -122,7 +134,8 @@
         when(mWifiConfigManager.getScanDetailCacheForNetwork(anyInt()))
                 .thenReturn(mScanDetailCache);
         when(mContext.getResources()).thenReturn(mResources);
-        mWifiScoreReport = new WifiScoreReport(mContext, mWifiConfigManager, new Clock());
+        mClock = new FakeClock();
+        mWifiScoreReport = new WifiScoreReport(mContext, mWifiConfigManager, mClock);
     }
 
     /**
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java b/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
index 055050d..e43bdc2 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
@@ -400,7 +400,9 @@
     public void testSetWifiEnabledFromNetworkSettingsHolderWhenInAirplaneMode() throws Exception {
         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
         when(mSettingsStore.isAirplaneModeOn()).thenReturn(true);
-        when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
+        when(mContext.checkPermission(
+                eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
+                        .thenReturn(PackageManager.PERMISSION_GRANTED);
         assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true));
         verify(mWifiController).sendMessage(eq(CMD_WIFI_TOGGLED));
     }
@@ -413,7 +415,9 @@
     public void testSetWifiEnabledFromAppFailsWhenInAirplaneMode() throws Exception {
         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
         when(mSettingsStore.isAirplaneModeOn()).thenReturn(true);
-        when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
+        when(mContext.checkPermission(
+                eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
+                        .thenReturn(PackageManager.PERMISSION_DENIED);
         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
         verify(mWifiController, never()).sendMessage(eq(CMD_WIFI_TOGGLED));
     }
@@ -426,7 +430,9 @@
     public void testSetWifiEnabledFromNetworkSettingsHolderWhenApEnabled() throws Exception {
         when(mWifiStateMachine.syncGetWifiApState()).thenReturn(WifiManager.WIFI_AP_STATE_ENABLED);
         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
-        when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
+        when(mContext.checkPermission(
+                eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
+                        .thenReturn(PackageManager.PERMISSION_GRANTED);
         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
         assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true));
         verify(mWifiController).sendMessage(eq(CMD_WIFI_TOGGLED));
@@ -438,7 +444,9 @@
     @Test
     public void testSetWifiEnabledFromAppFailsWhenApEnabled() throws Exception {
         when(mWifiStateMachine.syncGetWifiApState()).thenReturn(WifiManager.WIFI_AP_STATE_ENABLED);
-        when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
+        when(mContext.checkPermission(
+                eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
+                        .thenReturn(PackageManager.PERMISSION_DENIED);
         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
         verify(mSettingsStore, never()).handleWifiToggled(anyBoolean());
diff --git a/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java b/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java
index 929a5fe..c63db86 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java
@@ -30,6 +30,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -42,6 +43,7 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.UserInfo;
+import android.hardware.wifi.supplicant.V1_0.ISupplicantStaIfaceCallback;
 import android.net.ConnectivityManager;
 import android.net.DhcpResults;
 import android.net.LinkProperties;
@@ -74,6 +76,7 @@
 import android.os.Message;
 import android.os.Messenger;
 import android.os.PowerManager;
+import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.UserManager;
@@ -97,6 +100,7 @@
 import com.android.server.wifi.hotspot2.NetworkDetail;
 import com.android.server.wifi.hotspot2.PasspointManager;
 import com.android.server.wifi.p2p.WifiP2pServiceImpl;
+import com.android.server.wifi.util.WifiPermissionsUtil;
 
 import org.junit.After;
 import org.junit.Before;
@@ -138,6 +142,7 @@
     private static final int WPS_SUPPLICANT_NETWORK_ID = 5;
     private static final int WPS_FRAMEWORK_NETWORK_ID = 10;
     private static final String DEFAULT_TEST_SSID = "\"GoogleGuest\"";
+    private static final String OP_PACKAGE_NAME = "com.xxx";
 
     private long mBinderToken;
 
@@ -226,6 +231,8 @@
         when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(
                 mock(ConnectivityManager.class));
 
+        when(context.getOpPackageName()).thenReturn(OP_PACKAGE_NAME);
+
         return context;
     }
 
@@ -338,6 +345,7 @@
     @Mock IClientInterface mClientInterface;
     @Mock IBinder mApInterfaceBinder;
     @Mock IBinder mClientInterfaceBinder;
+    @Mock IBinder mPackageManagerBinder;
     @Mock WifiConfigManager mWifiConfigManager;
     @Mock WifiNative mWifiNative;
     @Mock WifiConnectivityManager mWifiConnectivityManager;
@@ -345,6 +353,7 @@
     @Mock WifiStateTracker mWifiStateTracker;
     @Mock PasspointManager mPasspointManager;
     @Mock SelfRecovery mSelfRecovery;
+    @Mock WifiPermissionsUtil mWifiPermissionsUtil;
     @Mock IpManager mIpManager;
     @Mock TelephonyManager mTelephonyManager;
     @Mock WrongPasswordNotifier mWrongPasswordNotifier;
@@ -390,6 +399,7 @@
         when(mWifiInjector.getWifiMonitor()).thenReturn(mWifiMonitor);
         when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative);
         when(mWifiInjector.getSelfRecovery()).thenReturn(mSelfRecovery);
+        when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil);
         when(mWifiInjector.makeTelephonyManager()).thenReturn(mTelephonyManager);
         when(mWifiInjector.getClock()).thenReturn(mClock);
 
@@ -829,6 +839,7 @@
                 .thenReturn(new NetworkUpdateResult(0));
         when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(config));
         when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config);
+        when(mWifiConfigManager.getConfiguredNetworkWithPassword(0)).thenReturn(config);
 
         mLooper.startAutoDispatch();
         mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config);
@@ -958,7 +969,7 @@
 
         when(mScanDetailCache.getScanDetail(sBSSID)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID, sFreq));
-        when(mScanDetailCache.get(sBSSID)).thenReturn(
+        when(mScanDetailCache.getScanResult(sBSSID)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID, sFreq).getScanResult());
 
         mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID);
@@ -1560,31 +1571,29 @@
     }
 
     /**
-     * Verify successful Wps PBC network connection.
+     * Sunny-day scenario for WPS connections. Verifies that after a START_WPS and
+     * NETWORK_CONNECTION_EVENT command, WifiStateMachine will have transitioned to ObtainingIpState
      */
     @Test
     public void wpsPbcConnectSuccess() throws Exception {
         loadComponentsInStaMode();
         mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
         mLooper.dispatchAll();
+        assertEquals("DisconnectedState", getCurrentState().getName());
 
-        when(mWifiNative.startWpsPbc(eq(sBSSID))).thenReturn(true);
         WpsInfo wpsInfo = new WpsInfo();
         wpsInfo.setup = WpsInfo.PBC;
         wpsInfo.BSSID = sBSSID;
-
+        when(mWifiNative.removeAllNetworks()).thenReturn(true);
+        when(mWifiNative.startWpsPbc(anyString())).thenReturn(true);
         mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo);
         mLooper.dispatchAll();
-        verify(mWifiNative).startWpsPbc(eq(sBSSID));
-
         assertEquals("WpsRunningState", getCurrentState().getName());
 
         setupMocksForWpsNetworkMigration();
-
         mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
         mLooper.dispatchAll();
-
-        assertEquals("DisconnectedState", getCurrentState().getName());
+        assertEquals("ObtainingIpState", getCurrentState().getName());
         verifyMocksForWpsNetworkMigration();
     }
 
@@ -1610,6 +1619,68 @@
     }
 
     /**
+     * Verify that if Supplicant generates multiple networks for a WPS configuration,
+     * WifiStateMachine cycles into DisconnectedState
+     */
+    @Test
+    public void wpsPbcConnectFailure_tooManyConfigs() throws Exception {
+        loadComponentsInStaMode();
+        mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
+        mLooper.dispatchAll();
+        assertEquals("DisconnectedState", getCurrentState().getName());
+
+        WpsInfo wpsInfo = new WpsInfo();
+        wpsInfo.setup = WpsInfo.PBC;
+        wpsInfo.BSSID = sBSSID;
+        when(mWifiNative.removeAllNetworks()).thenReturn(true);
+        when(mWifiNative.startWpsPbc(anyString())).thenReturn(true);
+        mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo);
+        mLooper.dispatchAll();
+        assertEquals("WpsRunningState", getCurrentState().getName());
+
+        setupMocksForWpsNetworkMigration();
+        doAnswer(new AnswerWithArguments() {
+            public boolean answer(Map<String, WifiConfiguration> configs,
+                                  SparseArray<Map<String, String>> networkExtras) throws Exception {
+                configs.put("dummy1", new WifiConfiguration());
+                configs.put("dummy2", new WifiConfiguration());
+                return true;
+            }
+        }).when(mWifiNative).migrateNetworksFromSupplicant(any(Map.class), any(SparseArray.class));
+        mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
+        mLooper.dispatchAll();
+        assertTrue("DisconnectedState".equals(getCurrentState().getName()));
+    }
+
+    /**
+     * Verify that when supplicant fails to load networks during WPS, WifiStateMachine cycles into
+     * DisconnectedState
+     */
+    @Test
+    public void wpsPbcConnectFailure_migrateNetworksFailure() throws Exception {
+        loadComponentsInStaMode();
+        mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
+        mLooper.dispatchAll();
+        assertEquals("DisconnectedState", getCurrentState().getName());
+
+        WpsInfo wpsInfo = new WpsInfo();
+        wpsInfo.setup = WpsInfo.PBC;
+        wpsInfo.BSSID = sBSSID;
+        when(mWifiNative.removeAllNetworks()).thenReturn(true);
+        when(mWifiNative.startWpsPbc(anyString())).thenReturn(true);
+        mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo);
+        mLooper.dispatchAll();
+        assertEquals("WpsRunningState", getCurrentState().getName());
+
+        setupMocksForWpsNetworkMigration();
+        when(mWifiNative.migrateNetworksFromSupplicant(any(Map.class), any(SparseArray.class)))
+                .thenReturn(false);
+        mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
+        mLooper.dispatchAll();
+        assertEquals("DisconnectedState", getCurrentState().getName());
+    }
+
+    /**
      * Verify successful Wps Pin Display network connection.
      */
     @Test
@@ -1634,7 +1705,7 @@
         mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
         mLooper.dispatchAll();
 
-        assertEquals("DisconnectedState", getCurrentState().getName());
+        assertEquals("ObtainingIpState", getCurrentState().getName());
         verifyMocksForWpsNetworkMigration();
     }
 
@@ -1707,13 +1778,12 @@
     }
 
     private void setupMocksForWpsNetworkMigration() {
-        // Now trigger the network connection event for adding the WPS network.
+        WifiConfiguration config = new WifiConfiguration();
+        config.networkId = WPS_SUPPLICANT_NETWORK_ID;
+        config.SSID = DEFAULT_TEST_SSID;
         doAnswer(new AnswerWithArguments() {
             public boolean answer(Map<String, WifiConfiguration> configs,
                                   SparseArray<Map<String, String>> networkExtras) throws Exception {
-                WifiConfiguration config = new WifiConfiguration();
-                config.networkId = WPS_SUPPLICANT_NETWORK_ID;
-                config.SSID = DEFAULT_TEST_SSID;
                 configs.put("dummy", config);
                 return true;
             }
@@ -1722,6 +1792,10 @@
                 .thenReturn(new NetworkUpdateResult(WPS_FRAMEWORK_NETWORK_ID));
         when(mWifiConfigManager.enableNetwork(eq(WPS_FRAMEWORK_NETWORK_ID), anyBoolean(), anyInt()))
                 .thenReturn(true);
+        when(mWifiNative.getFrameworkNetworkId(eq(WPS_FRAMEWORK_NETWORK_ID))).thenReturn(
+                WPS_FRAMEWORK_NETWORK_ID);
+        when(mWifiConfigManager.getConfiguredNetwork(eq(WPS_FRAMEWORK_NETWORK_ID))).thenReturn(
+                config);
     }
 
     private void verifyMocksForWpsNetworkMigration() {
@@ -1748,7 +1822,7 @@
                 .thenReturn(mScanDetailCache);
         when(mScanDetailCache.getScanDetail(sBSSID1)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID1, sFreq1));
-        when(mScanDetailCache.get(sBSSID1)).thenReturn(
+        when(mScanDetailCache.getScanResult(sBSSID1)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID1, sFreq1).getScanResult());
 
         // This simulates the behavior of roaming to network with |sBSSID1|, |sFreq1|.
@@ -1776,7 +1850,7 @@
                 .thenReturn(mScanDetailCache);
         when(mScanDetailCache.getScanDetail(sBSSID1)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID1, sFreq1));
-        when(mScanDetailCache.get(sBSSID1)).thenReturn(
+        when(mScanDetailCache.getScanResult(sBSSID1)).thenReturn(
                 getGoogleGuestScanDetail(TEST_RSSI, sBSSID1, sFreq1).getScanResult());
 
         // This simulates the behavior of roaming to network with |sBSSID1|, |sFreq1|.
@@ -1856,6 +1930,124 @@
     }
 
     /**
+     * Test that the process uid has full wifiInfo access.
+     * Also tests that {@link WifiStateMachine#syncRequestConnectionInfo(String)} always
+     * returns a copy of WifiInfo.
+     */
+    @Test
+    public void testConnectedIdsAreVisibleFromOwnUid() throws Exception {
+        assertEquals(Process.myUid(), Binder.getCallingUid());
+        WifiInfo wifiInfo = mWsm.getWifiInfo();
+        wifiInfo.setBSSID(sBSSID);
+        wifiInfo.setSSID(WifiSsid.createFromAsciiEncoded(sSSID));
+
+        connect();
+        WifiInfo connectionInfo = mWsm.syncRequestConnectionInfo(mContext.getOpPackageName());
+
+        assertNotEquals(wifiInfo, connectionInfo);
+        assertEquals(wifiInfo.getSSID(), connectionInfo.getSSID());
+        assertEquals(wifiInfo.getBSSID(), connectionInfo.getBSSID());
+    }
+
+    /**
+     * Test that connected SSID and BSSID are not exposed to an app that does not have the
+     * appropriate permissions.
+     * Also tests that {@link WifiStateMachine#syncRequestConnectionInfo(String)} always
+     * returns a copy of WifiInfo.
+     */
+    @Test
+    public void testConnectedIdsAreHiddenFromRandomApp() throws Exception {
+        int actualUid = Binder.getCallingUid();
+        int fakeUid = Process.myUid() + 100000;
+        assertNotEquals(actualUid, fakeUid);
+        BinderUtil.setUid(fakeUid);
+        try {
+            WifiInfo wifiInfo = mWsm.getWifiInfo();
+
+            // Get into a connected state, with known BSSID and SSID
+            connect();
+            assertEquals(sBSSID, wifiInfo.getBSSID());
+            assertEquals(sWifiSsid, wifiInfo.getWifiSsid());
+
+            when(mWifiPermissionsUtil.canAccessScanResults(anyString(), eq(fakeUid), anyInt()))
+                    .thenReturn(false);
+
+            WifiInfo connectionInfo = mWsm.syncRequestConnectionInfo(mContext.getOpPackageName());
+
+            assertNotEquals(wifiInfo, connectionInfo);
+            assertEquals(WifiSsid.NONE, connectionInfo.getSSID());
+            assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID());
+        } finally {
+            BinderUtil.setUid(actualUid);
+        }
+    }
+
+    /**
+     * Test that connected SSID and BSSID are not exposed to an app that does not have the
+     * appropriate permissions, when canAccessScanResults raises a SecurityException.
+     * Also tests that {@link WifiStateMachine#syncRequestConnectionInfo(String)} always
+     * returns a copy of WifiInfo.
+     */
+    @Test
+    public void testConnectedIdsAreHiddenOnSecurityException() throws Exception {
+        int actualUid = Binder.getCallingUid();
+        int fakeUid = Process.myUid() + 100000;
+        assertNotEquals(actualUid, fakeUid);
+        BinderUtil.setUid(fakeUid);
+        try {
+            WifiInfo wifiInfo = mWsm.getWifiInfo();
+
+            // Get into a connected state, with known BSSID and SSID
+            connect();
+            assertEquals(sBSSID, wifiInfo.getBSSID());
+            assertEquals(sWifiSsid, wifiInfo.getWifiSsid());
+
+            when(mWifiPermissionsUtil.canAccessScanResults(anyString(), eq(fakeUid), anyInt()))
+                    .thenThrow(new SecurityException());
+
+            WifiInfo connectionInfo = mWsm.syncRequestConnectionInfo(mContext.getOpPackageName());
+
+            assertNotEquals(wifiInfo, connectionInfo);
+            assertEquals(WifiSsid.NONE, connectionInfo.getSSID());
+            assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID());
+        } finally {
+            BinderUtil.setUid(actualUid);
+        }
+    }
+
+    /**
+     * Test that connected SSID and BSSID are exposed to an app that does have the
+     * appropriate permissions.
+     */
+    @Test
+    public void testConnectedIdsAreVisibleFromPermittedApp() throws Exception {
+        int actualUid = Binder.getCallingUid();
+        int fakeUid = Process.myUid() + 100000;
+        BinderUtil.setUid(fakeUid);
+        try {
+            WifiInfo wifiInfo = mWsm.getWifiInfo();
+
+            // Get into a connected state, with known BSSID and SSID
+            connect();
+            assertEquals(sBSSID, wifiInfo.getBSSID());
+            assertEquals(sWifiSsid, wifiInfo.getWifiSsid());
+
+            when(mWifiPermissionsUtil.canAccessScanResults(anyString(), eq(fakeUid), anyInt()))
+                    .thenReturn(true);
+
+            WifiInfo connectionInfo = mWsm.syncRequestConnectionInfo(mContext.getOpPackageName());
+
+            assertNotEquals(wifiInfo, connectionInfo);
+            assertEquals(wifiInfo.getSSID(), connectionInfo.getSSID());
+            assertEquals(wifiInfo.getBSSID(), connectionInfo.getBSSID());
+            // Access to our MAC address uses a different permission, make sure it is not granted
+            assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getMacAddress());
+        } finally {
+            BinderUtil.setUid(actualUid);
+        }
+    }
+
+    /**
      * Adds the network without putting WifiStateMachine into ConnectMode.
      */
     @Test
@@ -1872,9 +2064,7 @@
     @Test
     public void testStartWps_nullWpsInfo() throws Exception {
         loadComponentsInStaMode();
-        mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
-        assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest());
-        assertEquals("DisconnectedState", getCurrentState().getName());
+
         mLooper.startAutoDispatch();
         Message reply = mWsmAsyncChannel.sendMessageSynchronously(WifiManager.START_WPS, 0, 0,
                 null);
@@ -1889,9 +2079,6 @@
     @Test
     public void testSyncDisableNetwork_failure() throws Exception {
         loadComponentsInStaMode();
-        mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
-        assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest());
-        assertEquals("DisconnectedState", getCurrentState().getName());
         when(mWifiConfigManager.disableNetwork(anyInt(), anyInt())).thenReturn(false);
 
         mLooper.startAutoDispatch();
@@ -2151,6 +2338,43 @@
     }
 
     /**
+     * Verifies that WifiStateMachine sets and unsets appropriate 'RecentFailureReason' values
+     * on a WifiConfiguration when it fails association, authentication, or successfully connects
+     */
+    @Test
+    public void testExtraFailureReason_ApIsBusy() throws Exception {
+        // Setup CONNECT_MODE & a WifiConfiguration
+        initializeAndAddNetworkAndVerifySuccess();
+        mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE);
+        mLooper.dispatchAll();
+        // Trigger a connection to this (CMD_START_CONNECT will actually fail, but it sets up
+        // targetNetworkId state)
+        mWsm.sendMessage(WifiStateMachine.CMD_START_CONNECT, 0, 0, sBSSID);
+        mLooper.dispatchAll();
+        // Simulate an ASSOCIATION_REJECTION_EVENT, due to the AP being busy
+        mWsm.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT, 0,
+                ISupplicantStaIfaceCallback.StatusCode.AP_UNABLE_TO_HANDLE_NEW_STA, sBSSID);
+        mLooper.dispatchAll();
+        verify(mWifiConfigManager).setRecentFailureAssociationStatus(eq(0),
+                eq(WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA));
+        assertEquals("DisconnectedState", getCurrentState().getName());
+
+        // Simulate an AUTHENTICATION_FAILURE_EVENT, which should clear the ExtraFailureReason
+        reset(mWifiConfigManager);
+        mWsm.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT, 0, 0, null);
+        mLooper.dispatchAll();
+        verify(mWifiConfigManager).clearRecentFailureReason(eq(0));
+        verify(mWifiConfigManager, never()).setRecentFailureAssociationStatus(anyInt(), anyInt());
+
+        // Simulate a NETWORK_CONNECTION_EVENT which should clear the ExtraFailureReason
+        reset(mWifiConfigManager);
+        mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
+        mLooper.dispatchAll();
+        verify(mWifiConfigManager).clearRecentFailureReason(eq(0));
+        verify(mWifiConfigManager, never()).setRecentFailureAssociationStatus(anyInt(), anyInt());
+    }
+
+    /**
      * Test that the helper method
      * {@link WifiStateMachine#shouldEvaluateWhetherToSendExplicitlySelected(WifiConfiguration)}
      * returns true when we connect to the last selected network before expiration of
@@ -2214,20 +2438,4 @@
         currentConfig.networkId = lastSelectedNetworkId - 1;
         assertFalse(mWsm.shouldEvaluateWhetherToSendExplicitlySelected(currentConfig));
     }
-
-    /**
-     * Test that {@link WifiStateMachine#syncRequestConnectionInfo()} always returns a copy of
-     * WifiInfo.
-     */
-    @Test
-    public void testSyncRequestConnectionInfoDoesNotReturnLocalReference() {
-        WifiInfo wifiInfo = mWsm.getWifiInfo();
-        wifiInfo.setBSSID(sBSSID);
-        wifiInfo.setSSID(WifiSsid.createFromAsciiEncoded(sSSID));
-
-        WifiInfo syncWifiInfo = mWsm.syncRequestConnectionInfo();
-        assertEquals(wifiInfo.getSSID(), syncWifiInfo.getSSID());
-        assertEquals(wifiInfo.getBSSID(), syncWifiInfo.getBSSID());
-        assertFalse(wifiInfo == syncWifiInfo);
-    }
 }
diff --git a/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java b/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
index 2617331..cca2045 100644
--- a/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
@@ -23,7 +23,10 @@
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.argThat;
 import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -33,6 +36,8 @@
 import android.net.wifi.IScanEvent;
 import android.net.wifi.IWifiScannerImpl;
 import android.net.wifi.IWificond;
+import android.net.wifi.ScanResult;
+import android.net.wifi.WifiEnterpriseConfig;
 import android.net.wifi.WifiScanner;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -48,6 +53,7 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.ArgumentMatcher;
 
+import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.HashSet;
@@ -60,6 +66,8 @@
 public class WificondControlTest {
     private WifiInjector mWifiInjector;
     private WifiMonitor mWifiMonitor;
+    private WifiMetrics mWifiMetrics;
+    private CarrierNetworkConfig mCarrierNetworkConfig;
     private WificondControl mWificondControl;
     private static final String TEST_INTERFACE_NAME = "test_wlan_if";
     private static final byte[] TEST_SSID =
@@ -68,7 +76,7 @@
             new byte[] {(byte) 0x12, (byte) 0xef, (byte) 0xa1,
                         (byte) 0x2c, (byte) 0x97, (byte) 0x8b};
     // This the IE buffer which is consistent with TEST_SSID.
-    private static final byte[] TEST_INFO_ELEMENT =
+    private static final byte[] TEST_INFO_ELEMENT_SSID =
             new byte[] {
                     // Element ID for SSID.
                     (byte) 0x00,
@@ -76,6 +84,17 @@
                     (byte) 0x0b,
                     // This is string "GoogleGuest"
                     'G', 'o', 'o', 'g', 'l', 'e', 'G', 'u', 'e', 's', 't'};
+    // RSN IE data indicating EAP key management.
+    private static final byte[] TEST_INFO_ELEMENT_RSN =
+            new byte[] {
+                    // Element ID for RSN.
+                    (byte) 0x30,
+                    // Length of the element data.
+                    (byte) 0x18,
+                    (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x0F, (byte) 0xAC, (byte) 0x02,
+                    (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x0F, (byte) 0xAC, (byte) 0x04,
+                    (byte) 0x00, (byte) 0x0F, (byte) 0xAC, (byte) 0x02, (byte) 0x01, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x0F, (byte) 0xAC, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
 
     private static final int TEST_FREQUENCY = 2456;
     private static final int TEST_SIGNAL_MBM = -4500;
@@ -86,7 +105,7 @@
             new NativeScanResult() {{
                 ssid = TEST_SSID;
                 bssid = TEST_BSSID;
-                infoElement = TEST_INFO_ELEMENT;
+                infoElement = TEST_INFO_ELEMENT_SSID;
                 frequency = TEST_FREQUENCY;
                 signalMbm = TEST_SIGNAL_MBM;
                 capability = TEST_CAPABILITY;
@@ -127,7 +146,10 @@
     public void setUp() throws Exception {
         mWifiInjector = mock(WifiInjector.class);
         mWifiMonitor = mock(WifiMonitor.class);
-        mWificondControl = new WificondControl(mWifiInjector, mWifiMonitor);
+        mWifiMetrics = mock(WifiMetrics.class);
+        when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);
+        mCarrierNetworkConfig = mock(CarrierNetworkConfig.class);
+        mWificondControl = new WificondControl(mWifiInjector, mWifiMonitor, mCarrierNetworkConfig);
     }
 
     /**
@@ -441,7 +463,8 @@
         assertTrue(mWificondControl.tearDownInterfaces());
 
         // getScanResults should fail.
-        assertEquals(0, mWificondControl.getScanResults().size());
+        assertEquals(0,
+                mWificondControl.getScanResults(WificondControl.SCAN_TYPE_SINGLE_SCAN).size());
     }
 
     /**
@@ -456,7 +479,12 @@
         NativeScanResult[] mockScanResults = {MOCK_NATIVE_SCAN_RESULT};
         when(scanner.getScanResults()).thenReturn(mockScanResults);
 
-        ArrayList<ScanDetail> returnedScanResults = mWificondControl.getScanResults();
+        ArrayList<ScanDetail> returnedScanResults = mWificondControl.getScanResults(
+                WificondControl.SCAN_TYPE_SINGLE_SCAN);
+        // The test IEs {@link #TEST_INFO_ELEMENT} doesn't contained RSN IE, which means non-EAP
+        // AP. So verify carrier network is not checked, since EAP is currently required for a
+        // carrier network.
+        verify(mCarrierNetworkConfig, never()).isCarrierNetwork(anyString());
         assertEquals(mockScanResults.length, returnedScanResults.size());
         // Since NativeScanResult is organized differently from ScanResult, this only checks
         // a few fields.
@@ -471,6 +499,60 @@
     }
 
     /**
+     * Verifies that scan result's carrier network info {@link ScanResult#isCarrierAp} and
+     * {@link ScanResult#getCarrierApEapType} is set appropriated based on the carrier network
+     * config.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void testGetScanResultsForCarrierAp() throws Exception {
+        IWifiScannerImpl scanner = setupClientInterfaceAndCreateMockWificondScanner();
+        assertNotNull(scanner);
+
+        // Include RSN IE to indicate EAP key management.
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        out.write(TEST_INFO_ELEMENT_SSID);
+        out.write(TEST_INFO_ELEMENT_RSN);
+        NativeScanResult nativeScanResult = new NativeScanResult(MOCK_NATIVE_SCAN_RESULT);
+        nativeScanResult.infoElement = out.toByteArray();
+        when(scanner.getScanResults()).thenReturn(new NativeScanResult[] {nativeScanResult});
+
+        // AP associated with a carrier network.
+        int eapType = WifiEnterpriseConfig.Eap.SIM;
+        String carrierName = "Test Carrier";
+        when(mCarrierNetworkConfig.isCarrierNetwork(new String(nativeScanResult.ssid)))
+                .thenReturn(true);
+        when(mCarrierNetworkConfig.getNetworkEapType(new String(nativeScanResult.ssid)))
+                .thenReturn(eapType);
+        when(mCarrierNetworkConfig.getCarrierName(new String(nativeScanResult.ssid)))
+                .thenReturn(carrierName);
+        ArrayList<ScanDetail> returnedScanResults = mWificondControl.getScanResults(
+                WificondControl.SCAN_TYPE_SINGLE_SCAN);
+        assertEquals(1, returnedScanResults.size());
+        // Verify returned scan result.
+        ScanResult scanResult = returnedScanResults.get(0).getScanResult();
+        assertArrayEquals(nativeScanResult.ssid, scanResult.SSID.getBytes());
+        assertTrue(scanResult.isCarrierAp);
+        assertEquals(eapType, scanResult.carrierApEapType);
+        assertEquals(carrierName, scanResult.carrierName);
+        reset(mCarrierNetworkConfig);
+
+        // AP not associated with a carrier network.
+        when(mCarrierNetworkConfig.isCarrierNetwork(new String(nativeScanResult.ssid)))
+                .thenReturn(false);
+        returnedScanResults = mWificondControl.getScanResults(
+                WificondControl.SCAN_TYPE_SINGLE_SCAN);
+        assertEquals(1, returnedScanResults.size());
+        // Verify returned scan result.
+        scanResult = returnedScanResults.get(0).getScanResult();
+        assertArrayEquals(nativeScanResult.ssid, scanResult.SSID.getBytes());
+        assertFalse(scanResult.isCarrierAp);
+        assertEquals(ScanResult.UNSPECIFIED, scanResult.carrierApEapType);
+        assertEquals(null, scanResult.carrierName);
+    }
+
+    /**
      * Verifies that Scan() can convert input parameters to SingleScanSettings correctly.
      */
     @Test
@@ -581,7 +663,7 @@
 
     /**
      * Verifies that WificondControl can invoke WifiMonitor broadcast methods upon pno scan
-     * reuslt event.
+     * result event.
      */
     @Test
     public void testPnoScanResultEvent() throws Exception {
@@ -592,11 +674,48 @@
         IPnoScanEvent pnoScanEvent = messageCaptor.getValue();
         assertNotNull(pnoScanEvent);
         pnoScanEvent.OnPnoNetworkFound();
-
         verify(mWifiMonitor).broadcastPnoScanResultEvent(any(String.class));
     }
 
     /**
+     * Verifies that WificondControl can invoke WifiMetrics pno scan count methods upon pno event.
+     */
+    @Test
+    public void testPnoScanEventsForMetrics() throws Exception {
+        IWifiScannerImpl scanner = setupClientInterfaceAndCreateMockWificondScanner();
+
+        ArgumentCaptor<IPnoScanEvent> messageCaptor = ArgumentCaptor.forClass(IPnoScanEvent.class);
+        verify(scanner).subscribePnoScanEvents(messageCaptor.capture());
+        IPnoScanEvent pnoScanEvent = messageCaptor.getValue();
+        assertNotNull(pnoScanEvent);
+
+        pnoScanEvent.OnPnoNetworkFound();
+        verify(mWifiMetrics).incrementPnoFoundNetworkEventCount();
+
+        pnoScanEvent.OnPnoScanFailed();
+        verify(mWifiMetrics).incrementPnoScanFailedCount();
+
+        pnoScanEvent.OnPnoScanOverOffloadStarted();
+        verify(mWifiMetrics).incrementPnoScanStartedOverOffloadCount();
+
+        pnoScanEvent.OnPnoScanOverOffloadFailed(0);
+        verify(mWifiMetrics).incrementPnoScanFailedOverOffloadCount();
+    }
+
+    /**
+     * Verifies that startPnoScan() can invoke WifiMetrics pno scan count methods correctly.
+     */
+    @Test
+    public void testStartPnoScanForMetrics() throws Exception {
+        IWifiScannerImpl scanner = setupClientInterfaceAndCreateMockWificondScanner();
+
+        when(scanner.startPnoScan(any(PnoSettings.class))).thenReturn(false);
+        assertFalse(mWificondControl.startPnoScan(TEST_PNO_SETTINGS));
+        verify(mWifiMetrics).incrementPnoScanStartAttempCount();
+        verify(mWifiMetrics).incrementPnoScanFailedCount();
+    }
+
+    /**
      * Verifies that abortScan() calls underlying wificond.
      */
     @Test
diff --git a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
index 8063004..227a196 100644
--- a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
@@ -83,7 +83,6 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
-import java.lang.reflect.Field;
 import java.util.Arrays;
 
 /**
@@ -99,7 +98,6 @@
     @Mock private WifiAwareNativeManager mMockNativeManager;
     @Mock private WifiAwareNativeApi mMockNative;
     @Mock private Context mMockContext;
-    @Mock private IWifiAwareManager mMockAwareService;
     @Mock private ConnectivityManager mMockCm;
     @Mock private INetworkManagementService mMockNwMgt;
     @Mock private WifiAwareDataPathStateManager.NetworkInterfaceWrapper mMockNetworkInterface;
@@ -172,7 +170,8 @@
         when(mPermissionsWrapperMock.getUidPermission(eq(Manifest.permission.CONNECTIVITY_INTERNAL),
                 anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
 
-        installDataPathStateManagerMocks();
+        mDut.mDataPathMgr.mNwService = mMockNwMgt;
+        mDut.mDataPathMgr.mNiWrapper = mMockNetworkInterface;
     }
 
     /**
@@ -252,7 +251,7 @@
             mMockLooper.dispatchAll();
         }
 
-        verifyNoMoreInteractions(mMockNative);
+        verifyNoMoreInteractions(mMockNative, mMockNwMgt);
     }
 
     /**
@@ -273,12 +272,12 @@
                 anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, false);
 
         // (1) request network
         NetworkRequest nr = getSessionNetworkRequest(clientId, res.mSessionId, res.mPeerHandle, pmk,
-                null, false);
+                null, false, 0);
 
         Message reqNetworkMsg = Message.obtain();
         reqNetworkMsg.what = NetworkFactory.CMD_REQUEST_NETWORK;
@@ -288,7 +287,7 @@
         mMockLooper.dispatchAll();
 
         // failure: no interactions with connectivity manager or native manager
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
     }
 
     /**
@@ -309,12 +308,12 @@
         ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, true);
 
         // (1) request network
         NetworkRequest nr = getSessionNetworkRequest(clientId, res.mSessionId, res.mPeerHandle,
-                null, null, true);
+                null, null, true, 0);
 
         Message reqNetworkMsg = Message.obtain();
         reqNetworkMsg.what = NetworkFactory.CMD_REQUEST_NETWORK;
@@ -342,7 +341,233 @@
         mMockLooper.dispatchAll();
 
         // failure if there's further activity
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
+    }
+
+    /**
+     * Validate multiple NDPs created on a single NDI. Most importantly that the interface is
+     * set up on first NDP and torn down on last NDP - and not when one or the other is created or
+     * deleted.
+     *
+     * Procedure:
+     * - create NDP 1, 2, and 3 (interface up only on first)
+     * - delete NDP 2, 1, and 3 (interface down only on last)
+     */
+    @Test
+    public void testMultipleNdpsOnSingleNdi() throws Exception {
+        final int clientId = 123;
+        final byte pubSubId = 58;
+        final int requestorId = 1341234;
+        final int ndpId = 2;
+        final byte[] peerDiscoveryMac = HexEncoding.decode("000102030405".toCharArray(), false);
+        final byte[] peerDataPathMac = HexEncoding.decode("0A0B0C0D0E0F".toCharArray(), false);
+        final int[] startOrder = {0, 1, 2};
+        final int[] endOrder = {1, 0, 2};
+        int networkRequestId = 0;
+
+        ArgumentCaptor<Messenger> messengerCaptor = ArgumentCaptor.forClass(Messenger.class);
+        ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
+        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback,
+                mMockNwMgt);
+        InOrder inOrderM = inOrder(mAwareMetricsMock);
+
+        NetworkRequest[] nrs = new NetworkRequest[3];
+        DataPathEndPointInfo[] ress = new DataPathEndPointInfo[3];
+        Messenger[] agentMessengers = new Messenger[3];
+        Messenger messenger = null;
+        boolean first = true;
+        for (int i : startOrder) {
+            networkRequestId += 1;
+            peerDiscoveryMac[5] = (byte) (peerDiscoveryMac[5] + 1);
+            peerDataPathMac[5] = (byte) (peerDataPathMac[5] + 1);
+
+            // (0) initialize
+            ress[i] = initDataPathEndPoint(first, clientId, (byte) (pubSubId + i),
+                    requestorId + i, peerDiscoveryMac, inOrder, inOrderM, false);
+            if (first) {
+                messenger = ress[i].mMessenger;
+            }
+
+            // (1) request network
+            nrs[i] = getSessionNetworkRequest(clientId, ress[i].mSessionId, ress[i].mPeerHandle,
+                    null, null, false, networkRequestId);
+
+            Message reqNetworkMsg = Message.obtain();
+            reqNetworkMsg.what = NetworkFactory.CMD_REQUEST_NETWORK;
+            reqNetworkMsg.obj = nrs[i];
+            reqNetworkMsg.arg1 = 0;
+            messenger.send(reqNetworkMsg);
+            mMockLooper.dispatchAll();
+            inOrder.verify(mMockNative).initiateDataPath(transactionId.capture(),
+                    eq(requestorId + i),
+                    eq(CHANNEL_NOT_REQUESTED), anyInt(), eq(peerDiscoveryMac),
+                    eq(sAwareInterfacePrefix + "0"), eq(null),
+                    eq(null), eq(false), any());
+
+            mDut.onInitiateDataPathResponseSuccess(transactionId.getValue(), ndpId + i);
+            mMockLooper.dispatchAll();
+
+            // (2) get confirmation
+            mDut.onDataPathConfirmNotification(ndpId + i, peerDataPathMac, true, 0, null);
+            mMockLooper.dispatchAll();
+            if (first) {
+                inOrder.verify(mMockNwMgt).setInterfaceUp(anyString());
+                inOrder.verify(mMockNwMgt).enableIpv6(anyString());
+
+                first = false;
+            }
+            inOrder.verify(mMockCm).registerNetworkAgent(messengerCaptor.capture(), any(), any(),
+                    any(), anyInt(), any());
+            agentMessengers[i] = messengerCaptor.getValue();
+            inOrderM.verify(mAwareMetricsMock).recordNdpStatus(eq(NanStatusType.SUCCESS),
+                    eq(false), anyLong());
+            inOrderM.verify(mAwareMetricsMock).recordNdpCreation(anyInt(), any());
+        }
+
+        // (3) end data-path (unless didn't get confirmation)
+        int index = 0;
+        for (int i: endOrder) {
+            Message endNetworkReqMsg = Message.obtain();
+            endNetworkReqMsg.what = NetworkFactory.CMD_CANCEL_REQUEST;
+            endNetworkReqMsg.obj = nrs[i];
+            messenger.send(endNetworkReqMsg);
+
+            Message endNetworkUsageMsg = Message.obtain();
+            endNetworkUsageMsg.what = AsyncChannel.CMD_CHANNEL_DISCONNECTED;
+            agentMessengers[i].send(endNetworkUsageMsg);
+            mMockLooper.dispatchAll();
+
+            inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId + i));
+
+            mDut.onEndDataPathResponse(transactionId.getValue(), true, 0);
+            mDut.onDataPathEndNotification(ndpId + i);
+            mMockLooper.dispatchAll();
+
+            if (index++ == endOrder.length - 1) {
+                inOrder.verify(mMockNwMgt).setInterfaceDown(anyString());
+            }
+            inOrderM.verify(mAwareMetricsMock).recordNdpSessionDuration(anyLong());
+        }
+
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
+    }
+
+    /**
+     * Validate that multiple NDP requests which resolve to the same canonical request are treated
+     * as one.
+     */
+    @Test
+    public void testMultipleIdenticalRequests() throws Exception {
+        final int numRequestsPre = 6;
+        final int numRequestsPost = 5;
+        final int clientId = 123;
+        final int ndpId = 5;
+        final byte[] peerDiscoveryMac = HexEncoding.decode("000102030405".toCharArray(), false);
+        final byte[] peerDataPathMac = HexEncoding.decode("0A0B0C0D0E0F".toCharArray(), false);
+        NetworkRequest[] nrs = new NetworkRequest[numRequestsPre + numRequestsPost];
+
+        ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
+        ArgumentCaptor<Messenger> agentMessengerCaptor = ArgumentCaptor.forClass(Messenger.class);
+
+        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback,
+                mMockNwMgt);
+        InOrder inOrderM = inOrder(mAwareMetricsMock);
+
+        // (1) initialize all clients
+        Messenger messenger = initOobDataPathEndPoint(true, clientId, inOrder, inOrderM);
+        for (int i = 1; i < numRequestsPre + numRequestsPost; ++i) {
+            initOobDataPathEndPoint(false, clientId + i, inOrder, inOrderM);
+        }
+
+        // (2) make 3 network requests (all identical under the hood)
+        for (int i = 0; i < numRequestsPre; ++i) {
+            nrs[i] = getDirectNetworkRequest(clientId + i,
+                    WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, peerDiscoveryMac, null,
+                    null);
+
+            Message reqNetworkMsg = Message.obtain();
+            reqNetworkMsg.what = NetworkFactory.CMD_REQUEST_NETWORK;
+            reqNetworkMsg.obj = nrs[i];
+            reqNetworkMsg.arg1 = 0;
+            messenger.send(reqNetworkMsg);
+        }
+        mMockLooper.dispatchAll();
+
+        // (3) verify the start NDP HAL request
+        inOrder.verify(mMockNative).initiateDataPath(transactionId.capture(), eq(0),
+                eq(CHANNEL_NOT_REQUESTED), anyInt(), eq(peerDiscoveryMac),
+                eq(sAwareInterfacePrefix + "0"), eq(null), eq(null), eq(true), any());
+
+        // (4) unregister request #0 (the primary)
+        Message endNetworkReqMsg = Message.obtain();
+        endNetworkReqMsg.what = NetworkFactory.CMD_CANCEL_REQUEST;
+        endNetworkReqMsg.obj = nrs[0];
+        messenger.send(endNetworkReqMsg);
+        mMockLooper.dispatchAll();
+
+        // (5) respond to the registration request
+        mDut.onInitiateDataPathResponseSuccess(transactionId.getValue(), ndpId);
+        mMockLooper.dispatchAll();
+
+        // (6) unregister request #1
+        endNetworkReqMsg = Message.obtain();
+        endNetworkReqMsg.what = NetworkFactory.CMD_CANCEL_REQUEST;
+        endNetworkReqMsg.obj = nrs[1];
+        messenger.send(endNetworkReqMsg);
+        mMockLooper.dispatchAll();
+
+        // (7) confirm the NDP creation
+        mDut.onDataPathConfirmNotification(ndpId, peerDataPathMac, true, 0, null);
+        mMockLooper.dispatchAll();
+
+        inOrder.verify(mMockNwMgt).setInterfaceUp(anyString());
+        inOrder.verify(mMockNwMgt).enableIpv6(anyString());
+        inOrder.verify(mMockCm).registerNetworkAgent(agentMessengerCaptor.capture(), any(), any(),
+                any(), anyInt(), any());
+        inOrderM.verify(mAwareMetricsMock).recordNdpStatus(eq(NanStatusType.SUCCESS),
+                eq(true), anyLong());
+        inOrderM.verify(mAwareMetricsMock).recordNdpCreation(anyInt(), any());
+
+        // (8) execute 'post' requests
+        for (int i = numRequestsPre; i < numRequestsPre + numRequestsPost; ++i) {
+            nrs[i] = getDirectNetworkRequest(clientId + i,
+                    WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, peerDiscoveryMac, null,
+                    null);
+
+            Message reqNetworkMsg = Message.obtain();
+            reqNetworkMsg.what = NetworkFactory.CMD_REQUEST_NETWORK;
+            reqNetworkMsg.obj = nrs[i];
+            reqNetworkMsg.arg1 = 0;
+            messenger.send(reqNetworkMsg);
+        }
+        mMockLooper.dispatchAll();
+
+        // (9) unregister all requests
+        for (int i = 2; i < numRequestsPre + numRequestsPost; ++i) {
+            endNetworkReqMsg = Message.obtain();
+            endNetworkReqMsg.what = NetworkFactory.CMD_CANCEL_REQUEST;
+            endNetworkReqMsg.obj = nrs[i];
+            messenger.send(endNetworkReqMsg);
+            mMockLooper.dispatchAll();
+        }
+
+        Message endNetworkUsageMsg = Message.obtain();
+        endNetworkUsageMsg.what = AsyncChannel.CMD_CHANNEL_DISCONNECTED;
+        agentMessengerCaptor.getValue().send(endNetworkUsageMsg);
+        mMockLooper.dispatchAll();
+
+        // (10) verify that NDP torn down
+        inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId));
+
+        mDut.onEndDataPathResponse(transactionId.getValue(), true, 0);
+        mDut.onDataPathEndNotification(ndpId);
+        mMockLooper.dispatchAll();
+
+        inOrder.verify(mMockNwMgt).setInterfaceDown(anyString());
+        inOrderM.verify(mAwareMetricsMock).recordNdpSessionDuration(anyLong());
+
+        verifyNoMoreInteractions(mMockNative, mMockCm, mMockCallback, mMockSessionCallback,
+                mAwareMetricsMock, mMockNwMgt);
     }
 
     /*
@@ -563,12 +788,12 @@
         InOrder inOrderM = inOrder(mAwareMetricsMock);
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, doPublish);
 
         // (1) request network
         NetworkRequest nr = getSessionNetworkRequest(clientId, res.mSessionId, res.mPeerHandle, pmk,
-                null, doPublish);
+                null, doPublish, 0);
 
         // corrupt the network specifier: reverse the role (so it's mis-matched)
         WifiAwareNetworkSpecifier ns =
@@ -603,7 +828,7 @@
                     eq(ndpId), eq(""), eq(null), eq(null), anyBoolean(), any());
         }
 
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
     }
 
     private void testDataPathInitiatorResponderInvalidUidUtility(boolean doPublish,
@@ -619,12 +844,12 @@
         InOrder inOrderM = inOrder(mAwareMetricsMock);
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, doPublish);
 
         // (1) create network request
         NetworkRequest nr = getSessionNetworkRequest(clientId, res.mSessionId, res.mPeerHandle, pmk,
-                null, doPublish);
+                null, doPublish, 0);
 
         // (2) corrupt request's UID
         WifiAwareNetworkSpecifier ns =
@@ -660,7 +885,7 @@
                     eq(ndpId), eq(""), eq(null), eq(null), anyBoolean(), any());
         }
 
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
     }
 
     private void testDataPathInitiatorUtility(boolean useDirect, boolean provideMac,
@@ -678,7 +903,8 @@
 
         ArgumentCaptor<Messenger> messengerCaptor = ArgumentCaptor.forClass(Messenger.class);
         ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
-        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback);
+        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback,
+                mMockNwMgt);
         InOrder inOrderM = inOrder(mAwareMetricsMock);
 
         if (!providePmk) {
@@ -694,7 +920,7 @@
         }
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, false);
 
         // (1) request network
@@ -707,7 +933,7 @@
         } else {
             nr = getSessionNetworkRequest(clientId, res.mSessionId,
                     provideMac ? res.mPeerHandle : null, providePmk ? pmk : null,
-                    providePassphrase ? passphrase : null, false);
+                    providePassphrase ? passphrase : null, false, 0);
         }
 
         Message reqNetworkMsg = Message.obtain();
@@ -737,6 +963,8 @@
             mDut.onDataPathConfirmNotification(ndpId, peerDataPathMac, true, 0,
                     peerToken.getBytes());
             mMockLooper.dispatchAll();
+            inOrder.verify(mMockNwMgt).setInterfaceUp(anyString());
+            inOrder.verify(mMockNwMgt).enableIpv6(anyString());
             inOrder.verify(mMockCm).registerNetworkAgent(messengerCaptor.capture(), any(), any(),
                     any(), anyInt(), any());
             inOrderM.verify(mAwareMetricsMock).recordNdpStatus(eq(NanStatusType.SUCCESS),
@@ -763,16 +991,16 @@
             Message endNetworkUsageMsg = Message.obtain();
             endNetworkUsageMsg.what = AsyncChannel.CMD_CHANNEL_DISCONNECTED;
             messengerCaptor.getValue().send(endNetworkUsageMsg);
-
-            mMockLooper.dispatchAll();
-            inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId));
             mDut.onEndDataPathResponse(transactionId.getValue(), true, 0);
             mDut.onDataPathEndNotification(ndpId);
             mMockLooper.dispatchAll();
+
+            inOrder.verify(mMockNwMgt).setInterfaceDown(anyString());
+            inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId));
             inOrderM.verify(mAwareMetricsMock).recordNdpSessionDuration(anyLong());
         }
 
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
     }
 
     private void testDataPathResponderUtility(boolean useDirect, boolean provideMac,
@@ -790,7 +1018,8 @@
 
         ArgumentCaptor<Messenger> messengerCaptor = ArgumentCaptor.forClass(Messenger.class);
         ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
-        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback);
+        InOrder inOrder = inOrder(mMockNative, mMockCm, mMockCallback, mMockSessionCallback,
+                mMockNwMgt);
         InOrder inOrderM = inOrder(mAwareMetricsMock);
 
         if (providePmk) {
@@ -800,7 +1029,7 @@
         }
 
         // (0) initialize
-        DataPathEndPointInfo res = initDataPathEndPoint(clientId, pubSubId, requestorId,
+        DataPathEndPointInfo res = initDataPathEndPoint(true, clientId, pubSubId, requestorId,
                 peerDiscoveryMac, inOrder, inOrderM, true);
 
         // (1) request network
@@ -813,7 +1042,7 @@
         } else {
             nr = getSessionNetworkRequest(clientId, res.mSessionId,
                     provideMac ? res.mPeerHandle : null, providePmk ? pmk : null,
-                    providePassphrase ? passphrase : null, true);
+                    providePassphrase ? passphrase : null, true, 0);
         }
 
         Message reqNetworkMsg = Message.obtain();
@@ -837,6 +1066,8 @@
             mDut.onDataPathConfirmNotification(ndpId, peerDataPathMac, true, 0,
                     peerToken.getBytes());
             mMockLooper.dispatchAll();
+            inOrder.verify(mMockNwMgt).setInterfaceUp(anyString());
+            inOrder.verify(mMockNwMgt).enableIpv6(anyString());
             inOrder.verify(mMockCm).registerNetworkAgent(messengerCaptor.capture(), any(), any(),
                     any(), anyInt(), any());
             inOrderM.verify(mAwareMetricsMock).recordNdpStatus(eq(NanStatusType.SUCCESS),
@@ -864,35 +1095,23 @@
             endNetworkUsageMsg.what = AsyncChannel.CMD_CHANNEL_DISCONNECTED;
             messengerCaptor.getValue().send(endNetworkUsageMsg);
 
-            mMockLooper.dispatchAll();
-            inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId));
             mDut.onEndDataPathResponse(transactionId.getValue(), true, 0);
             mDut.onDataPathEndNotification(ndpId);
             mMockLooper.dispatchAll();
+
+            inOrder.verify(mMockNwMgt).setInterfaceDown(anyString());
+            inOrder.verify(mMockNative).endDataPath(transactionId.capture(), eq(ndpId));
             inOrderM.verify(mAwareMetricsMock).recordNdpSessionDuration(anyLong());
         }
 
-        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock);
-    }
-
-    private void installDataPathStateManagerMocks() throws Exception {
-        Field field = WifiAwareStateManager.class.getDeclaredField("mDataPathMgr");
-        field.setAccessible(true);
-        Object mDataPathMgr = field.get(mDut);
-
-        field = WifiAwareDataPathStateManager.class.getDeclaredField("mNwService");
-        field.setAccessible(true);
-        field.set(mDataPathMgr, mMockNwMgt);
-
-        field = WifiAwareDataPathStateManager.class.getDeclaredField("mNiWrapper");
-        field.setAccessible(true);
-        field.set(mDataPathMgr, mMockNetworkInterface);
+        verifyNoMoreInteractions(mMockNative, mMockCm, mAwareMetricsMock, mMockNwMgt);
     }
 
     private NetworkRequest getSessionNetworkRequest(int clientId, int sessionId,
-            PeerHandle peerHandle, byte[] pmk, String passphrase, boolean doPublish)
+            PeerHandle peerHandle, byte[] pmk, String passphrase, boolean doPublish, int requestId)
             throws Exception {
-        final WifiAwareManager mgr = new WifiAwareManager(mMockContext, mMockAwareService);
+        final IWifiAwareManager mockAwareService = mock(IWifiAwareManager.class);
+        final WifiAwareManager mgr = new WifiAwareManager(mMockContext, mockAwareService);
         final ConfigRequest configRequest = new ConfigRequest.Builder().build();
         final PublishConfig publishConfig = new PublishConfig.Builder().build();
         final SubscribeConfig subscribeConfig = new SubscribeConfig.Builder().build();
@@ -910,30 +1129,33 @@
         DiscoverySessionCallback mockSessionCallback = mock(
                 DiscoverySessionCallback.class);
 
+        InOrder inOrderS = inOrder(mockAwareService, mockCallback, mockSessionCallback);
+
         mgr.attach(mMockLooperHandler, configRequest, mockCallback, null);
-        verify(mMockAwareService).connect(any(), any(),
+        inOrderS.verify(mockAwareService).connect(any(), any(),
                 clientProxyCallback.capture(), eq(configRequest), eq(false));
-        clientProxyCallback.getValue().onConnectSuccess(clientId);
+        IWifiAwareEventCallback iwaec = clientProxyCallback.getValue();
+        iwaec.onConnectSuccess(clientId);
         mMockLooper.dispatchAll();
-        verify(mockCallback).onAttached(sessionCaptor.capture());
+        inOrderS.verify(mockCallback).onAttached(sessionCaptor.capture());
         if (doPublish) {
             sessionCaptor.getValue().publish(publishConfig, mockSessionCallback,
                     mMockLooperHandler);
-            verify(mMockAwareService).publish(eq(clientId), eq(publishConfig),
+            inOrderS.verify(mockAwareService).publish(eq(clientId), eq(publishConfig),
                     sessionProxyCallback.capture());
         } else {
             sessionCaptor.getValue().subscribe(subscribeConfig, mockSessionCallback,
                     mMockLooperHandler);
-            verify(mMockAwareService).subscribe(eq(clientId), eq(subscribeConfig),
+            inOrderS.verify(mockAwareService).subscribe(eq(clientId), eq(subscribeConfig),
                     sessionProxyCallback.capture());
         }
         sessionProxyCallback.getValue().onSessionStarted(sessionId);
         mMockLooper.dispatchAll();
         if (doPublish) {
-            verify(mockSessionCallback).onPublishStarted(
+            inOrderS.verify(mockSessionCallback).onPublishStarted(
                     (PublishDiscoverySession) discoverySession.capture());
         } else {
-            verify(mockSessionCallback).onSubscribeStarted(
+            inOrderS.verify(mockSessionCallback).onSubscribeStarted(
                     (SubscribeDiscoverySession) discoverySession.capture());
         }
 
@@ -957,13 +1179,14 @@
         nc.setLinkDownstreamBandwidthKbps(1);
         nc.setSignalStrength(1);
 
-        return new NetworkRequest(nc, 0, 0, NetworkRequest.Type.NONE);
+        return new NetworkRequest(nc, 0, requestId, NetworkRequest.Type.NONE);
     }
 
     private NetworkRequest getDirectNetworkRequest(int clientId, int role, byte[] peer,
             byte[] pmk, String passphrase) throws Exception {
+        final IWifiAwareManager mockAwareService = mock(IWifiAwareManager.class);
         final ConfigRequest configRequest = new ConfigRequest.Builder().build();
-        final WifiAwareManager mgr = new WifiAwareManager(mMockContext, mMockAwareService);
+        final WifiAwareManager mgr = new WifiAwareManager(mMockContext, mockAwareService);
 
         ArgumentCaptor<WifiAwareSession> sessionCaptor = ArgumentCaptor.forClass(
                 WifiAwareSession.class);
@@ -973,7 +1196,7 @@
         AttachCallback mockCallback = mock(AttachCallback.class);
 
         mgr.attach(mMockLooperHandler, configRequest, mockCallback, null);
-        verify(mMockAwareService).connect(any(), any(),
+        verify(mockAwareService).connect(any(), any(),
                 clientProxyCallback.capture(), eq(configRequest), eq(false));
         clientProxyCallback.getValue().onConnectSuccess(clientId);
         mMockLooper.dispatchAll();
@@ -1000,61 +1223,22 @@
         return new NetworkRequest(nc, 0, 0, NetworkRequest.Type.REQUEST);
     }
 
-    private DataPathEndPointInfo initDataPathEndPoint(int clientId, byte pubSubId,
-            int requestorId, byte[] peerDiscoveryMac, InOrder inOrder, InOrder inOrderM,
-            boolean doPublish)
+    private DataPathEndPointInfo initDataPathEndPoint(boolean isFirstIteration, int clientId,
+            byte pubSubId, int requestorId, byte[] peerDiscoveryMac, InOrder inOrder,
+            InOrder inOrderM, boolean doPublish)
             throws Exception {
-        final int pid = 2000;
-        final String callingPackage = "com.android.somePackage";
         final String someMsg = "some arbitrary message from peer";
-        final ConfigRequest configRequest = new ConfigRequest.Builder().build();
         final PublishConfig publishConfig = new PublishConfig.Builder().build();
         final SubscribeConfig subscribeConfig = new SubscribeConfig.Builder().build();
 
-        Capabilities capabilities = new Capabilities();
-        capabilities.maxNdiInterfaces = 1;
-
         ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
         ArgumentCaptor<Integer> sessionId = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor<Integer> peerIdCaptor = ArgumentCaptor.forClass(Integer.class);
-        ArgumentCaptor<Messenger> messengerCaptor = ArgumentCaptor.forClass(Messenger.class);
-        ArgumentCaptor<String> strCaptor = ArgumentCaptor.forClass(String.class);
 
-        // (0) start/registrations
-        inOrder.verify(mMockCm).registerNetworkFactory(messengerCaptor.capture(),
-                strCaptor.capture());
-        collector.checkThat("factory name", "WIFI_AWARE_FACTORY", equalTo(strCaptor.getValue()));
-
-        // (1) get capabilities
-        mDut.queryCapabilities();
-        mMockLooper.dispatchAll();
-        inOrder.verify(mMockNative).getCapabilities(transactionId.capture());
-        mDut.onCapabilitiesUpdateResponse(transactionId.getValue(), capabilities);
-        mMockLooper.dispatchAll();
-
-        // (2) enable usage
-        mDut.enableUsage();
-        mMockLooper.dispatchAll();
-        inOrderM.verify(mAwareMetricsMock).recordEnableUsage();
-
-        // (3) create client & session & rx message
-        mDut.connect(clientId, Process.myUid(), pid, callingPackage, mMockCallback, configRequest,
-                false);
-        mMockLooper.dispatchAll();
-        inOrder.verify(mMockNative).enableAndConfigure(transactionId.capture(),
-                eq(configRequest), eq(false), eq(true), eq(true), eq(false));
-        mDut.onConfigSuccessResponse(transactionId.getValue());
-        mMockLooper.dispatchAll();
-        inOrder.verify(mMockCallback).onConnectSuccess(clientId);
-        inOrderM.verify(mAwareMetricsMock).recordAttachSession(eq(Process.myUid()), eq(false),
-                any());
-
-        inOrder.verify(mMockNative).createAwareNetworkInterface(transactionId.capture(),
-                strCaptor.capture());
-        collector.checkThat("interface created -- 0", sAwareInterfacePrefix + 0,
-                equalTo(strCaptor.getValue()));
-        mDut.onCreateDataPathInterfaceResponse(transactionId.getValue(), true, 0);
-        mMockLooper.dispatchAll();
+        Messenger messenger = null;
+        if (isFirstIteration) {
+            messenger = initOobDataPathEndPoint(true, clientId, inOrder, inOrderM);
+        }
 
         if (doPublish) {
             mDut.publish(clientId, publishConfig, mMockSessionCallback);
@@ -1084,7 +1268,70 @@
                 eq(someMsg.getBytes()));
 
         return new DataPathEndPointInfo(sessionId.getValue(), peerIdCaptor.getValue(),
-                messengerCaptor.getValue());
+                isFirstIteration ? messenger : null);
+    }
+
+    private Messenger initOobDataPathEndPoint(boolean startUpSequence, int clientId,
+            InOrder inOrder, InOrder inOrderM) throws Exception {
+        final int pid = 2000;
+        final String callingPackage = "com.android.somePackage";
+        final ConfigRequest configRequest = new ConfigRequest.Builder().build();
+
+        ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
+        ArgumentCaptor<Messenger> messengerCaptor = ArgumentCaptor.forClass(Messenger.class);
+        ArgumentCaptor<String> strCaptor = ArgumentCaptor.forClass(String.class);
+
+        Capabilities capabilities = new Capabilities();
+        capabilities.maxNdiInterfaces = 1;
+
+        if (startUpSequence) {
+            // (0) start/registrations
+            inOrder.verify(mMockCm).registerNetworkFactory(messengerCaptor.capture(),
+                    strCaptor.capture());
+            collector.checkThat("factory name", "WIFI_AWARE_FACTORY",
+                    equalTo(strCaptor.getValue()));
+
+            // (1) get capabilities
+            mDut.queryCapabilities();
+            mMockLooper.dispatchAll();
+            inOrder.verify(mMockNative).getCapabilities(transactionId.capture());
+            mDut.onCapabilitiesUpdateResponse(transactionId.getValue(), capabilities);
+            mMockLooper.dispatchAll();
+
+            // (2) enable usage
+            mDut.enableUsage();
+            mMockLooper.dispatchAll();
+            inOrderM.verify(mAwareMetricsMock).recordEnableUsage();
+        }
+
+        // (3) create client
+        mDut.connect(clientId, Process.myUid(), pid, callingPackage, mMockCallback,
+                configRequest,
+                false);
+        mMockLooper.dispatchAll();
+
+        if (startUpSequence) {
+            inOrder.verify(mMockNative).enableAndConfigure(transactionId.capture(),
+                    eq(configRequest), eq(false), eq(true), eq(true), eq(false));
+            mDut.onConfigSuccessResponse(transactionId.getValue());
+            mMockLooper.dispatchAll();
+        }
+
+        inOrder.verify(mMockCallback).onConnectSuccess(clientId);
+        inOrderM.verify(mAwareMetricsMock).recordAttachSession(eq(Process.myUid()), eq(false),
+                any());
+
+        if (startUpSequence) {
+            inOrder.verify(mMockNative).createAwareNetworkInterface(transactionId.capture(),
+                    strCaptor.capture());
+            collector.checkThat("interface created -- 0", sAwareInterfacePrefix + 0,
+                    equalTo(strCaptor.getValue()));
+            mDut.onCreateDataPathInterfaceResponse(transactionId.getValue(), true, 0);
+            mMockLooper.dispatchAll();
+            return messengerCaptor.getValue();
+        }
+
+        return null;
     }
 
     private static class DataPathEndPointInfo {
diff --git a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareMetricsTest.java b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareMetricsTest.java
index 8cd1e10..4252cfe 100644
--- a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareMetricsTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareMetricsTest.java
@@ -655,8 +655,7 @@
         WifiAwareDataPathStateManager.AwareNetworkRequestInformation anri =
                 new WifiAwareDataPathStateManager.AwareNetworkRequestInformation();
         anri.networkSpecifier = ns;
-        anri.state = WifiAwareDataPathStateManager.AwareNetworkRequestInformation
-                .STATE_RESPONDER_CONFIRMED;
+        anri.state = WifiAwareDataPathStateManager.AwareNetworkRequestInformation.STATE_CONFIRMED;
         anri.uid = uid;
         anri.interfaceName = interfaceName;
 
diff --git a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareRttStateManagerTest.java b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareRttStateManagerTest.java
index 616e68c..3df62f3 100644
--- a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareRttStateManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareRttStateManagerTest.java
@@ -74,7 +74,7 @@
         mTestLooper = new TestLooper();
         BidirectionalAsyncChannelServer server = new BidirectionalAsyncChannelServer(
                 mMockContext, mTestLooper.getLooper(), mMockHandler);
-        when(mMockRttService.getMessenger()).thenReturn(server.getMessenger());
+        when(mMockRttService.getMessenger(null, new int[1])).thenReturn(server.getMessenger());
 
         mDut.startWithRttService(mMockContext, mTestLooper.getLooper(), mMockRttService);
     }
diff --git a/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointNetworkEvaluatorTest.java b/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointNetworkEvaluatorTest.java
index 9f61ca0..7ddddd2 100644
--- a/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointNetworkEvaluatorTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointNetworkEvaluatorTest.java
@@ -59,6 +59,8 @@
     private static final int TEST_NETWORK_ID = 1;
     private static final String TEST_SSID1 = "ssid1";
     private static final String TEST_SSID2 = "ssid2";
+    private static final String TEST_BSSID1 = "01:23:45:56:78:9a";
+    private static final String TEST_BSSID2 = "23:12:34:90:81:12";
     private static final String TEST_FQDN1 = "test1.com";
     private static final String TEST_FQDN2 = "test2.com";
     private static final WifiConfiguration TEST_CONFIG1 = generateWifiConfig(TEST_FQDN1);
@@ -107,14 +109,18 @@
      * @param rssiLevel The RSSI level associated with the scan
      * @return {@link ScanDetail}
      */
-    private static ScanDetail generateScanDetail(String ssid) {
+    private static ScanDetail generateScanDetail(String ssid, String bssid) {
         NetworkDetail networkDetail = mock(NetworkDetail.class);
         when(networkDetail.isInterworking()).thenReturn(true);
         when(networkDetail.getAnt()).thenReturn(NetworkDetail.Ant.FreePublic);
 
         ScanDetail scanDetail = mock(ScanDetail.class);
+        ScanResult scanResult = new ScanResult();
+        scanResult.SSID = ssid;
+        scanResult.BSSID = bssid;
         when(scanDetail.getSSID()).thenReturn(ssid);
-        when(scanDetail.getScanResult()).thenReturn(new ScanResult());
+        when(scanDetail.getBSSIDString()).thenReturn(bssid);
+        when(scanDetail.getScanResult()).thenReturn(scanResult);
         when(scanDetail.getNetworkDetail()).thenReturn(networkDetail);
         return scanDetail;
     }
@@ -138,7 +144,8 @@
     @Test
     public void evaluateScansWithNoMatch() throws Exception {
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1), generateScanDetail(TEST_SSID2)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1),
+                generateScanDetail(TEST_SSID2, TEST_BSSID2)});
         List<Pair<ScanDetail, WifiConfiguration>> connectableNetworks = new ArrayList<>();
         when(mPasspointManager.matchProvider(any(ScanResult.class))).thenReturn(null);
         assertEquals(null, mEvaluator.evaluateNetworks(
@@ -177,7 +184,8 @@
     @Test
     public void evaluateScansWithNetworkMatchingHomeProvider() throws Exception {
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1), generateScanDetail(TEST_SSID2)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1),
+                generateScanDetail(TEST_SSID2, TEST_BSSID2)});
 
         // Setup matching providers for ScanDetail with TEST_SSID1.
         Pair<PasspointProvider, PasspointMatch> homeProvider = Pair.create(
@@ -219,7 +227,8 @@
     @Test
     public void evaluateScansWithNetworkMatchingRoamingProvider() throws Exception {
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1), generateScanDetail(TEST_SSID2)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1),
+                generateScanDetail(TEST_SSID2, TEST_BSSID2)});
 
         // Setup matching providers for ScanDetail with TEST_SSID1.
         Pair<PasspointProvider, PasspointMatch> roamingProvider = Pair.create(
@@ -261,7 +270,8 @@
     @Test
     public void evaluateScansWithHomeProviderNewtorkAndRoamingProviderNetwork() throws Exception {
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1), generateScanDetail(TEST_SSID2)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1),
+                generateScanDetail(TEST_SSID2, TEST_BSSID2)});
 
         // Setup matching providers for ScanDetail with TEST_SSID1.
         Pair<PasspointProvider, PasspointMatch> homeProvider = Pair.create(
@@ -305,7 +315,8 @@
     @Test
     public void evaluateScansWithActiveNetworkMatchingHomeProvider() throws Exception {
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1), generateScanDetail(TEST_SSID2)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1),
+                generateScanDetail(TEST_SSID2, TEST_BSSID2)});
 
         // Setup matching providers for both ScanDetail.
         Pair<PasspointProvider, PasspointMatch> homeProvider = Pair.create(
@@ -315,7 +326,7 @@
         WifiConfiguration currentNetwork = new WifiConfiguration();
         currentNetwork.networkId = TEST_NETWORK_ID;
         currentNetwork.SSID = ScanResultUtil.createQuotedSSID(TEST_SSID2);
-        String currentBssid = "12:23:34:45:12:0F";
+        String currentBssid = TEST_BSSID2;
 
         // Returning the same matching provider for both ScanDetail.
         List<Pair<ScanDetail, WifiConfiguration>> connectableNetworks = new ArrayList<>();
@@ -344,7 +355,7 @@
     public void evaluateScanMatchingSIMProviderWithoutSIMCard() throws Exception {
         // Setup ScanDetail and match providers.
         List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
-                generateScanDetail(TEST_SSID1)});
+                generateScanDetail(TEST_SSID1, TEST_BSSID1)});
         PasspointProvider testProvider = mock(PasspointProvider.class);
         Pair<PasspointProvider, PasspointMatch> homeProvider = Pair.create(
                 testProvider, PasspointMatch.HomeProvider);
@@ -357,6 +368,45 @@
                 scanDetails, null, null, false, false, connectableNetworks));
         assertTrue(connectableNetworks.isEmpty());
         verify(testProvider, never()).getWifiConfig();
+    }
 
+    /**
+     * Verify that when the current active network is matched, the scan info associated with
+     * the network is updated.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void evaluateScansMatchingActiveNetworkWithDifferentBSS() throws Exception {
+        List<ScanDetail> scanDetails = Arrays.asList(new ScanDetail[] {
+                generateScanDetail(TEST_SSID1, TEST_BSSID2)});
+        // Setup matching provider.
+        Pair<PasspointProvider, PasspointMatch> homeProvider = Pair.create(
+                TEST_PROVIDER1, PasspointMatch.HomeProvider);
+
+        // Setup currently connected network.
+        WifiConfiguration currentNetwork = new WifiConfiguration();
+        currentNetwork.networkId = TEST_NETWORK_ID;
+        currentNetwork.SSID = ScanResultUtil.createQuotedSSID(TEST_SSID1);
+        String currentBssid = TEST_BSSID1;
+
+        // Match the current connected network to a home provider.
+        List<Pair<ScanDetail, WifiConfiguration>> connectableNetworks = new ArrayList<>();
+        when(mPasspointManager.matchProvider(any(ScanResult.class))).thenReturn(homeProvider);
+        WifiConfiguration config = mEvaluator.evaluateNetworks(scanDetails, currentNetwork,
+                currentBssid, true, false, connectableNetworks);
+        assertEquals(1, connectableNetworks.size());
+
+        // Verify network candidate information is updated.
+        ArgumentCaptor<ScanResult> updatedCandidateScanResult =
+                ArgumentCaptor.forClass(ScanResult.class);
+        verify(mWifiConfigManager).setNetworkCandidateScanResult(eq(TEST_NETWORK_ID),
+                updatedCandidateScanResult.capture(), anyInt());
+        assertEquals(TEST_BSSID2, updatedCandidateScanResult.getValue().BSSID);
+        ArgumentCaptor<ScanDetail> updatedCandidateScanDetail =
+                ArgumentCaptor.forClass(ScanDetail.class);
+        verify(mWifiConfigManager).updateScanDetailForNetwork(eq(TEST_NETWORK_ID),
+                updatedCandidateScanDetail.capture());
+        assertEquals(TEST_BSSID2, updatedCandidateScanDetail.getValue().getBSSIDString());
     }
 }
diff --git a/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackTest.java b/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackTest.java
index 4443bb1..8b853a4 100644
--- a/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackTest.java
@@ -83,8 +83,8 @@
      */
     @Test
     public void testOnDeviceFound_success() throws Exception {
-        byte[] fakePrimaryDeviceTypeBytes = { 0x01, 0x02, 0x03 };
-        String fakePrimaryDeviceTypeString = "010203";
+        byte[] fakePrimaryDeviceTypeBytes = { 0x00, 0x01, 0x02, -1, 0x04, 0x05, 0x06, 0x07 };
+        String fakePrimaryDeviceTypeString = "1-02FF0405-1543";
         String fakeDeviceName = "test device name";
         short fakeConfigMethods = 0x1234;
         byte fakeCapabilities = 123;
@@ -131,8 +131,8 @@
      */
     @Test
     public void testOnDeviceFound_invalidArguments() throws Exception {
-        byte[] fakePrimaryDeviceTypeBytes = { 0x01, 0x02, 0x03 };
-        String fakePrimaryDeviceTypeString = "010203";
+        byte[] fakePrimaryDeviceTypeBytes = { 0x0, 0x01, 0x02, -1, 0x04, 0x05, 0x06, 0x07 };
+        String fakePrimaryDeviceTypeString = "1-02FF0405-1543";
         String fakeDeviceName = "test device name";
         short fakeConfigMethods = 0x1234;
         byte fakeCapabilities = 123;
diff --git a/tests/wifitests/src/com/android/server/wifi/scanner/WificondPnoScannerTest.java b/tests/wifitests/src/com/android/server/wifi/scanner/WificondPnoScannerTest.java
index c63a9a0..974cf66 100644
--- a/tests/wifitests/src/com/android/server/wifi/scanner/WificondPnoScannerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/scanner/WificondPnoScannerTest.java
@@ -429,6 +429,7 @@
         expectHwDisconnectedPnoScanStart(order, pnoSettings);
 
         // Setup scan results
+        when(mWifiNative.getPnoScanResults()).thenReturn(scanResults.getScanDetailArrayList());
         when(mWifiNative.getScanResults()).thenReturn(scanResults.getScanDetailArrayList());
 
         // Notify scan has finished
@@ -451,6 +452,7 @@
 
         order.verify(mWifiNative).scan(eq(expectedScanFreqs), any(Set.class));
 
+        when(mWifiNative.getPnoScanResults()).thenReturn(scanResults.getScanDetailArrayList());
         when(mWifiNative.getScanResults()).thenReturn(scanResults.getScanDetailArrayList());
 
         // Notify scan has finished
@@ -478,6 +480,7 @@
 
         // Setup scan results
         when(mWifiNative.getScanResults()).thenReturn(scanResults.getScanDetailArrayList());
+        when(mWifiNative.getPnoScanResults()).thenReturn(scanResults.getScanDetailArrayList());
 
         // Notify scan has finished
         mWifiMonitor.sendMessage(mWifiNative.getInterfaceName(), WifiMonitor.SCAN_RESULTS_EVENT);
diff --git a/tests/wifitests/src/com/android/server/wifi/util/MatrixTest.java b/tests/wifitests/src/com/android/server/wifi/util/MatrixTest.java
new file mode 100644
index 0000000..bfa1071
--- /dev/null
+++ b/tests/wifitests/src/com/android/server/wifi/util/MatrixTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import java.util.Random;
+
+/**
+ * Unit tests for {@link com.android.server.wifi.util.Matrix}.
+ */
+public class MatrixTest {
+    /**
+     * Test that both forms of constructor work
+     */
+    @Test
+    public void testConstructors() throws Exception {
+        assertEquals(new Matrix(3, 2), new Matrix(2, new double[]{0, 0, 0, 0, 0, 0}));
+    }
+
+    /**
+     * Test some degenerate cases
+     */
+    @Test
+    public void testDegenerate() throws Exception {
+        Matrix m1 = new Matrix(0, 20);
+        Matrix m2 = new Matrix(20, 0);
+        assertEquals(m1, m2.transpose());
+    }
+
+    /**
+     * Test addition
+     */
+    @Test
+    public void testAddition() throws Exception {
+        Matrix m1 = new Matrix(2, new double[]{1, 2, 3, 4});
+        Matrix m2 = new Matrix(2, new double[]{10, 20, 30, 40});
+        Matrix m3 = new Matrix(2, new double[]{11, 22, 33, 44});
+        assertEquals(m3, m1.plus(m2));
+    }
+
+    /**
+     * Test subtraction.
+     */
+    @Test
+    public void testSubtraction() throws Exception {
+        Matrix m1 = new Matrix(2, new double[]{1, 2, 3, 4});
+        Matrix m2 = new Matrix(2, new double[]{10, 20, 30, 40});
+        Matrix m3 = new Matrix(2, new double[]{11, 22, 33, 44});
+        assertEquals(m1, m3.minus(m2));
+    }
+
+    /**
+     * Test multiplication.
+     */
+    @Test
+    public void testMultiplication() throws Exception {
+        Matrix m1 = new Matrix(2, new double[]{1, 2, 3, 4});
+        Matrix m2 = new Matrix(2, new double[]{-3, 3, 7, 1});
+        Matrix m3 = new Matrix(2, new double[]{11, 5, 19, 13});
+        assertEquals(m3, m1.dot(m2));
+    }
+
+    /**
+     * Test that matrix inverse works (non-singular case).
+     */
+    @Test
+    public void testInverse() throws Exception {
+        Matrix i3 = new Matrix(3, new double[]{1, 0, 0, 0, 1, 0, 0, 0, 1});
+        Matrix f = new Matrix(3, new double[]{100, 100, 100, 100, 100, 100, 100, 100, 100});
+        Matrix m1 = new Matrix(3, new double[]{10, 1, -1, 2, 14, -1, 0, 2, 20});
+        Matrix m2 = m1.inverse();
+        Matrix m12 = m1.dot(m2);
+        Matrix m21 = m2.dot(m1);
+        // Add f here to wash out the roundoff errors
+        assertEquals(i3.plus(f), m12.plus(f));
+        assertEquals(i3.plus(f), m21.plus(f));
+    }
+
+    /**
+     * Test that attempting to invert a singular matrix throws an exception.
+     * @throws Exception
+     */
+    @Test(expected = ArithmeticException.class)
+    public void testSingularity() throws Exception {
+        Matrix m1 = new Matrix(3, new double[]{10, 1, -1, 0, 0, 0, 0, 0, 0});
+        Matrix m2 = m1.inverse();
+    }
+
+    /**
+     * Test that a copy is equal to the original, and that hash codes match,
+     * and that string versions match.
+     */
+    @Test
+    public void testCopy() throws Exception {
+        Random random = new Random();
+        Matrix m1 = new Matrix(3, 4);
+        for (int i = 0; i < m1.mem.length; i++) {
+            m1.mem[i] = random.nextDouble();
+        }
+        Matrix m2 = new Matrix(m1);
+        assertEquals(m1, m2);
+        assertEquals(m1.hashCode(), m2.hashCode());
+        assertEquals(m1.toString(), m2.toString());
+    }
+}
diff --git a/tests/wifitests/src/com/android/server/wifi/util/NativeUtilTest.java b/tests/wifitests/src/com/android/server/wifi/util/NativeUtilTest.java
index 3f51c5a..367e6b3 100644
--- a/tests/wifitests/src/com/android/server/wifi/util/NativeUtilTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/util/NativeUtilTest.java
@@ -98,10 +98,25 @@
     }
 
     /**
+     * Test that conversion of ssid bytes to quoted UTF8 string ssid works.
+     */
+    @Test
+    public void testUtf8SsidDecode() throws Exception {
+        assertEquals(
+                new ArrayList<>(
+                        Arrays.asList((byte) 0x41, (byte) 0x6e, (byte) 0x64, (byte) 0x72,
+                                (byte) 0x6f, (byte) 0x69, (byte) 0x64, (byte) 0x41, (byte) 0x50,
+                                (byte) 0xe3, (byte) 0x81, (byte) 0x8f, (byte) 0xe3, (byte) 0x81,
+                                (byte) 0xa0, (byte) 0xe3, (byte) 0x81, (byte) 0x95, (byte) 0xe3,
+                                (byte) 0x81, (byte) 0x84)),
+                NativeUtil.decodeSsid("\"AndroidAPください\""));
+    }
+
+    /**
      * Test that conversion of ssid bytes to hex string ssid works.
      */
     @Test
-    public void testNonAsciiSsidDecode() throws Exception {
+    public void testNonSsidDecode() throws Exception {
         assertEquals(
                 new ArrayList<>(
                         Arrays.asList((byte) 0xf5, (byte) 0xe4, (byte) 0xab, (byte) 0x78,
@@ -110,10 +125,10 @@
     }
 
     /**
-     * Test that conversion of ssid bytes to quoted ASCII string ssid works.
+     * Test that conversion of ssid bytes to quoted string ssid works.
      */
     @Test
-    public void testAsciiSsidEncode() throws Exception {
+    public void testSsidEncode() throws Exception {
         assertEquals(
                 "\"ssid_test123\"",
                 NativeUtil.encodeSsid(new ArrayList<>(
@@ -126,7 +141,7 @@
      * Test that conversion of byte array to hex string works when the byte array contains 0.
      */
     @Test
-    public void testNullCharInAsciiSsidEncode() throws Exception {
+    public void testNullCharInSsidEncode() throws Exception {
         assertEquals(
                 "007369645f74657374313233",
                 NativeUtil.encodeSsid(new ArrayList<>(
@@ -139,7 +154,7 @@
      * Test that conversion of byte array to hex string ssid works.
      */
     @Test
-    public void testNonAsciiSsidEncode() throws Exception {
+    public void testNonSsidEncode() throws Exception {
         assertEquals(
                 "f5e4ab78ab3432439a",
                 NativeUtil.encodeSsid(new ArrayList<>(