Merge "[Refactor] move BPF tests to BpfCoordinatorTest" into main
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 520124d..ab3ed66 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -100,9 +100,6 @@
       "name": "TetheringIntegrationTests"
     },
     {
-      "name": "traffic_controller_unit_test"
-    },
-    {
       "name": "libnetworkstats_test"
     },
     {
@@ -134,10 +131,6 @@
       "name": "dns_helper_unit_test"
     },
     {
-      "name": "traffic_controller_unit_test",
-      "keywords": ["netd-device-kernel-4.9", "netd-device-kernel-4.14"]
-    },
-    {
       "name": "FrameworksNetDeflakeTest"
     },
     // Postsubmit on virtual devices to monitor flakiness of @SkipPresubmit methods
@@ -274,9 +267,6 @@
       ]
     },
     {
-      "name": "traffic_controller_unit_test[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
-    },
-    {
       "name": "libnetworkstats_test[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
     },
     {
diff --git a/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java b/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
index c6468a0..c274165 100644
--- a/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
+++ b/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
@@ -23,7 +23,7 @@
 import android.content.Context;
 import android.net.INetd;
 import android.net.RoutingCoordinatorManager;
-import android.net.connectivity.TiramisuConnectivityInternalApiUtil;
+import android.net.connectivity.ConnectivityInternalApiUtil;
 import android.net.ip.IpServer;
 import android.os.Build;
 import android.os.Handler;
@@ -133,7 +133,7 @@
     public LateSdk<RoutingCoordinatorManager> getRoutingCoordinator(Context context) {
         if (!SdkLevel.isAtLeastS()) return new LateSdk<>(null);
         return new LateSdk<>(
-                TiramisuConnectivityInternalApiUtil.getRoutingCoordinatorManager(context));
+                ConnectivityInternalApiUtil.getRoutingCoordinatorManager(context));
     }
 
     /**
diff --git a/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java b/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
index e94febb..e845f3f 100644
--- a/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
+++ b/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
@@ -19,7 +19,7 @@
 import android.companion.AssociationInfo;
 import android.companion.CompanionDeviceManager;
 import android.content.Context;
-import android.net.connectivity.TiramisuConnectivityInternalApiUtil;
+import android.net.connectivity.ConnectivityInternalApiUtil;
 import android.net.wear.ICompanionDeviceManagerProxy;
 import android.os.Build;
 import android.os.RemoteException;
@@ -39,7 +39,7 @@
     @RequiresApi(Build.VERSION_CODES.TIRAMISU)
     public CompanionDeviceManagerProxy(Context context) {
         mService = ICompanionDeviceManagerProxy.Stub.asInterface(
-                TiramisuConnectivityInternalApiUtil.getCompanionDeviceManagerProxyService(context));
+                ConnectivityInternalApiUtil.getCompanionDeviceManagerProxyService(context));
     }
 
     /**
diff --git a/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java b/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
index 0702aa7..1c4a662 100644
--- a/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
+++ b/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
@@ -366,6 +366,11 @@
         private volatile Collection<TetheredClient> mClients = null;
         private volatile Network mUpstream = null;
 
+        // The dnsmasq in R might block netd for 20 seconds, which can also block tethering
+        // enable/disable for 20 seconds. To fix this, changing the timeouts from 5 seconds to 30
+        // seconds. See b/289881008.
+        private static final int EXPANDED_TIMEOUT_MS = 30000;
+
         MyTetheringEventCallback(TetheringManager tm, String iface) {
             this(tm, iface, null);
             mAcceptAnyUpstream = true;
@@ -424,13 +429,13 @@
         }
 
         public void awaitInterfaceTethered() throws Exception {
-            assertTrue("Ethernet not tethered after " + TIMEOUT_MS + "ms",
-                    mTetheringStartedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+            assertTrue("Ethernet not tethered after " + EXPANDED_TIMEOUT_MS + "ms",
+                    mTetheringStartedLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
         }
 
         public void awaitInterfaceLocalOnly() throws Exception {
-            assertTrue("Ethernet not local-only after " + TIMEOUT_MS + "ms",
-                    mLocalOnlyStartedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+            assertTrue("Ethernet not local-only after " + EXPANDED_TIMEOUT_MS + "ms",
+                    mLocalOnlyStartedLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
         }
 
         // Used to check if the callback has registered. When the callback is registered,
@@ -444,8 +449,9 @@
         }
 
         public void awaitCallbackRegistered() throws Exception {
-            if (!mCallbackRegisteredLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
-                fail("Did not receive callback registered signal after " + TIMEOUT_MS + "ms");
+            if (!mCallbackRegisteredLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+                fail("Did not receive callback registered signal after " + EXPANDED_TIMEOUT_MS
+                        + "ms");
             }
         }
 
@@ -457,11 +463,11 @@
             if (!mInterfaceWasTethered && !mInterfaceWasLocalOnly) return;
 
             if (mInterfaceWasTethered) {
-                assertTrue(mIface + " not untethered after " + TIMEOUT_MS + "ms",
-                        mTetheringStoppedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+                assertTrue(mIface + " not untethered after " + EXPANDED_TIMEOUT_MS + "ms",
+                        mTetheringStoppedLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
             } else if (mInterfaceWasLocalOnly) {
-                assertTrue(mIface + " not untethered after " + TIMEOUT_MS + "ms",
-                        mLocalOnlyStoppedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+                assertTrue(mIface + " not untethered after " + EXPANDED_TIMEOUT_MS + "ms",
+                        mLocalOnlyStoppedLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
             } else {
                 fail(mIface + " cannot be both tethered and local-only. Update this test class.");
             }
@@ -488,8 +494,9 @@
         }
 
         public Collection<TetheredClient> awaitClientConnected() throws Exception {
-            assertTrue("Did not receive client connected callback after " + TIMEOUT_MS + "ms",
-                    mClientConnectedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+            assertTrue("Did not receive client connected callback after "
+                    + EXPANDED_TIMEOUT_MS + "ms",
+                    mClientConnectedLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS));
             return mClients;
         }
 
@@ -506,10 +513,10 @@
         }
 
         public Network awaitUpstreamChanged(boolean throwTimeoutException) throws Exception {
-            if (!mUpstreamLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+            if (!mUpstreamLatch.await(EXPANDED_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                 final String errorMessage = "Did not receive upstream "
                             + (mAcceptAnyUpstream ? "any" : mExpectedUpstream)
-                            + " callback after " + TIMEOUT_MS + "ms";
+                            + " callback after " + EXPANDED_TIMEOUT_MS + "ms";
 
                 if (throwTimeoutException) {
                     throw new TimeoutException(errorMessage);
diff --git a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
index 076fde3..4949eaa 100644
--- a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
+++ b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
@@ -47,7 +47,7 @@
 import android.util.Log;
 
 import androidx.annotation.NonNull;
-import androidx.test.filters.MediumTest;
+import androidx.test.filters.LargeTest;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.net.module.util.Ipv6Utils;
@@ -79,7 +79,7 @@
 import java.util.concurrent.TimeoutException;
 
 @RunWith(AndroidJUnit4.class)
-@MediumTest
+@LargeTest
 public class EthernetTetheringTest extends EthernetTetheringTestBase {
     @Rule
     public final DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
diff --git a/framework-t/api/system-lint-baseline.txt b/framework-t/api/system-lint-baseline.txt
index 9baf991..c6055f6 100644
--- a/framework-t/api/system-lint-baseline.txt
+++ b/framework-t/api/system-lint-baseline.txt
@@ -5,3 +5,149 @@
 
 GenericException: android.net.IpSecManager.IpSecTunnelInterface#finalize():
     Methods must not throw generic exceptions (`java.lang.Throwable`)
+
+
+UnflaggedApi: android.nearby.CredentialElement#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.CredentialElement.equals(Object)
+UnflaggedApi: android.nearby.CredentialElement#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.CredentialElement.hashCode()
+UnflaggedApi: android.nearby.DataElement#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.DataElement.equals(Object)
+UnflaggedApi: android.nearby.DataElement#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.DataElement.hashCode()
+UnflaggedApi: android.nearby.NearbyDevice#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.equals(Object)
+UnflaggedApi: android.nearby.NearbyDevice#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.hashCode()
+UnflaggedApi: android.nearby.NearbyDevice#toString():
+    New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.toString()
+UnflaggedApi: android.nearby.OffloadCapability#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.equals(Object)
+UnflaggedApi: android.nearby.OffloadCapability#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.hashCode()
+UnflaggedApi: android.nearby.OffloadCapability#toString():
+    New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.toString()
+UnflaggedApi: android.nearby.PresenceCredential#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.PresenceCredential.equals(Object)
+UnflaggedApi: android.nearby.PresenceCredential#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.PresenceCredential.hashCode()
+UnflaggedApi: android.nearby.PublicCredential#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.PublicCredential.equals(Object)
+UnflaggedApi: android.nearby.PublicCredential#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.PublicCredential.hashCode()
+UnflaggedApi: android.nearby.ScanRequest#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.equals(Object)
+UnflaggedApi: android.nearby.ScanRequest#hashCode():
+    New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.hashCode()
+UnflaggedApi: android.nearby.ScanRequest#toString():
+    New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.toString()
+UnflaggedApi: android.net.EthernetNetworkManagementException#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkManagementException.equals(Object)
+UnflaggedApi: android.net.EthernetNetworkManagementException#hashCode():
+    New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkManagementException.hashCode()
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.equals(Object)
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#hashCode():
+    New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.hashCode()
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#toString():
+    New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.toString()
+UnflaggedApi: android.net.IpSecManager.IpSecTunnelInterface#finalize():
+    New API must be flagged with @FlaggedApi: method android.net.IpSecManager.IpSecTunnelInterface.finalize()
+UnflaggedApi: android.net.IpSecManager.IpSecTunnelInterface#toString():
+    New API must be flagged with @FlaggedApi: method android.net.IpSecManager.IpSecTunnelInterface.toString()
+UnflaggedApi: android.net.IpSecTransform.Builder#buildTunnelModeTransform(java.net.InetAddress, android.net.IpSecManager.SecurityParameterIndex):
+    New API must be flagged with @FlaggedApi: method android.net.IpSecTransform.Builder.buildTunnelModeTransform(java.net.InetAddress,android.net.IpSecManager.SecurityParameterIndex)
+UnflaggedApi: android.net.NetworkStats.Entry#toString():
+    New API must be flagged with @FlaggedApi: method android.net.NetworkStats.Entry.toString()
+UnflaggedApi: android.net.nsd.NsdManager#registerOffloadEngine(String, long, long, java.util.concurrent.Executor, android.net.nsd.OffloadEngine):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.NsdManager.registerOffloadEngine(String,long,long,java.util.concurrent.Executor,android.net.nsd.OffloadEngine)
+UnflaggedApi: android.net.nsd.NsdManager#unregisterOffloadEngine(android.net.nsd.OffloadEngine):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.NsdManager.unregisterOffloadEngine(android.net.nsd.OffloadEngine)
+UnflaggedApi: android.net.nsd.OffloadEngine:
+    New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadEngine
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_CAPABILITY_BYPASS_MULTICAST_LOCK:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_CAPABILITY_BYPASS_MULTICAST_LOCK
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_FILTER_QUERIES:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_FILTER_QUERIES
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_FILTER_REPLIES:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_FILTER_REPLIES
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_REPLY:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_REPLY
+UnflaggedApi: android.net.nsd.OffloadEngine#onOffloadServiceRemoved(android.net.nsd.OffloadServiceInfo):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadEngine.onOffloadServiceRemoved(android.net.nsd.OffloadServiceInfo)
+UnflaggedApi: android.net.nsd.OffloadEngine#onOffloadServiceUpdated(android.net.nsd.OffloadServiceInfo):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadEngine.onOffloadServiceUpdated(android.net.nsd.OffloadServiceInfo)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo:
+    New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadServiceInfo
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#CONTENTS_FILE_DESCRIPTOR:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#CREATOR:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.CREATOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#OffloadServiceInfo(android.net.nsd.OffloadServiceInfo.Key, java.util.List<java.lang.String>, String, byte[], int, long):
+    New API must be flagged with @FlaggedApi: constructor android.net.nsd.OffloadServiceInfo(android.net.nsd.OffloadServiceInfo.Key,java.util.List<java.lang.String>,String,byte[],int,long)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_STABILITY_LOCAL:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_STABILITY_LOCAL
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_STABILITY_VINTF:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_STABILITY_VINTF
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_WRITE_RETURN_VALUE:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#describeContents():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.describeContents()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.equals(Object)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getHostname():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getHostname()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getKey():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getKey()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getOffloadPayload():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getOffloadPayload()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getOffloadType():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getOffloadType()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getPriority():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getPriority()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getSubtypes():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getSubtypes()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#hashCode():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.hashCode()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#toString():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.toString()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#writeToParcel(android.os.Parcel, int):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.writeToParcel(android.os.Parcel,int)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key:
+    New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadServiceInfo.Key
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#CONTENTS_FILE_DESCRIPTOR:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#CREATOR:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.CREATOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#Key(String, String):
+    New API must be flagged with @FlaggedApi: constructor android.net.nsd.OffloadServiceInfo.Key(String,String)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_STABILITY_LOCAL:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_STABILITY_LOCAL
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_STABILITY_VINTF:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_STABILITY_VINTF
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_WRITE_RETURN_VALUE:
+    New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#describeContents():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.describeContents()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#equals(Object):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.equals(Object)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#getServiceName():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.getServiceName()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#getServiceType():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.getServiceType()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#hashCode():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.hashCode()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#toString():
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.toString()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#writeToParcel(android.os.Parcel, int):
+    New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.writeToParcel(android.os.Parcel,int)
+UnflaggedApi: android.net.thread.ThreadNetworkController:
+    New API must be flagged with @FlaggedApi: class android.net.thread.ThreadNetworkController
+UnflaggedApi: android.net.thread.ThreadNetworkController#THREAD_VERSION_1_3:
+    New API must be flagged with @FlaggedApi: field android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3
+UnflaggedApi: android.net.thread.ThreadNetworkController#getThreadVersion():
+    New API must be flagged with @FlaggedApi: method android.net.thread.ThreadNetworkController.getThreadVersion()
+UnflaggedApi: android.net.thread.ThreadNetworkManager:
+    New API must be flagged with @FlaggedApi: class android.net.thread.ThreadNetworkManager
+UnflaggedApi: android.net.thread.ThreadNetworkManager#getAllThreadNetworkControllers():
+    New API must be flagged with @FlaggedApi: method android.net.thread.ThreadNetworkManager.getAllThreadNetworkControllers()
diff --git a/framework/Android.bp b/framework/Android.bp
index 103083f..c88bacc 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -266,6 +266,7 @@
         ":framework-connectivity-t-pre-jarjar{.jar}",
         ":framework-connectivity.stubs.module_lib{.jar}",
         ":framework-connectivity-t.stubs.module_lib{.jar}",
+        ":framework-connectivity-flagged-apis{.jar}",
         "jarjar-excludes.txt",
     ],
     tools: [
@@ -278,6 +279,7 @@
         "--prefix android.net.connectivity " +
         "--apistubs $(location :framework-connectivity.stubs.module_lib{.jar}) " +
         "--apistubs $(location :framework-connectivity-t.stubs.module_lib{.jar}) " +
+        "--apistubs $(location :framework-connectivity-flagged-apis{.jar}) " +
         // Make a ":"-separated list. There will be an extra ":" but empty items are ignored.
         "--unsupportedapi $$(printf ':%s' $(locations :connectivity-hiddenapi-files)) " +
         "--excludes $(location jarjar-excludes.txt) " +
@@ -289,6 +291,30 @@
     ],
 }
 
+droidstubs {
+    name: "framework-connectivity-flagged-apis-droidstubs",
+    srcs: [
+        ":framework-connectivity-sources",
+        ":framework-connectivity-tiramisu-updatable-sources",
+        ":framework-nearby-java-sources",
+        ":framework-thread-sources",
+    ],
+    flags: [
+        "--show-annotation android.annotation.FlaggedApi",
+    ],
+    aidl: {
+        include_dirs: [
+            "packages/modules/Connectivity/framework/aidl-export",
+            "frameworks/native/aidl/binder", // For PersistableBundle.aidl
+        ],
+    },
+}
+
+java_library {
+    name: "framework-connectivity-flagged-apis",
+    srcs: [":framework-connectivity-flagged-apis-droidstubs"],
+}
+
 // Library providing limited APIs within the connectivity module, so that R+ components like
 // Tethering have a controlled way to depend on newer components like framework-connectivity that
 // are not loaded on R.
@@ -306,7 +332,7 @@
         // Files listed here MUST all be annotated with @RequiresApi(Build.VERSION_CODES.S)
         // or above as appropriate so that API checks are enforced for R+ users of this library
         "src/android/net/RoutingCoordinatorManager.java",
-        "src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java",
+        "src/android/net/connectivity/ConnectivityInternalApiUtil.java",
     ],
     visibility: [
         "//packages/modules/Connectivity/Tethering:__subpackages__",
diff --git a/framework/aidl-export/android/net/LocalNetworkInfo.aidl b/framework/aidl-export/android/net/LocalNetworkInfo.aidl
new file mode 100644
index 0000000..fa0bc41
--- /dev/null
+++ b/framework/aidl-export/android/net/LocalNetworkInfo.aidl
@@ -0,0 +1,20 @@
+/**
+ *
+ * Copyright (C) 2023 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 android.net;
+
+parcelable LocalNetworkInfo;
diff --git a/framework/jarjar-excludes.txt b/framework/jarjar-excludes.txt
index bd513d2..09abd17 100644
--- a/framework/jarjar-excludes.txt
+++ b/framework/jarjar-excludes.txt
@@ -23,6 +23,7 @@
 # of these classes must be protected by a check for >= S SDK.
 # It's unlikely anybody else declares a hidden class with this name ?
 android\.net\.RoutingCoordinatorManager(\$.+)?
+android\.net\.LocalNetworkInfo(\$.+)?
 
 # KeepaliveUtils is used by ConnectivityManager CTS
 # TODO: move into service-connectivity so framework-connectivity stops using
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index eb8f8c3..66b2840 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -3963,16 +3963,21 @@
          * @param network The {@link Network} of the satisfying network.
          * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
          * @param linkProperties The {@link LinkProperties} of the satisfying network.
+         * @param localInfo The {@link LocalNetworkInfo} of the satisfying network, or null
+         *                  if this network is not a local network.
          * @param blocked Whether access to the {@link Network} is blocked due to system policy.
          * @hide
          */
         public final void onAvailable(@NonNull Network network,
                 @NonNull NetworkCapabilities networkCapabilities,
-                @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
+                @NonNull LinkProperties linkProperties,
+                @Nullable LocalNetworkInfo localInfo,
+                @BlockedReason int blocked) {
             // Internally only this method is called when a new network is available, and
             // it calls the callback in the same way and order that older versions used
             // to call so as not to change the behavior.
             onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
+            if (null != localInfo) onLocalNetworkInfoChanged(network, localInfo);
             onBlockedStatusChanged(network, blocked);
         }
 
@@ -3989,7 +3994,8 @@
          */
         public void onAvailable(@NonNull Network network,
                 @NonNull NetworkCapabilities networkCapabilities,
-                @NonNull LinkProperties linkProperties, boolean blocked) {
+                @NonNull LinkProperties linkProperties,
+                boolean blocked) {
             onAvailable(network);
             if (!networkCapabilities.hasCapability(
                     NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
@@ -4116,6 +4122,19 @@
                 @NonNull LinkProperties linkProperties) {}
 
         /**
+         * Called when there is a change in the {@link LocalNetworkInfo} for this network.
+         *
+         * This is only called for local networks, that is those with the
+         * NET_CAPABILITY_LOCAL_NETWORK network capability.
+         *
+         * @param network the {@link Network} whose local network info has changed.
+         * @param localNetworkInfo the new {@link LocalNetworkInfo} for this network.
+         * @hide
+         */
+        public void onLocalNetworkInfoChanged(@NonNull Network network,
+                @NonNull LocalNetworkInfo localNetworkInfo) {}
+
+        /**
          * Called when the network the framework connected to for this request suspends data
          * transmission temporarily.
          *
@@ -4209,27 +4228,29 @@
     }
 
     /** @hide */
-    public static final int CALLBACK_PRECHECK            = 1;
+    public static final int CALLBACK_PRECHECK                   = 1;
     /** @hide */
-    public static final int CALLBACK_AVAILABLE           = 2;
+    public static final int CALLBACK_AVAILABLE                  = 2;
     /** @hide arg1 = TTL */
-    public static final int CALLBACK_LOSING              = 3;
+    public static final int CALLBACK_LOSING                     = 3;
     /** @hide */
-    public static final int CALLBACK_LOST                = 4;
+    public static final int CALLBACK_LOST                       = 4;
     /** @hide */
-    public static final int CALLBACK_UNAVAIL             = 5;
+    public static final int CALLBACK_UNAVAIL                    = 5;
     /** @hide */
-    public static final int CALLBACK_CAP_CHANGED         = 6;
+    public static final int CALLBACK_CAP_CHANGED                = 6;
     /** @hide */
-    public static final int CALLBACK_IP_CHANGED          = 7;
+    public static final int CALLBACK_IP_CHANGED                 = 7;
     /** @hide obj = NetworkCapabilities, arg1 = seq number */
-    private static final int EXPIRE_LEGACY_REQUEST       = 8;
+    private static final int EXPIRE_LEGACY_REQUEST              = 8;
     /** @hide */
-    public static final int CALLBACK_SUSPENDED           = 9;
+    public static final int CALLBACK_SUSPENDED                  = 9;
     /** @hide */
-    public static final int CALLBACK_RESUMED             = 10;
+    public static final int CALLBACK_RESUMED                    = 10;
     /** @hide */
-    public static final int CALLBACK_BLK_CHANGED         = 11;
+    public static final int CALLBACK_BLK_CHANGED                = 11;
+    /** @hide */
+    public static final int CALLBACK_LOCAL_NETWORK_INFO_CHANGED = 12;
 
     /** @hide */
     public static String getCallbackName(int whichCallback) {
@@ -4245,6 +4266,7 @@
             case CALLBACK_SUSPENDED:    return "CALLBACK_SUSPENDED";
             case CALLBACK_RESUMED:      return "CALLBACK_RESUMED";
             case CALLBACK_BLK_CHANGED:  return "CALLBACK_BLK_CHANGED";
+            case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: return "CALLBACK_LOCAL_NETWORK_INFO_CHANGED";
             default:
                 return Integer.toString(whichCallback);
         }
@@ -4299,7 +4321,8 @@
                 case CALLBACK_AVAILABLE: {
                     NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
                     LinkProperties lp = getObject(message, LinkProperties.class);
-                    callback.onAvailable(network, cap, lp, message.arg1);
+                    LocalNetworkInfo lni = getObject(message, LocalNetworkInfo.class);
+                    callback.onAvailable(network, cap, lp, lni, message.arg1);
                     break;
                 }
                 case CALLBACK_LOSING: {
@@ -4324,6 +4347,11 @@
                     callback.onLinkPropertiesChanged(network, lp);
                     break;
                 }
+                case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
+                    final LocalNetworkInfo info = getObject(message, LocalNetworkInfo.class);
+                    callback.onLocalNetworkInfoChanged(network, info);
+                    break;
+                }
                 case CALLBACK_SUSPENDED: {
                     callback.onNetworkSuspended(network);
                     break;
diff --git a/framework/src/android/net/LocalNetworkInfo.java b/framework/src/android/net/LocalNetworkInfo.java
new file mode 100644
index 0000000..f945133
--- /dev/null
+++ b/framework/src/android/net/LocalNetworkInfo.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2023 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 android.net;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+
+/**
+ * Information about a local network.
+ *
+ * This is sent to ConnectivityManager.NetworkCallback.
+ * @hide
+ */
+// TODO : make public
+public final class LocalNetworkInfo implements Parcelable {
+    @Nullable private final Network mUpstreamNetwork;
+
+    public LocalNetworkInfo(@Nullable final Network upstreamNetwork) {
+        this.mUpstreamNetwork = upstreamNetwork;
+    }
+
+    /**
+     * Return the upstream network, or null if none.
+     */
+    @Nullable
+    public Network getUpstreamNetwork() {
+        return mUpstreamNetwork;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(@NonNull final Parcel dest, final int flags) {
+        dest.writeParcelable(mUpstreamNetwork, flags);
+    }
+
+    @Override
+    public String toString() {
+        return "LocalNetworkInfo { upstream=" + mUpstreamNetwork + " }";
+    }
+
+    public static final @NonNull Creator<LocalNetworkInfo> CREATOR = new Creator<>() {
+        public LocalNetworkInfo createFromParcel(Parcel in) {
+            final Network upstreamNetwork = in.readParcelable(null);
+            return new LocalNetworkInfo(upstreamNetwork);
+        }
+
+        @Override
+        public LocalNetworkInfo[] newArray(final int size) {
+            return new LocalNetworkInfo[size];
+        }
+    };
+
+    /**
+     * Builder for LocalNetworkInfo
+     */
+    public static final class Builder {
+        @Nullable private Network mUpstreamNetwork;
+
+        /**
+         * Set the upstream network, or null if none.
+         * @return the builder
+         */
+        @NonNull public Builder setUpstreamNetwork(@Nullable final Network network) {
+            mUpstreamNetwork = network;
+            return this;
+        }
+
+        /**
+         * Build the LocalNetworkInfo
+         */
+        @NonNull public LocalNetworkInfo build() {
+            return new LocalNetworkInfo(mUpstreamNetwork);
+        }
+    }
+}
diff --git a/framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java b/framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
similarity index 94%
rename from framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java
rename to framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
index c2d75d2..79f1f65 100644
--- a/framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java
+++ b/framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
@@ -35,9 +35,8 @@
  * linter).
  * @hide
  */
-// TODO : rename this so that it doesn't reference "Tiramisu" since it can be used in S.
 @RequiresApi(Build.VERSION_CODES.S)
-public class TiramisuConnectivityInternalApiUtil {
+public class ConnectivityInternalApiUtil {
 
     /**
      * Get a service binder token for
diff --git a/nearby/framework/Android.bp b/nearby/framework/Android.bp
index f329295..4bb9efd 100644
--- a/nearby/framework/Android.bp
+++ b/nearby/framework/Android.bp
@@ -26,6 +26,7 @@
     ],
     path: "java",
     visibility: [
+        "//packages/modules/Connectivity/framework:__subpackages__",
         "//packages/modules/Connectivity/framework-t:__subpackages__",
     ],
 }
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index 46afd31..804e709 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -640,12 +640,8 @@
         // on the experiment flag, BpfNetMaps starts C SkDestroyListener (existing code) or
         // NetworkStatsService starts Java SkDestroyListener (new code).
         final BpfNetMaps bpfNetMaps = mDeps.makeBpfNetMaps(mContext);
-        if (bpfNetMaps.isSkDestroyListenerRunning()) {
-            mSkDestroyListener = null;
-        } else {
-            mSkDestroyListener = mDeps.makeSkDestroyListener(mCookieTagMap, mHandler);
-            mHandler.post(mSkDestroyListener::start);
-        }
+        mSkDestroyListener = mDeps.makeSkDestroyListener(mCookieTagMap, mHandler);
+        mHandler.post(mSkDestroyListener::start);
     }
 
     /**
diff --git a/service/Android.bp b/service/Android.bp
index 7def200..15ae501 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -124,7 +124,6 @@
         "libmodules-utils-build",
         "libnetjniutils",
         "libnet_utils_device_common_bpfjni",
-        "libtraffic_controller",
         "netd_aidl_interface-lateststable-ndk",
     ],
     shared_libs: [
diff --git a/service/jni/com_android_server_BpfNetMaps.cpp b/service/jni/com_android_server_BpfNetMaps.cpp
index 50a0635..29f6a60 100644
--- a/service/jni/com_android_server_BpfNetMaps.cpp
+++ b/service/jni/com_android_server_BpfNetMaps.cpp
@@ -14,179 +14,13 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "TrafficControllerJni"
-
-#include "TrafficController.h"
-
-#include "netd.h"
+#include "bpf/BpfUtils.h"
 
 #include <jni.h>
-#include <log/log.h>
 #include <nativehelper/JNIHelp.h>
-#include <nativehelper/ScopedUtfChars.h>
-#include <nativehelper/ScopedPrimitiveArray.h>
-#include <netjniutils/netjniutils.h>
-#include <net/if.h>
-#include <private/android_filesystem_config.h>
-#include <unistd.h>
-#include <vector>
-
-
-using android::net::TrafficController;
-using android::netdutils::Status;
-
-using UidOwnerMatchType::PENALTY_BOX_MATCH;
-using UidOwnerMatchType::HAPPY_BOX_MATCH;
-
-static android::net::TrafficController mTc;
 
 namespace android {
 
-#define CHECK_LOG(status) \
-  do { \
-    if (!isOk(status)) \
-      ALOGE("%s failed, error code = %d", __func__, status.code()); \
-  } while (0)
-
-static void native_init(JNIEnv* env, jclass clazz, jboolean startSkDestroyListener) {
-  Status status = mTc.start(startSkDestroyListener);
-  CHECK_LOG(status);
-  if (!isOk(status)) {
-    uid_t uid = getuid();
-    ALOGE("BpfNetMaps jni init failure as uid=%d", uid);
-    // We probably only ever get called from system_server (ie. AID_SYSTEM)
-    // or from tests, and never from network_stack (ie. AID_NETWORK_STACK).
-    // However, if we ever do add calls from production network_stack code
-    // we do want to make sure this initializes correctly.
-    // TODO: Fix tests to not use this jni lib, so we can unconditionally abort()
-    if (uid == AID_SYSTEM || uid == AID_NETWORK_STACK) abort();
-  }
-}
-
-static jint native_addNaughtyApp(JNIEnv* env, jobject self, jint uid) {
-  const uint32_t appUids = static_cast<uint32_t>(abs(uid));
-  Status status = mTc.updateUidOwnerMap(appUids, PENALTY_BOX_MATCH,
-      TrafficController::IptOp::IptOpInsert);
-  CHECK_LOG(status);
-  return (jint)status.code();
-}
-
-static jint native_removeNaughtyApp(JNIEnv* env, jobject self, jint uid) {
-  const uint32_t appUids = static_cast<uint32_t>(abs(uid));
-  Status status = mTc.updateUidOwnerMap(appUids, PENALTY_BOX_MATCH,
-      TrafficController::IptOp::IptOpDelete);
-  CHECK_LOG(status);
-  return (jint)status.code();
-}
-
-static jint native_addNiceApp(JNIEnv* env, jobject self, jint uid) {
-  const uint32_t appUids = static_cast<uint32_t>(abs(uid));
-  Status status = mTc.updateUidOwnerMap(appUids, HAPPY_BOX_MATCH,
-      TrafficController::IptOp::IptOpInsert);
-  CHECK_LOG(status);
-  return (jint)status.code();
-}
-
-static jint native_removeNiceApp(JNIEnv* env, jobject self, jint uid) {
-  const uint32_t appUids = static_cast<uint32_t>(abs(uid));
-  Status status = mTc.updateUidOwnerMap(appUids, HAPPY_BOX_MATCH,
-      TrafficController::IptOp::IptOpDelete);
-  CHECK_LOG(status);
-  return (jint)status.code();
-}
-
-static jint native_setChildChain(JNIEnv* env, jobject self, jint childChain, jboolean enable) {
-  auto chain = static_cast<ChildChain>(childChain);
-  int res = mTc.toggleUidOwnerMap(chain, enable);
-  if (res) ALOGE("%s failed, error code = %d", __func__, res);
-  return (jint)res;
-}
-
-static jint native_replaceUidChain(JNIEnv* env, jobject self, jstring name, jboolean isAllowlist,
-                                   jintArray jUids) {
-    const ScopedUtfChars chainNameUtf8(env, name);
-    if (chainNameUtf8.c_str() == nullptr) return -EINVAL;
-    const std::string chainName(chainNameUtf8.c_str());
-
-    ScopedIntArrayRO uids(env, jUids);
-    if (uids.get() == nullptr) return -EINVAL;
-
-    size_t size = uids.size();
-    static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
-    std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
-    int res = mTc.replaceUidOwnerMap(chainName, isAllowlist, data);
-    if (res) ALOGE("%s failed, error code = %d", __func__, res);
-    return (jint)res;
-}
-
-static jint native_setUidRule(JNIEnv* env, jobject self, jint childChain, jint uid,
-                              jint firewallRule) {
-    auto chain = static_cast<ChildChain>(childChain);
-    auto rule = static_cast<FirewallRule>(firewallRule);
-    FirewallType fType = mTc.getFirewallType(chain);
-
-    int res = mTc.changeUidOwnerRule(chain, uid, rule, fType);
-    if (res) ALOGE("%s failed, error code = %d", __func__, res);
-    return (jint)res;
-}
-
-static jint native_addUidInterfaceRules(JNIEnv* env, jobject self, jstring ifName,
-                                        jintArray jUids) {
-    // Null ifName is a wildcard to allow apps to receive packets on all interfaces and ifIndex is
-    // set to 0.
-    int ifIndex = 0;
-    if (ifName != nullptr) {
-        const ScopedUtfChars ifNameUtf8(env, ifName);
-        const std::string interfaceName(ifNameUtf8.c_str());
-        ifIndex = if_nametoindex(interfaceName.c_str());
-    }
-
-    ScopedIntArrayRO uids(env, jUids);
-    if (uids.get() == nullptr) return -EINVAL;
-
-    size_t size = uids.size();
-    static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
-    std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
-    Status status = mTc.addUidInterfaceRules(ifIndex, data);
-    CHECK_LOG(status);
-    return (jint)status.code();
-}
-
-static jint native_removeUidInterfaceRules(JNIEnv* env, jobject self, jintArray jUids) {
-    ScopedIntArrayRO uids(env, jUids);
-    if (uids.get() == nullptr) return -EINVAL;
-
-    size_t size = uids.size();
-    static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
-    std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
-    Status status = mTc.removeUidInterfaceRules(data);
-    CHECK_LOG(status);
-    return (jint)status.code();
-}
-
-static jint native_updateUidLockdownRule(JNIEnv* env, jobject self, jint uid, jboolean add) {
-    Status status = mTc.updateUidLockdownRule(uid, add);
-    CHECK_LOG(status);
-    return (jint)status.code();
-}
-
-static jint native_swapActiveStatsMap(JNIEnv* env, jobject self) {
-    Status status = mTc.swapActiveStatsMap();
-    CHECK_LOG(status);
-    return (jint)status.code();
-}
-
-static void native_setPermissionForUids(JNIEnv* env, jobject self, jint permission,
-                                        jintArray jUids) {
-    ScopedIntArrayRO uids(env, jUids);
-    if (uids.get() == nullptr) return;
-
-    size_t size = uids.size();
-    static_assert(sizeof(*(uids.get())) == sizeof(uid_t));
-    std::vector<uid_t> data ((uid_t *)&uids[0], (uid_t*)&uids[size]);
-    mTc.setPermissionForUids(permission, data);
-}
-
 static jint native_synchronizeKernelRCU(JNIEnv* env, jobject self) {
     return -bpf::synchronizeKernelRCU();
 }
@@ -197,32 +31,6 @@
 // clang-format off
 static const JNINativeMethod gMethods[] = {
     /* name, signature, funcPtr */
-    {"native_init", "(Z)V",
-    (void*)native_init},
-    {"native_addNaughtyApp", "(I)I",
-    (void*)native_addNaughtyApp},
-    {"native_removeNaughtyApp", "(I)I",
-    (void*)native_removeNaughtyApp},
-    {"native_addNiceApp", "(I)I",
-    (void*)native_addNiceApp},
-    {"native_removeNiceApp", "(I)I",
-    (void*)native_removeNiceApp},
-    {"native_setChildChain", "(IZ)I",
-    (void*)native_setChildChain},
-    {"native_replaceUidChain", "(Ljava/lang/String;Z[I)I",
-    (void*)native_replaceUidChain},
-    {"native_setUidRule", "(III)I",
-    (void*)native_setUidRule},
-    {"native_addUidInterfaceRules", "(Ljava/lang/String;[I)I",
-    (void*)native_addUidInterfaceRules},
-    {"native_removeUidInterfaceRules", "([I)I",
-    (void*)native_removeUidInterfaceRules},
-    {"native_updateUidLockdownRule", "(IZ)I",
-    (void*)native_updateUidLockdownRule},
-    {"native_swapActiveStatsMap", "()I",
-    (void*)native_swapActiveStatsMap},
-    {"native_setPermissionForUids", "(I[I)V",
-    (void*)native_setPermissionForUids},
     {"native_synchronizeKernelRCU", "()I",
     (void*)native_synchronizeKernelRCU},
 };
diff --git a/service/native/Android.bp b/service/native/Android.bp
deleted file mode 100644
index 697fcbd..0000000
--- a/service/native/Android.bp
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2022 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 {
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-cc_library {
-    name: "libtraffic_controller",
-    defaults: ["netd_defaults"],
-    srcs: [
-        "TrafficController.cpp",
-    ],
-    header_libs: [
-        "bpf_connectivity_headers",
-    ],
-    static_libs: [
-        // TrafficController would use the constants of INetd so that add
-        // netd_aidl_interface-lateststable-ndk.
-        "netd_aidl_interface-lateststable-ndk",
-    ],
-    shared_libs: [
-        // TODO: Find a good way to remove libbase.
-        "libbase",
-        "libcutils",
-        "libnetdutils",
-        "libutils",
-        "liblog",
-    ],
-    export_include_dirs: ["include"],
-    sanitize: {
-        cfi: true,
-    },
-    apex_available: [
-        "com.android.tethering",
-    ],
-    min_sdk_version: "30",
-}
-
-cc_test {
-    name: "traffic_controller_unit_test",
-    test_suites: ["general-tests", "mts-tethering"],
-    test_config_template: ":net_native_test_config_template",
-    require_root: true,
-    local_include_dirs: ["include"],
-    header_libs: [
-        "bpf_connectivity_headers",
-    ],
-    srcs: [
-        "TrafficControllerTest.cpp",
-    ],
-    static_libs: [
-        "libbase",
-        "libgmock",
-        "liblog",
-        "libnetdutils",
-        "libtraffic_controller",
-        "libutils",
-        "libnetd_updatable",
-        "netd_aidl_interface-lateststable-ndk",
-    ],
-    compile_multilib: "both",
-    multilib: {
-        lib32: {
-            suffix: "32",
-        },
-        lib64: {
-            suffix: "64",
-        },
-    },
-}
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
deleted file mode 100644
index 8cd698e..0000000
--- a/service/native/TrafficController.cpp
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
- * Copyright (C) 2022 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.
- */
-
-#define LOG_TAG "TrafficController"
-#include <inttypes.h>
-#include <linux/if_ether.h>
-#include <linux/in.h>
-#include <linux/inet_diag.h>
-#include <linux/netlink.h>
-#include <linux/sock_diag.h>
-#include <linux/unistd.h>
-#include <net/if.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <map>
-#include <mutex>
-#include <unordered_set>
-#include <vector>
-
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <android-base/unique_fd.h>
-#include <netdutils/StatusOr.h>
-#include <netdutils/Syscalls.h>
-#include <netdutils/UidConstants.h>
-#include <netdutils/Utils.h>
-#include <private/android_filesystem_config.h>
-
-#include "TrafficController.h"
-#include "bpf/BpfMap.h"
-
-namespace android {
-namespace net {
-
-using base::StringPrintf;
-using base::unique_fd;
-using bpf::BpfMap;
-using bpf::synchronizeKernelRCU;
-using netdutils::NetlinkListener;
-using netdutils::NetlinkListenerInterface;
-using netdutils::Slice;
-using netdutils::sSyscalls;
-using netdutils::Status;
-using netdutils::statusFromErrno;
-using netdutils::StatusOr;
-
-constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
-constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
-
-const char* TrafficController::LOCAL_DOZABLE = "fw_dozable";
-const char* TrafficController::LOCAL_STANDBY = "fw_standby";
-const char* TrafficController::LOCAL_POWERSAVE = "fw_powersave";
-const char* TrafficController::LOCAL_RESTRICTED = "fw_restricted";
-const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
-const char* TrafficController::LOCAL_OEM_DENY_1 = "fw_oem_deny_1";
-const char* TrafficController::LOCAL_OEM_DENY_2 = "fw_oem_deny_2";
-const char* TrafficController::LOCAL_OEM_DENY_3 = "fw_oem_deny_3";
-
-static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
-              "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
-static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
-              "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
-
-#define FLAG_MSG_TRANS(result, flag, value) \
-    do {                                    \
-        if ((value) & (flag)) {             \
-            (result).append(" " #flag);     \
-            (value) &= ~(flag);             \
-        }                                   \
-    } while (0)
-
-const std::string uidMatchTypeToString(uint32_t match) {
-    std::string matchType;
-    FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
-    FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
-    FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
-    FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
-    FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
-    FLAG_MSG_TRANS(matchType, RESTRICTED_MATCH, match);
-    FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
-    FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
-    FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
-    FLAG_MSG_TRANS(matchType, OEM_DENY_1_MATCH, match);
-    FLAG_MSG_TRANS(matchType, OEM_DENY_2_MATCH, match);
-    FLAG_MSG_TRANS(matchType, OEM_DENY_3_MATCH, match);
-    if (match) {
-        return StringPrintf("Unknown match: %u", match);
-    }
-    return matchType;
-}
-
-const std::string UidPermissionTypeToString(int permission) {
-    if (permission == INetd::PERMISSION_NONE) {
-        return "PERMISSION_NONE";
-    }
-    if (permission == INetd::PERMISSION_UNINSTALLED) {
-        // This should never appear in the map, complain loudly if it does.
-        return "PERMISSION_UNINSTALLED error!";
-    }
-    std::string permissionType;
-    FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
-    FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
-    if (permission) {
-        return StringPrintf("Unknown permission: %u", permission);
-    }
-    return permissionType;
-}
-
-StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
-    const auto& sys = sSyscalls.get();
-    ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
-    const int domain = AF_NETLINK;
-    const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
-    const int protocol = NETLINK_INET_DIAG;
-    ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
-
-    // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
-    // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
-    // periodically dump all sockets and remove the tag entries for sockets that have been closed.
-    // For now, set a large-enough buffer that we can close hundreds of sockets without getting
-    // ENOBUFS and leaking mCookieTagMap entries.
-    int rcvbuf = 512 * 1024;
-    auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
-    if (!ret.ok()) {
-        ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
-    }
-
-    sockaddr_nl addr = {
-        .nl_family = AF_NETLINK,
-        .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
-                     1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
-    RETURN_IF_NOT_OK(sys.bind(sock, addr));
-
-    const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
-    RETURN_IF_NOT_OK(sys.connect(sock, kernel));
-
-    std::unique_ptr<NetlinkListenerInterface> listener =
-            std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
-
-    return listener;
-}
-
-Status TrafficController::initMaps() {
-    std::lock_guard guard(mMutex);
-
-    RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
-    RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
-    RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
-    RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
-    RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
-    RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
-    RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
-
-    RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
-
-    RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
-    RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
-    ALOGI("%s successfully", __func__);
-
-    return netdutils::status::ok;
-}
-
-Status TrafficController::start(bool startSkDestroyListener) {
-    RETURN_IF_NOT_OK(initMaps());
-
-    if (!startSkDestroyListener) {
-        return netdutils::status::ok;
-    }
-
-    auto result = makeSkDestroyListener();
-    if (!isOk(result)) {
-        ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
-    } else {
-        mSkDestroyListener = std::move(result.value());
-    }
-    // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
-    const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
-        std::lock_guard guard(mMutex);
-        inet_diag_msg diagmsg = {};
-        if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
-            ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
-            return;
-        }
-        uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
-                               (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
-
-        Status s = mCookieTagMap.deleteValue(sock_cookie);
-        if (!isOk(s) && s.code() != ENOENT) {
-            ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
-            return;
-        }
-    };
-    expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
-
-    // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
-    // properly.
-    const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
-        // Ignore NLMSG_DONE  messages
-        inet_diag_msg diagmsg = {};
-        extract(msg, diagmsg);
-    };
-    expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
-
-    return netdutils::status::ok;
-}
-
-Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
-                                              FirewallType type) {
-    std::lock_guard guard(mMutex);
-    if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
-        RETURN_IF_NOT_OK(addRule(uid, match));
-    } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
-        RETURN_IF_NOT_OK(removeRule(uid, match));
-    } else {
-        //Cannot happen.
-        return statusFromErrno(EINVAL, "");
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
-    auto oldMatch = mUidOwnerMap.readValue(uid);
-    if (oldMatch.ok()) {
-        UidOwnerValue newMatch = {
-                .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
-                .rule = oldMatch.value().rule & ~match,
-        };
-        if (newMatch.rule == 0) {
-            RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
-        } else {
-            RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
-        }
-    } else {
-        return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
-    if (match != IIF_MATCH && iif != 0) {
-        return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
-    }
-    auto oldMatch = mUidOwnerMap.readValue(uid);
-    if (oldMatch.ok()) {
-        UidOwnerValue newMatch = {
-                .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
-                .rule = oldMatch.value().rule | match,
-        };
-        RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
-    } else {
-        UidOwnerValue newMatch = {
-                .iif = iif,
-                .rule = match,
-        };
-        RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::updateUidOwnerMap(const uint32_t uid,
-                                            UidOwnerMatchType matchType, IptOp op) {
-    std::lock_guard guard(mMutex);
-    if (op == IptOpDelete) {
-        RETURN_IF_NOT_OK(removeRule(uid, matchType));
-    } else if (op == IptOpInsert) {
-        RETURN_IF_NOT_OK(addRule(uid, matchType));
-    } else {
-        // Cannot happen.
-        return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
-    }
-    return netdutils::status::ok;
-}
-
-FirewallType TrafficController::getFirewallType(ChildChain chain) {
-    switch (chain) {
-        case DOZABLE:
-            return ALLOWLIST;
-        case STANDBY:
-            return DENYLIST;
-        case POWERSAVE:
-            return ALLOWLIST;
-        case RESTRICTED:
-            return ALLOWLIST;
-        case LOW_POWER_STANDBY:
-            return ALLOWLIST;
-        case OEM_DENY_1:
-            return DENYLIST;
-        case OEM_DENY_2:
-            return DENYLIST;
-        case OEM_DENY_3:
-            return DENYLIST;
-        case NONE:
-        default:
-            return DENYLIST;
-    }
-}
-
-int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
-                                          FirewallType type) {
-    Status res;
-    switch (chain) {
-        case DOZABLE:
-            res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
-            break;
-        case STANDBY:
-            res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
-            break;
-        case POWERSAVE:
-            res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
-            break;
-        case RESTRICTED:
-            res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
-            break;
-        case LOW_POWER_STANDBY:
-            res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
-            break;
-        case OEM_DENY_1:
-            res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
-            break;
-        case OEM_DENY_2:
-            res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
-            break;
-        case OEM_DENY_3:
-            res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
-            break;
-        case NONE:
-        default:
-            ALOGW("Unknown child chain: %d", chain);
-            return -EINVAL;
-    }
-    if (!isOk(res)) {
-        ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
-              res.msg().c_str(), rule, type);
-        return -res.code();
-    }
-    return 0;
-}
-
-Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
-                                            const std::vector<int32_t>& uids) {
-    std::lock_guard guard(mMutex);
-    std::set<int32_t> uidSet(uids.begin(), uids.end());
-    std::vector<uint32_t> uidsToDelete;
-    auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
-                                                    const BpfMap<uint32_t, UidOwnerValue>&) {
-        if (uidSet.find((int32_t) key) == uidSet.end()) {
-            uidsToDelete.push_back(key);
-        }
-        return base::Result<void>();
-    };
-    RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
-
-    for(auto uid : uidsToDelete) {
-        RETURN_IF_NOT_OK(removeRule(uid, match));
-    }
-
-    for (auto uid : uids) {
-        RETURN_IF_NOT_OK(addRule(uid, match));
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::addUidInterfaceRules(const int iif,
-                                               const std::vector<int32_t>& uidsToAdd) {
-    std::lock_guard guard(mMutex);
-
-    for (auto uid : uidsToAdd) {
-        netdutils::Status result = addRule(uid, IIF_MATCH, iif);
-        if (!isOk(result)) {
-            ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
-        }
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
-    std::lock_guard guard(mMutex);
-
-    for (auto uid : uidsToDelete) {
-        netdutils::Status result = removeRule(uid, IIF_MATCH);
-        if (!isOk(result)) {
-            ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
-        }
-    }
-    return netdutils::status::ok;
-}
-
-Status TrafficController::updateUidLockdownRule(const uid_t uid, const bool add) {
-    std::lock_guard guard(mMutex);
-
-    netdutils::Status result = add ? addRule(uid, LOCKDOWN_VPN_MATCH)
-                               : removeRule(uid, LOCKDOWN_VPN_MATCH);
-    if (!isOk(result)) {
-        ALOGW("%s Lockdown rule failed(%d): uid=%d",
-              (add ? "add": "remove"), result.code(), uid);
-    }
-    return result;
-}
-
-int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
-                                          const std::vector<int32_t>& uids) {
-    // FirewallRule rule = isAllowlist ? ALLOW : DENY;
-    // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
-    Status res;
-    if (!name.compare(LOCAL_DOZABLE)) {
-        res = replaceRulesInMap(DOZABLE_MATCH, uids);
-    } else if (!name.compare(LOCAL_STANDBY)) {
-        res = replaceRulesInMap(STANDBY_MATCH, uids);
-    } else if (!name.compare(LOCAL_POWERSAVE)) {
-        res = replaceRulesInMap(POWERSAVE_MATCH, uids);
-    } else if (!name.compare(LOCAL_RESTRICTED)) {
-        res = replaceRulesInMap(RESTRICTED_MATCH, uids);
-    } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
-        res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
-    } else if (!name.compare(LOCAL_OEM_DENY_1)) {
-        res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
-    } else if (!name.compare(LOCAL_OEM_DENY_2)) {
-        res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
-    } else if (!name.compare(LOCAL_OEM_DENY_3)) {
-        res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
-    } else {
-        ALOGE("unknown chain name: %s", name.c_str());
-        return -EINVAL;
-    }
-    if (!isOk(res)) {
-        ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
-        return -res.code();
-    }
-    return 0;
-}
-
-int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
-    std::lock_guard guard(mMutex);
-    uint32_t key = UID_RULES_CONFIGURATION_KEY;
-    auto oldConfigure = mConfigurationMap.readValue(key);
-    if (!oldConfigure.ok()) {
-        ALOGE("Cannot read the old configuration from map: %s",
-              oldConfigure.error().message().c_str());
-        return -oldConfigure.error().code();
-    }
-    uint32_t match;
-    switch (chain) {
-        case DOZABLE:
-            match = DOZABLE_MATCH;
-            break;
-        case STANDBY:
-            match = STANDBY_MATCH;
-            break;
-        case POWERSAVE:
-            match = POWERSAVE_MATCH;
-            break;
-        case RESTRICTED:
-            match = RESTRICTED_MATCH;
-            break;
-        case LOW_POWER_STANDBY:
-            match = LOW_POWER_STANDBY_MATCH;
-            break;
-        case OEM_DENY_1:
-            match = OEM_DENY_1_MATCH;
-            break;
-        case OEM_DENY_2:
-            match = OEM_DENY_2_MATCH;
-            break;
-        case OEM_DENY_3:
-            match = OEM_DENY_3_MATCH;
-            break;
-        default:
-            return -EINVAL;
-    }
-    BpfConfig newConfiguration =
-            enable ? (oldConfigure.value() | match) : (oldConfigure.value() & ~match);
-    Status res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
-    if (!isOk(res)) {
-        ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
-    }
-    return -res.code();
-}
-
-Status TrafficController::swapActiveStatsMap() {
-    std::lock_guard guard(mMutex);
-
-    uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
-    auto oldConfigure = mConfigurationMap.readValue(key);
-    if (!oldConfigure.ok()) {
-        ALOGE("Cannot read the old configuration from map: %s",
-              oldConfigure.error().message().c_str());
-        return Status(oldConfigure.error().code(), oldConfigure.error().message());
-    }
-
-    // Write to the configuration map to inform the kernel eBPF program to switch
-    // from using one map to the other. Use flag BPF_EXIST here since the map should
-    // be already populated in initMaps.
-    uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
-    auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
-                                            BPF_EXIST);
-    if (!res.ok()) {
-        ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
-        return res;
-    }
-    // After changing the config, we need to make sure all the current running
-    // eBPF programs are finished and all the CPUs are aware of this config change
-    // before we modify the old map. So we do a special hack here to wait for
-    // the kernel to do a synchronize_rcu(). Once the kernel called
-    // synchronize_rcu(), the config we just updated will be available to all cores
-    // and the next eBPF programs triggered inside the kernel will use the new
-    // map configuration. So once this function returns we can safely modify the
-    // old stats map without concerning about race between the kernel and
-    // userspace.
-    int ret = synchronizeKernelRCU();
-    if (ret) {
-        ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
-        return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
-    }
-    return netdutils::status::ok;
-}
-
-void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
-    std::lock_guard guard(mMutex);
-    if (permission == INetd::PERMISSION_UNINSTALLED) {
-        for (uid_t uid : uids) {
-            // Clean up all permission information for the related uid if all the
-            // packages related to it are uninstalled.
-            mPrivilegedUser.erase(uid);
-            Status ret = mUidPermissionMap.deleteValue(uid);
-            if (!isOk(ret) && ret.code() != ENOENT) {
-                ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
-            }
-        }
-        return;
-    }
-
-    bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
-
-    for (uid_t uid : uids) {
-        if (privileged) {
-            mPrivilegedUser.insert(uid);
-        } else {
-            mPrivilegedUser.erase(uid);
-        }
-
-        // The map stores all the permissions that the UID has, except if the only permission
-        // the UID has is the INTERNET permission, then the UID should not appear in the map.
-        if (permission != INetd::PERMISSION_INTERNET) {
-            Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
-            if (!isOk(ret)) {
-                ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
-                      UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
-            }
-        } else {
-            Status ret = mUidPermissionMap.deleteValue(uid);
-            if (!isOk(ret) && ret.code() != ENOENT) {
-                ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
-            }
-        }
-    }
-}
-
-}  // namespace net
-}  // namespace android
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
deleted file mode 100644
index 99e9831..0000000
--- a/service/native/TrafficControllerTest.cpp
+++ /dev/null
@@ -1,822 +0,0 @@
-/*
- * Copyright 2022 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.
- *
- * TrafficControllerTest.cpp - unit tests for TrafficController.cpp
- */
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-#include <fcntl.h>
-#include <inttypes.h>
-#include <linux/inet_diag.h>
-#include <linux/sock_diag.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <gtest/gtest.h>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <binder/Status.h>
-
-#include <netdutils/MockSyscalls.h>
-
-#define BPF_MAP_MAKE_VISIBLE_FOR_TESTING
-#include "TrafficController.h"
-#include "bpf/BpfUtils.h"
-#include "NetdUpdatablePublic.h"
-
-using namespace android::bpf;  // NOLINT(google-build-using-namespace): grandfathered
-
-namespace android {
-namespace net {
-
-using android::netdutils::Status;
-using base::Result;
-using netdutils::isOk;
-using netdutils::statusFromErrno;
-
-constexpr int TEST_MAP_SIZE = 10;
-constexpr uid_t TEST_UID = 10086;
-constexpr uid_t TEST_UID2 = 54321;
-constexpr uid_t TEST_UID3 = 98765;
-constexpr uint32_t TEST_TAG = 42;
-constexpr uint32_t TEST_COUNTERSET = 1;
-constexpr int TEST_IFINDEX = 999;
-constexpr int RXPACKETS = 1;
-constexpr int RXBYTES = 100;
-constexpr int TXPACKETS = 0;
-constexpr int TXBYTES = 0;
-
-#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
-#define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
-
-class TrafficControllerTest : public ::testing::Test {
-  protected:
-    TrafficControllerTest() {}
-    TrafficController mTc;
-    BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
-    BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
-    BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
-    BpfMap<StatsKey, StatsValue> mFakeStatsMapB;  // makeTrafficControllerMapsInvalid only
-    BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ;  // makeTrafficControllerMapsInvalid only
-    BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
-    BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
-    BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
-    BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
-    BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
-
-    void SetUp() {
-        std::lock_guard guard(mTc.mMutex);
-        ASSERT_EQ(0, setrlimitForTest());
-
-        mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeCookieTagMap);
-
-        mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeAppUidStatsMap);
-
-        mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeStatsMapA);
-
-        mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_ARRAY, CONFIGURATION_MAP_SIZE);
-        ASSERT_VALID(mFakeConfigurationMap);
-
-        mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeUidOwnerMap);
-        mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeUidPermissionMap);
-
-        mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeUidCounterSetMap);
-
-        mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
-        ASSERT_VALID(mFakeIfaceIndexNameMap);
-
-        mTc.mCookieTagMap = mFakeCookieTagMap;
-        ASSERT_VALID(mTc.mCookieTagMap);
-        mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
-        ASSERT_VALID(mTc.mAppUidStatsMap);
-        mTc.mStatsMapA = mFakeStatsMapA;
-        ASSERT_VALID(mTc.mStatsMapA);
-        mTc.mConfigurationMap = mFakeConfigurationMap;
-        ASSERT_VALID(mTc.mConfigurationMap);
-
-        // Always write to stats map A by default.
-        static_assert(SELECT_MAP_A == 0);
-
-        mTc.mUidOwnerMap = mFakeUidOwnerMap;
-        ASSERT_VALID(mTc.mUidOwnerMap);
-        mTc.mUidPermissionMap = mFakeUidPermissionMap;
-        ASSERT_VALID(mTc.mUidPermissionMap);
-        mTc.mPrivilegedUser.clear();
-
-        mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
-        ASSERT_VALID(mTc.mUidCounterSetMap);
-
-        mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
-        ASSERT_VALID(mTc.mIfaceIndexNameMap);
-    }
-
-    void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
-        UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
-        EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
-        *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
-        StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
-                                    .txPackets = TXPACKETS, .txBytes = TXBYTES};
-        EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
-        EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
-        // put tag information back to statsKey
-        key->tag = tag;
-    }
-
-    void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
-        EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
-    }
-
-    void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
-        if (name == nullptr || ifaceIndex <= 0) return;
-
-        IfaceValue iface;
-        strlcpy(iface.name, name, sizeof(IfaceValue));
-        EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
-    }
-
-    void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
-        uint32_t uid = TEST_UID;
-        EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
-        Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
-        EXPECT_RESULT_OK(value);
-        EXPECT_TRUE(value.value().rule & match);
-
-        uid = TEST_UID2;
-        EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
-        value = mFakeUidOwnerMap.readValue(uid);
-        EXPECT_RESULT_OK(value);
-        EXPECT_TRUE(value.value().rule & match);
-
-        EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
-        value = mFakeUidOwnerMap.readValue(uid);
-        EXPECT_FALSE(value.ok());
-        EXPECT_EQ(ENOENT, value.error().code());
-
-        uid = TEST_UID;
-        EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
-        value = mFakeUidOwnerMap.readValue(uid);
-        EXPECT_FALSE(value.ok());
-        EXPECT_EQ(ENOENT, value.error().code());
-
-        uid = TEST_UID3;
-        EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
-        value = mFakeUidOwnerMap.readValue(uid);
-        EXPECT_FALSE(value.ok());
-        EXPECT_EQ(ENOENT, value.error().code());
-    }
-
-    void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
-        for (uint32_t uid : uids) {
-            Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
-            EXPECT_RESULT_OK(value);
-            EXPECT_TRUE(value.value().rule & match);
-        }
-        std::set<uint32_t> uidSet(uids.begin(), uids.end());
-        const auto checkNoOtherUid = [&uidSet](const int32_t& key,
-                                               const BpfMap<uint32_t, UidOwnerValue>&) {
-            EXPECT_NE(uidSet.end(), uidSet.find(key));
-            return Result<void>();
-        };
-        EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
-    }
-
-    void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
-                            UidOwnerMatchType match) {
-        bool isAllowlist = true;
-        EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
-        checkEachUidValue(uids, match);
-
-        isAllowlist = false;
-        EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
-        checkEachUidValue(uids, match);
-    }
-
-    void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
-                                 uint32_t expectedIif) {
-        for (uint32_t uid : appUids) {
-            Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
-            EXPECT_RESULT_OK(value);
-            EXPECT_EQ(expectedRule, value.value().rule)
-                    << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
-                    << value.value().rule;
-            EXPECT_EQ(expectedIif, value.value().iif)
-                    << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
-                    << value.value().iif;
-        }
-    }
-
-    template <class Key, class Value>
-    void expectMapEmpty(BpfMap<Key, Value>& map) {
-        auto isEmpty = map.isEmpty();
-        EXPECT_RESULT_OK(isEmpty);
-        EXPECT_TRUE(isEmpty.value());
-    }
-
-    void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
-        for (uid_t uid : appUids) {
-            Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
-            EXPECT_RESULT_OK(value);
-            EXPECT_EQ(expectedValue, value.value())
-                    << "Expected value for UID " << uid << " to be " << expectedValue
-                    << ", but was " << value.value();
-        }
-    }
-
-    void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
-        std::lock_guard guard(mTc.mMutex);
-        EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
-        for (uid_t uid : appUids) {
-            EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
-        }
-    }
-
-    void expectPrivilegedUserSetEmpty() {
-        std::lock_guard guard(mTc.mMutex);
-        EXPECT_TRUE(mTc.mPrivilegedUser.empty());
-    }
-
-    Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
-                              UidOwnerMatchType matchType, TrafficController::IptOp op) {
-        Status ret(0);
-        for (auto uid : appUids) {
-        ret = mTc.updateUidOwnerMap(uid, matchType, op);
-           if(!isOk(ret)) break;
-        }
-        return ret;
-    }
-};
-
-TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
-    uint32_t uid = TEST_UID;
-    ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
-    Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
-    ASSERT_RESULT_OK(value);
-    ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
-
-    ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
-    value = mFakeUidOwnerMap.readValue(uid);
-    ASSERT_RESULT_OK(value);
-    ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
-
-    ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
-    value = mFakeUidOwnerMap.readValue(uid);
-    ASSERT_RESULT_OK(value);
-    ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
-
-    ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
-    ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
-
-    uid = TEST_UID2;
-    ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
-    ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
-}
-
-TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
-    checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
-    checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
-    checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
-    checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
-    checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
-    checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
-    checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
-    checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
-    ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
-    ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
-}
-
-TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
-    std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
-    checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
-    checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
-    checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
-    checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
-    checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
-    checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
-    checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
-    checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
-    ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
-}
-
-TEST_F(TrafficControllerTest, TestReplaceSameChain) {
-    std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
-    checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
-    std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
-    checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
-    std::vector<uint32_t> appUids = {1000, 1001, 10012};
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpDelete)));
-    expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
-    std::vector<uint32_t> appUids = {1000, 1001, 10012};
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
-    expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
-    std::vector<uint32_t> appUids = {1000, 1001, 10012};
-    // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
-
-    // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
-    // HAPPY_BOX_MATCH.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
-
-    // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
-    expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
-
-    // Remove the same UIDs from the denylist and check the map is empty.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpDelete)));
-    ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
-}
-
-TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
-    std::vector<uint32_t> appUids = {1000, 1001, 10012};
-    // If the uid does not exist in the map, trying to delete a rule about it will fail.
-    ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
-                                         TrafficController::IptOpDelete)));
-    expectMapEmpty(mFakeUidOwnerMap);
-
-    // Add denylist rules for appUids.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
-                                        TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
-
-    // Delete (non-existent) denylist rules for appUids, and check that this silently does
-    // nothing if the uid is in the map but does not have denylist match. This is required because
-    // NetworkManagementService will try to remove a uid from denylist after adding it to the
-    // allowlist and if the remove fails it will not update the uid status.
-    ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpDelete)));
-    expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
-}
-
-TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
-    int iif0 = 15;
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
-    expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
-
-    // Add some non-overlapping new uids. They should coexist with existing rules
-    int iif1 = 16;
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
-    expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
-    expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
-
-    // Overwrite some existing uids
-    int iif2 = 17;
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
-    expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
-    expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
-    expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
-}
-
-TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
-    int iif0 = 15;
-    int iif1 = 16;
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
-    expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
-    expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
-
-    // Rmove some uids
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
-    expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
-    expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
-    checkEachUidValue({1000, 2000}, IIF_MATCH);  // Make sure there are only two uids remaining
-
-    // Remove non-existent uids shouldn't fail
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
-    expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
-    checkEachUidValue({1000}, IIF_MATCH);  // Make sure there are only one uid remaining
-
-    // Remove everything
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
-    expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
-    // Add Lockdown rules
-    ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
-    ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
-    expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
-
-    // Remove one of Lockdown rules
-    ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
-    expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
-
-    // Remove remaining Lockdown rule
-    ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
-    expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
-    // Set up existing PENALTY_BOX_MATCH rules
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
-
-    // Add some partially-overlapping uid owner rules and check result
-    int iif1 = 32;
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
-    expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
-    expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
-
-    // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
-                                        TrafficController::IptOpDelete)));
-    expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
-    expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
-
-    // Remove all uid interface rules
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
-    expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
-    // Make sure these are the only uids left
-    checkEachUidValue({1000}, PENALTY_BOX_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
-    int iif1 = 56;
-    // Set up existing uid interface rules
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
-    expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
-
-    // Add some partially-overlapping doze rules
-    EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
-    expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
-
-    // Introduce a third rule type (powersave) on various existing UIDs
-    EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
-    expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
-    expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
-
-    // Remove all doze rules
-    EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
-    expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
-    expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
-    expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
-
-    // Remove all powersave rules, expect ownerMap to only have uid interface rules left
-    EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
-    expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
-    // Make sure these are the only uids left
-    checkEachUidValue({10001, 10002}, IIF_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
-    // iif=0 is a wildcard
-    int iif = 0;
-    // Add interface rule with wildcard to uids
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
-    expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
-}
-
-TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
-    // iif=0 is a wildcard
-    int iif = 0;
-    // Add interface rule with wildcard to two uids
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
-    expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
-
-    // Remove interface rule from one of the uids
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
-    expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
-    checkEachUidValue({1001}, IIF_MATCH);
-
-    // Remove interface rule from the remaining uid
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
-    expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
-    // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
-                                        TrafficController::IptOpInsert)));
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
-                                        TrafficController::IptOpInsert)));
-
-    // iif=0 is a wildcard
-    int iif = 0;
-    // Add interface rule with wildcard to the existing uid
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
-    expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
-
-    // Remove interface rule with wildcard from the existing uid
-    ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
-    expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
-    // iif=0 is a wildcard
-    int iif = 0;
-    // Set up existing interface rule with wildcard
-    ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
-
-    // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
-                                        TrafficController::IptOpInsert)));
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
-                                        TrafficController::IptOpInsert)));
-    expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
-
-    // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
-                                        TrafficController::IptOpDelete)));
-    ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
-                                        TrafficController::IptOpDelete)));
-    expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
-}
-
-TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
-    expectMapEmpty(mFakeUidPermissionMap);
-    expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
-    expectPrivilegedUserSet(appUids);
-
-    std::vector<uid_t> uidToRemove = {TEST_UID};
-    mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
-
-    std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
-    expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
-    expectPrivilegedUserSet(uidRemain);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
-    expectMapEmpty(mFakeUidPermissionMap);
-    expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
-    expectPrivilegedUserSet(appUids);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
-    expectPrivilegedUserSetEmpty();
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
-    expectPrivilegedUserSet(appUids);
-
-    std::vector<uid_t> uidToRemove = {TEST_UID};
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
-
-    std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
-    expectPrivilegedUserSet(uidRemain);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
-    expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
-    expectPrivilegedUserSetEmpty();
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
-    std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
-    mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
-    expectMapEmpty(mFakeUidPermissionMap);
-
-    std::vector<uid_t> uidToAdd = {TEST_UID};
-    mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
-
-    expectPrivilegedUserSetEmpty();
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
-    expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
-    expectPrivilegedUserSet(appUids);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
-    expectPrivilegedUserSet(appUids);
-
-    mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
-    expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, getFirewallType) {
-    static const struct TestConfig {
-        ChildChain childChain;
-        FirewallType firewallType;
-    } testConfigs[] = {
-            // clang-format off
-            {NONE, DENYLIST},
-            {DOZABLE, ALLOWLIST},
-            {STANDBY, DENYLIST},
-            {POWERSAVE, ALLOWLIST},
-            {RESTRICTED, ALLOWLIST},
-            {LOW_POWER_STANDBY, ALLOWLIST},
-            {OEM_DENY_1, DENYLIST},
-            {OEM_DENY_2, DENYLIST},
-            {OEM_DENY_3, DENYLIST},
-            {INVALID_CHAIN, DENYLIST},
-            // clang-format on
-    };
-
-    for (const auto& config : testConfigs) {
-        SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
-        EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
-    }
-}
-
-constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
-constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
-
-using android::base::Error;
-using android::base::Result;
-using android::bpf::BpfMap;
-
-// This test set up a SkDestroyListener that is running parallel with the production
-// SkDestroyListener. The test will create thousands of sockets and tag them on the
-// production cookieUidTagMap and close them in a short time. When the number of
-// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
-// error. The error will be ignored by the production SkDestroyListener and the
-// test will clean up the tags in tearDown if there is any remains.
-
-// TODO: Instead of test the ENOBUFF error, we can test the production
-// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
-// triggered.
-class NetlinkListenerTest : public testing::Test {
-  protected:
-    NetlinkListenerTest() {}
-    BpfMap<uint64_t, UidTagValue> mCookieTagMap;
-
-    void SetUp() {
-        mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
-        ASSERT_TRUE(mCookieTagMap.isValid());
-    }
-
-    void TearDown() {
-        const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
-                                                BpfMap<uint64_t, UidTagValue>& map) {
-            if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
-                Result<void> res = map.deleteValue(key);
-                if (res.ok() || (res.error().code() == ENOENT)) {
-                    return Result<void>();
-                }
-                ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
-                      strerror(res.error().code()));
-            }
-            // Move forward to next cookie in the map.
-            return Result<void>();
-        };
-        EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
-    }
-
-    Result<void> checkNoGarbageTagsExist() {
-        const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
-                                         const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
-            if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
-                return Error(EUCLEAN) << "Closed socket is not untagged";
-            }
-            return {};
-        };
-        return mCookieTagMap.iterateWithValue(checkGarbageTags);
-    }
-
-    bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
-        std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
-        auto result = android::net::TrafficController::makeSkDestroyListener();
-        if (!isOk(result)) {
-            ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
-        } else {
-            skDestroyListener = std::move(result.value());
-        }
-        int rxErrorCount = 0;
-        // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
-        const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
-        skDestroyListener->registerSkErrorHandler(rxErrorHandler);
-        int fds[totalNumber];
-        for (int i = 0; i < totalNumber; i++) {
-            fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
-            // The likely reason for a failure is running out of available file descriptors.
-            EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
-            if (fds[i] < 0) {
-                // EXPECT_LE already failed above, so test case is a failure, but we don't
-                // want potentially tens of thousands of extra failures creating and then
-                // closing all these fds cluttering up the logs.
-                totalNumber = i;
-                break;
-            };
-            libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
-        }
-
-        // TODO: Use a separate thread that has its own fd table so we can
-        // close sockets even faster simply by terminating that thread.
-        for (int i = 0; i < totalNumber; i++) {
-            EXPECT_EQ(0, close(fds[i]));
-        }
-        // wait a bit for netlink listener to handle all the messages.
-        usleep(SOCK_CLOSE_WAIT_US);
-        if (expectError) {
-            // If ENOBUFS triggered, check it only called into the handler once, ie.
-            // that the netlink handler is not spinning.
-            int currentErrorCount = rxErrorCount;
-            // 0 error count is acceptable because the system has chances to close all sockets
-            // normally.
-            EXPECT_LE(0, rxErrorCount);
-            if (!rxErrorCount) return true;
-
-            usleep(ENOBUFS_POLL_WAIT_US);
-            EXPECT_EQ(currentErrorCount, rxErrorCount);
-        } else {
-            EXPECT_RESULT_OK(checkNoGarbageTagsExist());
-            EXPECT_EQ(0, rxErrorCount);
-        }
-        return false;
-    }
-};
-
-TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
-    checkMassiveSocketDestroy(10, false);
-    checkMassiveSocketDestroy(100, false);
-}
-
-// Disabled because flaky on blueline-userdebug; this test relies on the main thread
-// winning a race against the NetlinkListener::run() thread. There's no way to ensure
-// things will be scheduled the same way across all architectures and test environments.
-TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
-    bool needRetry = false;
-    int retryCount = 0;
-    do {
-        needRetry = checkMassiveSocketDestroy(32500, true);
-        if (needRetry) retryCount++;
-    } while (needRetry && retryCount < 3);
-    // Should review test if it can always close all sockets correctly.
-    EXPECT_GT(3, retryCount);
-}
-
-
-}  // namespace net
-}  // namespace android
diff --git a/service/native/include/TrafficController.h b/service/native/include/TrafficController.h
deleted file mode 100644
index 86cf50a..0000000
--- a/service/native/include/TrafficController.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2022 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.
- */
-
-#pragma once
-
-#include <set>
-#include <Common.h>
-
-#include "android-base/thread_annotations.h"
-#include "bpf/BpfMap.h"
-#include "netd.h"
-#include "netdutils/NetlinkListener.h"
-#include "netdutils/StatusOr.h"
-
-namespace android {
-namespace net {
-
-using netdutils::StatusOr;
-
-class TrafficController {
-  public:
-    /*
-     * Initialize the whole controller
-     */
-    netdutils::Status start(bool startSkDestroyListener);
-
-    /*
-     * Swap the stats map config from current active stats map to the idle one.
-     */
-    netdutils::Status swapActiveStatsMap() EXCLUDES(mMutex);
-
-    int changeUidOwnerRule(ChildChain chain, const uid_t uid, FirewallRule rule, FirewallType type);
-
-    int removeUidOwnerRule(const uid_t uid);
-
-    int replaceUidOwnerMap(const std::string& name, bool isAllowlist,
-                           const std::vector<int32_t>& uids);
-
-    enum IptOp { IptOpInsert, IptOpDelete };
-
-    netdutils::Status updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
-                                          FirewallType type) EXCLUDES(mMutex);
-
-    netdutils::Status replaceRulesInMap(UidOwnerMatchType match, const std::vector<int32_t>& uids)
-            EXCLUDES(mMutex);
-
-    netdutils::Status addUidInterfaceRules(const int ifIndex, const std::vector<int32_t>& uids)
-            EXCLUDES(mMutex);
-    netdutils::Status removeUidInterfaceRules(const std::vector<int32_t>& uids) EXCLUDES(mMutex);
-
-    netdutils::Status updateUidLockdownRule(const uid_t uid, const bool add) EXCLUDES(mMutex);
-
-    netdutils::Status updateUidOwnerMap(const uint32_t uid,
-                                        UidOwnerMatchType matchType, IptOp op) EXCLUDES(mMutex);
-
-    int toggleUidOwnerMap(ChildChain chain, bool enable) EXCLUDES(mMutex);
-
-    static netdutils::StatusOr<std::unique_ptr<netdutils::NetlinkListenerInterface>>
-    makeSkDestroyListener();
-
-    void setPermissionForUids(int permission, const std::vector<uid_t>& uids) EXCLUDES(mMutex);
-
-    FirewallType getFirewallType(ChildChain);
-
-    static const char* LOCAL_DOZABLE;
-    static const char* LOCAL_STANDBY;
-    static const char* LOCAL_POWERSAVE;
-    static const char* LOCAL_RESTRICTED;
-    static const char* LOCAL_LOW_POWER_STANDBY;
-    static const char* LOCAL_OEM_DENY_1;
-    static const char* LOCAL_OEM_DENY_2;
-    static const char* LOCAL_OEM_DENY_3;
-
-  private:
-    /*
-     * mCookieTagMap: Store the corresponding tag and uid for a specific socket.
-     * DO NOT hold any locks when modifying this map, otherwise when the untag
-     * operation is waiting for a lock hold by other process and there are more
-     * sockets being closed than can fit in the socket buffer of the netlink socket
-     * that receives them, then the kernel will drop some of these sockets and we
-     * won't delete their tags.
-     * Map Key: uint64_t socket cookie
-     * Map Value: UidTagValue, contains a uint32 uid and a uint32 tag.
-     */
-    bpf::BpfMap<uint64_t, UidTagValue> mCookieTagMap GUARDED_BY(mMutex);
-
-    /*
-     * mUidCounterSetMap: Store the counterSet of a specific uid.
-     * Map Key: uint32 uid.
-     * Map Value: uint32 counterSet specifies if the traffic is a background
-     * or foreground traffic.
-     */
-    bpf::BpfMap<uint32_t, uint8_t> mUidCounterSetMap GUARDED_BY(mMutex);
-
-    /*
-     * mAppUidStatsMap: Store the total traffic stats for a uid regardless of
-     * tag, counterSet and iface. The stats is used by TrafficStats.getUidStats
-     * API to return persistent stats for a specific uid since device boot.
-     */
-    bpf::BpfMap<uint32_t, StatsValue> mAppUidStatsMap;
-
-    /*
-     * mStatsMapA/mStatsMapB: Store the traffic statistics for a specific
-     * combination of uid, tag, iface and counterSet. These two maps contain
-     * both tagged and untagged traffic.
-     * Map Key: StatsKey contains the uid, tag, counterSet and ifaceIndex
-     * information.
-     * Map Value: Stats, contains packet count and byte count of each
-     * transport protocol on egress and ingress direction.
-     */
-    bpf::BpfMap<StatsKey, StatsValue> mStatsMapA GUARDED_BY(mMutex);
-
-    bpf::BpfMap<StatsKey, StatsValue> mStatsMapB GUARDED_BY(mMutex);
-
-    /*
-     * mIfaceIndexNameMap: Store the index name pair of each interface show up
-     * on the device since boot. The interface index is used by the eBPF program
-     * to correctly match the iface name when receiving a packet.
-     */
-    bpf::BpfMap<uint32_t, IfaceValue> mIfaceIndexNameMap;
-
-    /*
-     * mIfaceStataMap: Store per iface traffic stats gathered from xt_bpf
-     * filter.
-     */
-    bpf::BpfMap<uint32_t, StatsValue> mIfaceStatsMap;
-
-    /*
-     * mConfigurationMap: Store the current network policy about uid filtering
-     * and the current stats map in use. There are two configuration entries in
-     * the map right now:
-     * - Entry with UID_RULES_CONFIGURATION_KEY:
-     *    Store the configuration for the current uid rules. It indicates the device
-     *    is in doze/powersave/standby/restricted/low power standby/oem deny mode.
-     * - Entry with CURRENT_STATS_MAP_CONFIGURATION_KEY:
-     *    Stores the current live stats map that kernel program is writing to.
-     *    Userspace can do scraping and cleaning job on the other one depending on the
-     *    current configs.
-     */
-    bpf::BpfMap<uint32_t, uint32_t> mConfigurationMap GUARDED_BY(mMutex);
-
-    /*
-     * mUidOwnerMap: Store uids that are used for bandwidth control uid match.
-     */
-    bpf::BpfMap<uint32_t, UidOwnerValue> mUidOwnerMap GUARDED_BY(mMutex);
-
-    /*
-     * mUidOwnerMap: Store uids that are used for INTERNET permission check.
-     */
-    bpf::BpfMap<uint32_t, uint8_t> mUidPermissionMap GUARDED_BY(mMutex);
-
-    std::unique_ptr<netdutils::NetlinkListenerInterface> mSkDestroyListener;
-
-    netdutils::Status removeRule(uint32_t uid, UidOwnerMatchType match) REQUIRES(mMutex);
-
-    netdutils::Status addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif = 0)
-            REQUIRES(mMutex);
-
-    std::mutex mMutex;
-
-    netdutils::Status initMaps() EXCLUDES(mMutex);
-
-    // Keep track of uids that have permission UPDATE_DEVICE_STATS so we don't
-    // need to call back to system server for permission check.
-    std::set<uid_t> mPrivilegedUser GUARDED_BY(mMutex);
-
-    // For testing
-    friend class TrafficControllerTest;
-};
-
-}  // namespace net
-}  // namespace android
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index f20159c..b7e928d 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -35,14 +35,6 @@
 import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
 import static android.net.BpfNetMapsUtils.isFirewallAllowList;
 import static android.net.BpfNetMapsUtils.matchToString;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
 import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
 import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
 import static android.net.INetd.PERMISSION_INTERNET;
@@ -76,10 +68,8 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.modules.utils.BackgroundThread;
-import com.android.modules.utils.build.SdkLevel;
 import com.android.net.module.util.BpfDump;
 import com.android.net.module.util.BpfMap;
-import com.android.net.module.util.DeviceConfigUtils;
 import com.android.net.module.util.IBpfMap;
 import com.android.net.module.util.Struct;
 import com.android.net.module.util.Struct.S32;
@@ -116,7 +106,6 @@
     // Use legacy netd for releases before T.
     private static boolean sInitialized = false;
 
-    private static Boolean sEnableJavaBpfMap = null;
     private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
             "bpf_net_maps_force_disable_java_bpf_map";
 
@@ -149,14 +138,6 @@
     );
 
     /**
-     * Set sEnableJavaBpfMap for test.
-     */
-    @VisibleForTesting
-    public static void setEnableJavaBpfMapForTest(boolean enable) {
-        sEnableJavaBpfMap = enable;
-    }
-
-    /**
      * Set configurationMap for test.
      */
     @VisibleForTesting
@@ -319,22 +300,10 @@
      */
     private static synchronized void ensureInitialized(final Context context) {
         if (sInitialized) return;
-        if (sEnableJavaBpfMap == null) {
-            sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
-                    DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context,
-                            BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP);
-        }
-        Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
-
         initBpfMaps();
-        native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
         sInitialized = true;
     }
 
-    public boolean isSkDestroyListenerRunning() {
-        return !sEnableJavaBpfMap;
-    }
-
     /**
      * Dependencies of BpfNetMaps, for injection in tests.
      */
@@ -476,12 +445,7 @@
     public void addNaughtyApp(final int uid) {
         throwIfPreT("addNaughtyApp is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
-        } else {
-            final int err = native_addNaughtyApp(uid);
-            maybeThrow(err, "Unable to add naughty app");
-        }
+        addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
     }
 
     /**
@@ -495,12 +459,7 @@
     public void removeNaughtyApp(final int uid) {
         throwIfPreT("removeNaughtyApp is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
-        } else {
-            final int err = native_removeNaughtyApp(uid);
-            maybeThrow(err, "Unable to remove naughty app");
-        }
+        removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
     }
 
     /**
@@ -514,12 +473,7 @@
     public void addNiceApp(final int uid) {
         throwIfPreT("addNiceApp is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
-        } else {
-            final int err = native_addNiceApp(uid);
-            maybeThrow(err, "Unable to add nice app");
-        }
+        addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
     }
 
     /**
@@ -533,12 +487,7 @@
     public void removeNiceApp(final int uid) {
         throwIfPreT("removeNiceApp is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
-        } else {
-            final int err = native_removeNiceApp(uid);
-            maybeThrow(err, "Unable to remove nice app");
-        }
+        removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
     }
 
     /**
@@ -554,21 +503,16 @@
     public void setChildChain(final int childChain, final boolean enable) {
         throwIfPreT("setChildChain is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            final long match = getMatchByFirewallChain(childChain);
-            try {
-                synchronized (sUidRulesConfigBpfMapLock) {
-                    final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
-                    final long newConfig = enable ? (config.val | match) : (config.val & ~match);
-                    sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
-                }
-            } catch (ErrnoException e) {
-                throw new ServiceSpecificException(e.errno,
-                        "Unable to set child chain: " + Os.strerror(e.errno));
+        final long match = getMatchByFirewallChain(childChain);
+        try {
+            synchronized (sUidRulesConfigBpfMapLock) {
+                final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
+                final long newConfig = enable ? (config.val | match) : (config.val & ~match);
+                sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
             }
-        } else {
-            final int err = native_setChildChain(childChain, enable);
-            maybeThrow(err, "Unable to set child chain");
+        } catch (ErrnoException e) {
+            throw new ServiceSpecificException(e.errno,
+                    "Unable to set child chain: " + Os.strerror(e.errno));
         }
     }
 
@@ -611,75 +555,38 @@
     public void replaceUidChain(final int chain, final int[] uids) {
         throwIfPreT("replaceUidChain is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            final long match;
-            try {
-                match = getMatchByFirewallChain(chain);
-            } catch (ServiceSpecificException e) {
-                // Throws IllegalArgumentException to keep the behavior of
-                // ConnectivityManager#replaceFirewallChain API
-                throw new IllegalArgumentException("Invalid firewall chain: " + chain);
-            }
-            final Set<Integer> uidSet = asSet(uids);
-            final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
-            try {
-                synchronized (sUidOwnerMap) {
-                    sUidOwnerMap.forEach((uid, config) -> {
-                        // config could be null if there is a concurrent entry deletion.
-                        // http://b/220084230. But sUidOwnerMap update must be done while holding a
-                        // lock, so this should not happen.
-                        if (config == null) {
-                            Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
-                        } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
-                            uidSetToRemoveRule.add((int) uid.val);
-                        }
-                    });
+        final long match;
+        try {
+            match = getMatchByFirewallChain(chain);
+        } catch (ServiceSpecificException e) {
+            // Throws IllegalArgumentException to keep the behavior of
+            // ConnectivityManager#replaceFirewallChain API
+            throw new IllegalArgumentException("Invalid firewall chain: " + chain);
+        }
+        final Set<Integer> uidSet = asSet(uids);
+        final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
+        try {
+            synchronized (sUidOwnerMap) {
+                sUidOwnerMap.forEach((uid, config) -> {
+                    // config could be null if there is a concurrent entry deletion.
+                    // http://b/220084230. But sUidOwnerMap update must be done while holding a
+                    // lock, so this should not happen.
+                    if (config == null) {
+                        Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
+                    } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
+                        uidSetToRemoveRule.add((int) uid.val);
+                    }
+                });
 
-                    for (final int uid : uidSetToRemoveRule) {
-                        removeRule(uid, match, "replaceUidChain");
-                    }
-                    for (final int uid : uids) {
-                        addRule(uid, match, "replaceUidChain");
-                    }
+                for (final int uid : uidSetToRemoveRule) {
+                    removeRule(uid, match, "replaceUidChain");
                 }
-            } catch (ErrnoException | ServiceSpecificException e) {
-                Log.e(TAG, "replaceUidChain failed: " + e);
+                for (final int uid : uids) {
+                    addRule(uid, match, "replaceUidChain");
+                }
             }
-        } else {
-            final int err;
-            switch (chain) {
-                case FIREWALL_CHAIN_DOZABLE:
-                    err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_STANDBY:
-                    err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_POWERSAVE:
-                    err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_RESTRICTED:
-                    err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_LOW_POWER_STANDBY:
-                    err = native_replaceUidChain(
-                            "fw_low_power_standby", true /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_OEM_DENY_1:
-                    err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_OEM_DENY_2:
-                    err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
-                    break;
-                case FIREWALL_CHAIN_OEM_DENY_3:
-                    err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
-                    break;
-                default:
-                    throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
-                            + chain);
-            }
-            if (err != 0) {
-                Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
-            }
+        } catch (ErrnoException | ServiceSpecificException e) {
+            Log.e(TAG, "replaceUidChain failed: " + e);
         }
     }
 
@@ -696,20 +603,15 @@
     public void setUidRule(final int childChain, final int uid, final int firewallRule) {
         throwIfPreT("setUidRule is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            final long match = getMatchByFirewallChain(childChain);
-            final boolean isAllowList = isFirewallAllowList(childChain);
-            final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
-                    || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
+        final long match = getMatchByFirewallChain(childChain);
+        final boolean isAllowList = isFirewallAllowList(childChain);
+        final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
+                || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
 
-            if (add) {
-                addRule(uid, match, "setUidRule");
-            } else {
-                removeRule(uid, match, "setUidRule");
-            }
+        if (add) {
+            addRule(uid, match, "setUidRule");
         } else {
-            final int err = native_setUidRule(childChain, uid, firewallRule);
-            maybeThrow(err, "Unable to set uid rule");
+            removeRule(uid, match, "setUidRule");
         }
     }
 
@@ -812,29 +714,24 @@
             return;
         }
 
-        if (sEnableJavaBpfMap) {
-            // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
-            // ifIndex is set to 0.
-            final int ifIndex;
-            if (ifName == null) {
-                ifIndex = 0;
-            } else {
-                ifIndex = mDeps.getIfIndex(ifName);
-                if (ifIndex == 0) {
-                    throw new ServiceSpecificException(ENODEV,
-                            "Failed to get index of interface " + ifName);
-                }
-            }
-            for (final int uid : uids) {
-                try {
-                    addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
-                } catch (ServiceSpecificException e) {
-                    Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
-                }
-            }
+        // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
+        // ifIndex is set to 0.
+        final int ifIndex;
+        if (ifName == null) {
+            ifIndex = 0;
         } else {
-            final int err = native_addUidInterfaceRules(ifName, uids);
-            maybeThrow(err, "Unable to add uid interface rules");
+            ifIndex = mDeps.getIfIndex(ifName);
+            if (ifIndex == 0) {
+                throw new ServiceSpecificException(ENODEV,
+                        "Failed to get index of interface " + ifName);
+            }
+        }
+        for (final int uid : uids) {
+            try {
+                addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
+            } catch (ServiceSpecificException e) {
+                Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
+            }
         }
     }
 
@@ -855,17 +752,12 @@
             return;
         }
 
-        if (sEnableJavaBpfMap) {
-            for (final int uid : uids) {
-                try {
-                    removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
-                } catch (ServiceSpecificException e) {
-                    Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
-                }
+        for (final int uid : uids) {
+            try {
+                removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
+            } catch (ServiceSpecificException e) {
+                Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
             }
-        } else {
-            final int err = native_removeUidInterfaceRules(uids);
-            maybeThrow(err, "Unable to remove uid interface rules");
         }
     }
 
@@ -881,15 +773,10 @@
     public void updateUidLockdownRule(final int uid, final boolean add) {
         throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            if (add) {
-                addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
-            } else {
-                removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
-            }
+        if (add) {
+            addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
         } else {
-            final int err = native_updateUidLockdownRule(uid, add);
-            maybeThrow(err, "Unable to update lockdown rule");
+            removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
         }
     }
 
@@ -904,33 +791,28 @@
     public void swapActiveStatsMap() {
         throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
 
-        if (sEnableJavaBpfMap) {
-            try {
-                synchronized (sCurrentStatsMapConfigLock) {
-                    final long config = sConfigurationMap.getValue(
-                            CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
-                    final long newConfig = (config == STATS_SELECT_MAP_A)
-                            ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
-                    sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
-                            new U32(newConfig));
-                }
-            } catch (ErrnoException e) {
-                throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
+        try {
+            synchronized (sCurrentStatsMapConfigLock) {
+                final long config = sConfigurationMap.getValue(
+                        CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
+                final long newConfig = (config == STATS_SELECT_MAP_A)
+                        ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
+                sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
+                        new U32(newConfig));
             }
-
-            // After changing the config, it's needed to make sure all the current running eBPF
-            // programs are finished and all the CPUs are aware of this config change before the old
-            // map is modified. So special hack is needed here to wait for the kernel to do a
-            // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
-            // be available to all cores and the next eBPF programs triggered inside the kernel will
-            // use the new map configuration. So once this function returns it is safe to modify the
-            // old stats map without concerning about race between the kernel and userspace.
-            final int err = mDeps.synchronizeKernelRCU();
-            maybeThrow(err, "synchronizeKernelRCU failed");
-        } else {
-            final int err = native_swapActiveStatsMap();
-            maybeThrow(err, "Unable to swap active stats map");
+        } catch (ErrnoException e) {
+            throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
         }
+
+        // After changing the config, it's needed to make sure all the current running eBPF
+        // programs are finished and all the CPUs are aware of this config change before the old
+        // map is modified. So special hack is needed here to wait for the kernel to do a
+        // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
+        // be available to all cores and the next eBPF programs triggered inside the kernel will
+        // use the new map configuration. So once this function returns it is safe to modify the
+        // old stats map without concerning about race between the kernel and userspace.
+        final int err = mDeps.synchronizeKernelRCU();
+        maybeThrow(err, "synchronizeKernelRCU failed");
     }
 
     /**
@@ -949,29 +831,25 @@
             return;
         }
 
-        if (sEnableJavaBpfMap) {
-            // Remove the entry if package is uninstalled or uid has only INTERNET permission.
-            if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
-                for (final int uid : uids) {
-                    try {
-                        sUidPermissionMap.deleteEntry(new S32(uid));
-                    } catch (ErrnoException e) {
-                        Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
-                    }
-                }
-                return;
-            }
-
+        // Remove the entry if package is uninstalled or uid has only INTERNET permission.
+        if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
             for (final int uid : uids) {
                 try {
-                    sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
+                    sUidPermissionMap.deleteEntry(new S32(uid));
                 } catch (ErrnoException e) {
-                    Log.e(TAG, "Failed to set permission "
-                            + permissions + " to uid " + uid + ": " + e);
+                    Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
                 }
             }
-        } else {
-            native_setPermissionForUids(permissions, uids);
+            return;
+        }
+
+        for (final int uid : uids) {
+            try {
+                sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
+            } catch (ErrnoException e) {
+                Log.e(TAG, "Failed to set permission "
+                        + permissions + " to uid " + uid + ": " + e);
+            }
         }
     }
 
@@ -1147,7 +1025,6 @@
         pw.println("TrafficController");  // required by CTS testDumpBpfNetMaps
 
         pw.println();
-        pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
         if (verbose) {
             pw.println();
             pw.println("BPF map content:");
@@ -1186,44 +1063,5 @@
     }
 
     @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private static native void native_init(boolean startSkDestroyListener);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_addNaughtyApp(int uid);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_removeNaughtyApp(int uid);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_addNiceApp(int uid);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_removeNiceApp(int uid);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_setChildChain(int childChain, boolean enable);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_setUidRule(int childChain, int uid, int firewallRule);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_addUidInterfaceRules(String ifName, int[] uids);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_removeUidInterfaceRules(int[] uids);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_updateUidLockdownRule(int uid, boolean add);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native int native_swapActiveStatsMap();
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-    private native void native_setPermissionForUids(int permissions, int[] uids);
-
-    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
     private static native int native_synchronizeKernelRCU();
 }
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index 50b4134..d8417c1 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -168,6 +168,7 @@
 import android.net.IpPrefix;
 import android.net.LinkProperties;
 import android.net.LocalNetworkConfig;
+import android.net.LocalNetworkInfo;
 import android.net.MatchAllNetworkSpecifier;
 import android.net.NativeNetworkConfig;
 import android.net.NativeNetworkType;
@@ -4183,7 +4184,7 @@
                 }
                 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
                     final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
-                    updateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
+                    handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
                     break;
                 }
                 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
@@ -4946,7 +4947,7 @@
         notifyIfacesChangedForNetworkStats();
         // If this was a local network forwarded to some upstream, or if some local network was
         // forwarded to this nai, then disable forwarding rules now.
-        maybeDisableForwardRulesForDisconnectingNai(nai);
+        maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
         // If this is a local network with an upstream selector, remove the associated network
         // request.
         if (nai.isLocalNetwork()) {
@@ -5069,7 +5070,7 @@
     }
 
     private void maybeDisableForwardRulesForDisconnectingNai(
-            @NonNull final NetworkAgentInfo disconnecting) {
+            @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
         // Step 1 : maybe this network was the upstream for one or more local networks.
         for (final NetworkAgentInfo local : mNetworkAgentInfos) {
             if (!local.isLocalNetwork()) continue;
@@ -5082,6 +5083,13 @@
             final NetworkAgentInfo satisfier = nri.getSatisfier();
             if (disconnecting != satisfier) continue;
             removeLocalNetworkUpstream(local, disconnecting);
+            // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
+            // correctly contains null as an upstream.
+            if (sendCallbacks) {
+                nri.setSatisfier(null, null);
+                notifyNetworkCallbacks(local,
+                        ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
+            }
         }
 
         // Step 2 : maybe this is a local network that had an upstream.
@@ -5148,8 +5156,10 @@
             mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
         }
         // Remove any forwarding rules to and from the interface for this network, since
-        // the interface is going to go away.
-        maybeDisableForwardRulesForDisconnectingNai(nai);
+        // the interface is going to go away. Don't send the callbacks however ; if the network
+        // was is being disconnected the callbacks have already been sent, and if it is being
+        // destroyed pending replacement they will be sent when it is disconnected.
+        maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
         try {
             mNetd.networkDestroy(nai.network.getNetId());
         } catch (RemoteException | ServiceSpecificException e) {
@@ -8320,7 +8330,7 @@
         }
 
         if (nai.isLocalNetwork()) {
-            updateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
+            handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
         }
         nai.notifyRegistered();
         NetworkInfo networkInfo = nai.networkInfo;
@@ -8988,7 +8998,7 @@
     }
 
     // oldConfig is null iff this is the original registration of the local network config
-    private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
+    private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
             @Nullable final LocalNetworkConfig oldConfig,
             @NonNull final LocalNetworkConfig newConfig) {
         if (!nai.isLocalNetwork()) {
@@ -9021,6 +9031,12 @@
                 // If there is an old satisfier, but no new request, then remove the old upstream.
                 removeLocalNetworkUpstream(nai, oldSatisfier);
                 nai.localNetworkConfig = configBuilder.build();
+                // When there is a new request, the rematch sees the new request and sends the
+                // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
+                // But here there is no new request, so the rematch won't see anything. Send
+                // callbacks to apps now to tell them about the loss of upstream.
+                notifyNetworkCallbacks(nai,
+                        ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
                 return;
             }
         }
@@ -9042,12 +9058,14 @@
                 nri.setSatisfier(oldSatisfier, nr);
             }
             nai.localNetworkConfig = configBuilder.build();
+            // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
+            // nai.localNetworkConfig is set, since it will base its callbacks on the old
+            // satisfier and the new request.
             handleRegisterNetworkRequest(nri);
         } else {
             configBuilder.setUpstreamSelector(oldRequest);
             nai.localNetworkConfig = configBuilder.build();
         }
-
     }
 
     /**
@@ -9378,6 +9396,21 @@
         releasePendingNetworkRequestWithDelay(pendingIntent);
     }
 
+    @Nullable
+    private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
+        if (!nai.isLocalNetwork()) return null;
+        final Network upstream;
+        final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
+        if (null == selector) {
+            upstream = null;
+        } else {
+            final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
+            final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
+            upstream = (null == satisfier) ? null : satisfier.network;
+        }
+        return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
+    }
+
     // networkAgent is only allowed to be null if notificationType is
     // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
     // available, while all other cases are about some particular network.
@@ -9413,6 +9446,10 @@
                 putParcelable(bundle, nc);
                 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
                         networkAgent.linkProperties, nri.mPid, nri.mUid));
+                // The local network info is often null, so can't use the static putParcelable
+                // method here.
+                bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
+                        localNetworkInfoForNai(networkAgent));
                 // For this notification, arg1 contains the blocked status.
                 msg.arg1 = arg1;
                 break;
@@ -9444,6 +9481,14 @@
                 msg.arg1 = arg1;
                 break;
             }
+            case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
+                if (!networkAgent.isLocalNetwork()) {
+                    Log.wtf(TAG, "Callback for local info for a non-local network");
+                    return;
+                }
+                putParcelable(bundle, localNetworkInfoForNai(networkAgent));
+                break;
+            }
         }
         msg.what = notificationType;
         msg.setData(bundle);
@@ -10077,6 +10122,7 @@
                     loge("Can't update forwarding rules", e);
                 }
             }
+            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
         }
 
         updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt b/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
index df9c61a..05c0444 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
@@ -18,6 +18,7 @@
 
 import android.net.ConnectivityManager.NetworkCallback
 import android.net.LinkProperties
+import android.net.LocalNetworkInfo
 import android.net.Network
 import android.net.NetworkCapabilities
 import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED
@@ -28,6 +29,7 @@
 import com.android.testutils.RecorderCallback.CallbackEntry.BlockedStatusInt
 import com.android.testutils.RecorderCallback.CallbackEntry.CapabilitiesChanged
 import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged
+import com.android.testutils.RecorderCallback.CallbackEntry.LocalInfoChanged
 import com.android.testutils.RecorderCallback.CallbackEntry.Losing
 import com.android.testutils.RecorderCallback.CallbackEntry.Lost
 import com.android.testutils.RecorderCallback.CallbackEntry.Resumed
@@ -68,6 +70,10 @@
             override val network: Network,
             val lp: LinkProperties
         ) : CallbackEntry()
+        data class LocalInfoChanged(
+            override val network: Network,
+            val info: LocalNetworkInfo
+        ) : CallbackEntry()
         data class Suspended(override val network: Network) : CallbackEntry()
         data class Resumed(override val network: Network) : CallbackEntry()
         data class Losing(override val network: Network, val maxMsToLive: Int) : CallbackEntry()
@@ -94,6 +100,8 @@
             @JvmField
             val LINK_PROPERTIES_CHANGED = LinkPropertiesChanged::class
             @JvmField
+            val LOCAL_INFO_CHANGED = LocalInfoChanged::class
+            @JvmField
             val SUSPENDED = Suspended::class
             @JvmField
             val RESUMED = Resumed::class
@@ -131,6 +139,11 @@
         history.add(LinkPropertiesChanged(network, lp))
     }
 
+    override fun onLocalNetworkInfoChanged(network: Network, info: LocalNetworkInfo) {
+        Log.d(TAG, "onLocalNetworkInfoChanged $network $info")
+        history.add(LocalInfoChanged(network, info))
+    }
+
     override fun onBlockedStatusChanged(network: Network, blocked: Boolean) {
         Log.d(TAG, "onBlockedStatusChanged $network $blocked")
         history.add(BlockedStatus(network, blocked))
@@ -430,37 +443,63 @@
         suspended: Boolean = false,
         validated: Boolean? = true,
         blocked: Boolean = false,
+        upstream: Network? = null,
         tmt: Long = defaultTimeoutMs
     ) {
-        expectAvailableCallbacksCommon(net, suspended, validated, tmt)
+        expectAvailableCallbacksCommon(net, suspended, validated, upstream, tmt)
         expect<BlockedStatus>(net, tmt) { it.blocked == blocked }
     }
 
+    // For backward compatibility, add a method that allows callers to specify a timeout but
+    // no upstream.
+    fun expectAvailableCallbacks(
+        net: Network,
+        suspended: Boolean = false,
+        validated: Boolean? = true,
+        blocked: Boolean = false,
+        tmt: Long = defaultTimeoutMs
+    ) = expectAvailableCallbacks(net, suspended, validated, blocked, upstream = null, tmt = tmt)
+
     fun expectAvailableCallbacks(
         net: Network,
         suspended: Boolean,
         validated: Boolean,
         blockedReason: Int,
+        upstream: Network? = null,
         tmt: Long
     ) {
-        expectAvailableCallbacksCommon(net, suspended, validated, tmt)
+        expectAvailableCallbacksCommon(net, suspended, validated, upstream, tmt)
         expect<BlockedStatusInt>(net) { it.reason == blockedReason }
     }
 
+    // For backward compatibility, add a method that allows callers to specify a timeout but
+    // no upstream.
+    fun expectAvailableCallbacks(
+            net: Network,
+            suspended: Boolean = false,
+            validated: Boolean = true,
+            blockedReason: Int,
+            tmt: Long = defaultTimeoutMs
+    ) = expectAvailableCallbacks(net, suspended, validated, blockedReason, upstream = null, tmt)
+
     private fun expectAvailableCallbacksCommon(
         net: Network,
         suspended: Boolean,
         validated: Boolean?,
+        upstream: Network?,
         tmt: Long
     ) {
         expect<Available>(net, tmt)
         if (suspended) {
             expect<Suspended>(net, tmt)
         }
-        expect<CapabilitiesChanged>(net, tmt) {
+        val caps = expect<CapabilitiesChanged>(net, tmt) {
             validated == null || validated == it.caps.hasCapability(NET_CAPABILITY_VALIDATED)
-        }
+        }.caps
         expect<LinkPropertiesChanged>(net, tmt)
+        if (caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK)) {
+            expect<LocalInfoChanged>(net, tmt) { it.info.upstreamNetwork == upstream }
+        }
     }
 
     // Backward compatibility for existing Java code. Use named arguments instead and remove all
@@ -507,13 +546,15 @@
         val network: Network
     }
 
+    @JvmOverloads
     fun expectAvailableCallbacks(
         n: HasNetwork,
         suspended: Boolean,
         validated: Boolean,
         blocked: Boolean,
+        upstream: Network? = null,
         timeoutMs: Long
-    ) = expectAvailableCallbacks(n.network, suspended, validated, blocked, timeoutMs)
+    ) = expectAvailableCallbacks(n.network, suspended, validated, blocked, upstream, timeoutMs)
 
     fun expectAvailableAndSuspendedCallbacks(n: HasNetwork, expectValidated: Boolean) {
         expectAvailableAndSuspendedCallbacks(n.network, expectValidated)
diff --git a/tests/common/java/android/net/CaptivePortalDataTest.kt b/tests/common/java/android/net/CaptivePortalDataTest.kt
index f927380..67a523c 100644
--- a/tests/common/java/android/net/CaptivePortalDataTest.kt
+++ b/tests/common/java/android/net/CaptivePortalDataTest.kt
@@ -19,21 +19,20 @@
 import android.os.Build
 import androidx.test.filters.SmallTest
 import com.android.modules.utils.build.SdkLevel
-import com.android.testutils.assertParcelingIsLossless
 import com.android.testutils.DevSdkIgnoreRule
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import com.android.testutils.DevSdkIgnoreRunner
+import com.android.testutils.assertParcelingIsLossless
+import kotlin.test.assertEquals
+import kotlin.test.assertNotEquals
 import org.junit.Assert.assertFalse
 import org.junit.Assert.assertTrue
 import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
-import kotlin.test.assertEquals
-import kotlin.test.assertNotEquals
 
 @SmallTest
 @RunWith(DevSdkIgnoreRunner::class)
-@IgnoreUpTo(Build.VERSION_CODES.Q)
 class CaptivePortalDataTest {
     @Rule @JvmField
     val ignoreRule = DevSdkIgnoreRule()
diff --git a/tests/common/java/android/net/KeepalivePacketDataTest.kt b/tests/common/java/android/net/KeepalivePacketDataTest.kt
index 403d6b5..97a45fc 100644
--- a/tests/common/java/android/net/KeepalivePacketDataTest.kt
+++ b/tests/common/java/android/net/KeepalivePacketDataTest.kt
@@ -17,27 +17,20 @@
 
 import android.net.InvalidPacketException.ERROR_INVALID_IP_ADDRESS
 import android.net.InvalidPacketException.ERROR_INVALID_PORT
-import android.os.Build
 import androidx.test.filters.SmallTest
 import androidx.test.runner.AndroidJUnit4
-import com.android.testutils.DevSdkIgnoreRule
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import com.android.testutils.NonNullTestUtils
 import java.net.InetAddress
 import java.util.Arrays
 import org.junit.Assert.assertEquals
 import org.junit.Assert.assertTrue
 import org.junit.Assert.fail
-import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
 @RunWith(AndroidJUnit4::class)
 @SmallTest
 class KeepalivePacketDataTest {
-    @Rule @JvmField
-    val ignoreRule: DevSdkIgnoreRule = DevSdkIgnoreRule()
-
     private val INVALID_PORT = 65537
     private val TEST_DST_PORT = 4244
     private val TEST_SRC_PORT = 4243
@@ -60,7 +53,6 @@
             NonNullTestUtils.nullUnsafe(dstAddress), dstPort, data)
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testConstructor() {
         try {
             TestKeepalivePacketData(srcAddress = null)
@@ -99,22 +91,17 @@
     }
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testSrcAddress() = assertEquals(TEST_SRC_ADDRV4, TestKeepalivePacketData().srcAddress)
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testDstAddress() = assertEquals(TEST_DST_ADDRV4, TestKeepalivePacketData().dstAddress)
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testSrcPort() = assertEquals(TEST_SRC_PORT, TestKeepalivePacketData().srcPort)
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testDstPort() = assertEquals(TEST_DST_PORT, TestKeepalivePacketData().dstPort)
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     fun testPacket() = assertTrue(Arrays.equals(TESTBYTES, TestKeepalivePacketData().packet))
 }
diff --git a/tests/common/java/android/net/LinkPropertiesTest.java b/tests/common/java/android/net/LinkPropertiesTest.java
index d2e7c99..8f14572 100644
--- a/tests/common/java/android/net/LinkPropertiesTest.java
+++ b/tests/common/java/android/net/LinkPropertiesTest.java
@@ -134,13 +134,10 @@
         assertFalse(lp.isIpv4Provisioned());
         assertFalse(lp.isIpv6Provisioned());
         assertFalse(lp.isPrivateDnsActive());
-
-        if (SdkLevel.isAtLeastR()) {
-            assertNull(lp.getDhcpServerAddress());
-            assertFalse(lp.isWakeOnLanSupported());
-            assertNull(lp.getCaptivePortalApiUrl());
-            assertNull(lp.getCaptivePortalData());
-        }
+        assertNull(lp.getDhcpServerAddress());
+        assertFalse(lp.isWakeOnLanSupported());
+        assertNull(lp.getCaptivePortalApiUrl());
+        assertNull(lp.getCaptivePortalData());
     }
 
     private LinkProperties makeTestObject() {
@@ -162,12 +159,10 @@
         lp.setMtu(MTU);
         lp.setTcpBufferSizes(TCP_BUFFER_SIZES);
         lp.setNat64Prefix(new IpPrefix("2001:db8:0:64::/96"));
-        if (SdkLevel.isAtLeastR()) {
-            lp.setDhcpServerAddress(DHCPSERVER);
-            lp.setWakeOnLanSupported(true);
-            lp.setCaptivePortalApiUrl(CAPPORT_API_URL);
-            lp.setCaptivePortalData((CaptivePortalData) getCaptivePortalData());
-        }
+        lp.setDhcpServerAddress(DHCPSERVER);
+        lp.setWakeOnLanSupported(true);
+        lp.setCaptivePortalApiUrl(CAPPORT_API_URL);
+        lp.setCaptivePortalData((CaptivePortalData) getCaptivePortalData());
         return lp;
     }
 
@@ -206,19 +201,17 @@
         assertTrue(source.isIdenticalTcpBufferSizes(target));
         assertTrue(target.isIdenticalTcpBufferSizes(source));
 
-        if (SdkLevel.isAtLeastR()) {
-            assertTrue(source.isIdenticalDhcpServerAddress(target));
-            assertTrue(source.isIdenticalDhcpServerAddress(source));
+        assertTrue(source.isIdenticalDhcpServerAddress(target));
+        assertTrue(source.isIdenticalDhcpServerAddress(source));
 
-            assertTrue(source.isIdenticalWakeOnLan(target));
-            assertTrue(target.isIdenticalWakeOnLan(source));
+        assertTrue(source.isIdenticalWakeOnLan(target));
+        assertTrue(target.isIdenticalWakeOnLan(source));
 
-            assertTrue(source.isIdenticalCaptivePortalApiUrl(target));
-            assertTrue(target.isIdenticalCaptivePortalApiUrl(source));
+        assertTrue(source.isIdenticalCaptivePortalApiUrl(target));
+        assertTrue(target.isIdenticalCaptivePortalApiUrl(source));
 
-            assertTrue(source.isIdenticalCaptivePortalData(target));
-            assertTrue(target.isIdenticalCaptivePortalData(source));
-        }
+        assertTrue(source.isIdenticalCaptivePortalData(target));
+        assertTrue(target.isIdenticalCaptivePortalData(source));
 
         // Check result of equals().
         assertTrue(source.equals(target));
@@ -1017,7 +1010,7 @@
         assertParcelingIsLossless(source);
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testLinkPropertiesParcelable() throws Exception {
         final LinkProperties source = makeLinkPropertiesForParceling();
 
@@ -1035,7 +1028,7 @@
     }
 
     // Parceling of the scope was broken until Q-QPR2
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testLinkLocalDnsServerParceling() throws Exception {
         final String strAddress = "fe80::1%lo";
         final LinkProperties lp = new LinkProperties();
@@ -1158,7 +1151,7 @@
         assertFalse(lp.isPrivateDnsActive());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testDhcpServerAddress() {
         final LinkProperties lp = makeTestObject();
         assertEquals(DHCPSERVER, lp.getDhcpServerAddress());
@@ -1167,7 +1160,7 @@
         assertNull(lp.getDhcpServerAddress());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testWakeOnLanSupported() {
         final LinkProperties lp = makeTestObject();
         assertTrue(lp.isWakeOnLanSupported());
@@ -1176,7 +1169,7 @@
         assertFalse(lp.isWakeOnLanSupported());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testCaptivePortalApiUrl() {
         final LinkProperties lp = makeTestObject();
         assertEquals(CAPPORT_API_URL, lp.getCaptivePortalApiUrl());
@@ -1185,7 +1178,7 @@
         assertNull(lp.getCaptivePortalApiUrl());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testCaptivePortalData() {
         final LinkProperties lp = makeTestObject();
         assertEquals(getCaptivePortalData(), lp.getCaptivePortalData());
@@ -1238,7 +1231,7 @@
         assertTrue(Ipv6.hasIpv6DnsServer());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testHasIpv4UnreachableDefaultRoute() {
         final LinkProperties lp = makeTestObject();
         assertFalse(lp.hasIpv4UnreachableDefaultRoute());
@@ -1249,7 +1242,7 @@
         assertFalse(lp.hasIpv6UnreachableDefaultRoute());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testHasIpv6UnreachableDefaultRoute() {
         final LinkProperties lp = makeTestObject();
         assertFalse(lp.hasIpv6UnreachableDefaultRoute());
diff --git a/tests/common/java/android/net/MatchAllNetworkSpecifierTest.kt b/tests/common/java/android/net/MatchAllNetworkSpecifierTest.kt
index 4a4859d..70adbd7 100644
--- a/tests/common/java/android/net/MatchAllNetworkSpecifierTest.kt
+++ b/tests/common/java/android/net/MatchAllNetworkSpecifierTest.kt
@@ -52,7 +52,6 @@
     }
 
     @Test
-    @IgnoreUpTo(Build.VERSION_CODES.Q)
     @IgnoreAfter(Build.VERSION_CODES.R)
     // Only run this test on Android R.
     // The method - satisfiedBy() has changed to canBeSatisfiedBy() starting from Android R, so the
diff --git a/tests/common/java/android/net/NattKeepalivePacketDataTest.kt b/tests/common/java/android/net/NattKeepalivePacketDataTest.kt
index e5806a6..1148eff 100644
--- a/tests/common/java/android/net/NattKeepalivePacketDataTest.kt
+++ b/tests/common/java/android/net/NattKeepalivePacketDataTest.kt
@@ -82,7 +82,7 @@
         dstPort: Int = NATT_PORT
     ) = NattKeepalivePacketData.nattKeepalivePacket(srcAddress, srcPort, dstAddress, dstPort)
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testConstructor() {
         assertFailsWith<InvalidPacketException>(
             "Dst port is not NATT port should cause exception") {
@@ -132,12 +132,12 @@
         assertEquals(TEST_ADDRV6, packet2.dstAddress)
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testParcel() {
         assertParcelingIsLossless(nattKeepalivePacket())
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testEquals() {
         assertEqualBothWays(nattKeepalivePacket(), nattKeepalivePacket())
         assertNotEquals(nattKeepalivePacket(dstAddress = TEST_SRC_ADDRV4), nattKeepalivePacket())
@@ -146,7 +146,7 @@
         assertNotEquals(nattKeepalivePacket(srcPort = TEST_PORT2), nattKeepalivePacket())
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testHashCode() {
         assertEquals(nattKeepalivePacket().hashCode(), nattKeepalivePacket().hashCode())
     }
diff --git a/tests/common/java/android/net/NetworkAgentConfigTest.kt b/tests/common/java/android/net/NetworkAgentConfigTest.kt
index c05cdbd..d640a73 100644
--- a/tests/common/java/android/net/NetworkAgentConfigTest.kt
+++ b/tests/common/java/android/net/NetworkAgentConfigTest.kt
@@ -16,19 +16,15 @@
 
 package android.net
 
-import android.os.Build
 import androidx.test.filters.SmallTest
 import androidx.test.runner.AndroidJUnit4
 import com.android.modules.utils.build.SdkLevel.isAtLeastS
 import com.android.modules.utils.build.SdkLevel.isAtLeastT
 import com.android.testutils.ConnectivityModuleTest
-import com.android.testutils.DevSdkIgnoreRule
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import com.android.testutils.assertParcelingIsLossless
 import org.junit.Assert.assertEquals
 import org.junit.Assert.assertFalse
 import org.junit.Assert.assertTrue
-import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
@@ -36,10 +32,7 @@
 @SmallTest
 @ConnectivityModuleTest
 class NetworkAgentConfigTest {
-    @Rule @JvmField
-    val ignoreRule = DevSdkIgnoreRule()
-
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testParcelNetworkAgentConfig() {
         val config = NetworkAgentConfig.Builder().apply {
             setExplicitlySelected(true)
@@ -58,7 +51,7 @@
         assertParcelingIsLossless(config)
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testBuilder() {
         val testExtraInfo = "mylegacyExtraInfo"
         val config = NetworkAgentConfig.Builder().apply {
diff --git a/tests/common/java/android/net/NetworkCapabilitiesTest.java b/tests/common/java/android/net/NetworkCapabilitiesTest.java
index bec9a4a..3a3459b 100644
--- a/tests/common/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/common/java/android/net/NetworkCapabilitiesTest.java
@@ -61,7 +61,6 @@
 import static android.net.NetworkCapabilities.TRANSPORT_WIFI_AWARE;
 import static android.os.Process.INVALID_UID;
 
-import static com.android.modules.utils.build.SdkLevel.isAtLeastR;
 import static com.android.modules.utils.build.SdkLevel.isAtLeastS;
 import static com.android.modules.utils.build.SdkLevel.isAtLeastT;
 import static com.android.modules.utils.build.SdkLevel.isAtLeastV;
@@ -382,10 +381,9 @@
             netCap.setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2));
             netCap.setUids(uids);
         }
-        if (isAtLeastR()) {
-            netCap.setOwnerUid(123);
-            netCap.setAdministratorUids(new int[] {5, 11});
-        }
+
+        netCap.setOwnerUid(123);
+        netCap.setAdministratorUids(new int[] {5, 11});
         assertParcelingIsLossless(netCap);
         netCap.setSSID(TEST_SSID);
         testParcelSane(netCap);
@@ -397,10 +395,8 @@
                 .addCapability(NET_CAPABILITY_INTERNET)
                 .addCapability(NET_CAPABILITY_EIMS)
                 .addCapability(NET_CAPABILITY_NOT_METERED);
-        if (isAtLeastR()) {
-            netCap.setRequestorPackageName("com.android.test");
-            netCap.setRequestorUid(9304);
-        }
+        netCap.setRequestorPackageName("com.android.test");
+        netCap.setRequestorUid(9304);
         assertParcelingIsLossless(netCap);
         netCap.setSSID(TEST_SSID);
         testParcelSane(netCap);
@@ -820,16 +816,12 @@
             assertTrue(nc2.hasForbiddenCapability(NET_CAPABILITY_NOT_ROAMING));
         }
 
-        if (isAtLeastR()) {
-            assertTrue(TEST_SSID.equals(nc2.getSsid()));
-        }
-
+        assertTrue(TEST_SSID.equals(nc2.getSsid()));
         nc1.setSSID(DIFFERENT_TEST_SSID);
         nc2.set(nc1);
         assertEquals(nc1, nc2);
-        if (isAtLeastR()) {
-            assertTrue(DIFFERENT_TEST_SSID.equals(nc2.getSsid()));
-        }
+        assertTrue(DIFFERENT_TEST_SSID.equals(nc2.getSsid()));
+
         if (isAtLeastS()) {
             nc1.setUids(uidRanges(10, 13));
         } else {
diff --git a/tests/common/java/android/net/NetworkProviderTest.kt b/tests/common/java/android/net/NetworkProviderTest.kt
index c6a7346..0d35960 100644
--- a/tests/common/java/android/net/NetworkProviderTest.kt
+++ b/tests/common/java/android/net/NetworkProviderTest.kt
@@ -39,6 +39,12 @@
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import com.android.testutils.DevSdkIgnoreRunner
 import com.android.testutils.TestableNetworkOfferCallback
+import java.util.UUID
+import java.util.concurrent.Executor
+import java.util.concurrent.RejectedExecutionException
+import kotlin.test.assertEquals
+import kotlin.test.assertNotEquals
+import kotlin.test.fail
 import org.junit.After
 import org.junit.Before
 import org.junit.Rule
@@ -47,12 +53,6 @@
 import org.mockito.Mockito.doReturn
 import org.mockito.Mockito.mock
 import org.mockito.Mockito.verifyNoMoreInteractions
-import java.util.UUID
-import java.util.concurrent.Executor
-import java.util.concurrent.RejectedExecutionException
-import kotlin.test.assertEquals
-import kotlin.test.assertNotEquals
-import kotlin.test.fail
 
 private const val DEFAULT_TIMEOUT_MS = 5000L
 private const val DEFAULT_NO_CALLBACK_TIMEOUT_MS = 200L
@@ -62,7 +62,6 @@
 private val PROVIDER_NAME = "NetworkProviderTest"
 
 @RunWith(DevSdkIgnoreRunner::class)
-@IgnoreUpTo(Build.VERSION_CODES.Q)
 @ConnectivityModuleTest
 class NetworkProviderTest {
     @Rule @JvmField
diff --git a/tests/common/java/android/net/NetworkSpecifierTest.kt b/tests/common/java/android/net/NetworkSpecifierTest.kt
index b960417..7edb474 100644
--- a/tests/common/java/android/net/NetworkSpecifierTest.kt
+++ b/tests/common/java/android/net/NetworkSpecifierTest.kt
@@ -15,21 +15,18 @@
  */
 package android.net
 
-import android.os.Build
 import androidx.test.filters.SmallTest
 import com.android.testutils.ConnectivityModuleTest
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import com.android.testutils.DevSdkIgnoreRunner
-import org.junit.Test
-import org.junit.runner.RunWith
 import kotlin.test.assertEquals
 import kotlin.test.assertFalse
 import kotlin.test.assertNotEquals
 import kotlin.test.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
 
 @SmallTest
 @RunWith(DevSdkIgnoreRunner::class)
-@IgnoreUpTo(Build.VERSION_CODES.Q)
 @ConnectivityModuleTest
 class NetworkSpecifierTest {
     private class TestNetworkSpecifier(
diff --git a/tests/common/java/android/net/NetworkStackTest.java b/tests/common/java/android/net/NetworkStackTest.java
index f8f9c72..13550f9 100644
--- a/tests/common/java/android/net/NetworkStackTest.java
+++ b/tests/common/java/android/net/NetworkStackTest.java
@@ -17,16 +17,11 @@
 
 import static org.junit.Assert.assertEquals;
 
-import android.os.Build;
 import android.os.IBinder;
 
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.testutils.DevSdkIgnoreRule;
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
-
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
@@ -34,16 +29,13 @@
 
 @RunWith(AndroidJUnit4.class)
 public class NetworkStackTest {
-    @Rule
-    public DevSdkIgnoreRule mDevSdkIgnoreRule = new DevSdkIgnoreRule();
-
     @Mock private IBinder mConnectorBinder;
 
     @Before public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testGetService() {
         NetworkStack.setServiceForTest(mConnectorBinder);
         assertEquals(NetworkStack.getService(), mConnectorBinder);
diff --git a/tests/common/java/android/net/NetworkTest.java b/tests/common/java/android/net/NetworkTest.java
index c102cb3..86d2463 100644
--- a/tests/common/java/android/net/NetworkTest.java
+++ b/tests/common/java/android/net/NetworkTest.java
@@ -161,8 +161,7 @@
         assertEquals(16290598925L, three.getNetworkHandle());
     }
 
-    // getNetId() did not exist in Q
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testGetNetId() {
         assertEquals(1234, new Network(1234).getNetId());
         assertEquals(2345, new Network(2345, true).getNetId());
diff --git a/tests/common/java/android/net/RouteInfoTest.java b/tests/common/java/android/net/RouteInfoTest.java
index 5b28b84..154dc4c 100644
--- a/tests/common/java/android/net/RouteInfoTest.java
+++ b/tests/common/java/android/net/RouteInfoTest.java
@@ -31,17 +31,11 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.os.Build;
-
-import androidx.core.os.BuildCompat;
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.testutils.ConnectivityModuleTest;
-import com.android.testutils.DevSdkIgnoreRule;
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -53,9 +47,6 @@
 @SmallTest
 @ConnectivityModuleTest
 public class RouteInfoTest {
-    @Rule
-    public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule();
-
     private static final int INVALID_ROUTE_TYPE = -1;
 
     private InetAddress Address(String addr) {
@@ -66,11 +57,6 @@
         return new IpPrefix(prefix);
     }
 
-    private static boolean isAtLeastR() {
-        // BuildCompat.isAtLeastR is documented to return false on release SDKs (including R)
-        return Build.VERSION.SDK_INT > Build.VERSION_CODES.Q || BuildCompat.isAtLeastR();
-    }
-
     @Test
     public void testConstructor() {
         RouteInfo r;
@@ -204,130 +190,108 @@
         assertTrue(r.isDefaultRoute());
         assertTrue(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
+
 
         r = new RouteInfo(Prefix("::/0"), Address("::"), "wlan0");
         assertFalse(r.isHostRoute());
         assertTrue(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertTrue(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("192.0.2.0/24"), null, "wlan0");
         assertFalse(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("2001:db8::/48"), null, "wlan0");
         assertFalse(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("192.0.2.0/32"), Address("0.0.0.0"), "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("2001:db8::/128"), Address("::"), "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("192.0.2.0/32"), null, "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("2001:db8::/128"), null, "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("::/128"), Address("fe80::"), "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("0.0.0.0/32"), Address("192.0.2.1"), "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(Prefix("0.0.0.0/32"), Address("192.0.2.1"), "wlan0");
         assertTrue(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE);
         assertFalse(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertTrue(r.isIPv4UnreachableDefault());
-            assertFalse(r.isIPv6UnreachableDefault());
-        }
+        assertTrue(r.isIPv4UnreachableDefault());
+        assertFalse(r.isIPv6UnreachableDefault());
 
         r = new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE);
         assertFalse(r.isHostRoute());
         assertFalse(r.isDefaultRoute());
         assertFalse(r.isIPv4Default());
         assertFalse(r.isIPv6Default());
-        if (isAtLeastR()) {
-            assertFalse(r.isIPv4UnreachableDefault());
-            assertTrue(r.isIPv6UnreachableDefault());
-        }
+        assertFalse(r.isIPv4UnreachableDefault());
+        assertTrue(r.isIPv6UnreachableDefault());
     }
 
     @Test
@@ -376,14 +340,14 @@
         assertParcelingIsLossless(r);
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testMtuParceling() {
         final RouteInfo r = new RouteInfo(Prefix("ff02::1/128"), Address("2001:db8::"), "testiface",
                 RTN_UNREACHABLE, 1450 /* mtu */);
         assertParcelingIsLossless(r);
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testMtu() {
         RouteInfo r;
         r = new RouteInfo(Prefix("0.0.0.0/0"), Address("0.0.0.0"), "wlan0",
@@ -394,7 +358,7 @@
         assertEquals(0, r.getMtu());
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     public void testRouteKey() {
         RouteInfo.RouteKey k1, k2;
         // Only prefix, null gateway and null interface
diff --git a/tests/common/java/android/net/netstats/NetworkStatsApiTest.kt b/tests/common/java/android/net/netstats/NetworkStatsApiTest.kt
index c90b1aa..8cef6aa 100644
--- a/tests/common/java/android/net/netstats/NetworkStatsApiTest.kt
+++ b/tests/common/java/android/net/netstats/NetworkStatsApiTest.kt
@@ -28,25 +28,18 @@
 import android.net.NetworkStats.SET_DEFAULT
 import android.net.NetworkStats.SET_FOREGROUND
 import android.net.NetworkStats.TAG_NONE
-import android.os.Build
 import androidx.test.filters.SmallTest
-import com.android.testutils.DevSdkIgnoreRule
 import com.android.testutils.assertNetworkStatsEquals
 import com.android.testutils.assertParcelingIsLossless
+import kotlin.test.assertEquals
 import org.junit.Before
-import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.JUnit4
-import kotlin.test.assertEquals
 
 @RunWith(JUnit4::class)
 @SmallTest
 class NetworkStatsApiTest {
-    @Rule
-    @JvmField
-    val ignoreRule = DevSdkIgnoreRule(ignoreClassUpTo = Build.VERSION_CODES.Q)
-
     private val testStatsEmpty = NetworkStats(0L, 0)
 
     // Note that these variables need to be initialized outside of constructor, initialize
diff --git a/tests/common/java/android/net/util/SocketUtilsTest.kt b/tests/common/java/android/net/util/SocketUtilsTest.kt
index aaf97f3..520cf07 100644
--- a/tests/common/java/android/net/util/SocketUtilsTest.kt
+++ b/tests/common/java/android/net/util/SocketUtilsTest.kt
@@ -16,7 +16,6 @@
 
 package android.net.util
 
-import android.os.Build
 import android.system.NetlinkSocketAddress
 import android.system.Os
 import android.system.OsConstants.AF_INET
@@ -27,13 +26,10 @@
 import android.system.PacketSocketAddress
 import androidx.test.filters.SmallTest
 import androidx.test.runner.AndroidJUnit4
-import com.android.testutils.DevSdkIgnoreRule
-import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
 import org.junit.Assert.assertEquals
 import org.junit.Assert.assertFalse
 import org.junit.Assert.assertTrue
 import org.junit.Assert.fail
-import org.junit.Rule
 import org.junit.Test
 import org.junit.runner.RunWith
 
@@ -44,9 +40,6 @@
 @RunWith(AndroidJUnit4::class)
 @SmallTest
 class SocketUtilsTest {
-    @Rule @JvmField
-    val ignoreRule = DevSdkIgnoreRule()
-
     @Test
     fun testMakeNetlinkSocketAddress() {
         val nlAddress = SocketUtils.makeNetlinkSocketAddress(TEST_PORT, RTMGRP_NEIGH)
@@ -67,7 +60,7 @@
         assertTrue("Not PacketSocketAddress object", pkAddress2 is PacketSocketAddress)
     }
 
-    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    @Test
     fun testMakePacketSocketAddress() {
         val pkAddress = SocketUtils.makePacketSocketAddress(
                 ETH_P_ALL, TEST_INDEX, ByteArray(6) { FF_BYTE })
diff --git a/tests/unit/java/com/android/server/BpfNetMapsTest.java b/tests/unit/java/com/android/server/BpfNetMapsTest.java
index 1e08fcc..ea905d5 100644
--- a/tests/unit/java/com/android/server/BpfNetMapsTest.java
+++ b/tests/unit/java/com/android/server/BpfNetMapsTest.java
@@ -161,7 +161,6 @@
         doReturn(TEST_IF_INDEX).when(mDeps).getIfIndex(TEST_IF_NAME);
         doReturn(TEST_IF_NAME).when(mDeps).getIfName(TEST_IF_INDEX);
         doReturn(0).when(mDeps).synchronizeKernelRCU();
-        BpfNetMaps.setEnableJavaBpfMapForTest(true /* enable */);
         BpfNetMaps.setConfigurationMapForTest(mConfigurationMap);
         mConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(0));
         mConfigurationMap.updateEntry(
diff --git a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
index 3a76ad0..235f7de 100644
--- a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
+++ b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
@@ -38,10 +38,7 @@
 import android.os.Build
 import com.android.testutils.DevSdkIgnoreRule
 import com.android.testutils.DevSdkIgnoreRunner
-import com.android.testutils.RecorderCallback.CallbackEntry.Available
-import com.android.testutils.RecorderCallback.CallbackEntry.BlockedStatus
-import com.android.testutils.RecorderCallback.CallbackEntry.CapabilitiesChanged
-import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged
+import com.android.testutils.RecorderCallback.CallbackEntry.LocalInfoChanged
 import com.android.testutils.RecorderCallback.CallbackEntry.Lost
 import com.android.testutils.TestableNetworkCallback
 import org.junit.Test
@@ -114,10 +111,7 @@
                 .build(),
                 lnc = LocalNetworkConfig.Builder().build())
         agent.connect()
-        cb.expect<Available>(agent.network)
-        cb.expect<CapabilitiesChanged>(agent.network)
-        cb.expect<LinkPropertiesChanged>(agent.network)
-        cb.expect<BlockedStatus>(agent.network)
+        cb.expectAvailableCallbacks(agent.network, validated = false)
         agent.sendNetworkCapabilities(NetworkCapabilities.Builder().build())
         cb.expect<Lost>(agent.network)
 
@@ -125,10 +119,7 @@
                 .build(),
                 lnc = null)
         agent2.connect()
-        cb.expect<Available>(agent2.network)
-        cb.expect<CapabilitiesChanged>(agent2.network)
-        cb.expect<LinkPropertiesChanged>(agent2.network)
-        cb.expect<BlockedStatus>(agent2.network)
+        cb.expectAvailableCallbacks(agent2.network, validated = false)
         agent2.sendNetworkCapabilities(NetworkCapabilities.Builder()
                 .addCapability(NET_CAPABILITY_LOCAL_NETWORK)
                 .build())
@@ -153,10 +144,11 @@
         )
         localAgent.connect()
 
-        cb.expect<Available>(localAgent.network)
-        cb.expect<CapabilitiesChanged>(localAgent.network)
-        cb.expect<LinkPropertiesChanged>(localAgent.network)
-        cb.expect<BlockedStatus>(localAgent.network)
+        cb.expectAvailableCallbacks(localAgent.network, validated = false)
+
+        val wifiAgent = Agent(score = keepScore(), lp = lp("wifi0"),
+                nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
+        wifiAgent.connect()
 
         val newLnc = LocalNetworkConfig.Builder()
                 .setUpstreamSelector(NetworkRequest.Builder()
@@ -165,6 +157,21 @@
                 .build()
         localAgent.sendLocalNetworkConfig(newLnc)
 
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgent.network
+        }
+
+        localAgent.sendLocalNetworkConfig(LocalNetworkConfig.Builder().build())
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
+        localAgent.sendLocalNetworkConfig(newLnc)
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgent.network
+        }
+
+        wifiAgent.disconnect()
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
         localAgent.disconnect()
     }
 
@@ -204,6 +211,9 @@
         wifiAgent.connect()
 
         cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgent.network
+        }
 
         clearInvocations(netd)
         val inOrder = inOrder(netd)
@@ -218,6 +228,7 @@
         wifiAgent2.connect()
 
         cb.expectAvailableCallbacks(wifiAgent2.network, validated = false)
+        cb.expect<LocalInfoChanged> { it.info.upstreamNetwork == wifiAgent2.network }
         cb.expect<Lost> { it.network == wifiAgent.network }
 
         inOrder.verify(netd).ipfwdAddInterfaceForward("local0", wifiIface2)
@@ -252,7 +263,10 @@
                 nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
         wifiAgent.connect()
 
-        cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+        cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgent.network
+        }
 
         clearInvocations(netd)
         wifiAgent.unregisterAfterReplacement(TIMEOUT_MS.toInt())
@@ -260,6 +274,7 @@
         verify(netd).networkDestroy(wifiAgent.network.netId)
         verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi0")
 
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
         cb.expect<Lost> { it.network == wifiAgent.network }
     }
 
@@ -294,7 +309,12 @@
         val wifiAgent = Agent(lp = lp("wifi0"), nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
         wifiAgent.connect()
 
-        cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+        cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+        listOf(cb, localCb).forEach {
+            it.expect<LocalInfoChanged>(localAgent.network) {
+                it.info.upstreamNetwork == wifiAgent.network
+            }
+        }
 
         verify(netd).ipfwdAddInterfaceForward("local0", "wifi0")
 
@@ -303,8 +323,10 @@
         val localAgent2 = Agent(nc = localNc, lp = lp("local0"), lnc = lnc, score = localScore)
         localAgent2.connect()
 
-        localCb.expectAvailableCallbacks(localAgent2.network, validated = false)
-        cb.expectAvailableCallbacks(localAgent2.network, validated = false)
+        localCb.expectAvailableCallbacks(localAgent2.network,
+                validated = false, upstream = wifiAgent.network)
+        cb.expectAvailableCallbacks(localAgent2.network,
+                validated = false, upstream = wifiAgent.network)
         cb.expect<Lost> { it.network == localAgent.network }
     }
 
@@ -316,9 +338,11 @@
 
         val wifiAgent = Agent(lp = lp("wifi0"), nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
         wifiAgent.connect()
-        cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+        cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
 
-        // Set up a local agent that should forward its traffic to the best wifi upstream.
+        // Unregister wifi pending replacement, then set up a local agent that would have
+        // this network as its upstream.
+        wifiAgent.unregisterAfterReplacement(LONG_TIMEOUT_MS)
         val localAgent = Agent(nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_LOCAL_NETWORK),
                 lp = lp("local0"),
                 lnc = LocalNetworkConfig.Builder()
@@ -331,14 +355,18 @@
                         .build())
         )
 
-        // ...but destroy the wifi agent before connecting it
-        wifiAgent.unregisterAfterReplacement(LONG_TIMEOUT_MS)
-
+        // Connect the local agent. The zombie wifi is its upstream, but the stack doesn't
+        // tell netd to add the forward since the wifi0 interface has gone.
         localAgent.connect()
-        cb.expectAvailableCallbacks(localAgent.network, validated = false)
+        cb.expectAvailableCallbacks(localAgent.network,
+                validated = false, upstream = wifiAgent.network)
 
-        verify(netd).ipfwdAddInterfaceForward("local0", "wifi0")
-        verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi0")
+        verify(netd, never()).ipfwdAddInterfaceForward("local0", "wifi0")
+
+        // Disconnect wifi without a replacement. Expect an update with upstream null.
+        wifiAgent.disconnect()
+        verify(netd, never()).ipfwdAddInterfaceForward("local0", "wifi0")
+        cb.expect<LocalInfoChanged> { it.info.upstreamNetwork == null }
     }
 
     @Test
@@ -366,19 +394,34 @@
         val wifiAgentDun = Agent(score = keepScore(), lp = lp("wifi1"),
                 nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
 
+        val cb = TestableNetworkCallback()
+        cm.registerNetworkCallback(NetworkRequest.Builder()
+                .addCapability(NET_CAPABILITY_LOCAL_NETWORK)
+                .build(),
+                cb)
+        cb.expectAvailableCallbacks(localAgent.network, validated = false)
+
         val inOrder = inOrder(netd)
         inOrder.verify(netd, never()).ipfwdAddInterfaceForward(any(), any())
+        cb.assertNoCallback()
 
         wifiAgent.connect()
         inOrder.verify(netd, never()).ipfwdAddInterfaceForward(any(), any())
+        cb.assertNoCallback()
 
         cellAgentDun.connect()
         inOrder.verify(netd).ipfwdEnableForwarding(any())
         inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "cell0")
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == cellAgentDun.network
+        }
 
         wifiAgentDun.connect()
         inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "cell0")
         inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi1")
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgentDun.network
+        }
 
         // Make sure sending the same config again doesn't do anything
         repeat(5) {
@@ -387,6 +430,10 @@
         inOrder.verifyNoMoreInteractions()
 
         wifiAgentDun.disconnect()
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == cellAgentDun.network
+        }
         inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi1")
         // This can take a little bit of time because it needs to wait for the rematch
         inOrder.verify(netd, timeout(MEDIUM_TIMEOUT_MS)).ipfwdAddInterfaceForward("local0", "cell0")
@@ -394,15 +441,35 @@
         cellAgentDun.disconnect()
         inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "cell0")
         inOrder.verify(netd).ipfwdDisableForwarding(any())
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
 
         val wifiAgentDun2 = Agent(score = keepScore(), lp = lp("wifi2"),
                 nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
         wifiAgentDun2.connect()
         inOrder.verify(netd).ipfwdEnableForwarding(any())
         inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi2")
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgentDun2.network
+        }
 
-        localAgent.disconnect()
+        wifiAgentDun2.disconnect()
         inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi2")
         inOrder.verify(netd).ipfwdDisableForwarding(any())
+        cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
+        val wifiAgentDun3 = Agent(score = keepScore(), lp = lp("wifi3"),
+                nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
+        wifiAgentDun3.connect()
+        inOrder.verify(netd).ipfwdEnableForwarding(any())
+        inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi3")
+        cb.expect<LocalInfoChanged>(localAgent.network) {
+            it.info.upstreamNetwork == wifiAgentDun3.network
+        }
+
+        localAgent.disconnect()
+        inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi3")
+        inOrder.verify(netd).ipfwdDisableForwarding(any())
+        cb.expect<Lost>(localAgent.network)
+        cb.assertNoCallback()
     }
 }
diff --git a/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java b/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
index bda9373..520acbd 100644
--- a/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
+++ b/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
@@ -43,9 +43,10 @@
     /** @hide */
     public static final int LENGTH_TIMESTAMP = Long.BYTES;
 
-    private static final long TICKS_UPPER_BOUND = 0x8000;
+    private static final int TICKS_UPPER_BOUND = 0x8000;
 
-    private final Instant mInstant;
+    private final long mSeconds;
+    private final int mTicks;
     private final boolean mIsAuthoritativeSource;
 
     /**
@@ -55,18 +56,34 @@
      * {@link instant#getNano()} based on frequency of 32768 Hz, and {@code isAuthoritativeSource}
      * is set to {@code true}.
      *
+     * <p>Note that this conversion can lose precision and a value returned by {@link #toInstant}
+     * may not equal exactly the {@code instant}.
+     *
      * @throws IllegalArgumentException if {@code instant.getEpochSecond()} is larger than {@code
      *     0xffffffffffffL}
+     * @see toInstant
      */
     @NonNull
     public static OperationalDatasetTimestamp fromInstant(@NonNull Instant instant) {
-        return new OperationalDatasetTimestamp(instant, /* isAuthoritativeSource= */ true);
+        int ticks = getRoundedTicks(instant.getNano());
+        long seconds = instant.getEpochSecond() + ticks / TICKS_UPPER_BOUND;
+        // the rounded ticks can be 0x8000 if instant.getNano() >= 999984742
+        ticks = ticks % TICKS_UPPER_BOUND;
+        return new OperationalDatasetTimestamp(seconds, ticks, true /* isAuthoritativeSource */);
     }
 
-    /** Converts this {@link OperationalDatasetTimestamp} object to an {@link Instant}. */
+    /**
+     * Converts this {@link OperationalDatasetTimestamp} object to an {@link Instant}.
+     *
+     * <p>Note that the return value may not equal exactly the {@code instant} if this object is
+     * created with {@link #fromInstant}.
+     *
+     * @see fromInstant
+     */
     @NonNull
     public Instant toInstant() {
-        return mInstant;
+        long nanos = Math.round((double) mTicks * 1000000000L / TICKS_UPPER_BOUND);
+        return Instant.ofEpochSecond(mSeconds, nanos);
     }
 
     /**
@@ -100,10 +117,7 @@
     public byte[] toTlvValue() {
         byte[] tlv = new byte[LENGTH_TIMESTAMP];
         ByteBuffer buffer = ByteBuffer.wrap(tlv);
-        long encodedValue =
-                (mInstant.getEpochSecond() << 16)
-                        | ((mInstant.getNano() * TICKS_UPPER_BOUND / 1000000000L) << 1)
-                        | (mIsAuthoritativeSource ? 1 : 0);
+        long encodedValue = (mSeconds << 16) | (mTicks << 1) | (mIsAuthoritativeSource ? 1 : 0);
         buffer.putLong(encodedValue);
         return tlv;
     }
@@ -125,10 +139,6 @@
             @IntRange(from = 0x0, to = 0xffffffffffffL) long seconds,
             @IntRange(from = 0x0, to = 0x7fff) int ticks,
             boolean isAuthoritativeSource) {
-        this(makeInstant(seconds, ticks), isAuthoritativeSource);
-    }
-
-    private static Instant makeInstant(long seconds, int ticks) {
         checkArgument(
                 seconds >= 0 && seconds <= 0xffffffffffffL,
                 "seconds exceeds allowed range (seconds = %d,"
@@ -138,25 +148,8 @@
                 ticks >= 0 && ticks <= 0x7fff,
                 "ticks exceeds allowed ranged (ticks = %d, allowedRange" + " = [0x0, 0x7fff])",
                 ticks);
-        long nanos = Math.round((double) ticks * 1000000000L / TICKS_UPPER_BOUND);
-        return Instant.ofEpochSecond(seconds, nanos);
-    }
-
-    /**
-     * Creates new {@link OperationalDatasetTimestamp} object.
-     *
-     * @throws IllegalArgumentException if {@code instant.getEpochSecond()} is larger than {@code
-     *     0xffffffffffffL}
-     */
-    private OperationalDatasetTimestamp(@NonNull Instant instant, boolean isAuthoritativeSource) {
-        requireNonNull(instant, "instant cannot be null");
-        long seconds = instant.getEpochSecond();
-        checkArgument(
-                seconds >= 0 && seconds <= 0xffffffffffffL,
-                "instant seconds exceeds allowed range (seconds = %d, allowedRange = [0x0,"
-                        + " 0xffffffffffffL])",
-                seconds);
-        mInstant = instant;
+        mSeconds = seconds;
+        mTicks = ticks;
         mIsAuthoritativeSource = isAuthoritativeSource;
     }
 
@@ -171,13 +164,12 @@
 
     /** Returns the seconds portion of the timestamp. */
     public @IntRange(from = 0x0, to = 0xffffffffffffL) long getSeconds() {
-        return mInstant.getEpochSecond() + getRoundedTicks(mInstant.getNano()) / TICKS_UPPER_BOUND;
+        return mSeconds;
     }
 
     /** Returns the ticks portion of the timestamp. */
     public @IntRange(from = 0x0, to = 0x7fff) int getTicks() {
-        // the rounded ticks can be 0x8000 if mInstant.getNano() >= 999984742
-        return (int) (getRoundedTicks(mInstant.getNano()) % TICKS_UPPER_BOUND);
+        return mTicks;
     }
 
     /** Returns {@code true} if the timestamp comes from an authoritative source. */
@@ -208,13 +200,14 @@
             return false;
         } else {
             OperationalDatasetTimestamp otherTimestamp = (OperationalDatasetTimestamp) other;
-            return mInstant.equals(otherTimestamp.mInstant)
+            return mSeconds == otherTimestamp.mSeconds
+                    && mTicks == otherTimestamp.mTicks
                     && mIsAuthoritativeSource == otherTimestamp.mIsAuthoritativeSource;
         }
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(mInstant, mIsAuthoritativeSource);
+        return Objects.hash(mSeconds, mTicks, mIsAuthoritativeSource);
     }
 }
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkController.java b/thread/framework/java/android/net/thread/ThreadNetworkController.java
index 7575757..fc77b1a 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkController.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkController.java
@@ -31,7 +31,7 @@
  * Provides the primary API for controlling all aspects of a Thread network.
  *
  * @hide
-*/
+ */
 @FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
 @SystemApi
 public final class ThreadNetworkController {
diff --git a/thread/scripts/make-pretty.sh b/thread/scripts/make-pretty.sh
new file mode 100755
index 0000000..e4bd459
--- /dev/null
+++ b/thread/scripts/make-pretty.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+
+SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
+
+GOOGLE_JAVA_FORMAT=$SCRIPT_DIR/../../../../../prebuilts/tools/common/google-java-format/google-java-format
+
+$GOOGLE_JAVA_FORMAT --aosp -i $(find $SCRIPT_DIR/../ -name "*.java")
diff --git a/thread/tests/cts/Android.bp b/thread/tests/cts/Android.bp
index ce770e0..b75b8e6 100644
--- a/thread/tests/cts/Android.bp
+++ b/thread/tests/cts/Android.bp
@@ -44,6 +44,7 @@
     libs: [
         "android.test.base",
         "android.test.runner",
+        "framework-connectivity-flagged-apis"
     ],
     // Test coverage system runs on different devices. Need to
     // compile for all architectures.
diff --git a/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java b/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
index 32063fc..2244a89 100644
--- a/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
+++ b/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
@@ -27,6 +27,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.time.Instant;
+
 /** Unit tests for {@link OperationalDatasetTimestamp}. */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
@@ -58,4 +60,22 @@
 
         assertThat(timestamp2).isEqualTo(timestamp1);
     }
+
+    @Test
+    public void toTlvValue_timestampFromInstant_conversionIsLossLess() {
+        // This results in ticks = 999938900 / 1000000000 * 32768 = 32765.9978752 ~= 32766.
+        // The ticks 32766 is then converted back to 999938964.84375 ~= 999938965 nanoseconds.
+        // A wrong implementation may save Instant.getNano() and compare against the nanoseconds
+        // and results in precision loss when converted between OperationalDatasetTimestamp and the
+        // TLV values.
+        OperationalDatasetTimestamp timestamp1 =
+                OperationalDatasetTimestamp.fromInstant(Instant.ofEpochSecond(100, 999938900));
+
+        OperationalDatasetTimestamp timestamp2 =
+                OperationalDatasetTimestamp.fromTlvValue(timestamp1.toTlvValue());
+
+        assertThat(timestamp2.getSeconds()).isEqualTo(100);
+        assertThat(timestamp2.getTicks()).isEqualTo(32766);
+        assertThat(timestamp2).isEqualTo(timestamp1);
+    }
 }