Merge "ONA: Enable new UI and connection flow." into oc-mr1-dev
diff --git a/service/java/com/android/server/wifi/RttService.java b/service/java/com/android/server/wifi/RttService.java
index 89de870..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;
@@ -41,14 +37,12 @@
 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
@@ -131,7 +125,9 @@
                     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);
                         }
@@ -169,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,
@@ -201,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;
@@ -252,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) {
@@ -353,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();
@@ -445,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) {
@@ -541,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;
                     }
@@ -594,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;
@@ -719,7 +662,7 @@
             }
         }
 
-        boolean enforcePermissionCheck(Message msg) {
+        private boolean enforcePermissionCheck(Message msg) {
             try {
                 mContext.enforcePermission(Manifest.permission.LOCATION_HARDWARE,
                          -1, msg.sendingUid, "LocationRTT");
@@ -730,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)
@@ -777,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 29c6d4f..75b39b2 100644
--- a/service/java/com/android/server/wifi/WifiConfigManager.java
+++ b/service/java/com/android/server/wifi/WifiConfigManager.java
@@ -47,7 +47,6 @@
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.server.LocalServices;
-import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy;
 import com.android.server.wifi.hotspot2.PasspointManager;
 import com.android.server.wifi.util.TelephonyUtil;
 import com.android.server.wifi.util.WifiPermissionsUtil;
@@ -248,7 +247,6 @@
     private final TelephonyManager mTelephonyManager;
     private final WifiKeyStore mWifiKeyStore;
     private final WifiConfigStore mWifiConfigStore;
-    private final WifiConfigStoreLegacy mWifiConfigStoreLegacy;
     private final WifiPermissionsUtil mWifiPermissionsUtil;
     private final WifiPermissionsWrapper mWifiPermissionsWrapper;
     /**
@@ -342,7 +340,7 @@
     WifiConfigManager(
             Context context, Clock clock, UserManager userManager,
             TelephonyManager telephonyManager, WifiKeyStore wifiKeyStore,
-            WifiConfigStore wifiConfigStore, WifiConfigStoreLegacy wifiConfigStoreLegacy,
+            WifiConfigStore wifiConfigStore,
             WifiPermissionsUtil wifiPermissionsUtil,
             WifiPermissionsWrapper wifiPermissionsWrapper,
             NetworkListStoreData networkListStoreData,
@@ -354,7 +352,6 @@
         mTelephonyManager = telephonyManager;
         mWifiKeyStore = wifiKeyStore;
         mWifiConfigStore = wifiConfigStore;
-        mWifiConfigStoreLegacy = wifiConfigStoreLegacy;
         mWifiPermissionsUtil = wifiPermissionsUtil;
         mWifiPermissionsWrapper = wifiPermissionsWrapper;
 
@@ -1927,7 +1924,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;
@@ -2697,46 +2694,6 @@
     }
 
     /**
-     * Migrate data from legacy store files. The function performs the following operations:
-     * 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.
-     *
-     * @return true if migration was successful or not needed (fresh install), false if it failed.
-     */
-    public boolean migrateFromLegacyStore() {
-        if (!mWifiConfigStoreLegacy.areStoresPresent()) {
-            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>(),
-                storeData.getDeletedEphemeralSSIDs());
-
-        // Setup user store for the current user in case it have not setup yet, so that data
-        // owned by the current user will be backed to the user store.
-        if (mDeferredUserUnlockRead) {
-            mWifiConfigStore.setUserStore(WifiConfigStore.createUserFile(mCurrentUserId));
-            mDeferredUserUnlockRead = false;
-        }
-
-        if (!saveToStore(true)) {
-            return false;
-        }
-        mWifiConfigStoreLegacy.removeStores();
-        Log.d(TAG, "Migration from legacy store completed");
-        return true;
-    }
-
-    /**
      * Read the config store and load the in-memory lists from the store data retrieved and sends
      * out the networks changed broadcast.
      *
@@ -2750,10 +2707,7 @@
     public boolean loadFromStore() {
         if (!mWifiConfigStore.areStoresPresent()) {
             Log.d(TAG, "New store files not found. No saved networks loaded!");
-            if (!mWifiConfigStoreLegacy.areStoresPresent()) {
-                // No legacy store files either, so reset the pending store read flag.
-                mPendingStoreRead = false;
-            }
+            mPendingStoreRead = false;
             return true;
         }
         // If the user unlock comes in before we load from store, which means the user store have
diff --git a/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java b/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java
deleted file mode 100644
index 39e48a5..0000000
--- a/service/java/com/android/server/wifi/WifiConfigStoreLegacy.java
+++ /dev/null
@@ -1,354 +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 android.net.IpConfiguration;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiEnterpriseConfig;
-import android.os.Environment;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.server.net.IpConfigStore;
-import com.android.server.wifi.hotspot2.LegacyPasspointConfig;
-import com.android.server.wifi.hotspot2.LegacyPasspointConfigParser;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * This class provides the API's to load network configurations from legacy store
- * mechanism (Pre O release).
- * This class loads network configurations from:
- * 1. /data/misc/wifi/networkHistory.txt
- * 2. /data/misc/wifi/wpa_supplicant.conf
- * 3. /data/misc/wifi/ipconfig.txt
- * 4. /data/misc/wifi/PerProviderSubscription.conf
- *
- * The order of invocation of the public methods during migration is the following:
- * 1. Check if legacy stores are present using {@link #areStoresPresent()}.
- * 2. Load all the store data using {@link #read()}
- * 3. Write the store data to the new store.
- * 4. Remove all the legacy stores using {@link #removeStores()}
- *
- * NOTE: This class should only be used from WifiConfigManager and is not thread-safe!
- *
- * TODO(b/31065385): Passpoint config store data migration & deletion.
- */
-public class WifiConfigStoreLegacy {
-    /**
-     * Log tag.
-     */
-    private static final String TAG = "WifiConfigStoreLegacy";
-    /**
-     * NetworkHistory config store file path.
-     */
-    private static final File NETWORK_HISTORY_FILE =
-            new File(WifiNetworkHistory.NETWORK_HISTORY_CONFIG_FILE);
-    /**
-     * Passpoint config store file path.
-     */
-    private static final File PPS_FILE =
-            new File(Environment.getDataMiscDirectory(), "wifi/PerProviderSubscription.conf");
-    /**
-     * IpConfig config store file path.
-     */
-    private static final File IP_CONFIG_FILE =
-            new File(Environment.getDataMiscDirectory(), "wifi/ipconfig.txt");
-    /**
-     * List of external dependencies for WifiConfigManager.
-     */
-    private final WifiNetworkHistory mWifiNetworkHistory;
-    private final WifiNative mWifiNative;
-    private final IpConfigStore mIpconfigStore;
-
-    private final LegacyPasspointConfigParser mPasspointConfigParser;
-
-    WifiConfigStoreLegacy(WifiNetworkHistory wifiNetworkHistory,
-            WifiNative wifiNative, IpConfigStore ipConfigStore,
-            LegacyPasspointConfigParser passpointConfigParser) {
-        mWifiNetworkHistory = wifiNetworkHistory;
-        mWifiNative = wifiNative;
-        mIpconfigStore = ipConfigStore;
-        mPasspointConfigParser = passpointConfigParser;
-    }
-
-    /**
-     * Helper function to lookup the WifiConfiguration object from configKey to WifiConfiguration
-     * object map using the hashcode of the configKey.
-     *
-     * @param configurationMap Map of configKey to WifiConfiguration object.
-     * @param hashCode         hash code of the configKey to match.
-     * @return
-     */
-    private static WifiConfiguration lookupWifiConfigurationUsingConfigKeyHash(
-            Map<String, WifiConfiguration> configurationMap, int hashCode) {
-        for (Map.Entry<String, WifiConfiguration> entry : configurationMap.entrySet()) {
-            if (entry.getKey().hashCode() == hashCode) {
-                return entry.getValue();
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Helper function to load {@link IpConfiguration} data from the ip config store file and
-     * populate the provided configuration map.
-     *
-     * @param configurationMap Map of configKey to WifiConfiguration object.
-     */
-    private void loadFromIpConfigStore(Map<String, WifiConfiguration> configurationMap) {
-        // This is a map of the hash code of the network's configKey to the corresponding
-        // IpConfiguration.
-        SparseArray<IpConfiguration> ipConfigurations =
-                mIpconfigStore.readIpAndProxyConfigurations(IP_CONFIG_FILE.getAbsolutePath());
-        if (ipConfigurations == null || ipConfigurations.size() == 0) {
-            Log.w(TAG, "No ip configurations found in ipconfig store");
-            return;
-        }
-        for (int i = 0; i < ipConfigurations.size(); i++) {
-            int id = ipConfigurations.keyAt(i);
-            WifiConfiguration config =
-                    lookupWifiConfigurationUsingConfigKeyHash(configurationMap, id);
-            // This is the only place the map is looked up through a (dangerous) hash-value!
-            if (config == null || config.ephemeral) {
-                Log.w(TAG, "configuration found for missing network, nid=" + id
-                        + ", ignored, networks.size=" + Integer.toString(ipConfigurations.size()));
-            } else {
-                config.setIpConfiguration(ipConfigurations.valueAt(i));
-            }
-        }
-    }
-
-    /**
-     * Helper function to load {@link WifiConfiguration} data from networkHistory file and populate
-     * the provided configuration map and deleted ephemeral ssid list.
-     *
-     * @param configurationMap      Map of configKey to WifiConfiguration object.
-     * @param deletedEphemeralSSIDs Map of configKey to WifiConfiguration object.
-     */
-    private void loadFromNetworkHistory(
-            Map<String, WifiConfiguration> configurationMap, Set<String> deletedEphemeralSSIDs) {
-        // TODO: Need  to revisit the scan detail cache persistance. We're not doing it in the new
-        // config store, so ignore it here as well.
-        Map<Integer, ScanDetailCache> scanDetailCaches = new HashMap<>();
-        mWifiNetworkHistory.readNetworkHistory(
-                configurationMap, scanDetailCaches, deletedEphemeralSSIDs);
-    }
-
-    /**
-     * Helper function to load {@link WifiConfiguration} data from wpa_supplicant and populate
-     * the provided configuration map and network extras.
-     *
-     * This method needs to manually parse the wpa_supplicant.conf file to retrieve some of the
-     * password fields like psk, wep_keys. password, etc.
-     *
-     * @param configurationMap Map of configKey to WifiConfiguration object.
-     * @param networkExtras    Map of network extras parsed from wpa_supplicant.
-     */
-    private void loadFromWpaSupplicant(
-            Map<String, WifiConfiguration> configurationMap,
-            SparseArray<Map<String, String>> networkExtras) {
-        if (!mWifiNative.migrateNetworksFromSupplicant(configurationMap, networkExtras)) {
-            Log.wtf(TAG, "Failed to load wifi configurations from wpa_supplicant");
-            return;
-        }
-        if (configurationMap.isEmpty()) {
-            Log.w(TAG, "No wifi configurations found in wpa_supplicant");
-            return;
-        }
-    }
-
-    /**
-     * Helper function to update {@link WifiConfiguration} that represents a Passpoint
-     * configuration.
-     *
-     * This method will manually parse PerProviderSubscription.conf file to retrieve missing
-     * fields: provider friendly name, roaming consortium OIs, realm, IMSI.
-     *
-     * @param configurationMap Map of configKey to WifiConfiguration object.
-     * @param networkExtras    Map of network extras parsed from wpa_supplicant.
-     */
-    private void loadFromPasspointConfigStore(
-            Map<String, WifiConfiguration> configurationMap,
-            SparseArray<Map<String, String>> networkExtras) {
-        Map<String, LegacyPasspointConfig> passpointConfigMap = null;
-        try {
-            passpointConfigMap = mPasspointConfigParser.parseConfig(PPS_FILE.getAbsolutePath());
-        } catch (IOException e) {
-            Log.w(TAG, "Failed to read/parse Passpoint config file: " + e.getMessage());
-        }
-
-        List<String> entriesToBeRemoved = new ArrayList<>();
-        for (Map.Entry<String, WifiConfiguration> entry : configurationMap.entrySet()) {
-            WifiConfiguration wifiConfig = entry.getValue();
-            // Ignore non-Enterprise network since enterprise configuration is required for
-            // Passpoint.
-            if (wifiConfig.enterpriseConfig == null || wifiConfig.enterpriseConfig.getEapMethod()
-                    == WifiEnterpriseConfig.Eap.NONE) {
-                continue;
-            }
-            // Ignore configuration without FQDN.
-            Map<String, String> extras = networkExtras.get(wifiConfig.networkId);
-            if (extras == null || !extras.containsKey(SupplicantStaNetworkHal.ID_STRING_KEY_FQDN)) {
-                continue;
-            }
-            String fqdn = networkExtras.get(wifiConfig.networkId).get(
-                    SupplicantStaNetworkHal.ID_STRING_KEY_FQDN);
-
-            // Remove the configuration if failed to find the matching configuration in the
-            // Passpoint configuration file.
-            if (passpointConfigMap == null || !passpointConfigMap.containsKey(fqdn)) {
-                entriesToBeRemoved.add(entry.getKey());
-                continue;
-            }
-
-            // Update the missing Passpoint configuration fields to this WifiConfiguration.
-            LegacyPasspointConfig passpointConfig = passpointConfigMap.get(fqdn);
-            wifiConfig.isLegacyPasspointConfig = true;
-            wifiConfig.FQDN = fqdn;
-            wifiConfig.providerFriendlyName = passpointConfig.mFriendlyName;
-            if (passpointConfig.mRoamingConsortiumOis != null) {
-                wifiConfig.roamingConsortiumIds = Arrays.copyOf(
-                        passpointConfig.mRoamingConsortiumOis,
-                        passpointConfig.mRoamingConsortiumOis.length);
-            }
-            if (passpointConfig.mImsi != null) {
-                wifiConfig.enterpriseConfig.setPlmn(passpointConfig.mImsi);
-            }
-            if (passpointConfig.mRealm != null) {
-                wifiConfig.enterpriseConfig.setRealm(passpointConfig.mRealm);
-            }
-        }
-
-        // Remove any incomplete Passpoint configurations. Should never happen, in case it does
-        // remove them to avoid maintaining any invalid Passpoint configurations.
-        for (String key : entriesToBeRemoved) {
-            Log.w(TAG, "Remove incomplete Passpoint configuration: " + key);
-            configurationMap.remove(key);
-        }
-    }
-
-    /**
-     * Helper function to load from the different legacy stores:
-     * 1. Read the network configurations from wpa_supplicant using {@link WifiNative}.
-     * 2. Read the network configurations from networkHistory.txt using {@link WifiNetworkHistory}.
-     * 3. Read the Ip configurations from ipconfig.txt using {@link IpConfigStore}.
-     * 4. Read all the passpoint info from PerProviderSubscription.conf using
-     * {@link LegacyPasspointConfigParser}.
-     */
-    public WifiConfigStoreDataLegacy read() {
-        final Map<String, WifiConfiguration> configurationMap = new HashMap<>();
-        final SparseArray<Map<String, String>> networkExtras = new SparseArray<>();
-        final Set<String> deletedEphemeralSSIDs = new HashSet<>();
-
-        loadFromWpaSupplicant(configurationMap, networkExtras);
-        loadFromNetworkHistory(configurationMap, deletedEphemeralSSIDs);
-        loadFromIpConfigStore(configurationMap);
-        loadFromPasspointConfigStore(configurationMap, networkExtras);
-
-        // Now create config store data instance to be returned.
-        return new WifiConfigStoreDataLegacy(
-                new ArrayList<>(configurationMap.values()), deletedEphemeralSSIDs);
-    }
-
-    /**
-     * Function to check if the legacy store files are present and hence load from those stores and
-     * then delete them.
-     *
-     * @return true if legacy store files are present, false otherwise.
-     */
-    public boolean areStoresPresent() {
-        // We may have to keep the wpa_supplicant.conf file around. So, just use networkhistory.txt
-        // as a check to see if we have not yet migrated or not. This should be the last file
-        // that is deleted after migration.
-        File file = new File(WifiNetworkHistory.NETWORK_HISTORY_CONFIG_FILE);
-        return file.exists();
-    }
-
-    /**
-     * Method to remove all the legacy store files. This should only be invoked once all
-     * the data has been migrated to the new store file.
-     * 1. Removes all networks from wpa_supplicant and saves it to wpa_supplicant.conf
-     * 2. Deletes ipconfig.txt
-     * 3. Deletes networkHistory.txt
-     *
-     * @return true if all the store files were deleted successfully, false otherwise.
-     */
-    public boolean removeStores() {
-        // TODO(b/29352330): Delete wpa_supplicant.conf file instead.
-        // First remove all networks from wpa_supplicant and save configuration.
-        if (!mWifiNative.removeAllNetworks()) {
-            Log.e(TAG, "Removing networks from wpa_supplicant failed");
-        }
-
-        // Now remove the ipconfig.txt file.
-        if (!IP_CONFIG_FILE.delete()) {
-            Log.e(TAG, "Removing ipconfig.txt failed");
-        }
-
-        // Now finally remove network history.txt
-        if (!NETWORK_HISTORY_FILE.delete()) {
-            Log.e(TAG, "Removing networkHistory.txt failed");
-        }
-
-        if (!PPS_FILE.delete()) {
-            Log.e(TAG, "Removing PerProviderSubscription.conf failed");
-        }
-
-        Log.i(TAG, "All legacy stores removed!");
-        return true;
-    }
-
-    /**
-     * Interface used to set a masked value in the provided configuration. The masked value is
-     * retrieved by parsing the wpa_supplicant.conf file.
-     */
-    private interface MaskedWpaSupplicantFieldSetter {
-        void setValue(WifiConfiguration config, String value);
-    }
-
-    /**
-     * Class used to encapsulate all the store data retrieved from the legacy (Pre O) store files.
-     */
-    public static class WifiConfigStoreDataLegacy {
-        private List<WifiConfiguration> mConfigurations;
-        private Set<String> mDeletedEphemeralSSIDs;
-        // private List<HomeSP> mHomeSps;
-
-        WifiConfigStoreDataLegacy(List<WifiConfiguration> configurations,
-                Set<String> deletedEphemeralSSIDs) {
-            mConfigurations = configurations;
-            mDeletedEphemeralSSIDs = deletedEphemeralSSIDs;
-        }
-
-        public List<WifiConfiguration> getConfigurations() {
-            return mConfigurations;
-        }
-
-        public Set<String> getDeletedEphemeralSSIDs() {
-            return mDeletedEphemeralSSIDs;
-        }
-    }
-}
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 a983776..7e730c8 100644
--- a/service/java/com/android/server/wifi/WifiConnectivityManager.java
+++ b/service/java/com/android/server/wifi/WifiConnectivityManager.java
@@ -512,6 +512,8 @@
         }
         @Override
         public void onSavedNetworkUpdated(int networkId) {
+            // User might have changed meteredOverride, so update capabilties
+            mStateMachine.updateCapabilities();
             updatePnoScan();
         }
         @Override
@@ -562,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(
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 95a68f1..fc3af83 100644
--- a/service/java/com/android/server/wifi/WifiInjector.java
+++ b/service/java/com/android/server/wifi/WifiInjector.java
@@ -45,7 +45,6 @@
 import com.android.server.net.DelayedDiskWrite;
 import com.android.server.net.IpConfigStore;
 import com.android.server.wifi.aware.WifiAwareMetrics;
-import com.android.server.wifi.hotspot2.LegacyPasspointConfigParser;
 import com.android.server.wifi.hotspot2.PasspointManager;
 import com.android.server.wifi.hotspot2.PasspointNetworkEvaluator;
 import com.android.server.wifi.hotspot2.PasspointObjectFactory;
@@ -101,9 +100,7 @@
     private final WifiMulticastLockManager mWifiMulticastLockManager;
     private final WifiConfigStore mWifiConfigStore;
     private final WifiKeyStore mWifiKeyStore;
-    private final WifiNetworkHistory mWifiNetworkHistory;
     private final IpConfigStore mIpConfigStore;
-    private final WifiConfigStoreLegacy mWifiConfigStoreLegacy;
     private final WifiConfigManager mWifiConfigManager;
     private final WifiConnectivityHelper mWifiConnectivityHelper;
     private final LocalLog mConnectivityLocalLog;
@@ -195,15 +192,11 @@
                 WifiConfigStore.createSharedFile());
         // Legacy config store
         DelayedDiskWrite writer = new DelayedDiskWrite();
-        mWifiNetworkHistory = new WifiNetworkHistory(mContext, writer);
         mIpConfigStore = new IpConfigStore(writer);
-        mWifiConfigStoreLegacy = new WifiConfigStoreLegacy(
-                mWifiNetworkHistory, mWifiNative, mIpConfigStore,
-                new LegacyPasspointConfigParser());
         // Config Manager
         mWifiConfigManager = new WifiConfigManager(mContext, mClock,
                 UserManager.get(mContext), TelephonyManager.from(mContext),
-                mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy, mWifiPermissionsUtil,
+                mWifiKeyStore, mWifiConfigStore, mWifiPermissionsUtil,
                 mWifiPermissionsWrapper, new NetworkListStoreData(),
                 new DeletedEphemeralSsidsStoreData());
         mWifiMetrics.setWifiConfigManager(mWifiConfigManager);
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
deleted file mode 100644
index 282f605..0000000
--- a/service/java/com/android/server/wifi/WifiNetworkHistory.java
+++ /dev/null
@@ -1,630 +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 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;
-
-import java.io.BufferedInputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.EOFException;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.util.BitSet;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Provides an API to read and write the network history from WifiConfigurations to file
- * This is largely separate and extra to the supplicant config file.
- */
-public class WifiNetworkHistory {
-    public static final String TAG = "WifiNetworkHistory";
-    private static final boolean DBG = true;
-    private static final boolean VDBG = true;
-    static final String NETWORK_HISTORY_CONFIG_FILE = Environment.getDataDirectory()
-            + "/misc/wifi/networkHistory.txt";
-    /* Network History Keys */
-    private static final String SSID_KEY = "SSID";
-    static final String CONFIG_KEY = "CONFIG";
-    private static final String CONFIG_BSSID_KEY = "CONFIG_BSSID";
-    private static final String CHOICE_KEY = "CHOICE";
-    private static final String CHOICE_TIME_KEY = "CHOICE_TIME";
-    private static final String LINK_KEY = "LINK";
-    private static final String BSSID_KEY = "BSSID";
-    private static final String BSSID_KEY_END = "/BSSID";
-    private static final String RSSI_KEY = "RSSI";
-    private static final String FREQ_KEY = "FREQ";
-    private static final String DATE_KEY = "DATE";
-    private static final String MILLI_KEY = "MILLI";
-    private static final String NETWORK_ID_KEY = "ID";
-    private static final String PRIORITY_KEY = "PRIORITY";
-    private static final String DEFAULT_GW_KEY = "DEFAULT_GW";
-    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 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";
-    private static final String CONNECT_UID_KEY = "CONNECT_UID_KEY";
-    private static final String UPDATE_UID_KEY = "UPDATE_UID";
-    private static final String FQDN_KEY = "FQDN";
-    private static final String SCORER_OVERRIDE_KEY = "SCORER_OVERRIDE";
-    private static final String SCORER_OVERRIDE_AND_SWITCH_KEY = "SCORER_OVERRIDE_AND_SWITCH";
-    private static final String VALIDATED_INTERNET_ACCESS_KEY = "VALIDATED_INTERNET_ACCESS";
-    private static final String NO_INTERNET_ACCESS_REPORTS_KEY = "NO_INTERNET_ACCESS_REPORTS";
-    private static final String NO_INTERNET_ACCESS_EXPECTED_KEY = "NO_INTERNET_ACCESS_EXPECTED";
-    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";
-    private static final String UPDATE_NAME_KEY = "UPDATE_NAME";
-    private static final String USER_APPROVED_KEY = "USER_APPROVED";
-    private static final String CREATION_TIME_KEY = "CREATION_TIME";
-    private static final String UPDATE_TIME_KEY = "UPDATE_TIME";
-    static final String SHARED_KEY = "SHARED";
-    private static final String NETWORK_SELECTION_STATUS_KEY = "NETWORK_SELECTION_STATUS";
-    private static final String NETWORK_SELECTION_DISABLE_REASON_KEY =
-            "NETWORK_SELECTION_DISABLE_REASON";
-    private static final String HAS_EVER_CONNECTED_KEY = "HAS_EVER_CONNECTED";
-
-    private static final String SEPARATOR = ":  ";
-    private static final String NL = "\n";
-
-    protected final DelayedDiskWrite mWriter;
-    Context mContext;
-    /*
-     * Lost config list, whenever we read a config from networkHistory.txt that was not in
-     * wpa_supplicant.conf
-     */
-    HashSet<String> mLostConfigsDbg = new HashSet<String>();
-
-    public WifiNetworkHistory(Context c, DelayedDiskWrite writer) {
-        mContext = c;
-        mWriter = writer;
-    }
-
-    /**
-     * Write network history to file, for configured networks
-     *
-     * @param networks List of ConfiguredNetworks to write to NetworkHistory
-     */
-    public void writeKnownNetworkHistory(final List<WifiConfiguration> networks,
-            final ConcurrentHashMap<Integer, ScanDetailCache> scanDetailCaches,
-            final Set<String> deletedEphemeralSSIDs) {
-
-        /* Make a copy */
-        //final List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
-
-        //for (WifiConfiguration config : mConfiguredNetworks.valuesForAllUsers()) {
-        //    networks.add(new WifiConfiguration(config));
-        //}
-
-        mWriter.write(NETWORK_HISTORY_CONFIG_FILE, new DelayedDiskWrite.Writer() {
-            public void onWriteCalled(DataOutputStream out) throws IOException {
-                for (WifiConfiguration config : networks) {
-                    //loge("onWriteCalled write SSID: " + config.SSID);
-                   /* if (config.getLinkProperties() != null)
-                        loge(" lp " + config.getLinkProperties().toString());
-                    else
-                        loge("attempt config w/o lp");
-                    */
-                    NetworkSelectionStatus status = config.getNetworkSelectionStatus();
-                    if (VDBG) {
-                        int numlink = 0;
-                        if (config.linkedConfigurations != null) {
-                            numlink = config.linkedConfigurations.size();
-                        }
-                        String disableTime;
-                        if (config.getNetworkSelectionStatus().isNetworkEnabled()) {
-                            disableTime = "";
-                        } else {
-                            disableTime = "Disable time: " + DateFormat.getInstance().format(
-                                    config.getNetworkSelectionStatus().getDisableTime());
-                        }
-                        logd("saving network history: " + config.configKey()  + " gw: "
-                                + config.defaultGwMacAddress + " Network Selection-status: "
-                                + status.getNetworkStatusString()
-                                + disableTime + " ephemeral=" + config.ephemeral
-                                + " choice:" + status.getConnectChoice()
-                                + " link:" + numlink
-                                + " status:" + config.status
-                                + " nid:" + config.networkId
-                                + " hasEverConnected: " + status.getHasEverConnected());
-                    }
-
-                    if (!isValid(config)) {
-                        continue;
-                    }
-
-                    if (config.SSID == null) {
-                        if (VDBG) {
-                            logv("writeKnownNetworkHistory trying to write config with null SSID");
-                        }
-                        continue;
-                    }
-                    if (VDBG) {
-                        logv("writeKnownNetworkHistory write config " + config.configKey());
-                    }
-                    out.writeUTF(CONFIG_KEY + SEPARATOR + config.configKey() + NL);
-
-                    if (config.SSID != null) {
-                        out.writeUTF(SSID_KEY + SEPARATOR + config.SSID + NL);
-                    }
-                    if (config.BSSID != null) {
-                        out.writeUTF(CONFIG_BSSID_KEY + SEPARATOR + config.BSSID + NL);
-                    } else {
-                        out.writeUTF(CONFIG_BSSID_KEY + SEPARATOR + "null" + NL);
-                    }
-                    if (config.FQDN != null) {
-                        out.writeUTF(FQDN_KEY + SEPARATOR + config.FQDN + NL);
-                    }
-
-                    out.writeUTF(PRIORITY_KEY + SEPARATOR + Integer.toString(config.priority) + NL);
-                    out.writeUTF(NETWORK_ID_KEY + SEPARATOR
-                            + Integer.toString(config.networkId) + NL);
-                    out.writeUTF(SELF_ADDED_KEY + SEPARATOR
-                            + Boolean.toString(config.selfAdded) + NL);
-                    out.writeUTF(DID_SELF_ADD_KEY + SEPARATOR
-                            + Boolean.toString(config.didSelfAdd) + NL);
-                    out.writeUTF(NO_INTERNET_ACCESS_REPORTS_KEY + SEPARATOR
-                            + Integer.toString(config.numNoInternetAccessReports) + NL);
-                    out.writeUTF(VALIDATED_INTERNET_ACCESS_KEY + SEPARATOR
-                            + Boolean.toString(config.validatedInternetAccess) + NL);
-                    out.writeUTF(NO_INTERNET_ACCESS_EXPECTED_KEY + SEPARATOR +
-                            Boolean.toString(config.noInternetAccessExpected) + NL);
-                    out.writeUTF(EPHEMERAL_KEY + SEPARATOR
-                            + 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) {
-                        out.writeUTF(CREATION_TIME_KEY + SEPARATOR + config.creationTime + NL);
-                    }
-                    if (config.updateTime != null) {
-                        out.writeUTF(UPDATE_TIME_KEY + SEPARATOR + config.updateTime + NL);
-                    }
-                    if (config.peerWifiConfiguration != null) {
-                        out.writeUTF(PEER_CONFIGURATION_KEY + SEPARATOR
-                                + config.peerWifiConfiguration + NL);
-                    }
-                    out.writeUTF(SCORER_OVERRIDE_KEY + SEPARATOR
-                            + Integer.toString(config.numScorerOverride) + NL);
-                    out.writeUTF(SCORER_OVERRIDE_AND_SWITCH_KEY + SEPARATOR
-                            + Integer.toString(config.numScorerOverrideAndSwitchedNetwork) + NL);
-                    out.writeUTF(NUM_ASSOCIATION_KEY + SEPARATOR
-                            + Integer.toString(config.numAssociation) + NL);
-                    out.writeUTF(CREATOR_UID_KEY + SEPARATOR
-                            + Integer.toString(config.creatorUid) + NL);
-                    out.writeUTF(CONNECT_UID_KEY + SEPARATOR
-                            + Integer.toString(config.lastConnectUid) + NL);
-                    out.writeUTF(UPDATE_UID_KEY + SEPARATOR
-                            + Integer.toString(config.lastUpdateUid) + NL);
-                    out.writeUTF(CREATOR_NAME_KEY + SEPARATOR
-                            + config.creatorName + NL);
-                    out.writeUTF(UPDATE_NAME_KEY + SEPARATOR
-                            + config.lastUpdateName + NL);
-                    out.writeUTF(USER_APPROVED_KEY + SEPARATOR
-                            + Integer.toString(config.userApproved) + NL);
-                    out.writeUTF(SHARED_KEY + SEPARATOR + Boolean.toString(config.shared) + NL);
-                    String allowedKeyManagementString =
-                            makeString(config.allowedKeyManagement,
-                                    WifiConfiguration.KeyMgmt.strings);
-                    out.writeUTF(AUTH_KEY + SEPARATOR
-                            + allowedKeyManagementString + NL);
-                    out.writeUTF(NETWORK_SELECTION_STATUS_KEY + SEPARATOR
-                            + status.getNetworkSelectionStatus() + NL);
-                    out.writeUTF(NETWORK_SELECTION_DISABLE_REASON_KEY + SEPARATOR
-                            + status.getNetworkSelectionDisableReason() + NL);
-
-                    if (status.getConnectChoice() != null) {
-                        out.writeUTF(CHOICE_KEY + SEPARATOR + status.getConnectChoice() + NL);
-                        out.writeUTF(CHOICE_TIME_KEY + SEPARATOR
-                                + status.getConnectChoiceTimestamp() + NL);
-                    }
-
-                    if (config.linkedConfigurations != null) {
-                        log("writeKnownNetworkHistory write linked "
-                                + config.linkedConfigurations.size());
-
-                        for (String key : config.linkedConfigurations.keySet()) {
-                            out.writeUTF(LINK_KEY + SEPARATOR + key + NL);
-                        }
-                    }
-
-                    String macAddress = config.defaultGwMacAddress;
-                    if (macAddress != null) {
-                        out.writeUTF(DEFAULT_GW_KEY + SEPARATOR + macAddress + NL);
-                    }
-
-                    if (getScanDetailCache(config, scanDetailCaches) != null) {
-                        for (ScanDetail scanDetail : getScanDetailCache(config,
-                                    scanDetailCaches).values()) {
-                            ScanResult result = scanDetail.getScanResult();
-                            out.writeUTF(BSSID_KEY + SEPARATOR
-                                    + result.BSSID + NL);
-                            out.writeUTF(FREQ_KEY + SEPARATOR
-                                    + Integer.toString(result.frequency) + NL);
-
-                            out.writeUTF(RSSI_KEY + SEPARATOR
-                                    + Integer.toString(result.level) + NL);
-
-                            out.writeUTF(BSSID_KEY_END + NL);
-                        }
-                    }
-                    out.writeUTF(HAS_EVER_CONNECTED_KEY + SEPARATOR
-                            + Boolean.toString(status.getHasEverConnected()) + NL);
-                    out.writeUTF(NL);
-                    // Add extra blank lines for clarity
-                    out.writeUTF(NL);
-                    out.writeUTF(NL);
-                }
-                if (deletedEphemeralSSIDs != null && deletedEphemeralSSIDs.size() > 0) {
-                    for (String ssid : deletedEphemeralSSIDs) {
-                        out.writeUTF(DELETED_EPHEMERAL_KEY);
-                        out.writeUTF(ssid);
-                        out.writeUTF(NL);
-                    }
-                }
-            }
-        });
-    }
-
-    /**
-     * Adds information stored in networkHistory.txt to the given configs. The configs are provided
-     * as a mapping from configKey to WifiConfiguration, because the WifiConfigurations themselves
-     * do not contain sufficient information to compute their configKeys until after the information
-     * that is stored in networkHistory.txt has been added to them.
-     *
-     * @param configs mapping from configKey to a WifiConfiguration that contains the information
-     *         information read from wpa_supplicant.conf
-     */
-    public void readNetworkHistory(Map<String, WifiConfiguration> configs,
-            Map<Integer, ScanDetailCache> scanDetailCaches,
-            Set<String> deletedEphemeralSSIDs) {
-
-        try (DataInputStream in =
-                     new DataInputStream(new BufferedInputStream(
-                             new FileInputStream(NETWORK_HISTORY_CONFIG_FILE)))) {
-
-            String bssid = null;
-            String ssid = null;
-
-            int freq = 0;
-            int status = 0;
-            long seen = 0;
-            int rssi = WifiConfiguration.INVALID_RSSI;
-            String caps = null;
-
-            WifiConfiguration config = null;
-            while (true) {
-                String line = in.readUTF();
-                if (line == null) {
-                    break;
-                }
-                int colon = line.indexOf(':');
-                if (colon < 0) {
-                    continue;
-                }
-
-                String key = line.substring(0, colon).trim();
-                String value = line.substring(colon + 1).trim();
-
-                if (key.equals(CONFIG_KEY)) {
-                    config = configs.get(value);
-
-                    // skip reading that configuration data
-                    // since we don't have a corresponding network ID
-                    if (config == null) {
-                        Log.e(TAG, "readNetworkHistory didnt find netid for hash="
-                                + Integer.toString(value.hashCode())
-                                + " key: " + value);
-                        mLostConfigsDbg.add(value);
-                        continue;
-                    } else {
-                        // After an upgrade count old connections as owned by system
-                        if (config.creatorName == null || config.lastUpdateName == null) {
-                            config.creatorName =
-                                mContext.getPackageManager().getNameForUid(Process.SYSTEM_UID);
-                            config.lastUpdateName = config.creatorName;
-
-                            if (DBG) {
-                                Log.w(TAG, "Upgrading network " + config.networkId
-                                        + " to " + config.creatorName);
-                            }
-                        }
-                    }
-                } else if (config != null) {
-                    NetworkSelectionStatus networkStatus = config.getNetworkSelectionStatus();
-                    switch (key) {
-                        case SSID_KEY:
-                            if (config.isPasspoint()) {
-                                break;
-                            }
-                            ssid = value;
-                            if (config.SSID != null && !config.SSID.equals(ssid)) {
-                                loge("Error parsing network history file, mismatched SSIDs");
-                                config = null; //error
-                                ssid = null;
-                            } else {
-                                config.SSID = ssid;
-                            }
-                            break;
-                        case CONFIG_BSSID_KEY:
-                            config.BSSID = value.equals("null") ? null : value;
-                            break;
-                        case FQDN_KEY:
-                            // Check for literal 'null' to be backwards compatible.
-                            config.FQDN = value.equals("null") ? null : value;
-                            break;
-                        case DEFAULT_GW_KEY:
-                            config.defaultGwMacAddress = value;
-                            break;
-                        case SELF_ADDED_KEY:
-                            config.selfAdded = Boolean.parseBoolean(value);
-                            break;
-                        case DID_SELF_ADD_KEY:
-                            config.didSelfAdd = Boolean.parseBoolean(value);
-                            break;
-                        case NO_INTERNET_ACCESS_REPORTS_KEY:
-                            config.numNoInternetAccessReports = Integer.parseInt(value);
-                            break;
-                        case VALIDATED_INTERNET_ACCESS_KEY:
-                            config.validatedInternetAccess = Boolean.parseBoolean(value);
-                            break;
-                        case NO_INTERNET_ACCESS_EXPECTED_KEY:
-                            config.noInternetAccessExpected = Boolean.parseBoolean(value);
-                            break;
-                        case CREATION_TIME_KEY:
-                            config.creationTime = value;
-                            break;
-                        case UPDATE_TIME_KEY:
-                            config.updateTime = value;
-                            break;
-                        case EPHEMERAL_KEY:
-                            config.ephemeral = Boolean.parseBoolean(value);
-                            break;
-                        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;
-                        case CREATOR_UID_KEY:
-                            config.creatorUid = Integer.parseInt(value);
-                            break;
-                        case SCORER_OVERRIDE_KEY:
-                            config.numScorerOverride = Integer.parseInt(value);
-                            break;
-                        case SCORER_OVERRIDE_AND_SWITCH_KEY:
-                            config.numScorerOverrideAndSwitchedNetwork = Integer.parseInt(value);
-                            break;
-                        case NUM_ASSOCIATION_KEY:
-                            config.numAssociation = Integer.parseInt(value);
-                            break;
-                        case CONNECT_UID_KEY:
-                            config.lastConnectUid = Integer.parseInt(value);
-                            break;
-                        case UPDATE_UID_KEY:
-                            config.lastUpdateUid = Integer.parseInt(value);
-                            break;
-                        case PEER_CONFIGURATION_KEY:
-                            config.peerWifiConfiguration = value;
-                            break;
-                        case NETWORK_SELECTION_STATUS_KEY:
-                            int networkStatusValue = Integer.parseInt(value);
-                            // Reset temporarily disabled network status
-                            if (networkStatusValue ==
-                                    NetworkSelectionStatus.NETWORK_SELECTION_TEMPORARY_DISABLED) {
-                                networkStatusValue =
-                                        NetworkSelectionStatus.NETWORK_SELECTION_ENABLED;
-                            }
-                            networkStatus.setNetworkSelectionStatus(networkStatusValue);
-                            break;
-                        case NETWORK_SELECTION_DISABLE_REASON_KEY:
-                            networkStatus.setNetworkSelectionDisableReason(Integer.parseInt(value));
-                            break;
-                        case CHOICE_KEY:
-                            networkStatus.setConnectChoice(value);
-                            break;
-                        case CHOICE_TIME_KEY:
-                            networkStatus.setConnectChoiceTimestamp(Long.parseLong(value));
-                            break;
-                        case LINK_KEY:
-                            if (config.linkedConfigurations == null) {
-                                config.linkedConfigurations = new HashMap<>();
-                            } else {
-                                config.linkedConfigurations.put(value, -1);
-                            }
-                            break;
-                        case BSSID_KEY:
-                            status = 0;
-                            ssid = null;
-                            bssid = null;
-                            freq = 0;
-                            seen = 0;
-                            rssi = WifiConfiguration.INVALID_RSSI;
-                            caps = "";
-                            break;
-                        case RSSI_KEY:
-                            rssi = Integer.parseInt(value);
-                            break;
-                        case FREQ_KEY:
-                            freq = Integer.parseInt(value);
-                            break;
-                        case DATE_KEY:
-                            /*
-                             * when reading the configuration from file we don't update the date
-                             * so as to avoid reading back stale or non-sensical data that would
-                             * depend on network time.
-                             * The date of a WifiConfiguration should only come from actual scan
-                             * result.
-                             *
-                            String s = key.replace(FREQ_KEY, "");
-                            seen = Integer.getInteger(s);
-                            */
-                            break;
-                        case BSSID_KEY_END:
-                            if ((bssid != null) && (ssid != null)) {
-                                if (getScanDetailCache(config, scanDetailCaches) != null) {
-                                    WifiSsid wssid = WifiSsid.createFromAsciiEncoded(ssid);
-                                    ScanDetail scanDetail = new ScanDetail(wssid, bssid,
-                                            caps, rssi, freq, (long) 0, seen);
-                                    getScanDetailCache(config, scanDetailCaches).put(scanDetail);
-                                }
-                            }
-                            break;
-                        case DELETED_EPHEMERAL_KEY:
-                            if (!TextUtils.isEmpty(value)) {
-                                deletedEphemeralSSIDs.add(value);
-                            }
-                            break;
-                        case CREATOR_NAME_KEY:
-                            config.creatorName = value;
-                            break;
-                        case UPDATE_NAME_KEY:
-                            config.lastUpdateName = value;
-                            break;
-                        case USER_APPROVED_KEY:
-                            config.userApproved = Integer.parseInt(value);
-                            break;
-                        case SHARED_KEY:
-                            config.shared = Boolean.parseBoolean(value);
-                            break;
-                        case HAS_EVER_CONNECTED_KEY:
-                            networkStatus.setHasEverConnected(Boolean.parseBoolean(value));
-                            break;
-                    }
-                }
-            }
-        } catch (EOFException e) {
-            // do nothing
-        } catch (FileNotFoundException e) {
-            Log.i(TAG, "readNetworkHistory: no config file, " + e);
-        } catch (NumberFormatException e) {
-            Log.e(TAG, "readNetworkHistory: failed to parse, " + e, e);
-        } catch (IOException e) {
-            Log.e(TAG, "readNetworkHistory: failed to read, " + e, e);
-        }
-    }
-
-    /**
-     * Ported this out of WifiServiceImpl, I have no idea what it's doing
-     * <TODO> figure out what/why this is doing
-     * <TODO> Port it into WifiConfiguration, then remove all the silly business from ServiceImpl
-     */
-    public boolean isValid(WifiConfiguration config) {
-        if (config.allowedKeyManagement == null) {
-            return false;
-        }
-        if (config.allowedKeyManagement.cardinality() > 1) {
-            if (config.allowedKeyManagement.cardinality() != 2) {
-                return false;
-            }
-            if (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) {
-                return false;
-            }
-            if ((!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X))
-                    && (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    private static String makeString(BitSet set, String[] strings) {
-        StringBuffer buf = new StringBuffer();
-        int nextSetBit = -1;
-
-        /* Make sure all set bits are in [0, strings.length) to avoid
-         * going out of bounds on strings.  (Shouldn't happen, but...) */
-        set = set.get(0, strings.length);
-
-        while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
-            buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
-        }
-
-        // remove trailing space
-        if (set.cardinality() > 0) {
-            buf.setLength(buf.length() - 1);
-        }
-
-        return buf.toString();
-    }
-
-    protected void logv(String s) {
-        Log.v(TAG, s);
-    }
-    protected void logd(String s) {
-        Log.d(TAG, s);
-    }
-    protected void log(String s) {
-        Log.d(TAG, s);
-    }
-    protected void loge(String s) {
-        loge(s, false);
-    }
-    protected void loge(String s, boolean stack) {
-        if (stack) {
-            Log.e(TAG, s + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
-                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
-                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
-                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
-        } else {
-            Log.e(TAG, s);
-        }
-    }
-
-    private ScanDetailCache getScanDetailCache(WifiConfiguration config,
-            Map<Integer, ScanDetailCache> scanDetailCaches) {
-        if (config == null || scanDetailCaches == null) return null;
-        ScanDetailCache cache = scanDetailCaches.get(config.networkId);
-        if (cache == null && config.networkId != WifiConfiguration.INVALID_NETWORK_ID) {
-            cache =
-                    new ScanDetailCache(
-                            config, WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE,
-                            WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE);
-            scanDetailCaches.put(config.networkId, cache);
-        }
-        return cache;
-    }
-}
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/WifiServiceImpl.java b/service/java/com/android/server/wifi/WifiServiceImpl.java
index 6ef1020..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);
@@ -1739,7 +1744,7 @@
     @Override
     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.
@@ -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 90fb2f6..41a5994 100644
--- a/service/java/com/android/server/wifi/WifiStateMachine.java
+++ b/service/java/com/android/server/wifi/WifiStateMachine.java
@@ -1913,9 +1913,13 @@
 
     public List<WifiConfiguration> syncGetConfiguredNetworks(int uuid, AsyncChannel channel) {
         Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONFIGURED_NETWORKS, uuid);
-        List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
-        resultMsg.recycle();
-        return result;
+        if (resultMsg == null) { // an error has occurred
+            return null;
+        } else {
+            List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
+            resultMsg.recycle();
+            return result;
+        }
     }
 
     public List<WifiConfiguration> syncGetPrivilegedConfiguredNetwork(AsyncChannel channel) {
@@ -3483,14 +3487,14 @@
         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();
+        // Set meteredHint if DHCP result says network is metered
+        if (dhcpResults.hasMeteredHint()) {
+            mWifiInfo.setMeteredHint(true);
+        }
+
+        updateCapabilities(config);
     }
 
     private void handleSuccessfulIpConfiguration() {
@@ -3502,7 +3506,7 @@
                     WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE);
 
             // Tell the framework whether the newly connected network is trusted or untrusted.
-            updateCapabilities();
+            updateCapabilities(c);
         }
         if (c != null) {
             ScanResult result = getCurrentScanResult();
@@ -4271,10 +4275,6 @@
                     mLastSignalLevel = -1;
 
                     mWifiInfo.setMacAddress(mWifiNative.getMacAddress());
-                    // Attempt to migrate data out of legacy store.
-                    if (!mWifiConfigManager.migrateFromLegacyStore()) {
-                        Log.e(TAG, "Failed to migrate from legacy config store");
-                    }
                     initializeWpsDetails();
                     sendSupplicantConnectionChangedBroadcast(true);
                     transitionTo(mSupplicantStartedState);
@@ -4862,7 +4862,7 @@
             return null;
         }
 
-        return scanDetailCache.get(BSSID);
+        return scanDetailCache.getScanResult(BSSID);
     }
 
     String getCurrentBSSID() {
@@ -5420,7 +5420,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);
                             }
@@ -5508,7 +5508,11 @@
         }
     }
 
-    private void updateCapabilities() {
+    public void updateCapabilities() {
+        updateCapabilities(getCurrentWifiConfiguration());
+    }
+
+    private void updateCapabilities(WifiConfiguration config) {
         final NetworkCapabilities result = new NetworkCapabilities(mDfltNetworkCapabilities);
 
         if (mWifiInfo != null && !mWifiInfo.isEphemeral()) {
@@ -5517,7 +5521,7 @@
             result.removeCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
         }
 
-        if (mWifiInfo != null && !mWifiInfo.getMeteredHint()) {
+        if (mWifiInfo != null && !WifiConfiguration.isMetered(config, mWifiInfo)) {
             result.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
         } else {
             result.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
@@ -5529,7 +5533,9 @@
             result.setSignalStrength(NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED);
         }
 
-        mNetworkAgent.sendNetworkCapabilities(result);
+        if (mNetworkAgent != null) {
+            mNetworkAgent.sendNetworkCapabilities(result);
+        }
     }
 
     /**
@@ -5973,7 +5979,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);
                                 }
@@ -6144,7 +6150,9 @@
                 if (mVerboseLoggingEnabled) {
                     log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected);
                 }
-                mNetworkAgent.explicitlySelected(config.noInternetAccessExpected);
+                if (mNetworkAgent != null) {
+                    mNetworkAgent.explicitlySelected(config.noInternetAccessExpected);
+                }
             }
         }
 
@@ -6516,13 +6524,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:
@@ -6775,7 +6787,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,
@@ -6871,13 +6887,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();
@@ -6888,15 +6908,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 005f360..056777f 100644
--- a/service/java/com/android/server/wifi/WificondControl.java
+++ b/service/java/com/android/server/wifi/WificondControl.java
@@ -51,6 +51,13 @@
     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;
@@ -92,24 +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");
-            // Update metrics
+            mWifiInjector.getWifiMetrics().incrementPnoScanStartedOverOffloadCount();
         }
 
         @Override
         public void OnPnoScanOverOffloadFailed(int reason) {
             Log.d(TAG, "Pno scan over offload failed");
-            // Update metrics
+            mWifiInjector.getWifiMetrics().incrementPnoScanFailedOverOffloadCount();
         }
     }
 
@@ -334,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;
@@ -463,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 ead0c5f..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;
 
 /**
@@ -86,7 +88,7 @@
 
     private final WifiAwareStateManager mMgr;
     public NetworkInterfaceWrapper mNiWrapper = new NetworkInterfaceWrapper();
-    private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities();
+    private static final NetworkCapabilities sNetworkCapabilitiesFilter = new NetworkCapabilities();
     private final Set<String> mInterfaces = new HashSet<>();
     private final Map<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
             mNetworkRequestsCache = new ArrayMap<>();
@@ -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.
@@ -468,7 +482,7 @@
             NetworkInfo networkInfo = new NetworkInfo(ConnectivityManager.TYPE_NONE, 0,
                     NETWORK_TAG, "");
             NetworkCapabilities networkCapabilities = new NetworkCapabilities(
-                    mNetworkCapabilitiesFilter);
+                    sNetworkCapabilitiesFilter);
             LinkProperties linkProperties = new LinkProperties();
 
             boolean interfaceUsedByAnotherNdp = isInterfaceUpAndUsedByAnotherNdp(nnri);
@@ -481,6 +495,7 @@
                             + ": can't configure network - "
                             + e);
                     mMgr.endDataPath(ndpId);
+                    nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                     return networkSpecifier;
                 }
             } else {
@@ -490,8 +505,8 @@
                 }
             }
 
-            if (!mNiWrapper.configureAgentProperties(nnri, networkSpecifier, ndpId, networkInfo,
-                    networkCapabilities, linkProperties)) {
+            if (!mNiWrapper.configureAgentProperties(nnri, nnri.equivalentSpecifiers, ndpId,
+                    networkInfo, networkCapabilities, linkProperties)) {
                 return networkSpecifier;
             }
 
@@ -499,7 +514,7 @@
                     AGENT_TAG_PREFIX + nnri.ndpId,
                     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(),
@@ -538,10 +553,13 @@
         }
 
         tearDownInterfaceIfPossible(nnriE.getValue());
-        if (nnriE.getValue().state == AwareNetworkRequestInformation.STATE_CONFIRMED) {
+        if (nnriE.getValue().state == AwareNetworkRequestInformation.STATE_CONFIRMED
+                || nnriE.getValue().state == AwareNetworkRequestInformation.STATE_TERMINATING) {
             mAwareMetrics.recordNdpSessionDuration(nnriE.getValue().startTimestamp);
         }
         mNetworkRequestsCache.remove(nnriE.getKey());
+
+        mNetworkFactory.tickleConnectivityIfWaiting();
     }
 
     /**
@@ -578,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) {
@@ -622,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
@@ -638,6 +674,25 @@
                 return false;
             }
 
+            // 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;
+            }
+
             mNetworkRequestsCache.put(networkSpecifier, nnri);
 
             return true;
@@ -725,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.
@@ -771,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, "");
@@ -811,8 +873,9 @@
                 continue;
             }
 
-            if (nri.interfaceName.equals(lnri.interfaceName)
-                    && lnri.state == AwareNetworkRequestInformation.STATE_CONFIRMED) {
+            if (nri.interfaceName.equals(lnri.interfaceName) && (
+                    lnri.state == AwareNetworkRequestInformation.STATE_CONFIRMED
+                            || lnri.state == AwareNetworkRequestInformation.STATE_TERMINATING)) {
                 return true;
             }
         }
@@ -858,6 +921,7 @@
         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;
 
@@ -866,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;
@@ -1002,6 +1108,7 @@
             nnri.peerInstanceId = peerInstanceId;
             nnri.peerDiscoveryMac = peerMac;
             nnri.networkSpecifier = ns;
+            nnri.equivalentSpecifiers.add(ns);
 
             return nnri;
         }
@@ -1018,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();
         }
     }
@@ -1033,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;
@@ -1044,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();
@@ -1064,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;
             }
 
@@ -1071,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));
@@ -1088,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/WifiAwareRttStateManager.java b/service/java/com/android/server/wifi/aware/WifiAwareRttStateManager.java
index afc044c..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.
@@ -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/hotspot2/LegacyPasspointConfigParser.java b/service/java/com/android/server/wifi/hotspot2/LegacyPasspointConfigParser.java
deleted file mode 100644
index 31795f1..0000000
--- a/service/java/com/android/server/wifi/hotspot2/LegacyPasspointConfigParser.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/*
- * 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.hotspot2;
-
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Pair;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Utility class for parsing legacy (N and older) Passpoint configuration file content
- * (/data/misc/wifi/PerProviderSubscription.conf).  In N and older, only Release 1 is supported.
- *
- * This class only retrieve the relevant Release 1 configuration fields that are not backed
- * elsewhere.  Below are relevant fields:
- * - FQDN (used for linking with configuration data stored elsewhere)
- * - Friendly Name
- * - Roaming Consortium
- * - Realm
- * - IMSI (for SIM credential)
- *
- * Below is an example content of a Passpoint configuration file:
- *
- * tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)
- * 8:MgmtTree+
- * 17:PerProviderSubscription+
- * 4:r1i1+
- * 6:HomeSP+
- * c:FriendlyName=d:Test Provider
- * 4:FQDN=8:test.net
- * 13:RoamingConsortiumOI=9:1234,5678
- * .
- * a:Credential+
- * 10:UsernamePassword+
- * 8:Username=4:user
- * 8:Password=4:pass
- *
- * 9:EAPMethod+
- * 7:EAPType=2:21
- * b:InnerMethod=3:PAP
- * .
- * .
- * 5:Realm=a:boingo.com
- * .
- * .
- * .
- * .
- *
- * Each string is prefixed with a "|StringBytesInHex|:".
- * '+' indicates start of a new internal node.
- * '.' indicates end of the current internal node.
- * '=' indicates "value" of a leaf node.
- *
- */
-public class LegacyPasspointConfigParser {
-    private static final String TAG = "LegacyPasspointConfigParser";
-
-    private static final String TAG_MANAGEMENT_TREE = "MgmtTree";
-    private static final String TAG_PER_PROVIDER_SUBSCRIPTION = "PerProviderSubscription";
-    private static final String TAG_HOMESP = "HomeSP";
-    private static final String TAG_FQDN = "FQDN";
-    private static final String TAG_FRIENDLY_NAME = "FriendlyName";
-    private static final String TAG_ROAMING_CONSORTIUM_OI = "RoamingConsortiumOI";
-    private static final String TAG_CREDENTIAL = "Credential";
-    private static final String TAG_REALM = "Realm";
-    private static final String TAG_SIM = "SIM";
-    private static final String TAG_IMSI = "IMSI";
-
-    private static final String LONG_ARRAY_SEPARATOR = ",";
-    private static final String END_OF_INTERNAL_NODE_INDICATOR = ".";
-    private static final char START_OF_INTERNAL_NODE_INDICATOR = '+';
-    private static final char STRING_PREFIX_INDICATOR = ':';
-    private static final char STRING_VALUE_INDICATOR = '=';
-
-    /**
-     * An abstraction for a node within a tree.  A node can be an internal node (contained
-     * children nodes) or a leaf node (contained a String value).
-     */
-    private abstract static class Node {
-        private final String mName;
-        Node(String name) {
-            mName = name;
-        }
-
-        /**
-         * @return the name of the node
-         */
-        public String getName() {
-            return mName;
-        }
-
-        /**
-         * Applies for internal node only.
-         *
-         * @return the list of children nodes.
-         */
-        public abstract List<Node> getChildren();
-
-        /**
-         * Applies for leaf node only.
-         *
-         * @return the string value of the node
-         */
-        public abstract String getValue();
-    }
-
-    /**
-     * Class representing an internal node of a tree.  It contained a list of child nodes.
-     */
-    private static class InternalNode extends Node {
-        private final List<Node> mChildren;
-        InternalNode(String name, List<Node> children) {
-            super(name);
-            mChildren = children;
-        }
-
-        @Override
-        public List<Node> getChildren() {
-            return mChildren;
-        }
-
-        @Override
-        public String getValue() {
-            return null;
-        }
-    }
-
-    /**
-     * Class representing a leaf node of a tree.  It contained a String type value.
-     */
-    private static class LeafNode extends Node {
-        private final String mValue;
-        LeafNode(String name, String value) {
-            super(name);
-            mValue = value;
-        }
-
-        @Override
-        public List<Node> getChildren() {
-            return null;
-        }
-
-        @Override
-        public String getValue() {
-            return mValue;
-        }
-    }
-
-    public LegacyPasspointConfigParser() {}
-
-    /**
-     * Parse the legacy Passpoint configuration file content, only retrieve the relevant
-     * configurations that are not saved elsewhere.
-     *
-     * For both N and M, only Release 1 is supported. Most of the configurations are saved
-     * elsewhere as part of the {@link android.net.wifi.WifiConfiguration} data.
-     * The configurations needed from the legacy Passpoint configuration file are:
-     *
-     * - FQDN - needed to be able to link to the associated {@link WifiConfiguration} data
-     * - Friendly Name
-     * - Roaming Consortium OIs
-     * - Realm
-     * - IMSI (for SIM credential)
-     *
-     * Make this function non-static so that it can be mocked during unit test.
-     *
-     * @param fileName The file name of the configuration file
-     * @return Map of FQDN to {@link LegacyPasspointConfig}
-     * @throws IOException
-     */
-    public Map<String, LegacyPasspointConfig> parseConfig(String fileName)
-            throws IOException {
-        Map<String, LegacyPasspointConfig> configs = new HashMap<>();
-        BufferedReader in = new BufferedReader(new FileReader(fileName));
-        in.readLine();      // Ignore the first line which contained the header.
-
-        // Convert the configuration data to a management tree represented by a root {@link Node}.
-        Node root = buildNode(in);
-
-        if (root == null || root.getChildren() == null) {
-            Log.d(TAG, "Empty configuration data");
-            return configs;
-        }
-
-        // Verify root node name.
-        if (!TextUtils.equals(TAG_MANAGEMENT_TREE, root.getName())) {
-            throw new IOException("Unexpected root node: " + root.getName());
-        }
-
-        // Process and retrieve the configuration from each PPS (PerProviderSubscription) node.
-        List<Node> ppsNodes = root.getChildren();
-        for (Node ppsNode : ppsNodes) {
-            LegacyPasspointConfig config = processPpsNode(ppsNode);
-            configs.put(config.mFqdn, config);
-        }
-        return configs;
-    }
-
-    /**
-     * Build a {@link Node} from the current line in the buffer.  A node can be an internal
-     * node (ends with '+') or a leaf node.
-     *
-     * @param in Input buffer to read data from
-     * @return {@link Node} representing the current line
-     * @throws IOException
-     */
-    private static Node buildNode(BufferedReader in) throws IOException {
-        // Read until non-empty line.
-        String currentLine = null;
-        while ((currentLine = in.readLine()) != null) {
-            if (!currentLine.isEmpty()) {
-                break;
-            }
-        }
-
-        // Return null if EOF is reached.
-        if (currentLine == null) {
-            return null;
-        }
-
-        // Remove the leading and the trailing whitespaces.
-        currentLine = currentLine.trim();
-
-        // Check for the internal node terminator.
-        if (TextUtils.equals(END_OF_INTERNAL_NODE_INDICATOR, currentLine)) {
-            return null;
-        }
-
-        // Parse the name-value of the current line.  The value will be null if the current line
-        // is not a leaf node (e.g. line ends with a '+').
-        // Each line is encoded in UTF-8.
-        Pair<String, String> nameValuePair =
-                parseLine(currentLine.getBytes(StandardCharsets.UTF_8));
-        if (nameValuePair.second != null) {
-            return new LeafNode(nameValuePair.first, nameValuePair.second);
-        }
-
-        // Parse the children contained under this internal node.
-        List<Node> children = new ArrayList<>();
-        Node child = null;
-        while ((child = buildNode(in)) != null) {
-            children.add(child);
-        }
-        return new InternalNode(nameValuePair.first, children);
-    }
-
-    /**
-     * Process a PPS (PerProviderSubscription) node to retrieve Passpoint configuration data.
-     *
-     * @param ppsNode The PPS node to process
-     * @return {@link LegacyPasspointConfig}
-     * @throws IOException
-     */
-    private static LegacyPasspointConfig processPpsNode(Node ppsNode) throws IOException {
-        if (ppsNode.getChildren() == null || ppsNode.getChildren().size() != 1) {
-            throw new IOException("PerProviderSubscription node should contain "
-                    + "one instance node");
-        }
-
-        if (!TextUtils.equals(TAG_PER_PROVIDER_SUBSCRIPTION, ppsNode.getName())) {
-            throw new IOException("Unexpected name for PPS node: " + ppsNode.getName());
-        }
-
-        // Retrieve the PPS instance node.
-        Node instanceNode = ppsNode.getChildren().get(0);
-        if (instanceNode.getChildren() == null) {
-            throw new IOException("PPS instance node doesn't contained any children");
-        }
-
-        // Process and retrieve the relevant configurations under the PPS instance node.
-        LegacyPasspointConfig config = new LegacyPasspointConfig();
-        for (Node node : instanceNode.getChildren()) {
-            switch (node.getName()) {
-                case TAG_HOMESP:
-                    processHomeSPNode(node, config);
-                    break;
-                case TAG_CREDENTIAL:
-                    processCredentialNode(node, config);
-                    break;
-                default:
-                    Log.d(TAG, "Ignore uninterested field under PPS instance: " + node.getName());
-                    break;
-            }
-        }
-        if (config.mFqdn == null) {
-            throw new IOException("PPS instance missing FQDN");
-        }
-        return config;
-    }
-
-    /**
-     * Process a HomeSP node to retrieve configuration data into the given |config|.
-     *
-     * @param homeSpNode The HomeSP node to process
-     * @param config The config object to fill in the data
-     * @throws IOException
-     */
-    private static void processHomeSPNode(Node homeSpNode, LegacyPasspointConfig config)
-            throws IOException {
-        if (homeSpNode.getChildren() == null) {
-            throw new IOException("HomeSP node should contain at least one child node");
-        }
-
-        for (Node node : homeSpNode.getChildren()) {
-            switch (node.getName()) {
-                case TAG_FQDN:
-                    config.mFqdn = getValue(node);
-                    break;
-                case TAG_FRIENDLY_NAME:
-                    config.mFriendlyName = getValue(node);
-                    break;
-                case TAG_ROAMING_CONSORTIUM_OI:
-                    config.mRoamingConsortiumOis = parseLongArray(getValue(node));
-                    break;
-                default:
-                    Log.d(TAG, "Ignore uninterested field under HomeSP: " + node.getName());
-                    break;
-            }
-        }
-    }
-
-    /**
-     * Process a Credential node to retrieve configuration data into the given |config|.
-     *
-     * @param credentialNode The Credential node to process
-     * @param config The config object to fill in the data
-     * @throws IOException
-     */
-    private static void processCredentialNode(Node credentialNode,
-            LegacyPasspointConfig config)
-            throws IOException {
-        if (credentialNode.getChildren() == null) {
-            throw new IOException("Credential node should contain at least one child node");
-        }
-
-        for (Node node : credentialNode.getChildren()) {
-            switch (node.getName()) {
-                case TAG_REALM:
-                    config.mRealm = getValue(node);
-                    break;
-                case TAG_SIM:
-                    processSimNode(node, config);
-                    break;
-                default:
-                    Log.d(TAG, "Ignore uninterested field under Credential: " + node.getName());
-                    break;
-            }
-        }
-    }
-
-    /**
-     * Process a SIM node to retrieve configuration data into the given |config|.
-     *
-     * @param simNode The SIM node to process
-     * @param config The config object to fill in the data
-     * @throws IOException
-     */
-    private static void processSimNode(Node simNode, LegacyPasspointConfig config)
-            throws IOException {
-        if (simNode.getChildren() == null) {
-            throw new IOException("SIM node should contain at least one child node");
-        }
-
-        for (Node node : simNode.getChildren()) {
-            switch (node.getName()) {
-                case TAG_IMSI:
-                    config.mImsi = getValue(node);
-                    break;
-                default:
-                    Log.d(TAG, "Ignore uninterested field under SIM: " + node.getName());
-                    break;
-            }
-        }
-    }
-
-    /**
-     * Parse the given line in the legacy Passpoint configuration file.
-     * A line can be in the following formats:
-     * 2:ab+         // internal node
-     * 2:ab=2:bc     // leaf node
-     * .             // end of internal node
-     *
-     * @param line The line to parse
-     * @return name-value pair, a value of null indicates internal node
-     * @throws IOException
-     */
-    private static Pair<String, String> parseLine(byte[] lineBytes) throws IOException {
-        Pair<String, Integer> nameIndexPair = parseString(lineBytes, 0);
-        int currentIndex = nameIndexPair.second;
-        try {
-            if (lineBytes[currentIndex] == START_OF_INTERNAL_NODE_INDICATOR) {
-                return Pair.create(nameIndexPair.first, null);
-            }
-
-            if (lineBytes[currentIndex] != STRING_VALUE_INDICATOR) {
-                throw new IOException("Invalid line - missing both node and value indicator: "
-                        + new String(lineBytes, StandardCharsets.UTF_8));
-            }
-        } catch (IndexOutOfBoundsException e) {
-            throw new IOException("Invalid line - " + e.getMessage() + ": "
-                    + new String(lineBytes, StandardCharsets.UTF_8));
-        }
-        Pair<String, Integer> valueIndexPair = parseString(lineBytes, currentIndex + 1);
-        return Pair.create(nameIndexPair.first, valueIndexPair.first);
-    }
-
-    /**
-     * Parse a string value in the given line from the given start index.
-     * A string value is in the following format:
-     * |HexByteLength|:|String|
-     *
-     * The length value indicates the number of UTF-8 bytes in hex for the given string.
-     *
-     * For example: 3:abc
-     *
-     * @param lineBytes The UTF-8 bytes of the line to parse
-     * @param startIndex The start index from the given line to parse from
-     * @return Pair of a string value and an index pointed to character after the string value
-     * @throws IOException
-     */
-    private static Pair<String, Integer> parseString(byte[] lineBytes, int startIndex)
-            throws IOException {
-        // Locate the index that separate length and the string value.
-        int prefixIndex = -1;
-        for (int i = startIndex; i < lineBytes.length; i++) {
-            if (lineBytes[i] == STRING_PREFIX_INDICATOR) {
-                prefixIndex = i;
-                break;
-            }
-        }
-        if (prefixIndex == -1) {
-            throw new IOException("Invalid line - missing string prefix: "
-                    + new String(lineBytes, StandardCharsets.UTF_8));
-        }
-
-        try {
-            String lengthStr = new String(lineBytes, startIndex, prefixIndex - startIndex,
-                    StandardCharsets.UTF_8);
-            int length = Integer.parseInt(lengthStr, 16);
-            int strStartIndex = prefixIndex + 1;
-            // The length might account for bytes for the whitespaces, since the whitespaces are
-            // already trimmed, ignore them.
-            if ((strStartIndex + length) > lineBytes.length) {
-                length = lineBytes.length - strStartIndex;
-            }
-            return Pair.create(
-                    new String(lineBytes, strStartIndex, length, StandardCharsets.UTF_8),
-                    strStartIndex + length);
-        } catch (NumberFormatException | IndexOutOfBoundsException e) {
-            throw new IOException("Invalid line - " + e.getMessage() + ": "
-                    + new String(lineBytes, StandardCharsets.UTF_8));
-        }
-    }
-
-    /**
-     * Parse a long array from the given string.
-     *
-     * @param str The string to parse
-     * @return long[]
-     * @throws IOException
-     */
-    private static long[] parseLongArray(String str)
-            throws IOException {
-        String[] strArray = str.split(LONG_ARRAY_SEPARATOR);
-        long[] longArray = new long[strArray.length];
-        for (int i = 0; i < longArray.length; i++) {
-            try {
-                longArray[i] = Long.parseLong(strArray[i], 16);
-            } catch (NumberFormatException e) {
-                throw new IOException("Invalid long integer value: " + strArray[i]);
-            }
-        }
-        return longArray;
-    }
-
-    /**
-     * Get the String value of the given node.  An IOException will be thrown if the given
-     * node doesn't contain a String value (internal node).
-     *
-     * @param node The node to get the value from
-     * @return String
-     * @throws IOException
-     */
-    private static String getValue(Node node) throws IOException {
-        if (node.getValue() == null) {
-            throw new IOException("Attempt to retreive value from non-leaf node: "
-                    + node.getName());
-        }
-        return node.getValue();
-    }
-}
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/NativeUtil.java b/service/java/com/android/server/wifi/util/NativeUtil.java
index 95ee11e..84f9351 100644
--- a/service/java/com/android/server/wifi/util/NativeUtil.java
+++ b/service/java/com/android/server/wifi/util/NativeUtil.java
@@ -210,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");
         }
@@ -232,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() + "\"";
@@ -259,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.
      *
@@ -280,7 +280,7 @@
      * @throws IllegalArgumentException for null bytes.
      */
     public static String encodeSsid(ArrayList<Byte> ssidBytes) {
-        return bytesToHexOrQuotedAsciiString(ssidBytes);
+        return bytesToHexOrQuotedString(ssidBytes);
     }
 
     /**
diff --git a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
index 6caca46..069e5a8 100644
--- a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
+++ b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
@@ -114,6 +114,25 @@
         }
     }
 
+
+    /**
+     * 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.
@@ -243,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/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java b/tests/wifitests/src/com/android/server/wifi/RttServiceTest.java
index b2b40e2..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();
@@ -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/WifiConfigManagerTest.java b/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
index a85e574..d14c8fc 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
@@ -43,7 +43,6 @@
 import android.util.Pair;
 
 import com.android.internal.R;
-import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy;
 import com.android.server.wifi.util.WifiPermissionsUtil;
 import com.android.server.wifi.util.WifiPermissionsWrapper;
 
@@ -101,7 +100,6 @@
     @Mock private TelephonyManager mTelephonyManager;
     @Mock private WifiKeyStore mWifiKeyStore;
     @Mock private WifiConfigStore mWifiConfigStore;
-    @Mock private WifiConfigStoreLegacy mWifiConfigStoreLegacy;
     @Mock private PackageManager mPackageManager;
     @Mock private DevicePolicyManagerInternal mDevicePolicyManagerInternal;
     @Mock private WifiPermissionsUtil mWifiPermissionsUtil;
@@ -1144,7 +1142,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);
     }
@@ -2539,74 +2537,6 @@
     }
 
     /**
-     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
-     * attempts to migrate data from legacy stores when the legacy store files are present.
-     */
-    @Test
-    public void testMigrationFromLegacyStore() throws Exception {
-        // Create the store data to be returned from legacy stores.
-        List<WifiConfiguration> networks = new ArrayList<>();
-        networks.add(WifiConfigurationTestUtil.createPskNetwork());
-        networks.add(WifiConfigurationTestUtil.createEapNetwork());
-        networks.add(WifiConfigurationTestUtil.createWepNetwork());
-        String deletedEphemeralSSID = "EphemeralSSID";
-        Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID));
-        WifiConfigStoreDataLegacy storeData =
-                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
-        // all the networks above from the legacy store.
-        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
-
-        verify(mWifiConfigStoreLegacy).read();
-        verify(mWifiConfigStoreLegacy).removeStores();
-
-        List<WifiConfiguration> retrievedNetworks =
-                mWifiConfigManager.getConfiguredNetworksWithPasswords();
-        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
-                networks, retrievedNetworks);
-        assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID));
-    }
-
-    /**
-     * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()}
-     * does not attempt to migrate data from legacy stores when the legacy store files are absent
-     * (i.e migration was already done once).
-     */
-    @Test
-    public void testNoDuplicateMigrationFromLegacyStore() throws Exception {
-        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
-
-        // Now trigger a migration from legacy store.
-        assertTrue(mWifiConfigManager.migrateFromLegacyStore());
-
-        verify(mWifiConfigStoreLegacy, never()).read();
-        verify(mWifiConfigStoreLegacy, never()).removeStores();
-    }
-
-    /**
-     * 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.
@@ -2614,12 +2544,10 @@
     @Test
     public void testFreshInstallDoesNotLoadFromStore() throws Exception {
         when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
-        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
 
         assertTrue(mWifiConfigManager.loadFromStore());
 
         verify(mWifiConfigStore, never()).read();
-        verify(mWifiConfigStoreLegacy, never()).read();
 
         assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
     }
@@ -2632,11 +2560,9 @@
     public void testHandleUserSwitchAfterFreshInstall() throws Exception {
         int user2 = TEST_DEFAULT_USER + 1;
         when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
-        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
 
         assertTrue(mWifiConfigManager.loadFromStore());
         verify(mWifiConfigStore, never()).read();
-        verify(mWifiConfigStoreLegacy, never()).read();
 
         setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>());
         // Now switch the user to user 2.
@@ -3395,7 +3321,7 @@
         mWifiConfigManager =
                 new WifiConfigManager(
                         mContext, mClock, mUserManager, mTelephonyManager,
-                        mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy,
+                        mWifiKeyStore, mWifiConfigStore,
                         mWifiPermissionsUtil, mWifiPermissionsWrapper, mNetworkListStoreData,
                         mDeletedEphemeralSsidsStoreData);
         mWifiConfigManager.enableVerboseLogging(1);
@@ -3990,7 +3916,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/WifiConfigStoreLegacyTest.java b/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreLegacyTest.java
deleted file mode 100644
index 4b4e875..0000000
--- a/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreLegacyTest.java
+++ /dev/null
@@ -1,273 +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.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import android.app.test.MockAnswerUtil.AnswerWithArguments;
-import android.net.IpConfiguration;
-import android.net.wifi.WifiConfiguration;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.text.TextUtils;
-import android.util.SparseArray;
-
-import com.android.server.net.IpConfigStore;
-import com.android.server.wifi.hotspot2.LegacyPasspointConfig;
-import com.android.server.wifi.hotspot2.LegacyPasspointConfigParser;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Unit tests for {@link com.android.server.wifi.WifiConfigStoreLegacy}.
- */
-@SmallTest
-public class WifiConfigStoreLegacyTest {
-    private static final String MASKED_FIELD_VALUE = "*";
-
-    // Test mocks
-    @Mock private WifiNative mWifiNative;
-    @Mock private WifiNetworkHistory mWifiNetworkHistory;
-    @Mock private IpConfigStore mIpconfigStore;
-    @Mock private LegacyPasspointConfigParser mPasspointConfigParser;
-
-    /**
-     * Test instance of WifiConfigStore.
-     */
-    private WifiConfigStoreLegacy mWifiConfigStore;
-
-
-    /**
-     * Setup the test environment.
-     */
-    @Before
-    public void setUp() throws Exception {
-        MockitoAnnotations.initMocks(this);
-
-        mWifiConfigStore = new WifiConfigStoreLegacy(mWifiNetworkHistory, mWifiNative,
-                mIpconfigStore, mPasspointConfigParser);
-    }
-
-    /**
-     * Called after each test
-     */
-    @After
-    public void cleanup() {
-        validateMockitoUsage();
-    }
-
-    /**
-     * Verify loading of network configurations from legacy stores. This is verifying the population
-     * of the masked wpa_supplicant fields using wpa_supplicant.conf file.
-     */
-    @Test
-    public void testLoadFromStores() throws Exception {
-        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
-        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
-        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
-        WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork();
-        eapNetwork.enterpriseConfig.setPassword("EapPassword");
-
-        // Initialize Passpoint configuration data.
-        int passpointNetworkId = 1234;
-        String fqdn = passpointNetwork.FQDN;
-        String providerFriendlyName = passpointNetwork.providerFriendlyName;
-        long[] roamingConsortiumIds = new long[] {0x1234, 0x5678};
-        String realm = "test.com";
-        String imsi = "214321";
-
-        // Update Passpoint network.
-        // Network ID is used for lookup network extras, so use an unique ID for passpoint network.
-        passpointNetwork.networkId = passpointNetworkId;
-        passpointNetwork.enterpriseConfig.setPassword("PaspointPassword");
-        // Reset FQDN and provider friendly name so that the derived network from #read will
-        // obtained these information from networkExtras and {@link LegacyPasspointConfigParser}.
-        passpointNetwork.FQDN = null;
-        passpointNetwork.providerFriendlyName = null;
-
-        final List<WifiConfiguration> networks = new ArrayList<>();
-        networks.add(pskNetwork);
-        networks.add(wepNetwork);
-        networks.add(eapNetwork);
-        networks.add(passpointNetwork);
-
-        // Setup legacy Passpoint configuration data.
-        Map<String, LegacyPasspointConfig> passpointConfigs = new HashMap<>();
-        LegacyPasspointConfig passpointConfig = new LegacyPasspointConfig();
-        passpointConfig.mFqdn = fqdn;
-        passpointConfig.mFriendlyName = providerFriendlyName;
-        passpointConfig.mRoamingConsortiumOis = roamingConsortiumIds;
-        passpointConfig.mRealm = realm;
-        passpointConfig.mImsi = imsi;
-        passpointConfigs.put(fqdn, passpointConfig);
-
-        // Return the config data with passwords masked from wpa_supplicant control interface.
-        doAnswer(new AnswerWithArguments() {
-            public boolean answer(Map<String, WifiConfiguration> configs,
-                    SparseArray<Map<String, String>> networkExtras) {
-                for (Map.Entry<String, WifiConfiguration> entry:
-                        createWpaSupplicantLoadData(networks).entrySet()) {
-                    configs.put(entry.getKey(), entry.getValue());
-                }
-                // Setup networkExtras for Passpoint configuration.
-                networkExtras.put(passpointNetworkId, createNetworkExtrasForPasspointConfig(fqdn));
-                return true;
-            }
-        }).when(mWifiNative).migrateNetworksFromSupplicant(any(Map.class), any(SparseArray.class));
-
-        when(mPasspointConfigParser.parseConfig(anyString())).thenReturn(passpointConfigs);
-        WifiConfigStoreLegacy.WifiConfigStoreDataLegacy storeData = mWifiConfigStore.read();
-
-        // Update the expected configuration for Passpoint network.
-        passpointNetwork.isLegacyPasspointConfig = true;
-        passpointNetwork.FQDN = fqdn;
-        passpointNetwork.providerFriendlyName = providerFriendlyName;
-        passpointNetwork.roamingConsortiumIds = roamingConsortiumIds;
-        passpointNetwork.enterpriseConfig.setRealm(realm);
-        passpointNetwork.enterpriseConfig.setPlmn(imsi);
-
-        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigStore(
-                networks, storeData.getConfigurations());
-    }
-
-    private SparseArray<IpConfiguration> createIpConfigStoreLoadData(
-            List<WifiConfiguration> configurations) {
-        SparseArray<IpConfiguration> newIpConfigurations = new SparseArray<>();
-        for (WifiConfiguration config : configurations) {
-            newIpConfigurations.put(
-                    config.configKey().hashCode(),
-                    new IpConfiguration(config.getIpConfiguration()));
-        }
-        return newIpConfigurations;
-    }
-
-    private Map<String, String> createPskMap(List<WifiConfiguration> configurations) {
-        Map<String, String> pskMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.preSharedKey)) {
-                pskMap.put(config.configKey(), config.preSharedKey);
-            }
-        }
-        return pskMap;
-    }
-
-    private Map<String, String> createWepKey0Map(List<WifiConfiguration> configurations) {
-        Map<String, String> wepKeyMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.wepKeys[0])) {
-                wepKeyMap.put(config.configKey(), config.wepKeys[0]);
-            }
-        }
-        return wepKeyMap;
-    }
-
-    private Map<String, String> createWepKey1Map(List<WifiConfiguration> configurations) {
-        Map<String, String> wepKeyMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.wepKeys[1])) {
-                wepKeyMap.put(config.configKey(), config.wepKeys[1]);
-            }
-        }
-        return wepKeyMap;
-    }
-
-    private Map<String, String> createWepKey2Map(List<WifiConfiguration> configurations) {
-        Map<String, String> wepKeyMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.wepKeys[2])) {
-                wepKeyMap.put(config.configKey(), config.wepKeys[2]);
-            }
-        }
-        return wepKeyMap;
-    }
-
-    private Map<String, String> createWepKey3Map(List<WifiConfiguration> configurations) {
-        Map<String, String> wepKeyMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.wepKeys[3])) {
-                wepKeyMap.put(config.configKey(), config.wepKeys[3]);
-            }
-        }
-        return wepKeyMap;
-    }
-
-    private Map<String, String> createEapPasswordMap(List<WifiConfiguration> configurations) {
-        Map<String, String> eapPasswordMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            if (!TextUtils.isEmpty(config.enterpriseConfig.getPassword())) {
-                eapPasswordMap.put(config.configKey(), config.enterpriseConfig.getPassword());
-            }
-        }
-        return eapPasswordMap;
-    }
-
-    private Map<String, WifiConfiguration> createWpaSupplicantLoadData(
-            List<WifiConfiguration> configurations) {
-        Map<String, WifiConfiguration> configurationMap = new HashMap<>();
-        for (WifiConfiguration config : configurations) {
-            configurationMap.put(config.configKey(true), config);
-        }
-        return configurationMap;
-    }
-
-    private List<WifiConfiguration> createMaskedWifiConfigurations(
-            List<WifiConfiguration> configurations) {
-        List<WifiConfiguration> newConfigurations = new ArrayList<>();
-        for (WifiConfiguration config : configurations) {
-            newConfigurations.add(createMaskedWifiConfiguration(config));
-        }
-        return newConfigurations;
-    }
-
-    private WifiConfiguration createMaskedWifiConfiguration(WifiConfiguration configuration) {
-        WifiConfiguration newConfig = new WifiConfiguration(configuration);
-        if (!TextUtils.isEmpty(configuration.preSharedKey)) {
-            newConfig.preSharedKey = MASKED_FIELD_VALUE;
-        }
-        if (!TextUtils.isEmpty(configuration.wepKeys[0])) {
-            newConfig.wepKeys[0] = MASKED_FIELD_VALUE;
-        }
-        if (!TextUtils.isEmpty(configuration.wepKeys[1])) {
-            newConfig.wepKeys[1] = MASKED_FIELD_VALUE;
-        }
-        if (!TextUtils.isEmpty(configuration.wepKeys[2])) {
-            newConfig.wepKeys[2] = MASKED_FIELD_VALUE;
-        }
-        if (!TextUtils.isEmpty(configuration.wepKeys[3])) {
-            newConfig.wepKeys[3] = MASKED_FIELD_VALUE;
-        }
-        if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) {
-            newConfig.enterpriseConfig.setPassword(MASKED_FIELD_VALUE);
-        }
-        return newConfig;
-    }
-
-    private Map<String, String> createNetworkExtrasForPasspointConfig(String fqdn) {
-        Map<String, String> extras = new HashMap<>();
-        extras.put(SupplicantStaNetworkHal.ID_STRING_KEY_FQDN, fqdn);
-        return extras;
-    }
-}
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/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 5d5a5a6..c63db86 100644
--- a/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WifiStateMachineTest.java
@@ -969,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);
@@ -1571,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();
     }
 
@@ -1621,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
@@ -1645,7 +1705,7 @@
         mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null);
         mLooper.dispatchAll();
 
-        assertEquals("DisconnectedState", getCurrentState().getName());
+        assertEquals("ObtainingIpState", getCurrentState().getName());
         verifyMocksForWpsNetworkMigration();
     }
 
@@ -1718,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;
             }
@@ -1733,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() {
@@ -1759,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|.
@@ -1787,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|.
@@ -2001,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);
@@ -2018,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();
diff --git a/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java b/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
index 4dfa4cd..cca2045 100644
--- a/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/WificondControlTest.java
@@ -66,6 +66,7 @@
 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";
@@ -145,6 +146,8 @@
     public void setUp() throws Exception {
         mWifiInjector = mock(WifiInjector.class);
         mWifiMonitor = mock(WifiMonitor.class);
+        mWifiMetrics = mock(WifiMetrics.class);
+        when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);
         mCarrierNetworkConfig = mock(CarrierNetworkConfig.class);
         mWificondControl = new WificondControl(mWifiInjector, mWifiMonitor, mCarrierNetworkConfig);
     }
@@ -460,7 +463,8 @@
         assertTrue(mWificondControl.tearDownInterfaces());
 
         // getScanResults should fail.
-        assertEquals(0, mWificondControl.getScanResults().size());
+        assertEquals(0,
+                mWificondControl.getScanResults(WificondControl.SCAN_TYPE_SINGLE_SCAN).size());
     }
 
     /**
@@ -475,7 +479,8 @@
         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.
@@ -522,7 +527,8 @@
                 .thenReturn(eapType);
         when(mCarrierNetworkConfig.getCarrierName(new String(nativeScanResult.ssid)))
                 .thenReturn(carrierName);
-        ArrayList<ScanDetail> returnedScanResults = mWificondControl.getScanResults();
+        ArrayList<ScanDetail> returnedScanResults = mWificondControl.getScanResults(
+                WificondControl.SCAN_TYPE_SINGLE_SCAN);
         assertEquals(1, returnedScanResults.size());
         // Verify returned scan result.
         ScanResult scanResult = returnedScanResults.get(0).getScanResult();
@@ -535,7 +541,8 @@
         // AP not associated with a carrier network.
         when(mCarrierNetworkConfig.isCarrierNetwork(new String(nativeScanResult.ssid)))
                 .thenReturn(false);
-        returnedScanResults = mWificondControl.getScanResults();
+        returnedScanResults = mWificondControl.getScanResults(
+                WificondControl.SCAN_TYPE_SINGLE_SCAN);
         assertEquals(1, returnedScanResults.size());
         // Verify returned scan result.
         scanResult = returnedScanResults.get(0).getScanResult();
@@ -656,7 +663,7 @@
 
     /**
      * Verifies that WificondControl can invoke WifiMonitor broadcast methods upon pno scan
-     * reuslt event.
+     * result event.
      */
     @Test
     public void testPnoScanResultEvent() throws Exception {
@@ -667,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 37af1ba..227a196 100644
--- a/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
@@ -452,6 +452,124 @@
         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);
+    }
+
     /*
      * Initiator tests
      */
@@ -1109,60 +1227,17 @@
             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);
 
+        Messenger messenger = null;
         if (isFirstIteration) {
-            // (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 = initOobDataPathEndPoint(true, clientId, inOrder, inOrderM);
         }
 
         if (doPublish) {
@@ -1193,7 +1268,70 @@
                 eq(someMsg.getBytes()));
 
         return new DataPathEndPointInfo(sessionId.getValue(), peerIdCaptor.getValue(),
-                isFirstIteration ? messengerCaptor.getValue() : null);
+                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/hotspot2/LegacyPasspointConfigParserTest.java b/tests/wifitests/src/com/android/server/wifi/hotspot2/LegacyPasspointConfigParserTest.java
deleted file mode 100644
index 10ebceb..0000000
--- a/tests/wifitests/src/com/android/server/wifi/hotspot2/LegacyPasspointConfigParserTest.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * 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.hotspot2;
-
-import static org.junit.Assert.*;
-
-import android.os.FileUtils;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Unit tests for {@link com.android.server.wifi.hotspot2.LegacyPasspointConfigParser}.
- */
-@SmallTest
-public class LegacyPasspointConfigParserTest {
-    private static final String TEST_CONFIG =
-            "tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)\n"
-                    + "8:MgmtTree+\n"
-                    + "17:PerProviderSubscription+\n"
-                    + "4:r1i1+\n"
-                    + "6:HomeSP+\n"
-                    + "c:FriendlyName=12:Test Provider 1™\n"
-                    + "4:FQDN=9:test1.net\n"
-                    + "13:RoamingConsortiumOI=9:1234,5678\n"
-                    + ".\n"
-                    + "a:Credential+\n"
-                    + "10:UsernamePassword+\n"
-                    + "8:Username=5:user1\n"
-                    + "8:Password=5:pass1\n"
-                    + "\n"
-                    + "9:EAPMethod+\n"
-                    + "7:EAPType=2:21\n"
-                    + "b:InnerMethod=3:PAP\n"
-                    + ".\n"
-                    + ".\n"
-                    + "5:Realm=9:test1.com\n"
-                    + ".\n"
-                    + ".\n"
-                    + ".\n"
-                    + "17:PerProviderSubscription+\n"
-                    + "4:r1i2+\n"
-                    + "6:HomeSP+\n"
-                    + "c:FriendlyName=f:Test Provider 2\n"
-                    + "4:FQDN=9:test2.net\n"
-                    + ".\n"
-                    + "a:Credential+\n"
-                    + "3:SIM+\n"
-                    + "4:IMSI=4:1234\n"
-                    + "7:EAPType=2:18\n"
-                    + ".\n"
-                    + "5:Realm=9:test2.com\n"
-                    + ".\n"
-                    + ".\n"
-                    + ".\n"
-                    + ".\n";
-
-    /**
-     * Helper function for generating {@link LegacyPasspointConfig} objects based on the predefined
-     * test configuration string {@link #TEST_CONFIG}
-     *
-     * @return Map of FQDN to {@link LegacyPasspointConfig}
-     */
-    private Map<String, LegacyPasspointConfig> generateTestConfig() {
-        Map<String, LegacyPasspointConfig> configs = new HashMap<>();
-
-        LegacyPasspointConfig config1 = new LegacyPasspointConfig();
-        config1.mFqdn = "test1.net";
-        config1.mFriendlyName = "Test Provider 1™";
-        config1.mRoamingConsortiumOis = new long[] {0x1234, 0x5678};
-        config1.mRealm = "test1.com";
-        configs.put("test1.net", config1);
-
-        LegacyPasspointConfig config2 = new LegacyPasspointConfig();
-        config2.mFqdn = "test2.net";
-        config2.mFriendlyName = "Test Provider 2";
-        config2.mRealm = "test2.com";
-        config2.mImsi = "1234";
-        configs.put("test2.net", config2);
-
-        return configs;
-    }
-
-    /**
-     * Helper function for parsing configuration data.
-     *
-     * @param data The configuration data to parse
-     * @return Map of FQDN to {@link LegacyPasspointConfig}
-     * @throws Exception
-     */
-    private Map<String, LegacyPasspointConfig> parseConfig(String data) throws Exception {
-        // Write configuration data to file.
-        File configFile = File.createTempFile("LegacyPasspointConfig", "");
-        FileUtils.stringToFile(configFile, data);
-
-        // Parse the configuration file.
-        LegacyPasspointConfigParser parser = new LegacyPasspointConfigParser();
-        Map<String, LegacyPasspointConfig> configMap =
-                parser.parseConfig(configFile.getAbsolutePath());
-
-        configFile.delete();
-        return configMap;
-    }
-
-    /**
-     * Verify that the expected {@link LegacyPasspointConfig} objects are return when parsing
-     * predefined test configuration data {@link #TEST_CONFIG}.
-     *
-     * @throws Exception
-     */
-    @Test
-    public void parseTestConfig() throws Exception {
-        Map<String, LegacyPasspointConfig> parsedConfig = parseConfig(TEST_CONFIG);
-        assertEquals(generateTestConfig(), parsedConfig);
-    }
-
-    /**
-     * Verify that an empty map is return when parsing a configuration containing an empty
-     * configuration (MgmtTree).
-     *
-     * @throws Exception
-     */
-    @Test
-    public void parseEmptyConfig() throws Exception {
-        String emptyConfig = "tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)\n"
-                + "8:MgmtTree+\n"
-                + ".\n";
-        Map<String, LegacyPasspointConfig> parsedConfig = parseConfig(emptyConfig);
-        assertTrue(parsedConfig.isEmpty());
-    }
-
-    /**
-     * Verify that an empty map is return when parsing an empty configuration data.
-     *
-     * @throws Exception
-     */
-    @Test
-    public void parseEmptyData() throws Exception {
-        Map<String, LegacyPasspointConfig> parsedConfig = parseConfig("");
-        assertTrue(parsedConfig.isEmpty());
-    }
-
-    /**
-     * Verify that an IOException is thrown when parsing a configuration containing an unknown
-     * root name.  The expected root name is "MgmtTree".
-     *
-     * @throws Exception
-     */
-    @Test(expected = IOException.class)
-    public void parseConfigWithUnknownRootName() throws Exception {
-        String config = "tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)\n"
-                + "8:TestTest+\n"
-                + ".\n";
-        parseConfig(config);
-    }
-
-    /**
-     * Verify that an IOException is thrown when parsing a configuration containing a line with
-     * mismatched string length for the name.
-     *
-     * @throws Exception
-     */
-    @Test(expected = IOException.class)
-    public void parseConfigWithMismatchedStringLengthInName() throws Exception {
-        String config = "tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)\n"
-                + "9:MgmtTree+\n"
-                + ".\n";
-        parseConfig(config);
-    }
-
-    /**
-     * Verify that an IOException is thrown when parsing a configuration containing a line with
-     * mismatched string length for the value.
-     *
-     * @throws Exception
-     */
-    @Test(expected = IOException.class)
-    public void parseConfigWithMismatchedStringLengthInValue() throws Exception {
-        String config = "tree 3:1.2(urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0)\n"
-                + "8:MgmtTree+\n"
-                + "4:test=5:test\n"
-                + ".\n";
-        parseConfig(config);
-    }
-}
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/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<>(