Re-organize access to native interface through WifiStateTracker

Bug: 2339709
Change-Id: Ibb2eeb09b83dc24897116ea15a9016f81a08d442
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 8fa862d..62263a6 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -346,9 +346,8 @@
      */
     public boolean pingSupplicant() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.pingCommand();
-        }
+
+        return mWifiStateTracker.ping();
     }
 
     /**
@@ -357,20 +356,19 @@
      */
     public boolean startScan(boolean forceActive) {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            switch (mWifiStateTracker.getSupplicantState()) {
-                case DISCONNECTED:
-                case INACTIVE:
-                case SCANNING:
-                case DORMANT:
-                    break;
-                default:
-                    WifiNative.setScanResultHandlingCommand(
-                            WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
-                    break;
-            }
-            return WifiNative.scanCommand(forceActive);
+
+        switch (mWifiStateTracker.getSupplicantState()) {
+            case DISCONNECTED:
+            case INACTIVE:
+            case SCANNING:
+            case DORMANT:
+                break;
+            default:
+                mWifiStateTracker.setScanResultHandling(
+                        WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
+                break;
         }
+        return mWifiStateTracker.scan(forceActive);
     }
 
     /**
@@ -434,19 +432,18 @@
         }
 
         if (enable) {
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.loadDriver()) {
-                    Slog.e(TAG, "Failed to load Wi-Fi driver.");
-                    setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                    return false;
-                }
-                if (!WifiNative.startSupplicant()) {
-                    WifiNative.unloadDriver();
-                    Slog.e(TAG, "Failed to start supplicant daemon.");
-                    setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.loadDriver()) {
+                Slog.e(TAG, "Failed to load Wi-Fi driver.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                return false;
             }
+            if (!mWifiStateTracker.startSupplicant()) {
+                mWifiStateTracker.unloadDriver();
+                Slog.e(TAG, "Failed to start supplicant daemon.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                return false;
+            }
+
             registerForBroadcasts();
             mWifiStateTracker.startEventLoop();
         } else {
@@ -456,27 +453,27 @@
             mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
 
             boolean failedToStopSupplicantOrUnloadDriver = false;
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.stopSupplicant()) {
-                    Slog.e(TAG, "Failed to stop supplicant daemon.");
+
+            if (!mWifiStateTracker.stopSupplicant()) {
+                Slog.e(TAG, "Failed to stop supplicant daemon.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                failedToStopSupplicantOrUnloadDriver = true;
+            }
+
+            /**
+             * Reset connections and disable interface
+             * before we unload the driver
+             */
+            mWifiStateTracker.resetConnections(true);
+
+            if (!mWifiStateTracker.unloadDriver()) {
+                Slog.e(TAG, "Failed to unload Wi-Fi driver.");
+                if (!failedToStopSupplicantOrUnloadDriver) {
                     setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
                     failedToStopSupplicantOrUnloadDriver = true;
                 }
-
-                /**
-                 * Reset connections and disable interface
-                 * before we unload the driver
-                 */
-                mWifiStateTracker.resetConnections(true);
-
-                if (!WifiNative.unloadDriver()) {
-                    Slog.e(TAG, "Failed to unload Wi-Fi driver.");
-                    if (!failedToStopSupplicantOrUnloadDriver) {
-                        setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                        failedToStopSupplicantOrUnloadDriver = true;
-                    }
-                }
             }
+
             if (failedToStopSupplicantOrUnloadDriver) {
                 return false;
             }
@@ -553,9 +550,8 @@
      */
     public boolean disconnect() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.disconnectCommand();
-        }
+
+        return mWifiStateTracker.disconnect();
     }
 
     /**
@@ -564,9 +560,8 @@
      */
     public boolean reconnect() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.reconnectCommand();
-        }
+
+        return mWifiStateTracker.reconnectCommand();
     }
 
     /**
@@ -575,9 +570,8 @@
      */
     public boolean reassociate() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.reassociateCommand();
-        }
+
+        return mWifiStateTracker.reassociate();
     }
 
     private boolean getPersistedWifiApEnabled() {
@@ -650,12 +644,10 @@
         }
 
         if (enable) {
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.loadDriver()) {
-                    Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
-                    setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.loadDriver()) {
+                Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
+                setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
+                return false;
             }
 
             try {
@@ -672,12 +664,10 @@
                 Slog.e(TAG, "Exception in stopAccessPoint()");
             }
 
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.unloadDriver()) {
-                    Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
-                    setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.unloadDriver()) {
+                Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
+                setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
+                return false;
             }
         }
 
@@ -735,15 +725,15 @@
     public List<WifiConfiguration> getConfiguredNetworks() {
         enforceAccessPermission();
         String listStr;
+
         /*
          * We don't cache the list, because we want to allow
          * for the possibility that the configuration file
          * has been modified through some external means,
          * such as the wpa_cli command line program.
          */
-        synchronized (mWifiStateTracker) {
-            listStr = WifiNative.listNetworksCommand();
-        }
+        listStr = mWifiStateTracker.listNetworks();
+
         List<WifiConfiguration> networks =
             new ArrayList<WifiConfiguration>();
         if (listStr == null)
@@ -767,11 +757,10 @@
                    config.status = WifiConfiguration.Status.DISABLED;
                else
                    config.status = WifiConfiguration.Status.ENABLED;
-           } else
+           } else {
                config.status = WifiConfiguration.Status.ENABLED;
-           synchronized (mWifiStateTracker) {
-               readNetworkVariables(config);
            }
+           readNetworkVariables(config);
            networks.add(config);
        }
 
@@ -785,7 +774,7 @@
      * The caller must hold the synchronization monitor.
      * @param config the {@link WifiConfiguration} object to be filled in.
      */
-    private static void readNetworkVariables(WifiConfiguration config) {
+    private void readNetworkVariables(WifiConfiguration config) {
 
         int netId = config.networkId;
         if (netId < 0)
@@ -798,21 +787,21 @@
          */
         String value;
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
         if (!TextUtils.isEmpty(value)) {
             config.SSID = removeDoubleQuotes(value);
         } else {
             config.SSID = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
         if (!TextUtils.isEmpty(value)) {
             config.BSSID = value;
         } else {
             config.BSSID = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
         config.priority = -1;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -821,7 +810,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
         config.hiddenSSID = false;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -830,7 +819,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
         config.wepTxKeyIndex = -1;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -844,7 +833,7 @@
          * just a "*" if the key is set, or the null string otherwise.
          */
         for (int i = 0; i < 4; i++) {
-            value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
+            value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
             if (!TextUtils.isEmpty(value)) {
                 config.wepKeys[i] = value;
             } else {
@@ -856,14 +845,14 @@
          * Get the private shared key. Note that the actual keys are not passed back,
          * just a "*" if the key is set, or the null string otherwise.
          */
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
         if (!TextUtils.isEmpty(value)) {
             config.preSharedKey = value;
         } else {
             config.preSharedKey = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.Protocol.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -876,7 +865,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.KeyMgmt.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -889,7 +878,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.AuthAlgorithm.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -902,7 +891,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.PairwiseCipher.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -915,7 +904,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.GroupCipher.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -930,7 +919,7 @@
 
         for (WifiConfiguration.EnterpriseField field :
                 config.enterpriseFields) {
-            value = WifiNative.getNetworkVariableCommand(netId,
+            value = mWifiStateTracker.getNetworkVariable(netId,
                     field.varName());
             if (!TextUtils.isEmpty(value)) {
                 if (field != config.eap) value = removeDoubleQuotes(value);
@@ -955,6 +944,7 @@
      */
     public int addOrUpdateNetwork(WifiConfiguration config) {
         enforceChangePermission();
+
         /*
          * If the supplied networkId is -1, we create a new empty
          * network configuration. Otherwise, the networkId should
@@ -967,7 +957,7 @@
         // networkId of -1 means we want to create a new network
         synchronized (mWifiStateTracker) {
             if (newNetwork) {
-                netId = WifiNative.addNetworkCommand();
+                netId = mWifiStateTracker.addNetwork();
                 if (netId < 0) {
                     if (DBG) {
                         Slog.d(TAG, "Failed to add a network!");
@@ -976,7 +966,8 @@
                 }
                 doReconfig = true;
             } else {
-                String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
+                String priorityVal = mWifiStateTracker.getNetworkVariable(
+                                            netId, WifiConfiguration.priorityVarName);
                 currentPriority = -1;
                 if (!TextUtils.isEmpty(priorityVal)) {
                     try {
@@ -987,16 +978,17 @@
                 doReconfig = currentPriority != config.priority;
             }
             mNeedReconfig = mNeedReconfig || doReconfig;
+        }
 
-            setVariables: {
+        setVariables: {
             /*
              * Note that if a networkId for a non-existent network
-             * was supplied, then the first setNetworkVariableCommand()
+             * was supplied, then the first setNetworkVariable()
              * will fail, so we don't bother to make a separate check
              * for the validity of the ID up front.
              */
             if (config.SSID != null &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.ssidVarName,
                         convertToQuotedString(config.SSID))) {
@@ -1007,7 +999,7 @@
             }
 
             if (config.BSSID != null &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.bssidVarName,
                         config.BSSID)) {
@@ -1020,7 +1012,7 @@
             String allowedKeyManagementString =
                 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
             if (config.allowedKeyManagement.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.KeyMgmt.varName,
                         allowedKeyManagementString)) {
@@ -1034,7 +1026,7 @@
             String allowedProtocolsString =
                 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
             if (config.allowedProtocols.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.Protocol.varName,
                         allowedProtocolsString)) {
@@ -1048,7 +1040,7 @@
             String allowedAuthAlgorithmsString =
                 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
             if (config.allowedAuthAlgorithms.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.AuthAlgorithm.varName,
                         allowedAuthAlgorithmsString)) {
@@ -1062,7 +1054,7 @@
             String allowedPairwiseCiphersString =
                 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
             if (config.allowedPairwiseCiphers.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.PairwiseCipher.varName,
                         allowedPairwiseCiphersString)) {
@@ -1076,7 +1068,7 @@
             String allowedGroupCiphersString =
                 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
             if (config.allowedGroupCiphers.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.GroupCipher.varName,
                         allowedGroupCiphersString)) {
@@ -1090,7 +1082,7 @@
             // Prevent client screw-up by passing in a WifiConfiguration we gave it
             // by preventing "*" as a key.
             if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.pskVarName,
                         config.preSharedKey)) {
@@ -1106,7 +1098,7 @@
                     // Prevent client screw-up by passing in a WifiConfiguration we gave it
                     // by preventing "*" as a key.
                     if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
-                        if (!WifiNative.setNetworkVariableCommand(
+                        if (!mWifiStateTracker.setNetworkVariable(
                                     netId,
                                     WifiConfiguration.wepKeyVarNames[i],
                                     config.wepKeys[i])) {
@@ -1123,7 +1115,7 @@
             }
 
             if (hasSetKey) {
-                if (!WifiNative.setNetworkVariableCommand(
+                if (!mWifiStateTracker.setNetworkVariable(
                             netId,
                             WifiConfiguration.wepTxKeyIdxVarName,
                             Integer.toString(config.wepTxKeyIndex))) {
@@ -1136,7 +1128,7 @@
                 }
             }
 
-            if (!WifiNative.setNetworkVariableCommand(
+            if (!mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.priorityVarName,
                         Integer.toString(config.priority))) {
@@ -1147,7 +1139,7 @@
                 break setVariables;
             }
 
-            if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
+            if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.hiddenSSIDVarName,
                         Integer.toString(config.hiddenSSID ? 1 : 0))) {
@@ -1166,7 +1158,7 @@
                     if (field != config.eap) {
                         value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
                     }
-                    if (!WifiNative.setNetworkVariableCommand(
+                    if (!mWifiStateTracker.setNetworkVariable(
                                 netId,
                                 varName,
                                 value)) {
@@ -1179,21 +1171,20 @@
                 }
             }
             return netId;
-            }
+        }
 
-            /*
-             * For an update, if one of the setNetworkVariable operations fails,
-             * we might want to roll back all the changes already made. But the
-             * chances are that if anything is going to go wrong, it'll happen
-             * the first time we try to set one of the variables.
-             */
-            if (newNetwork) {
-                removeNetwork(netId);
-                if (DBG) {
-                    Slog.d(TAG,
-                            "Failed to set a network variable, removed network: "
-                            + netId);
-                }
+        /*
+         * For an update, if one of the setNetworkVariable operations fails,
+         * we might want to roll back all the changes already made. But the
+         * chances are that if anything is going to go wrong, it'll happen
+         * the first time we try to set one of the variables.
+         */
+        if (newNetwork) {
+            removeNetwork(netId);
+            if (DBG) {
+                Slog.d(TAG,
+                        "Failed to set a network variable, removed network: "
+                        + netId);
             }
         }
         return -1;
@@ -1260,15 +1251,13 @@
     public boolean enableNetwork(int netId, boolean disableOthers) {
         enforceChangePermission();
 
-        synchronized (mWifiStateTracker) {
-            String ifname = mWifiStateTracker.getInterfaceName();
-            NetworkUtils.enableInterface(ifname);
-            boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
-            if (!result) {
-                NetworkUtils.disableInterface(ifname);
-            }
-            return result;
+        String ifname = mWifiStateTracker.getInterfaceName();
+        NetworkUtils.enableInterface(ifname);
+        boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
+        if (!result) {
+            NetworkUtils.disableInterface(ifname);
         }
+        return result;
     }
 
     /**
@@ -1280,9 +1269,7 @@
     public boolean disableNetwork(int netId) {
         enforceChangePermission();
 
-        synchronized (mWifiStateTracker) {
-            return WifiNative.disableNetworkCommand(netId);
-        }
+        return mWifiStateTracker.disableNetwork(netId);
     }
 
     /**
@@ -1306,9 +1293,8 @@
     public List<ScanResult> getScanResults() {
         enforceAccessPermission();
         String reply;
-        synchronized (mWifiStateTracker) {
-            reply = WifiNative.scanResultsCommand();
-        }
+
+        reply = mWifiStateTracker.scanResults();
         if (reply == null) {
             return null;
         }
@@ -1456,11 +1442,12 @@
     public boolean saveConfiguration() {
         boolean result;
         enforceChangePermission();
+
         synchronized (mWifiStateTracker) {
-            result = WifiNative.saveConfigCommand();
+            result = mWifiStateTracker.saveConfig();
             if (result && mNeedReconfig) {
                 mNeedReconfig = false;
-                result = WifiNative.reloadConfigCommand();
+                result = mWifiStateTracker.reloadConfig();
 
                 if (result) {
                     Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
@@ -1532,18 +1519,17 @@
         int numChannels;
 
         enforceAccessPermission();
-        synchronized (mWifiStateTracker) {
-            /*
-             * If we can't get the value from the driver (e.g., because
-             * Wi-Fi is not currently enabled), get the value from
-             * Settings.
-             */
-            numChannels = WifiNative.getNumAllowedChannelsCommand();
-            if (numChannels < 0) {
-                numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
-                                                     Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
-                                                     -1);
-            }
+
+        /*
+         * If we can't get the value from the driver (e.g., because
+         * Wi-Fi is not currently enabled), get the value from
+         * Settings.
+         */
+        numChannels = mWifiStateTracker.getNumAllowedChannels();
+        if (numChannels < 0) {
+            numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
+                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
+                    -1);
         }
         return numChannels;
     }
@@ -2126,14 +2112,13 @@
 
     public void initializeMulticastFiltering() {
         enforceMulticastChangePermission();
+
         synchronized (mMulticasters) {
             // if anybody had requested filters be off, leave off
             if (mMulticasters.size() != 0) {
                 return;
             } else {
-                synchronized (mWifiStateTracker) {
-                    WifiNative.startPacketFiltering();
-                }
+                mWifiStateTracker.startPacketFiltering();
             }
         }
     }
@@ -2148,9 +2133,7 @@
             // our new size == 1 (first call), but this function won't
             // be called often and by making the stopPacket call each
             // time we're less fragile and self-healing.
-            synchronized (mWifiStateTracker) {
-                WifiNative.stopPacketFiltering();
-            }
+            mWifiStateTracker.stopPacketFiltering();
         }
 
         int uid = Binder.getCallingUid();
@@ -2182,13 +2165,12 @@
     private void removeMulticasterLocked(int i, int uid)
     {
         Multicaster removed = mMulticasters.remove(i);
+
         if (removed != null) {
             removed.unlinkDeathRecipient();
         }
         if (mMulticasters.size() == 0) {
-            synchronized (mWifiStateTracker) {
-                WifiNative.startPacketFiltering();
-            }
+            mWifiStateTracker.startPacketFiltering();
         }
 
         Long ident = Binder.clearCallingIdentity();
diff --git a/wifi/java/android/net/wifi/WifiMonitor.java b/wifi/java/android/net/wifi/WifiMonitor.java
index 0928d2b..266d801 100644
--- a/wifi/java/android/net/wifi/WifiMonitor.java
+++ b/wifi/java/android/net/wifi/WifiMonitor.java
@@ -272,10 +272,8 @@
             int connectTries = 0;
 
             while (true) {
-                synchronized (mWifiStateTracker) {
-                    if (WifiNative.connectToSupplicant()) {
-                        return true;
-                    }
+                if (mWifiStateTracker.connectToSupplicant()) {
+                    return true;
                 }
                 if (connectTries++ < 3) {
                     nap(5);
diff --git a/wifi/java/android/net/wifi/WifiNative.java b/wifi/java/android/net/wifi/WifiNative.java
index c3c519f..f98cd287 100644
--- a/wifi/java/android/net/wifi/WifiNative.java
+++ b/wifi/java/android/net/wifi/WifiNative.java
@@ -26,6 +26,9 @@
  * <p/>
  * Note that methods whose names are not of the form "xxxCommand()" do
  * not talk to the supplicant daemon.
+ * Also, note that all WifiNative calls should happen in the
+ * WifiStateTracker class except for waitForEvent() call which is
+ * on a separate monitor channel for WifiMonitor
  *
  * {@hide}
  */
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index 810e4d2..cc47d08 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -544,9 +544,7 @@
      */
     void notifyScanResultsAvailable() {
         // reset the supplicant's handling of scan results to "normal" mode
-        synchronized (this) {
-            WifiNative.setScanResultHandlingCommand(SUPPL_SCAN_HANDLING_NORMAL);
-        }
+        setScanResultHandling(SUPPL_SCAN_HANDLING_NORMAL);
         sendEmptyMessage(EVENT_SCAN_RESULTS_AVAILABLE);
     }
 
@@ -613,39 +611,6 @@
     }
 
     /**
-     * Set the number of allowed radio frequency channels from the system
-     * setting value, if any.
-     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
-     * the number of channels is invalid.
-     */
-    public synchronized boolean setNumAllowedChannels() {
-        try {
-            return setNumAllowedChannels(
-                    Settings.Secure.getInt(mContext.getContentResolver(),
-                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
-        } catch (Settings.SettingNotFoundException e) {
-            if (mNumAllowedChannels != 0) {
-                WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
-            }
-            // otherwise, use the driver default
-        }
-        return true;
-    }
-
-    /**
-     * Set the number of radio frequency channels that are allowed to be used
-     * in the current regulatory domain.
-     * @param numChannels the number of allowed channels. Must be greater than 0
-     * and less than or equal to 16.
-     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
-     * {@code numChannels} is outside the valid range.
-     */
-    public synchronized boolean setNumAllowedChannels(int numChannels) {
-        mNumAllowedChannels = numChannels;
-        return WifiNative.setNumAllowedChannelsCommand(numChannels);
-    }
-
-    /**
      * Set the run state to either "normal" or "scan-only".
      * @param scanOnlyMode true if the new mode should be scan-only.
      */
@@ -655,29 +620,19 @@
             int scanType = (scanOnlyMode ?
                     SUPPL_SCAN_HANDLING_LIST_ONLY : SUPPL_SCAN_HANDLING_NORMAL);
             if (LOCAL_LOGD) Log.v(TAG, "Scan-only mode changing to " + scanOnlyMode + " scanType=" + scanType);
-            if (WifiNative.setScanResultHandlingCommand(scanType)) {
+            if (setScanResultHandling(scanType)) {
                 mIsScanOnly = scanOnlyMode;
                 if (!isDriverStopped()) {
                     if (scanOnlyMode) {
-                        WifiNative.disconnectCommand();
+                        disconnect();
                     } else {
-                        WifiNative.reconnectCommand();
+                        reconnectCommand();
                     }
                 }
             }
         }
     }
 
-    /**
-     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
-     * some of the low-level scan parameters used by the driver are changed to
-     * reduce interference with A2DP streaming.
-     *
-     * @param isBluetoothPlaying whether to enable or disable this mode
-     */
-    public synchronized void setBluetoothScanMode(boolean isBluetoothPlaying) {
-        WifiNative.setBluetoothCoexistenceScanModeCommand(isBluetoothPlaying);
-    }
 
     private void checkIsBluetoothPlaying() {
         boolean isBluetoothPlaying = false;
@@ -765,10 +720,8 @@
                  * The MAC address isn't going to change, so just request it
                  * once here.
                  */
-                String macaddr;
-                synchronized (this) {
-                    macaddr = WifiNative.getMacAddressCommand();
-                }
+                String macaddr = getMacAddress();
+
                 if (macaddr != null) {
                     mWifiInfo.setMacAddress(macaddr);
                 }
@@ -831,9 +784,8 @@
                 // [ 1- 0] Connected to supplicant (1), disconnected from supplicant (0) ,
                 //         or supplicant died (2)
                 EventLog.writeEvent(EVENTLOG_SUPPLICANT_CONNECTION_STATE_CHANGED, died ? 2 : 0);
-                synchronized (this) {
-                    WifiNative.closeSupplicantConnection();
-                }
+                closeSupplicantConnection();
+
                 if (died) {
                     resetConnections(true);
                 }
@@ -861,9 +813,7 @@
                 // Only do this if we haven't gotten a new supplicant status since the timer
                 // started
                 if (mNumSupplicantStateChanges == msg.arg1) {
-                    synchronized (this) {
-                        WifiNative.scanCommand(false); // do a passive scan
-                    }
+                    scan(false); // do a passive scan
                 }
                 break;
 
@@ -954,13 +904,9 @@
                         if (mRunState == RUN_STATE_RUNNING && !mIsScanOnly && networkId != -1) {
                             sendMessageDelayed(reconnectMsg, RECONNECT_DELAY_MSECS);
                         } else if (mRunState == RUN_STATE_STOPPING) {
-                            synchronized (this) {
-                                WifiNative.stopDriverCommand();
-                            }
+                            stopDriver();
                         } else if (mRunState == RUN_STATE_STARTING && !mIsScanOnly) {
-                            synchronized (this) {
-                                WifiNative.reconnectCommand();
-                            }
+                            reconnectCommand();
                         }
                     } else if (newState == SupplicantState.DISCONNECTED) {
                         mHaveIpAddress = false;
@@ -1129,9 +1075,7 @@
                         }
                         addToBlacklist(BSSID);
                     }
-                    synchronized(this) {
-                        WifiNative.reconnectCommand();
-                    }
+                    reconnectCommand();
                 }
                 break;
 
@@ -1174,9 +1118,7 @@
                     mHaveIpAddress = false;
                     mWifiInfo.setIpAddress(0);
                     mObtainingIpAddress = false;
-                    synchronized(this) {
-                        WifiNative.disconnectCommand();
-                    }
+                    disconnect();
                 }
                 break;
 
@@ -1199,11 +1141,11 @@
                         if (mRunState == RUN_STATE_STARTING) {
                             mRunState = RUN_STATE_RUNNING;
                             if (!mIsScanOnly) {
-                                WifiNative.reconnectCommand();
+                                reconnectCommand();
                             } else {
                                 // In some situations, supplicant needs to be kickstarted to
                                 // start the background scanning
-                                WifiNative.scanCommand(true);
+                                scan(true);
                             }
                         }
                     }
@@ -1245,12 +1187,6 @@
         return disabledNetwork;
     }
 
-    public synchronized void setScanMode(boolean isScanModeActive) {
-        if (mIsScanModeActive != isScanModeActive) {
-            WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
-        }
-    }
-
     private void configureInterface() {
         checkPollTimer();
         mLastSignalLevel = -1;
@@ -1371,10 +1307,7 @@
     }
 
     private void requestConnectionStatus(WifiInfo info) {
-        String reply;
-        synchronized (this) {
-            reply = WifiNative.statusCommand();
-        }
+        String reply = status();
         if (reply == null) {
             return;
         }
@@ -1423,7 +1356,7 @@
      */
     private synchronized void requestPolledInfo(WifiInfo info, boolean polling)
     {
-        int newRssi = (polling ? WifiNative.getRssiApproxCommand() : WifiNative.getRssiCommand());
+        int newRssi = (polling ? getRssiApprox() : getRssi());
         if (newRssi != -1 && -200 < newRssi && newRssi < 256) { // screen out invalid values
             /* some implementations avoid negative values by adding 256
              * so we need to adjust for that here.
@@ -1451,7 +1384,7 @@
         } else {
             info.setRssi(-200);
         }
-        int newLinkSpeed = WifiNative.getLinkSpeedCommand();
+        int newLinkSpeed = getLinkSpeed();
         if (newLinkSpeed != -1) {
             info.setLinkSpeed(newLinkSpeed);
         }
@@ -1521,9 +1454,9 @@
 
             mRunState = RUN_STATE_STOPPING;
             if (mWifiInfo.getSupplicantState() == SupplicantState.DORMANT) {
-                return WifiNative.stopDriverCommand();
+                return stopDriver();
             } else {
-                return WifiNative.disconnectCommand();
+                return disconnect();
             }
         } else {
             /*
@@ -1547,17 +1480,213 @@
         if (mRunState == RUN_STATE_STOPPED) {
             mRunState = RUN_STATE_STARTING;
             resetConnections(true);
-            return WifiNative.startDriverCommand();
+            return startDriver();
         } else if (mRunState == RUN_STATE_STOPPING) {
             mRunState = RUN_STATE_STARTING;
         }
         return true;
     }
 
+    /**
+     * TODO: add documentation to all the native calls
+     * along with conditional checks to make sure
+     * native calls dont happen when wifi is not enabled
+     */
+
+    public synchronized boolean loadDriver() {
+        return WifiNative.loadDriver();
+    }
+
+    public synchronized boolean unloadDriver() {
+        return WifiNative.unloadDriver();
+    }
+
+    public synchronized boolean startSupplicant() {
+        return WifiNative.startSupplicant();
+    }
+
+    public synchronized boolean stopSupplicant() {
+        return WifiNative.stopSupplicant();
+    }
+
+    public synchronized boolean connectToSupplicant() {
+        return WifiNative.connectToSupplicant();
+    }
+
+    public synchronized void closeSupplicantConnection() {
+        WifiNative.closeSupplicantConnection();
+    }
+
+    public synchronized boolean ping() {
+        return WifiNative.pingCommand();
+    }
+
+    public synchronized boolean scan(boolean forceActive) {
+        return WifiNative.scanCommand(forceActive);
+    }
+
+    public synchronized boolean setScanResultHandling(int mode) {
+        return WifiNative.setScanResultHandlingCommand(mode);
+    }
+
+    public synchronized String scanResults() {
+        return WifiNative.scanResultsCommand();
+    }
+
+    public synchronized void setScanMode(boolean isScanModeActive) {
+        if (mIsScanModeActive != isScanModeActive) {
+            WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
+        }
+    }
+
+    public synchronized boolean disconnect() {
+        return WifiNative.disconnectCommand();
+    }
+
+    public synchronized boolean reconnectCommand() {
+        return WifiNative.reconnectCommand();
+    }
+
+    public synchronized int addNetwork() {
+        return WifiNative.addNetworkCommand();
+    }
+
     public synchronized boolean removeNetwork(int networkId) {
         return mDisconnectExpected = WifiNative.removeNetworkCommand(networkId);
     }
 
+    public synchronized boolean enableNetwork(int netId, boolean disableOthers) {
+        return WifiNative.enableNetworkCommand(netId, disableOthers);
+    }
+
+    public synchronized boolean disableNetwork(int netId) {
+        return WifiNative.disableNetworkCommand(netId);
+    }
+
+    public synchronized boolean reassociate() {
+        return WifiNative.reassociateCommand();
+    }
+
+    public synchronized boolean addToBlacklist(String bssid) {
+        return WifiNative.addToBlacklistCommand(bssid);
+    }
+
+    public synchronized boolean clearBlacklist() {
+        return WifiNative.clearBlacklistCommand();
+    }
+
+    public synchronized String listNetworks() {
+        return WifiNative.listNetworksCommand();
+    }
+
+    public synchronized String getNetworkVariable(int netId, String name) {
+        return WifiNative.getNetworkVariableCommand(netId, name);
+    }
+
+    public synchronized boolean setNetworkVariable(int netId, String name, String value) {
+        return WifiNative.setNetworkVariableCommand(netId, name, value);
+    }
+
+    public synchronized String status() {
+        return WifiNative.statusCommand();
+    }
+
+    public synchronized int getRssi() {
+        return WifiNative.getRssiApproxCommand();
+    }
+
+    public synchronized int getRssiApprox() {
+        return WifiNative.getRssiApproxCommand();
+    }
+
+    public synchronized int getLinkSpeed() {
+        return WifiNative.getLinkSpeedCommand();
+    }
+
+    public synchronized String getMacAddress() {
+        return WifiNative.getMacAddressCommand();
+    }
+
+    public synchronized boolean startDriver() {
+        return WifiNative.startDriverCommand();
+    }
+
+    public synchronized boolean stopDriver() {
+        return WifiNative.stopDriverCommand();
+    }
+
+    public synchronized boolean startPacketFiltering() {
+        return WifiNative.startPacketFiltering();
+    }
+
+    public synchronized boolean stopPacketFiltering() {
+        return WifiNative.stopPacketFiltering();
+    }
+
+    public synchronized boolean setPowerMode(int mode) {
+        return WifiNative.setPowerModeCommand(mode);
+    }
+
+    /**
+     * Set the number of allowed radio frequency channels from the system
+     * setting value, if any.
+     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
+     * the number of channels is invalid.
+     */
+    public synchronized boolean setNumAllowedChannels() {
+        try {
+            return setNumAllowedChannels(
+                    Settings.Secure.getInt(mContext.getContentResolver(),
+                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
+        } catch (Settings.SettingNotFoundException e) {
+            if (mNumAllowedChannels != 0) {
+                WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
+            }
+            // otherwise, use the driver default
+        }
+        return true;
+    }
+
+    /**
+     * Set the number of radio frequency channels that are allowed to be used
+     * in the current regulatory domain.
+     * @param numChannels the number of allowed channels. Must be greater than 0
+     * and less than or equal to 16.
+     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
+     * {@code numChannels} is outside the valid range.
+     */
+    public synchronized boolean setNumAllowedChannels(int numChannels) {
+        mNumAllowedChannels = numChannels;
+        return WifiNative.setNumAllowedChannelsCommand(numChannels);
+    }
+
+    public synchronized int getNumAllowedChannels() {
+        return WifiNative.getNumAllowedChannelsCommand();
+    }
+
+    public synchronized boolean setBluetoothCoexistenceMode(int mode) {
+        return WifiNative.setBluetoothCoexistenceModeCommand(mode);
+    }
+
+    /**
+     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
+     * some of the low-level scan parameters used by the driver are changed to
+     * reduce interference with A2DP streaming.
+     *
+     * @param isBluetoothPlaying whether to enable or disable this mode
+     */
+    public synchronized void setBluetoothScanMode(boolean isBluetoothPlaying) {
+        WifiNative.setBluetoothCoexistenceScanModeCommand(isBluetoothPlaying);
+    }
+
+    public synchronized boolean saveConfig() {
+        return WifiNative.saveConfigCommand();
+    }
+
+    public synchronized boolean reloadConfig() {
+        return WifiNative.reloadConfigCommand();
+    }
+
     public boolean setRadio(boolean turnOn) {
         return mWM.setWifiEnabled(turnOn);
     }
@@ -1571,7 +1700,7 @@
     public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) {
         return -1;
     }
-    
+
     /**
      * {@inheritDoc}
      * There are currently no Wi-Fi-specific features supported.
@@ -1706,18 +1835,6 @@
         mNumScansSinceNetworkStateChange = 0;
     }
     
-    public synchronized boolean reassociate() {
-        return WifiNative.reassociateCommand();
-    }
-
-    public synchronized boolean addToBlacklist(String bssid) {
-        return WifiNative.addToBlacklistCommand(bssid);
-    }
-    
-    public synchronized boolean clearBlacklist() {
-        return WifiNative.clearBlacklistCommand();
-    }
-    
     @Override
     public String toString() {
         StringBuffer sb = new StringBuffer();
@@ -1796,15 +1913,12 @@
                         modifiedBluetoothCoexistenceMode = true;
 
                         // Disable the coexistence mode
-                        synchronized (WifiStateTracker.this) {
-                            WifiNative.setBluetoothCoexistenceModeCommand(
-                                    WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
-                        }
+                        setBluetoothCoexistenceMode(
+                                WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
                     }
-                    
-                    synchronized (WifiStateTracker.this) {
-                        WifiNative.setPowerModeCommand(DRIVER_POWER_MODE_ACTIVE);
-                    }
+
+                    setPowerMode(DRIVER_POWER_MODE_ACTIVE);
+
                     synchronized (this) {
                         // A new request is being made, so assume we will callback
                         mCancelCallback = false;
@@ -1818,18 +1932,15 @@
                         Log.i(TAG, "DhcpHandler: DHCP request failed: " +
                             NetworkUtils.getDhcpError());
                     }
-                    synchronized (WifiStateTracker.this) {
-                        WifiNative.setPowerModeCommand(DRIVER_POWER_MODE_AUTO);
-                    }
-                    
+
+                    setPowerMode(DRIVER_POWER_MODE_AUTO);
+
                     if (modifiedBluetoothCoexistenceMode) {
                         // Set the coexistence mode back to its default value
-                        synchronized (WifiStateTracker.this) {
-                            WifiNative.setBluetoothCoexistenceModeCommand(
-                                    WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
-                        }
+                        setBluetoothCoexistenceMode(
+                                WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
                     }
-                    
+
                     synchronized (this) {
                         if (!mCancelCallback) {
                             mTarget.sendEmptyMessage(event);
@@ -1838,7 +1949,7 @@
                     break;
             }
         }
-        
+
         public synchronized void setCancelCallback(boolean cancelCallback) {
             mCancelCallback = cancelCallback;
         }