Merge "Move 'isProbing' field from RecordInfo to ServiceRegistration" 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/apex/Android.bp b/Tethering/apex/Android.bp
index ee44f3c..de9017a 100644
--- a/Tethering/apex/Android.bp
+++ b/Tethering/apex/Android.bp
@@ -80,6 +80,7 @@
         first: {
             jni_libs: [
                 "libservice-connectivity",
+                "libservice-thread-jni",
                 "libandroid_net_connectivity_com_android_net_module_util_jni",
             ],
             native_shared_libs: [
diff --git a/Tethering/common/TetheringLib/api/lint-baseline.txt b/Tethering/common/TetheringLib/api/lint-baseline.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Tethering/common/TetheringLib/api/lint-baseline.txt
diff --git a/Tethering/common/TetheringLib/api/module-lib-lint-baseline.txt b/Tethering/common/TetheringLib/api/module-lib-lint-baseline.txt
new file mode 100644
index 0000000..1d09598
--- /dev/null
+++ b/Tethering/common/TetheringLib/api/module-lib-lint-baseline.txt
@@ -0,0 +1,23 @@
+// Baseline format: 1.0
+BroadcastBehavior: android.net.TetheringManager#ACTION_TETHER_STATE_CHANGED:
+    Field 'ACTION_TETHER_STATE_CHANGED' is missing @BroadcastBehavior
+
+
+RequiresPermission: android.net.TetheringManager#requestLatestTetheringEntitlementResult(int, boolean, java.util.concurrent.Executor, android.net.TetheringManager.OnTetheringEntitlementResultListener):
+    Method 'requestLatestTetheringEntitlementResult' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#startTethering(android.net.TetheringManager.TetheringRequest, java.util.concurrent.Executor, android.net.TetheringManager.StartTetheringCallback):
+    Method 'startTethering' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#startTethering(int, java.util.concurrent.Executor, android.net.TetheringManager.StartTetheringCallback):
+    Method 'startTethering' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#stopAllTethering():
+    Method 'stopAllTethering' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#stopTethering(int):
+    Method 'stopTethering' documentation mentions permissions already declared by @RequiresPermission
+
+
+SdkConstant: android.net.TetheringManager#ACTION_TETHER_STATE_CHANGED:
+    Field 'ACTION_TETHER_STATE_CHANGED' is missing @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+
+
+Todo: android.net.TetheringConstants:
+    Documentation mentions 'TODO'
diff --git a/Tethering/common/TetheringLib/api/system-lint-baseline.txt b/Tethering/common/TetheringLib/api/system-lint-baseline.txt
new file mode 100644
index 0000000..e678ce1
--- /dev/null
+++ b/Tethering/common/TetheringLib/api/system-lint-baseline.txt
@@ -0,0 +1,17 @@
+// Baseline format: 1.0
+BroadcastBehavior: android.net.TetheringManager#ACTION_TETHER_STATE_CHANGED:
+    Field 'ACTION_TETHER_STATE_CHANGED' is missing @BroadcastBehavior
+
+
+RequiresPermission: android.net.TetheringManager#requestLatestTetheringEntitlementResult(int, boolean, java.util.concurrent.Executor, android.net.TetheringManager.OnTetheringEntitlementResultListener):
+    Method 'requestLatestTetheringEntitlementResult' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#startTethering(android.net.TetheringManager.TetheringRequest, java.util.concurrent.Executor, android.net.TetheringManager.StartTetheringCallback):
+    Method 'startTethering' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#stopAllTethering():
+    Method 'stopAllTethering' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.TetheringManager#stopTethering(int):
+    Method 'stopTethering' documentation mentions permissions already declared by @RequiresPermission
+
+
+SdkConstant: android.net.TetheringManager#ACTION_TETHER_STATE_CHANGED:
+    Field 'ACTION_TETHER_STATE_CHANGED' is missing @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
diff --git a/Tethering/jni/onload.cpp b/Tethering/jni/onload.cpp
index ed80128..fd40d41 100644
--- a/Tethering/jni/onload.cpp
+++ b/Tethering/jni/onload.cpp
@@ -25,7 +25,6 @@
 int register_com_android_net_module_util_BpfMap(JNIEnv* env, char const* class_name);
 int register_com_android_net_module_util_TcUtils(JNIEnv* env, char const* class_name);
 int register_com_android_networkstack_tethering_BpfCoordinator(JNIEnv* env);
-int register_com_android_networkstack_tethering_BpfUtils(JNIEnv* env);
 int register_com_android_networkstack_tethering_util_TetheringUtils(JNIEnv* env);
 
 extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
diff --git a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
index 2b14a42..4bd7e6a 100644
--- a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
+++ b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
@@ -1597,10 +1597,8 @@
 
         @Override
         public int hashCode() {
-            // TODO: if this is ever used in production code, don't pass ifindices
-            // to Objects.hash() to avoid autoboxing overhead.
-            return Objects.hash(upstreamIfindex, downstreamIfindex, sourcePrefix, inDstMac,
-                    outSrcMac, outDstMac);
+            return 13 * upstreamIfindex + 41 * downstreamIfindex
+                    + Objects.hash(sourcePrefix, inDstMac, outSrcMac, outDstMac);
         }
 
         @Override
@@ -1725,9 +1723,8 @@
 
         @Override
         public int hashCode() {
-            // TODO: if this is ever used in production code, don't pass ifindices
-            // to Objects.hash() to avoid autoboxing overhead.
-            return Objects.hash(upstreamIfindex, downstreamIfindex, address, srcMac, dstMac);
+            return 13 * upstreamIfindex + 41 * downstreamIfindex
+                    + Objects.hash(address, srcMac, dstMac);
         }
 
         @Override
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 1c4a662..377da91 100644
--- a/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
+++ b/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
@@ -146,8 +146,6 @@
     private final TetheringManager mTm = mContext.getSystemService(TetheringManager.class);
     private final PackageManager mPackageManager = mContext.getPackageManager();
     private final CtsNetUtils mCtsNetUtils = new CtsNetUtils(mContext);
-    private final UiAutomation mUiAutomation =
-            InstrumentationRegistry.getInstrumentation().getUiAutomation();
 
     // Late initialization in setUp()
     private boolean mRunTests;
@@ -276,7 +274,6 @@
         } finally {
             mHandlerThread.quitSafely();
             mHandlerThread.join();
-            mUiAutomation.dropShellPermissionIdentity();
         }
     }
 
diff --git a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
index 98b624b..a7064e8 100644
--- a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
+++ b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
@@ -35,15 +35,9 @@
 import static android.net.ip.IpServer.STATE_TETHERED;
 import static android.net.ip.IpServer.STATE_UNAVAILABLE;
 import static android.net.ip.IpServer.getTetherableIpv6Prefixes;
-import static android.system.OsConstants.ETH_P_IPV6;
 
 import static com.android.modules.utils.build.SdkLevel.isAtLeastT;
 import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
-import static com.android.net.module.util.netlink.NetlinkConstants.RTM_DELNEIGH;
-import static com.android.net.module.util.netlink.NetlinkConstants.RTM_NEWNEIGH;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_FAILED;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_REACHABLE;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_STALE;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -57,7 +51,6 @@
 import static org.mockito.Matchers.anyBoolean;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
@@ -66,7 +59,6 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.timeout;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -83,8 +75,6 @@
 import android.net.MacAddress;
 import android.net.RouteInfo;
 import android.net.RoutingCoordinatorManager;
-import android.net.TetherOffloadRuleParcel;
-import android.net.TetherStatsParcel;
 import android.net.dhcp.DhcpServerCallbacks;
 import android.net.dhcp.DhcpServingParamsParcel;
 import android.net.dhcp.IDhcpEventCallbacks;
@@ -96,40 +86,17 @@
 import android.os.RemoteException;
 import android.os.test.TestLooper;
 import android.text.TextUtils;
-import android.util.ArrayMap;
-import android.util.ArraySet;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.modules.utils.build.SdkLevel;
-import com.android.net.module.util.BpfMap;
 import com.android.net.module.util.InterfaceParams;
-import com.android.net.module.util.NetworkStackConstants;
 import com.android.net.module.util.SdkUtil.LateSdk;
 import com.android.net.module.util.SharedLog;
-import com.android.net.module.util.Struct.S32;
-import com.android.net.module.util.bpf.Tether4Key;
-import com.android.net.module.util.bpf.Tether4Value;
-import com.android.net.module.util.bpf.TetherStatsKey;
-import com.android.net.module.util.bpf.TetherStatsValue;
-import com.android.net.module.util.ip.ConntrackMonitor;
 import com.android.net.module.util.ip.IpNeighborMonitor;
-import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
-import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEventConsumer;
 import com.android.networkstack.tethering.BpfCoordinator;
-import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
-import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
 import com.android.networkstack.tethering.PrivateAddressCoordinator;
-import com.android.networkstack.tethering.Tether6Value;
-import com.android.networkstack.tethering.TetherDevKey;
-import com.android.networkstack.tethering.TetherDevValue;
-import com.android.networkstack.tethering.TetherDownstream6Key;
-import com.android.networkstack.tethering.TetherLimitKey;
-import com.android.networkstack.tethering.TetherLimitValue;
-import com.android.networkstack.tethering.TetherUpstream6Key;
 import com.android.networkstack.tethering.TetheringConfiguration;
 import com.android.networkstack.tethering.metrics.TetheringMetrics;
 import com.android.networkstack.tethering.util.InterfaceSet;
@@ -143,18 +110,13 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
-import org.mockito.ArgumentMatcher;
 import org.mockito.Captor;
 import org.mockito.InOrder;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.mockito.verification.VerificationMode;
 
 import java.net.Inet4Address;
-import java.net.Inet6Address;
 import java.net.InetAddress;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
 
@@ -219,16 +181,8 @@
             new LateSdk<>(SdkLevel.isAtLeastS() ? mock(RoutingCoordinatorManager.class) : null);
     @Mock private NetworkStatsManager mStatsManager;
     @Mock private TetheringConfiguration mTetherConfig;
-    @Mock private ConntrackMonitor mConntrackMonitor;
     @Mock private TetheringMetrics mTetheringMetrics;
-    @Mock private BpfMap<Tether4Key, Tether4Value> mBpfDownstream4Map;
-    @Mock private BpfMap<Tether4Key, Tether4Value> mBpfUpstream4Map;
-    @Mock private BpfMap<TetherDownstream6Key, Tether6Value> mBpfDownstream6Map;
-    @Mock private BpfMap<TetherUpstream6Key, Tether6Value> mBpfUpstream6Map;
-    @Mock private BpfMap<TetherStatsKey, TetherStatsValue> mBpfStatsMap;
-    @Mock private BpfMap<TetherLimitKey, TetherLimitValue> mBpfLimitMap;
-    @Mock private BpfMap<TetherDevKey, TetherDevValue> mBpfDevMap;
-    @Mock private BpfMap<S32, S32> mBpfErrorMap;
+    @Mock private BpfCoordinator mBpfCoordinator;
 
     @Captor private ArgumentCaptor<DhcpServingParamsParcel> mDhcpParamsCaptor;
 
@@ -238,9 +192,6 @@
             ArgumentCaptor.forClass(LinkProperties.class);
     private IpServer mIpServer;
     private InterfaceConfigurationParcel mInterfaceConfiguration;
-    private NeighborEventConsumer mNeighborEventConsumer;
-    private BpfCoordinator mBpfCoordinator;
-    private BpfCoordinator.Dependencies mBpfDeps;
 
     private void initStateMachine(int interfaceType) throws Exception {
         initStateMachine(interfaceType, false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
@@ -262,22 +213,20 @@
             mInterfaceConfiguration.prefixLength = BLUETOOTH_DHCP_PREFIX_LENGTH;
         }
 
-        ArgumentCaptor<NeighborEventConsumer> neighborCaptor =
-                ArgumentCaptor.forClass(NeighborEventConsumer.class);
-        doReturn(mIpNeighborMonitor).when(mDependencies).getIpNeighborMonitor(any(), any(),
-                neighborCaptor.capture());
+        doReturn(mIpNeighborMonitor).when(mDependencies).getIpNeighborMonitor(any(), any(), any());
 
         when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(usingBpfOffload);
         when(mTetherConfig.useLegacyDhcpServer()).thenReturn(usingLegacyDhcp);
         when(mTetherConfig.getP2pLeasesSubnetPrefixLength()).thenReturn(P2P_SUBNET_PREFIX_LENGTH);
+        when(mBpfCoordinator.isUsingBpfOffload()).thenReturn(usingBpfOffload);
         mIpServer = createIpServer(interfaceType);
+        verify(mIpNeighborMonitor).start();
         mIpServer.start();
-        mNeighborEventConsumer = neighborCaptor.getValue();
 
         // Starting the state machine always puts us in a consistent state and notifies
         // the rest of the world that we've changed from an unknown to available state.
         mLooper.dispatchAll();
-        reset(mNetd, mCallback);
+        reset(mNetd, mCallback, mIpNeighborMonitor);
 
         when(mRaDaemon.start()).thenReturn(true);
     }
@@ -294,23 +243,17 @@
         initStateMachine(interfaceType, usingLegacyDhcp, usingBpfOffload);
         dispatchCommand(IpServer.CMD_TETHER_REQUESTED, STATE_TETHERED);
         if (upstreamIface != null) {
+            InterfaceParams interfaceParams = mDependencies.getInterfaceParams(upstreamIface);
+            assertNotNull("missing upstream interface: " + upstreamIface, interfaceParams);
             LinkProperties lp = new LinkProperties();
             lp.setInterfaceName(upstreamIface);
             lp.setLinkAddresses(upstreamAddresses);
             dispatchTetherConnectionChanged(upstreamIface, lp, 0);
-            if (usingBpfOffload && !lp.getLinkAddresses().isEmpty()) {
-                Set<IpPrefix> upstreamPrefixes = getTetherableIpv6Prefixes(lp.getLinkAddresses());
-                InterfaceParams interfaceParams = mDependencies.getInterfaceParams(upstreamIface);
-                assertNotNull("missing upstream interface: " + upstreamIface, interfaceParams);
-                verify(mBpfCoordinator).updateAllIpv6Rules(
-                        mIpServer, TEST_IFACE_PARAMS, interfaceParams.index, upstreamPrefixes);
-                verifyStartUpstreamIpv6Forwarding(null, interfaceParams.index, upstreamPrefixes);
-            } else {
-                verifyNoUpstreamIpv6ForwardingChange(null);
-            }
+            Set<IpPrefix> upstreamPrefixes = getTetherableIpv6Prefixes(lp.getLinkAddresses());
+            verify(mBpfCoordinator).updateAllIpv6Rules(
+                    mIpServer, TEST_IFACE_PARAMS, interfaceParams.index, upstreamPrefixes);
         }
-        reset(mCallback, mAddressCoordinator);
-        resetNetdBpfMapAndCoordinator();
+        reset(mNetd, mBpfCoordinator, mCallback, mAddressCoordinator);
         when(mAddressCoordinator.requestDownstreamAddress(any(), anyInt(),
                 anyBoolean())).thenReturn(mTestAddress);
     }
@@ -363,80 +306,6 @@
     private IpServer createIpServer(final int interfaceType) {
         mLooper = new TestLooper();
         mHandler = new Handler(mLooper.getLooper());
-        mBpfDeps = new BpfCoordinator.Dependencies() {
-                    @NonNull
-                    public Handler getHandler() {
-                        return mHandler;
-                    }
-
-                    @NonNull
-                    public INetd getNetd() {
-                        return mNetd;
-                    }
-
-                    @NonNull
-                    public NetworkStatsManager getNetworkStatsManager() {
-                        return mStatsManager;
-                    }
-
-                    @NonNull
-                    public SharedLog getSharedLog() {
-                        return mSharedLog;
-                    }
-
-                    @Nullable
-                    public TetheringConfiguration getTetherConfig() {
-                        return mTetherConfig;
-                    }
-
-                    @NonNull
-                    public ConntrackMonitor getConntrackMonitor(
-                            ConntrackMonitor.ConntrackEventConsumer consumer) {
-                        return mConntrackMonitor;
-                    }
-
-                    @Nullable
-                    public BpfMap<Tether4Key, Tether4Value> getBpfDownstream4Map() {
-                        return mBpfDownstream4Map;
-                    }
-
-                    @Nullable
-                    public BpfMap<Tether4Key, Tether4Value> getBpfUpstream4Map() {
-                        return mBpfUpstream4Map;
-                    }
-
-                    @Nullable
-                    public BpfMap<TetherDownstream6Key, Tether6Value> getBpfDownstream6Map() {
-                        return mBpfDownstream6Map;
-                    }
-
-                    @Nullable
-                    public BpfMap<TetherUpstream6Key, Tether6Value> getBpfUpstream6Map() {
-                        return mBpfUpstream6Map;
-                    }
-
-                    @Nullable
-                    public BpfMap<TetherStatsKey, TetherStatsValue> getBpfStatsMap() {
-                        return mBpfStatsMap;
-                    }
-
-                    @Nullable
-                    public BpfMap<TetherLimitKey, TetherLimitValue> getBpfLimitMap() {
-                        return mBpfLimitMap;
-                    }
-
-                    @Nullable
-                    public BpfMap<TetherDevKey, TetherDevValue> getBpfDevMap() {
-                        return mBpfDevMap;
-                    }
-
-                    @Nullable
-                    public BpfMap<S32, S32> getBpfErrorMap() {
-                        return mBpfErrorMap;
-                    }
-                };
-
-        mBpfCoordinator = spy(new BpfCoordinator(mBpfDeps));
         return new IpServer(IFACE_NAME, mHandler, interfaceType, mSharedLog, mNetd, mBpfCoordinator,
                 mRoutingCoordinatorManager, mCallback, mTetherConfig, mAddressCoordinator,
                 mTetheringMetrics, mDependencies);
@@ -886,346 +755,19 @@
         verify(mDependencies, never()).makeDhcpServer(any(), any(), any());
     }
 
-    private InetAddress addr(String addr) throws Exception {
-        return InetAddresses.parseNumericAddress(addr);
-    }
-
-    private void recvNewNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
-        mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_NEWNEIGH, ifindex, addr,
-                nudState, mac));
-        mLooper.dispatchAll();
-    }
-
-    private void recvDelNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
-        mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_DELNEIGH, ifindex, addr,
-                nudState, mac));
-        mLooper.dispatchAll();
-    }
-
-    /**
-     * Custom ArgumentMatcher for TetherOffloadRuleParcel. This is needed because generated stable
-     * AIDL classes don't have equals(), so we cannot just use eq(). A custom assert, such as:
-     *
-     * private void checkFooCalled(StableParcelable p, ...) {
-     *     ArgumentCaptor<FooParam> captor = ArgumentCaptor.forClass(FooParam.class);
-     *     verify(mMock).foo(captor.capture());
-     *     Foo foo = captor.getValue();
-     *     assertFooMatchesExpectations(foo);
-     * }
-     *
-     * almost works, but not quite. This is because if the code under test calls foo() twice, the
-     * first call to checkFooCalled() matches both the calls, putting both calls into the captor,
-     * and then fails with TooManyActualInvocations. It also makes it harder to use other mockito
-     * features such as never(), inOrder(), etc.
-     *
-     * This approach isn't great because if the match fails, the error message is unhelpful
-     * (actual: "android.net.TetherOffloadRuleParcel@8c827b0" or some such), but at least it does
-     * work.
-     *
-     * TODO: consider making the error message more readable by adding a method that catching the
-     * AssertionFailedError and throwing a new assertion with more details. See
-     * NetworkMonitorTest#verifyNetworkTested.
-     *
-     * See ConnectivityServiceTest#assertRoutesAdded for an alternative approach which solves the
-     * TooManyActualInvocations problem described above by forcing the caller of the custom assert
-     * method to specify all expected invocations in one call. This is useful when the stable
-     * parcelable class being asserted on has a corresponding Java object (eg., RouteInfo and
-     * RouteInfoParcelable), and the caller can just pass in a list of them. It not useful here
-     * because there is no such object.
-     */
-    private static class TetherOffloadRuleParcelMatcher implements
-            ArgumentMatcher<TetherOffloadRuleParcel> {
-        public final int upstreamIfindex;
-        public final InetAddress dst;
-        public final MacAddress dstMac;
-
-        TetherOffloadRuleParcelMatcher(int upstreamIfindex, InetAddress dst, MacAddress dstMac) {
-            this.upstreamIfindex = upstreamIfindex;
-            this.dst = dst;
-            this.dstMac = dstMac;
-        }
-
-        public boolean matches(TetherOffloadRuleParcel parcel) {
-            return upstreamIfindex == parcel.inputInterfaceIndex
-                    && (TEST_IFACE_PARAMS.index == parcel.outputInterfaceIndex)
-                    && Arrays.equals(dst.getAddress(), parcel.destination)
-                    && (128 == parcel.prefixLength)
-                    && Arrays.equals(TEST_IFACE_PARAMS.macAddr.toByteArray(), parcel.srcL2Address)
-                    && Arrays.equals(dstMac.toByteArray(), parcel.dstL2Address);
-        }
-
-        public String toString() {
-            return String.format("TetherOffloadRuleParcelMatcher(%d, %s, %s",
-                    upstreamIfindex, dst.getHostAddress(), dstMac);
-        }
-    }
-
-    @NonNull
-    private static TetherOffloadRuleParcel matches(
-            int upstreamIfindex, InetAddress dst, MacAddress dstMac) {
-        return argThat(new TetherOffloadRuleParcelMatcher(upstreamIfindex, dst, dstMac));
-    }
-
-    @NonNull
-    private static Ipv6DownstreamRule makeDownstreamRule(int upstreamIfindex,
-            @NonNull InetAddress dst, @NonNull MacAddress dstMac) {
-        return new Ipv6DownstreamRule(upstreamIfindex, TEST_IFACE_PARAMS.index,
-                (Inet6Address) dst, TEST_IFACE_PARAMS.macAddr, dstMac);
-    }
-
-    @NonNull
-    private static TetherDownstream6Key makeDownstream6Key(int upstreamIfindex,
-            @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst) {
-        return new TetherDownstream6Key(upstreamIfindex, upstreamMac, dst.getAddress());
-    }
-
-    @NonNull
-    private static Tether6Value makeDownstream6Value(@NonNull final MacAddress dstMac) {
-        return new Tether6Value(TEST_IFACE_PARAMS.index, dstMac,
-                TEST_IFACE_PARAMS.macAddr, ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
-    }
-
-    private static long prefixToLong(IpPrefix prefix) {
-        return ByteBuffer.wrap(prefix.getRawAddress()).getLong();
-    }
-
-    private <T> T verifyWithOrder(@Nullable InOrder inOrder, @NonNull T t) {
-        return verifyWithOrder(inOrder, t, times(1));
-    }
-
-    private <T> T verifyWithOrder(@Nullable InOrder inOrder, @NonNull T t, VerificationMode mode) {
-        if (inOrder != null) {
-            return inOrder.verify(t, mode);
-        } else {
-            return verify(t, mode);
-        }
-    }
-
-    private void verifyTetherOffloadRuleAdd(@Nullable InOrder inOrder, int upstreamIfindex,
-            @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
-            @NonNull final MacAddress dstMac) throws Exception {
-        if (mBpfDeps.isAtLeastS()) {
-            verifyWithOrder(inOrder, mBpfDownstream6Map).updateEntry(
-                    makeDownstream6Key(upstreamIfindex, upstreamMac, dst),
-                    makeDownstream6Value(dstMac));
-        } else {
-            verifyWithOrder(inOrder, mNetd).tetherOffloadRuleAdd(matches(upstreamIfindex, dst,
-                    dstMac));
-        }
-    }
-
-    private void verifyNeverTetherOffloadRuleAdd(int upstreamIfindex,
-            @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
-            @NonNull final MacAddress dstMac) throws Exception {
-        if (mBpfDeps.isAtLeastS()) {
-            verify(mBpfDownstream6Map, never()).updateEntry(
-                    makeDownstream6Key(upstreamIfindex, upstreamMac, dst),
-                    makeDownstream6Value(dstMac));
-        } else {
-            verify(mNetd, never()).tetherOffloadRuleAdd(matches(upstreamIfindex, dst, dstMac));
-        }
-    }
-
-    private void verifyNeverTetherOffloadRuleAdd() throws Exception {
-        if (mBpfDeps.isAtLeastS()) {
-            verify(mBpfDownstream6Map, never()).updateEntry(any(), any());
-        } else {
-            verify(mNetd, never()).tetherOffloadRuleAdd(any());
-        }
-    }
-
-    private void verifyTetherOffloadRuleRemove(@Nullable InOrder inOrder, int upstreamIfindex,
-            @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
-            @NonNull final MacAddress dstMac) throws Exception {
-        if (mBpfDeps.isAtLeastS()) {
-            verifyWithOrder(inOrder, mBpfDownstream6Map).deleteEntry(makeDownstream6Key(
-                    upstreamIfindex, upstreamMac, dst));
-        } else {
-            // |dstMac| is not required for deleting rules. Used bacause tetherOffloadRuleRemove
-            // uses a whole rule to be a argument.
-            // See system/netd/server/TetherController.cpp/TetherController#removeOffloadRule.
-            verifyWithOrder(inOrder, mNetd).tetherOffloadRuleRemove(matches(upstreamIfindex, dst,
-                    dstMac));
-        }
-    }
-
-    private void verifyNeverTetherOffloadRuleRemove() throws Exception {
-        if (mBpfDeps.isAtLeastS()) {
-            verify(mBpfDownstream6Map, never()).deleteEntry(any());
-        } else {
-            verify(mNetd, never()).tetherOffloadRuleRemove(any());
-        }
-    }
-
-    private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex,
-            @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
-        if (!mBpfDeps.isAtLeastS()) return;
-        ArrayMap<TetherUpstream6Key, Tether6Value> expected = new ArrayMap<>();
-        for (IpPrefix upstreamPrefix : upstreamPrefixes) {
-            long prefix64 = prefixToLong(upstreamPrefix);
-            final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
-                    TEST_IFACE_PARAMS.macAddr, prefix64);
-            final Tether6Value value = new Tether6Value(upstreamIfindex,
-                    MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS,
-                    ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
-            expected.put(key, value);
-        }
-        ArgumentCaptor<TetherUpstream6Key> keyCaptor =
-                ArgumentCaptor.forClass(TetherUpstream6Key.class);
-        ArgumentCaptor<Tether6Value> valueCaptor =
-                ArgumentCaptor.forClass(Tether6Value.class);
-        verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).insertEntry(
-                keyCaptor.capture(), valueCaptor.capture());
-        List<TetherUpstream6Key> keys = keyCaptor.getAllValues();
-        List<Tether6Value> values = valueCaptor.getAllValues();
-        ArrayMap<TetherUpstream6Key, Tether6Value> captured = new ArrayMap<>();
-        for (int i = 0; i < keys.size(); i++) {
-            captured.put(keys.get(i), values.get(i));
-        }
-        assertEquals(expected, captured);
-    }
-
-    private void verifyStopUpstreamIpv6Forwarding(@Nullable InOrder inOrder,
-            @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
-        if (!mBpfDeps.isAtLeastS()) return;
-        Set<TetherUpstream6Key> expected = new ArraySet<>();
-        for (IpPrefix upstreamPrefix : upstreamPrefixes) {
-            long prefix64 = prefixToLong(upstreamPrefix);
-            final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
-                    TEST_IFACE_PARAMS.macAddr, prefix64);
-            expected.add(key);
-        }
-        ArgumentCaptor<TetherUpstream6Key> keyCaptor =
-                ArgumentCaptor.forClass(TetherUpstream6Key.class);
-        verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).deleteEntry(
-                keyCaptor.capture());
-        assertEquals(expected, new ArraySet(keyCaptor.getAllValues()));
-    }
-
-    private void verifyNoUpstreamIpv6ForwardingChange(@Nullable InOrder inOrder) throws Exception {
-        if (!mBpfDeps.isAtLeastS()) return;
-        if (inOrder != null) {
-            inOrder.verify(mBpfUpstream6Map, never()).deleteEntry(any());
-            inOrder.verify(mBpfUpstream6Map, never()).insertEntry(any(), any());
-            inOrder.verify(mBpfUpstream6Map, never()).updateEntry(any(), any());
-        } else {
-            verify(mBpfUpstream6Map, never()).deleteEntry(any());
-            verify(mBpfUpstream6Map, never()).insertEntry(any(), any());
-            verify(mBpfUpstream6Map, never()).updateEntry(any(), any());
-        }
-    }
-
-    @NonNull
-    private static TetherStatsParcel buildEmptyTetherStatsParcel(int ifIndex) {
-        TetherStatsParcel parcel = new TetherStatsParcel();
-        parcel.ifIndex = ifIndex;
-        return parcel;
-    }
-
-    private void resetNetdBpfMapAndCoordinator() throws Exception {
-        reset(mNetd, mBpfDownstream6Map, mBpfUpstream6Map, mBpfCoordinator);
-        // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
-        // potentially crash the test) if the stats map is empty.
-        when(mNetd.tetherOffloadGetStats()).thenReturn(new TetherStatsParcel[0]);
-        when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX))
-                .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX));
-        when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX2))
-                .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX2));
-        // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
-        // potentially crash the test) if the stats map is empty.
-        final TetherStatsValue allZeros = new TetherStatsValue(0, 0, 0, 0, 0, 0);
-        when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX))).thenReturn(allZeros);
-        when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX2))).thenReturn(allZeros);
-    }
-
     @Test
-    public void addRemoveipv6ForwardingRules() throws Exception {
+    public void ipv6UpstreamInterfaceChanges() throws Exception {
         initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
                 false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
 
-        final int myIfindex = TEST_IFACE_PARAMS.index;
-        final int notMyIfindex = myIfindex - 1;
-
-        final InetAddress neighA = InetAddresses.parseNumericAddress("2001:db8::1");
-        final InetAddress neighB = InetAddresses.parseNumericAddress("2001:db8::2");
-        final InetAddress neighLL = InetAddresses.parseNumericAddress("fe80::1");
-        final InetAddress neighMC = InetAddresses.parseNumericAddress("ff02::1234");
-        final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
-        final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
-        final MacAddress macB = MacAddress.fromString("11:22:33:00:00:0b");
-
-        resetNetdBpfMapAndCoordinator();
-        verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
-        // TODO: Perhaps verify the interaction of tetherOffloadSetInterfaceQuota and
-        // tetherOffloadGetAndClearStats in netd while the rules are changed.
-
-        // Events on other interfaces are ignored.
-        recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
-        // Events on this interface are received and sent to BpfCoordinator.
-        recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
-        resetNetdBpfMapAndCoordinator();
-
-        recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
-        resetNetdBpfMapAndCoordinator();
-
-        // Link-local and multicast neighbors are ignored.
-        recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-        recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
-        // A neighbor that is no longer valid causes the rule to be removed.
-        // NUD_FAILED events do not have a MAC address.
-        recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
-        verify(mBpfCoordinator).removeIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macNull));
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macNull);
-        resetNetdBpfMapAndCoordinator();
-
-        // A neighbor that is deleted causes the rule to be removed.
-        recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
-        verify(mBpfCoordinator).removeIpv6DownstreamRule(
-                mIpServer,  makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macNull));
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macNull);
-        resetNetdBpfMapAndCoordinator();
-
         // Upstream interface changes result in updating the rules.
-        recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
-        recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
-        resetNetdBpfMapAndCoordinator();
-
-        InOrder inOrder = inOrder(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
         LinkProperties lp = new LinkProperties();
         lp.setInterfaceName(UPSTREAM_IFACE2);
         lp.setLinkAddresses(UPSTREAM_ADDRESSES);
         dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp, -1);
         verify(mBpfCoordinator).updateAllIpv6Rules(
                 mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
-        verifyTetherOffloadRuleRemove(inOrder,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
-        verifyTetherOffloadRuleRemove(inOrder,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
-        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
-        verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
-        verifyTetherOffloadRuleAdd(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
-        verifyTetherOffloadRuleAdd(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
-        verifyNoUpstreamIpv6ForwardingChange(inOrder);
-        resetNetdBpfMapAndCoordinator();
+        reset(mBpfCoordinator);
 
         // Upstream link addresses change result in updating the rules.
         LinkProperties lp2 = new LinkProperties();
@@ -1234,17 +776,7 @@
         dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, -1);
         verify(mBpfCoordinator).updateAllIpv6Rules(
                 mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
-        verifyTetherOffloadRuleRemove(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
-        verifyTetherOffloadRuleRemove(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
-        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
-        verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
-        verifyTetherOffloadRuleAdd(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
-        verifyTetherOffloadRuleAdd(inOrder,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
-        resetNetdBpfMapAndCoordinator();
+        reset(mBpfCoordinator);
 
         // When the upstream is lost, rules are removed.
         dispatchTetherConnectionChanged(null, null, 0);
@@ -1254,156 +786,51 @@
         // See dispatchTetherConnectionChanged.
         verify(mBpfCoordinator, times(2)).updateAllIpv6Rules(
                 mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
-        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES2);
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
-        // Upstream lost doesn't clear the downstream rules from BpfCoordinator.
-        // Do that here.
-        recvDelNeigh(myIfindex, neighA, NUD_STALE, macA);
-        recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
-        verify(mBpfCoordinator).removeIpv6DownstreamRule(
-                mIpServer,  makeDownstreamRule(NO_UPSTREAM, neighA, macNull));
-        verify(mBpfCoordinator).removeIpv6DownstreamRule(
-                mIpServer,  makeDownstreamRule(NO_UPSTREAM, neighB, macNull));
-        resetNetdBpfMapAndCoordinator();
+        reset(mBpfCoordinator);
 
-        // If the upstream is IPv4-only, no IPv6 rules are added to BPF map.
+        // If the upstream is IPv4-only, no rules are added.
         dispatchTetherConnectionChanged(UPSTREAM_IFACE);
-        resetNetdBpfMapAndCoordinator();
-        recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
-        verifyNoUpstreamIpv6ForwardingChange(null);
-        // Downstream rules are only added to BpfCoordinator but not BPF map.
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(NO_UPSTREAM, neighA, macA));
-        verifyNeverTetherOffloadRuleAdd();
-        verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+        verify(mBpfCoordinator, never()).updateAllIpv6Rules(
+                mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
+        reset(mBpfCoordinator);
 
-        // Rules can be added again once upstream IPv6 connectivity is available. The existing rules
-        // with an upstream of NO_UPSTREAM are reapplied.
+        // Rules are added again once upstream IPv6 connectivity is available.
         lp.setInterfaceName(UPSTREAM_IFACE);
         dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
-        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
-        recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
+        verify(mBpfCoordinator).updateAllIpv6Rules(
+                mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+        reset(mBpfCoordinator);
 
         // If upstream IPv6 connectivity is lost, rules are removed.
-        resetNetdBpfMapAndCoordinator();
         dispatchTetherConnectionChanged(UPSTREAM_IFACE, null, 0);
         verify(mBpfCoordinator).updateAllIpv6Rules(
                 mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
-        verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+        reset(mBpfCoordinator);
 
-        // When upstream IPv6 connectivity comes back, upstream rules are added and downstream rules
-        // are reapplied.
+        // When upstream IPv6 connectivity comes back, rules are added.
         lp.setInterfaceName(UPSTREAM_IFACE);
         dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
-        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
-        resetNetdBpfMapAndCoordinator();
+        verify(mBpfCoordinator).updateAllIpv6Rules(
+                mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+        reset(mBpfCoordinator);
 
         // When the downstream interface goes down, rules are removed.
         mIpServer.stop();
         mLooper.dispatchAll();
         verify(mBpfCoordinator).clearAllIpv6Rules(mIpServer);
-        verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
-        verify(mIpNeighborMonitor).stop();
-        resetNetdBpfMapAndCoordinator();
-    }
-
-    @Test
-    public void enableDisableUsingBpfOffload() throws Exception {
-        final int myIfindex = TEST_IFACE_PARAMS.index;
-        final InetAddress neigh = InetAddresses.parseNumericAddress("2001:db8::1");
-        final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
-        final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
-
-        // Expect that rules can be only added/removed when the BPF offload config is enabled.
-        // Note that the BPF offload disabled case is not a realistic test case. Because IP
-        // neighbor monitor doesn't start if BPF offload is disabled, there should have no
-        // neighbor event listening. This is used for testing the protection check just in case.
-        // TODO: Perhaps remove the BPF offload disabled case test once this check isn't needed
-        // anymore.
-
-        // [1] Enable BPF offload.
-        // A neighbor that is added or deleted causes the rule to be added or removed.
-        initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
-                false /* usingLegacyDhcp */, true /* usingBpfOffload */);
-        resetNetdBpfMapAndCoordinator();
-
-        recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
-        verify(mBpfCoordinator).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neigh, macA));
-        verifyTetherOffloadRuleAdd(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neigh, macA);
-        resetNetdBpfMapAndCoordinator();
-
-        recvDelNeigh(myIfindex, neigh, NUD_STALE, macA);
-        verify(mBpfCoordinator).removeIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neigh, macNull));
-        verifyTetherOffloadRuleRemove(null,
-                UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neigh, macNull);
-        resetNetdBpfMapAndCoordinator();
-
-        // Upstream IPv6 connectivity change causes upstream rules change.
-        LinkProperties lp2 = new LinkProperties();
-        lp2.setInterfaceName(UPSTREAM_IFACE2);
-        lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
-        dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, 0);
         verify(mBpfCoordinator).updateAllIpv6Rules(
-                mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
-        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
-        resetNetdBpfMapAndCoordinator();
-
-        // [2] Disable BPF offload.
-        // A neighbor that is added or deleted doesn’t cause the rule to be added or removed.
-        initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
-                false /* usingLegacyDhcp */, false /* usingBpfOffload */);
-        resetNetdBpfMapAndCoordinator();
-
-        recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
-        verifyNeverTetherOffloadRuleAdd();
-        resetNetdBpfMapAndCoordinator();
-
-        recvDelNeigh(myIfindex, neigh, NUD_STALE, macA);
-        verifyNeverTetherOffloadRuleRemove();
-        resetNetdBpfMapAndCoordinator();
-
-        // Upstream IPv6 connectivity change doesn't cause the rule to be added or removed.
-        dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, 0);
-        verifyNoUpstreamIpv6ForwardingChange(null);
-        verifyNeverTetherOffloadRuleRemove();
-        resetNetdBpfMapAndCoordinator();
+                mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
+        reset(mBpfCoordinator);
     }
 
     @Test
-    public void doesNotStartIpNeighborMonitorIfBpfOffloadDisabled() throws Exception {
+    public void stopNeighborMonitoringWhenInterfaceDown() throws Exception {
         initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
-                false /* usingLegacyDhcp */, false /* usingBpfOffload */);
+                false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
 
-        // IP neighbor monitor doesn't start if BPF offload is disabled.
-        verify(mIpNeighborMonitor, never()).start();
+        mIpServer.stop();
+        mLooper.dispatchAll();
+        verify(mIpNeighborMonitor).stop();
     }
 
     private LinkProperties buildIpv6OnlyLinkProperties(final String iface) {
@@ -1659,75 +1086,4 @@
     public void testDadProxyUpdates_EnabledAfterR() throws Exception {
         checkDadProxyEnabled(true);
     }
-
-    @Test
-    public void testSkipVirtualNetworkInBpf() throws Exception {
-        initTetheredStateMachine(TETHERING_BLUETOOTH, null);
-        final LinkProperties v6Only = new LinkProperties();
-        v6Only.setInterfaceName(IPSEC_IFACE);
-        dispatchTetherConnectionChanged(IPSEC_IFACE, v6Only, 0);
-
-        verify(mBpfCoordinator).maybeAttachProgram(IFACE_NAME, IPSEC_IFACE);
-        verify(mNetd).tetherAddForward(IFACE_NAME, IPSEC_IFACE);
-        verify(mNetd).ipfwdAddInterfaceForward(IFACE_NAME, IPSEC_IFACE);
-
-        final int myIfindex = TEST_IFACE_PARAMS.index;
-        final InetAddress neigh = InetAddresses.parseNumericAddress("2001:db8::1");
-        final MacAddress mac = MacAddress.fromString("00:00:00:00:00:0a");
-        recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, mac);
-        verify(mBpfCoordinator, never()).addIpv6DownstreamRule(
-                mIpServer, makeDownstreamRule(IPSEC_IFINDEX, neigh, mac));
-    }
-
-    // TODO: move to BpfCoordinatorTest once IpNeighborMonitor is migrated to BpfCoordinator.
-    @Test
-    public void addRemoveTetherClient() throws Exception {
-        initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
-                false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
-
-        final int myIfindex = TEST_IFACE_PARAMS.index;
-        final int notMyIfindex = myIfindex - 1;
-
-        final InetAddress neighA = InetAddresses.parseNumericAddress("192.168.80.1");
-        final InetAddress neighB = InetAddresses.parseNumericAddress("192.168.80.2");
-        final InetAddress neighLL = InetAddresses.parseNumericAddress("169.254.0.1");
-        final InetAddress neighMC = InetAddresses.parseNumericAddress("224.0.0.1");
-        final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
-        final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
-        final MacAddress macB = MacAddress.fromString("11:22:33:00:00:0b");
-
-        // Events on other interfaces are ignored.
-        recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator);
-
-        // Events on this interface are received and sent to BpfCoordinator.
-        recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
-        verify(mBpfCoordinator).tetherOffloadClientAdd(mIpServer, new ClientInfo(myIfindex,
-                TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighA, macA));
-        clearInvocations(mBpfCoordinator);
-
-        recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
-        verify(mBpfCoordinator).tetherOffloadClientAdd(mIpServer, new ClientInfo(myIfindex,
-                TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighB, macB));
-        clearInvocations(mBpfCoordinator);
-
-        // Link-local and multicast neighbors are ignored.
-        recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator);
-        recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, macA);
-        verifyNoMoreInteractions(mBpfCoordinator);
-        clearInvocations(mBpfCoordinator);
-
-        // A neighbor that is no longer valid causes the client to be removed.
-        // NUD_FAILED events do not have a MAC address.
-        recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
-        verify(mBpfCoordinator).tetherOffloadClientRemove(mIpServer,  new ClientInfo(myIfindex,
-                TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighA, macNull));
-        clearInvocations(mBpfCoordinator);
-
-        // A neighbor that is deleted causes the client to be removed.
-        recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
-        verify(mBpfCoordinator).tetherOffloadClientRemove(mIpServer, new ClientInfo(myIfindex,
-                TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighB, macNull));
-    }
 }
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
index 7fbb670..6c1721e 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
@@ -25,6 +25,8 @@
 import static android.net.NetworkStats.TAG_NONE;
 import static android.net.NetworkStats.UID_ALL;
 import static android.net.NetworkStats.UID_TETHERING;
+import static android.net.TetheringManager.TETHERING_WIFI;
+import static android.net.ip.IpServer.STATE_TETHERED;
 import static android.net.netstats.provider.NetworkStatsProvider.QUOTA_UNLIMITED;
 import static android.system.OsConstants.ETH_P_IP;
 import static android.system.OsConstants.ETH_P_IPV6;
@@ -43,6 +45,11 @@
 import static com.android.net.module.util.netlink.ConntrackMessage.TupleProto;
 import static com.android.net.module.util.netlink.NetlinkConstants.IPCTNL_MSG_CT_DELETE;
 import static com.android.net.module.util.netlink.NetlinkConstants.IPCTNL_MSG_CT_NEW;
+import static com.android.net.module.util.netlink.NetlinkConstants.RTM_DELNEIGH;
+import static com.android.net.module.util.netlink.NetlinkConstants.RTM_NEWNEIGH;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_FAILED;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_REACHABLE;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_STALE;
 import static com.android.networkstack.tethering.BpfCoordinator.CONNTRACK_TIMEOUT_UPDATE_INTERVAL_MS;
 import static com.android.networkstack.tethering.BpfCoordinator.INVALID_MTU;
 import static com.android.networkstack.tethering.BpfCoordinator.NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED;
@@ -71,11 +78,15 @@
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.argThat;
 import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.when;
 
 import android.app.usage.NetworkStatsManager;
@@ -88,13 +99,16 @@
 import android.net.Network;
 import android.net.NetworkCapabilities;
 import android.net.NetworkStats;
+import android.net.RoutingCoordinatorManager;
 import android.net.TetherOffloadRuleParcel;
 import android.net.TetherStatsParcel;
 import android.net.ip.IpServer;
+import android.net.ip.RouterAdvertisementDaemon;
 import android.os.Build;
 import android.os.Handler;
 import android.os.test.TestLooper;
 import android.util.ArrayMap;
+import android.util.ArraySet;
 import android.util.SparseArray;
 
 import androidx.annotation.NonNull;
@@ -104,10 +118,12 @@
 
 import com.android.dx.mockito.inline.extended.ExtendedMockito;
 import com.android.internal.util.IndentingPrintWriter;
+import com.android.modules.utils.build.SdkLevel;
 import com.android.net.module.util.CollectionUtils;
 import com.android.net.module.util.IBpfMap;
 import com.android.net.module.util.InterfaceParams;
 import com.android.net.module.util.NetworkStackConstants;
+import com.android.net.module.util.SdkUtil.LateSdk;
 import com.android.net.module.util.SharedLog;
 import com.android.net.module.util.Struct.S32;
 import com.android.net.module.util.bpf.Tether4Key;
@@ -116,6 +132,9 @@
 import com.android.net.module.util.bpf.TetherStatsValue;
 import com.android.net.module.util.ip.ConntrackMonitor;
 import com.android.net.module.util.ip.ConntrackMonitor.ConntrackEventConsumer;
+import com.android.net.module.util.ip.IpNeighborMonitor;
+import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
+import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEventConsumer;
 import com.android.net.module.util.netlink.ConntrackMessage;
 import com.android.net.module.util.netlink.NetlinkConstants;
 import com.android.net.module.util.netlink.NetlinkUtils;
@@ -123,6 +142,8 @@
 import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
 import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
 import com.android.networkstack.tethering.BpfCoordinator.Ipv6UpstreamRule;
+import com.android.networkstack.tethering.metrics.TetheringMetrics;
+import com.android.networkstack.tethering.util.InterfaceSet;
 import com.android.testutils.DevSdkIgnoreRule;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
@@ -172,19 +193,27 @@
     private static final int UPSTREAM_IFINDEX2 = 1003;
     private static final int DOWNSTREAM_IFINDEX = 2001;
     private static final int DOWNSTREAM_IFINDEX2 = 2002;
+    private static final int IPSEC_IFINDEX = 103;
 
     private static final String UPSTREAM_IFACE = "rmnet0";
     private static final String UPSTREAM_XLAT_IFACE = "v4-rmnet0";
     private static final String UPSTREAM_IFACE2 = "wlan0";
     private static final String DOWNSTREAM_IFACE = "downstream1";
     private static final String DOWNSTREAM_IFACE2 = "downstream2";
+    private static final String IPSEC_IFACE = "ipsec0";
 
     private static final MacAddress DOWNSTREAM_MAC = MacAddress.fromString("12:34:56:78:90:ab");
     private static final MacAddress DOWNSTREAM_MAC2 = MacAddress.fromString("ab:90:78:56:34:12");
 
     private static final MacAddress MAC_A = MacAddress.fromString("00:00:00:00:00:0a");
     private static final MacAddress MAC_B = MacAddress.fromString("11:22:33:00:00:0b");
+    private static final MacAddress MAC_NULL = MacAddress.fromString("00:00:00:00:00:00");
 
+    private static final LinkAddress UPSTREAM_ADDRESS = new LinkAddress("2001:db8:0:1234::168/64");
+    private static final LinkAddress UPSTREAM_ADDRESS2 = new LinkAddress("2001:db8:0:abcd::168/64");
+    private static final Set<LinkAddress> UPSTREAM_ADDRESSES = Set.of(UPSTREAM_ADDRESS);
+    private static final Set<LinkAddress> UPSTREAM_ADDRESSES2 =
+            Set.of(UPSTREAM_ADDRESS, UPSTREAM_ADDRESS2);
     private static final IpPrefix UPSTREAM_PREFIX = new IpPrefix("2001:db8:0:1234::/64");
     private static final IpPrefix UPSTREAM_PREFIX2 = new IpPrefix("2001:db8:0:abcd::/64");
     private static final Set<IpPrefix> UPSTREAM_PREFIXES = Set.of(UPSTREAM_PREFIX);
@@ -196,6 +225,8 @@
             InetAddresses.parseNumericAddress("2001:db8:0:1234::1");
     private static final InetAddress NEIGH_B =
             InetAddresses.parseNumericAddress("2001:db8:0:1234::2");
+    private static final InetAddress NEIGH_LL = InetAddresses.parseNumericAddress("fe80::1");
+    private static final InetAddress NEIGH_MC = InetAddresses.parseNumericAddress("ff02::1234");
 
     private static final Inet4Address REMOTE_ADDR =
             (Inet4Address) InetAddresses.parseNumericAddress("140.112.8.116");
@@ -235,6 +266,9 @@
     private static final InterfaceParams DOWNSTREAM_IFACE_PARAMS2 = new InterfaceParams(
             DOWNSTREAM_IFACE2, DOWNSTREAM_IFINDEX2, DOWNSTREAM_MAC2,
             NetworkStackConstants.ETHER_MTU);
+    private static final InterfaceParams IPSEC_IFACE_PARAMS = new InterfaceParams(
+            IPSEC_IFACE, IPSEC_IFINDEX, MacAddress.ALL_ZEROS_ADDRESS,
+            NetworkStackConstants.ETHER_MTU);
 
     private static final Map<Integer, UpstreamInformation> UPSTREAM_INFORMATIONS = Map.of(
             UPSTREAM_IFINDEX, new UpstreamInformation(UPSTREAM_IFACE_PARAMS,
@@ -414,6 +448,14 @@
     @Mock private IpServer mIpServer2;
     @Mock private TetheringConfiguration mTetherConfig;
     @Mock private ConntrackMonitor mConntrackMonitor;
+    @Mock private IpNeighborMonitor mIpNeighborMonitor;
+    @Mock private RouterAdvertisementDaemon mRaDaemon;
+    @Mock private IpServer.Dependencies mIpServerDeps;
+    @Mock private IpServer.Callback mIpServerCallback;
+    @Mock private PrivateAddressCoordinator mAddressCoordinator;
+    private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinatorManager =
+            new LateSdk<>(SdkLevel.isAtLeastS() ? mock(RoutingCoordinatorManager.class) : null);
+    @Mock private TetheringMetrics mTetheringMetrics;
 
     // Late init since methods must be called by the thread that created this object.
     private TestableNetworkStatsProviderCbBinder mTetherStatsProviderCb;
@@ -422,6 +464,7 @@
     // Late init since the object must be initialized by the BPF coordinator instance because
     // it has to access the non-static function of BPF coordinator.
     private BpfConntrackEventConsumer mConsumer;
+    private NeighborEventConsumer mNeighborEventConsumer;
     private HashMap<IpServer, HashMap<Inet4Address, ClientInfo>> mTetherClients;
 
     private long mElapsedRealtimeNanos = 0;
@@ -429,6 +472,7 @@
     private final ArgumentCaptor<ArrayList> mStringArrayCaptor =
             ArgumentCaptor.forClass(ArrayList.class);
     private final TestLooper mTestLooper = new TestLooper();
+    private final Handler mHandler = new Handler(mTestLooper.getLooper());
     private final IBpfMap<Tether4Key, Tether4Value> mBpfDownstream4Map =
             spy(new TestBpfMap<>(Tether4Key.class, Tether4Value.class));
     private final IBpfMap<Tether4Key, Tether4Value> mBpfUpstream4Map =
@@ -449,7 +493,7 @@
             spy(new BpfCoordinator.Dependencies() {
                     @NonNull
                     public Handler getHandler() {
-                        return new Handler(mTestLooper.getLooper());
+                        return mHandler;
                     }
 
                     @NonNull
@@ -529,6 +573,24 @@
     @Before public void setUp() {
         MockitoAnnotations.initMocks(this);
         when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(true /* default value */);
+
+        // Simulate the behavior of RoutingCoordinator
+        if (null != mRoutingCoordinatorManager.value) {
+            doAnswer(it -> {
+                final String fromIface = (String) it.getArguments()[0];
+                final String toIface = (String) it.getArguments()[1];
+                mNetd.tetherAddForward(fromIface, toIface);
+                mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
+                return null;
+            }).when(mRoutingCoordinatorManager.value).addInterfaceForward(any(), any());
+            doAnswer(it -> {
+                final String fromIface = (String) it.getArguments()[0];
+                final String toIface = (String) it.getArguments()[1];
+                mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
+                mNetd.tetherRemoveForward(fromIface, toIface);
+                return null;
+            }).when(mRoutingCoordinatorManager.value).removeInterfaceForward(any(), any());
+        }
     }
 
     private void waitForIdle() {
@@ -542,7 +604,68 @@
     }
 
     @NonNull
+    private IpServer makeAndStartIpServer(String interfaceName, BpfCoordinator bpfCoordinator)
+            throws Exception {
+        final LinkAddress testAddress = new LinkAddress("192.168.42.5/24");
+        when(mIpServerDeps.getRouterAdvertisementDaemon(any())).thenReturn(mRaDaemon);
+        when(mIpServerDeps.getInterfaceParams(DOWNSTREAM_IFACE)).thenReturn(
+                DOWNSTREAM_IFACE_PARAMS);
+        when(mIpServerDeps.getInterfaceParams(UPSTREAM_IFACE)).thenReturn(UPSTREAM_IFACE_PARAMS);
+        when(mIpServerDeps.getInterfaceParams(UPSTREAM_IFACE2)).thenReturn(UPSTREAM_IFACE_PARAMS2);
+        when(mIpServerDeps.getInterfaceParams(IPSEC_IFACE)).thenReturn(IPSEC_IFACE_PARAMS);
+        when(mAddressCoordinator.requestDownstreamAddress(any(), anyInt(),
+                anyBoolean())).thenReturn(testAddress);
+        when(mRaDaemon.start()).thenReturn(true);
+        ArgumentCaptor<NeighborEventConsumer> neighborEventCaptor =
+                ArgumentCaptor.forClass(NeighborEventConsumer.class);
+        doReturn(mIpNeighborMonitor).when(mIpServerDeps).getIpNeighborMonitor(any(), any(),
+                neighborEventCaptor.capture());
+        final IpServer ipServer = new IpServer(
+                interfaceName, mHandler, TETHERING_WIFI, new SharedLog("test"), mNetd,
+                bpfCoordinator, mRoutingCoordinatorManager, mIpServerCallback, mTetherConfig,
+                mAddressCoordinator, mTetheringMetrics, mIpServerDeps);
+        ipServer.start();
+        ipServer.sendMessage(IpServer.CMD_TETHER_REQUESTED, STATE_TETHERED);
+        mTestLooper.dispatchAll();
+
+        LinkProperties lp = new LinkProperties();
+        lp.setInterfaceName(UPSTREAM_IFACE);
+        lp.setLinkAddresses(UPSTREAM_ADDRESSES);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, 0);
+
+        mNeighborEventConsumer = neighborEventCaptor.getValue();
+        return ipServer;
+    }
+
+    private void dispatchTetherConnectionChanged(IpServer ipServer, String upstreamIface,
+            LinkProperties v6lp, int ttlAdjustment) {
+        dispatchTetherConnectionChanged(ipServer, upstreamIface);
+        ipServer.sendMessage(IpServer.CMD_IPV6_TETHER_UPDATE, ttlAdjustment, 0, v6lp);
+        mTestLooper.dispatchAll();
+    }
+
+    private void dispatchTetherConnectionChanged(IpServer ipServer, String upstreamIface) {
+        final InterfaceSet ifs = (upstreamIface != null) ? new InterfaceSet(upstreamIface) : null;
+        ipServer.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED, ifs);
+        mTestLooper.dispatchAll();
+    }
+
+    private void recvNewNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
+        mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_NEWNEIGH, ifindex, addr,
+                nudState, mac));
+        mTestLooper.dispatchAll();
+    }
+
+    private void recvDelNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
+        mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_DELNEIGH, ifindex, addr,
+                nudState, mac));
+        mTestLooper.dispatchAll();
+    }
+
+    @NonNull
     private BpfCoordinator makeBpfCoordinator() throws Exception {
+        // mStatsManager will be invoked twice if BpfCoordinator is created the second time.
+        clearInvocations(mStatsManager);
         final BpfCoordinator coordinator = new BpfCoordinator(mDeps);
 
         mConsumer = coordinator.getBpfConntrackEventConsumerForTesting();
@@ -666,6 +789,51 @@
         }
     }
 
+    private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex,
+            @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
+        if (!mDeps.isAtLeastS()) return;
+        ArrayMap<TetherUpstream6Key, Tether6Value> expected = new ArrayMap<>();
+        for (IpPrefix upstreamPrefix : upstreamPrefixes) {
+            long prefix64 = prefixToLong(upstreamPrefix);
+            final TetherUpstream6Key key = new TetherUpstream6Key(DOWNSTREAM_IFACE_PARAMS.index,
+                    DOWNSTREAM_IFACE_PARAMS.macAddr, prefix64);
+            final Tether6Value value = new Tether6Value(upstreamIfindex,
+                    MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS, ETH_P_IPV6,
+                    NetworkStackConstants.ETHER_MTU);
+            expected.put(key, value);
+        }
+        ArgumentCaptor<TetherUpstream6Key> keyCaptor =
+                ArgumentCaptor.forClass(TetherUpstream6Key.class);
+        ArgumentCaptor<Tether6Value> valueCaptor =
+                ArgumentCaptor.forClass(Tether6Value.class);
+        verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).insertEntry(
+                keyCaptor.capture(), valueCaptor.capture());
+        List<TetherUpstream6Key> keys = keyCaptor.getAllValues();
+        List<Tether6Value> values = valueCaptor.getAllValues();
+        ArrayMap<TetherUpstream6Key, Tether6Value> captured = new ArrayMap<>();
+        for (int i = 0; i < keys.size(); i++) {
+            captured.put(keys.get(i), values.get(i));
+        }
+        assertEquals(expected, captured);
+    }
+
+    private void verifyStopUpstreamIpv6Forwarding(@Nullable InOrder inOrder,
+            @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
+        if (!mDeps.isAtLeastS()) return;
+        Set<TetherUpstream6Key> expected = new ArraySet<>();
+        for (IpPrefix upstreamPrefix : upstreamPrefixes) {
+            long prefix64 = prefixToLong(upstreamPrefix);
+            final TetherUpstream6Key key = new TetherUpstream6Key(DOWNSTREAM_IFACE_PARAMS.index,
+                    DOWNSTREAM_IFACE_PARAMS.macAddr, prefix64);
+            expected.add(key);
+        }
+        ArgumentCaptor<TetherUpstream6Key> keyCaptor =
+                ArgumentCaptor.forClass(TetherUpstream6Key.class);
+        verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).deleteEntry(
+                keyCaptor.capture());
+        assertEquals(expected, new ArraySet(keyCaptor.getAllValues()));
+    }
+
     private void verifyNoUpstreamIpv6ForwardingChange(@Nullable InOrder inOrder) throws Exception {
         if (!mDeps.isAtLeastS()) return;
         if (inOrder != null) {
@@ -708,6 +876,10 @@
         assertEquals(expected, captured);
     }
 
+    private void verifyAddDownstreamRule(@NonNull Ipv6DownstreamRule rule) throws Exception {
+        verifyAddDownstreamRule(null, rule);
+    }
+
     private void verifyAddDownstreamRule(@Nullable InOrder inOrder,
             @NonNull Ipv6DownstreamRule rule) throws Exception {
         if (mDeps.isAtLeastS()) {
@@ -752,6 +924,11 @@
         assertSameElements(expected, keyCaptor.getAllValues());
     }
 
+    private void verifyRemoveDownstreamRule(@NonNull final Ipv6DownstreamRule rule)
+            throws Exception {
+        verifyRemoveDownstreamRule(null, rule);
+    }
+
     private void verifyRemoveDownstreamRule(@Nullable InOrder inOrder,
             @NonNull final Ipv6DownstreamRule rule) throws Exception {
         if (mDeps.isAtLeastS()) {
@@ -1016,8 +1193,37 @@
         mTetherStatsProviderCb.assertNoCallback();
     }
 
-    // The custom ArgumentMatcher simply comes from IpServerTest.
-    // TODO: move both of them into a common utility class for reusing the code.
+    /**
+     * Custom ArgumentMatcher for TetherOffloadRuleParcel. This is needed because generated stable
+     * AIDL classes don't have equals(), so we cannot just use eq(). A custom assert, such as:
+     *
+     * private void checkFooCalled(StableParcelable p, ...) {
+     *     ArgumentCaptor<@FooParam> captor = ArgumentCaptor.forClass(FooParam.class);
+     *     verify(mMock).foo(captor.capture());
+     *     Foo foo = captor.getValue();
+     *     assertFooMatchesExpectations(foo);
+     * }
+     *
+     * almost works, but not quite. This is because if the code under test calls foo() twice, the
+     * first call to checkFooCalled() matches both the calls, putting both calls into the captor,
+     * and then fails with TooManyActualInvocations. It also makes it harder to use other mockito
+     * features such as never(), inOrder(), etc.
+     *
+     * This approach isn't great because if the match fails, the error message is unhelpful
+     * (actual: "android.net.TetherOffloadRuleParcel@8c827b0" or some such), but at least it does
+     * work.
+     *
+     * TODO: consider making the error message more readable by adding a method that catching the
+     * AssertionFailedError and throwing a new assertion with more details. See
+     * NetworkMonitorTest#verifyNetworkTested.
+     *
+     * See ConnectivityServiceTest#assertRoutesAdded for an alternative approach which solves the
+     * TooManyActualInvocations problem described above by forcing the caller of the custom assert
+     * method to specify all expected invocations in one call. This is useful when the stable
+     * parcelable class being asserted on has a corresponding Java object (eg., RouteInfo and
+     * RouteInfoParcelable), and the caller can just pass in a list of them. It not useful here
+     * because there is no such object.
+     */
     private static class TetherOffloadRuleParcelMatcher implements
             ArgumentMatcher<TetherOffloadRuleParcel> {
         public final int upstreamIfindex;
@@ -2064,8 +2270,7 @@
     }
 
     private static long prefixToLong(IpPrefix prefix) {
-        byte[] prefixBytes = Arrays.copyOf(prefix.getRawAddress(), 8);
-        return ByteBuffer.wrap(prefixBytes).getLong();
+        return ByteBuffer.wrap(prefix.getRawAddress()).getLong();
     }
 
     void checkRule4ExistInUpstreamDownstreamMap() throws Exception {
@@ -2135,7 +2340,7 @@
         assertNull(mTetherClients.get(mIpServer2));
     }
 
-    private void asseertClientInfoExist(@NonNull IpServer ipServer,
+    private void assertClientInfoExists(@NonNull IpServer ipServer,
             @NonNull ClientInfo clientInfo) {
         HashMap<Inet4Address, ClientInfo> clients = mTetherClients.get(ipServer);
         assertNotNull(clients);
@@ -2144,16 +2349,16 @@
 
     // Although either ClientInfo for a given downstream (IpServer) is not found or a given
     // client address is not found on a given downstream can be treated "ClientInfo not
-    // exist", we still want to know the real reason exactly. For example, we don't the
+    // exist", we still want to know the real reason exactly. For example, we don't know the
     // exact reason in the following:
-    //   assertNull(clients == null ? clients : clients.get(clientInfo.clientAddress));
+    //   assertNull(clients == null ? clients : clients.get(clientAddress));
     // This helper only verifies the case that the downstream still has at least one client.
     // In other words, ClientInfo for a given IpServer has not been removed yet.
-    private void asseertClientInfoNotExist(@NonNull IpServer ipServer,
-            @NonNull ClientInfo clientInfo) {
+    private void assertClientInfoDoesNotExist(@NonNull IpServer ipServer,
+            @NonNull Inet4Address clientAddress) {
         HashMap<Inet4Address, ClientInfo> clients = mTetherClients.get(ipServer);
         assertNotNull(clients);
-        assertNull(clients.get(clientInfo.clientAddress));
+        assertNull(clients.get(clientAddress));
     }
 
     @Test
@@ -2189,8 +2394,8 @@
         checkRule4NotExistInUpstreamDownstreamMap();
 
         // Client information should be not deleted.
-        asseertClientInfoExist(mIpServer, CLIENT_INFO_A);
-        asseertClientInfoExist(mIpServer2, CLIENT_INFO_B);
+        assertClientInfoExists(mIpServer, CLIENT_INFO_A);
+        assertClientInfoExists(mIpServer2, CLIENT_INFO_B);
     }
 
     @Test
@@ -2205,8 +2410,8 @@
                 PRIVATE_ADDR2, MAC_B);
         coordinator.tetherOffloadClientAdd(mIpServer, clientA);
         coordinator.tetherOffloadClientAdd(mIpServer, clientB);
-        asseertClientInfoExist(mIpServer, clientA);
-        asseertClientInfoExist(mIpServer, clientB);
+        assertClientInfoExists(mIpServer, clientA);
+        assertClientInfoExists(mIpServer, clientB);
 
         // Add the rules for client A and client B.
         final Tether4Key upstream4KeyA = makeUpstream4Key(
@@ -2230,8 +2435,8 @@
         // [2] Remove client information A. Only the rules on client A should be removed and
         // the rules on client B should exist.
         coordinator.tetherOffloadClientRemove(mIpServer, clientA);
-        asseertClientInfoNotExist(mIpServer, clientA);
-        asseertClientInfoExist(mIpServer, clientB);
+        assertClientInfoDoesNotExist(mIpServer, clientA.clientAddress);
+        assertClientInfoExists(mIpServer, clientB);
         assertNull(mBpfUpstream4Map.getValue(upstream4KeyA));
         assertNull(mBpfDownstream4Map.getValue(downstream4KeyA));
         assertEquals(upstream4ValueB, mBpfUpstream4Map.getValue(upstream4KeyB));
@@ -2239,9 +2444,9 @@
 
         // [3] Remove client information B. The rules on client B should be removed.
         // Exactly, ClientInfo for a given IpServer is removed because the last client B
-        // has been removed from the downstream. Can't use the helper #asseertClientInfoExist
+        // has been removed from the downstream. Can't use the helper #assertClientInfoExists
         // to check because the container ClientInfo for a given downstream has been removed.
-        // See #asseertClientInfoExist.
+        // See #assertClientInfoExists.
         coordinator.tetherOffloadClientRemove(mIpServer, clientB);
         assertNull(mTetherClients.get(mIpServer));
         assertNull(mBpfUpstream4Map.getValue(upstream4KeyB));
@@ -2581,4 +2786,296 @@
     public void testUpdateUpstreamNetworkState() throws Exception {
         verifyUpdateUpstreamNetworkState();
     }
+
+    @NonNull
+    private static TetherStatsParcel buildEmptyTetherStatsParcel(int ifIndex) {
+        TetherStatsParcel parcel = new TetherStatsParcel();
+        parcel.ifIndex = ifIndex;
+        return parcel;
+    }
+
+    private void resetNetdAndBpfMaps() throws Exception {
+        reset(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+        // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
+        // potentially crash the test) if the stats map is empty.
+        when(mNetd.tetherOffloadGetStats()).thenReturn(new TetherStatsParcel[0]);
+        when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX))
+                .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX));
+        when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX2))
+                .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX2));
+        // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
+        // potentially crash the test) if the stats map is empty.
+        final TetherStatsValue allZeros = new TetherStatsValue(0, 0, 0, 0, 0, 0);
+        when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX))).thenReturn(allZeros);
+        when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX2))).thenReturn(allZeros);
+    }
+
+    @Test
+    public void addRemoveIpv6ForwardingRules() throws Exception {
+        final int myIfindex = DOWNSTREAM_IFINDEX;
+        final int notMyIfindex = myIfindex - 1;
+        final BpfCoordinator coordinator = makeBpfCoordinator();
+        final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+
+        resetNetdAndBpfMaps();
+        verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+        // TODO: Perhaps verify the interaction of tetherOffloadSetInterfaceQuota and
+        // tetherOffloadGetAndClearStats in netd while the rules are changed.
+
+        // Events on other interfaces are ignored.
+        recvNewNeigh(notMyIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+        // Events on this interface are received and sent to BpfCoordinator.
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        final Ipv6DownstreamRule ruleA = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
+        verifyAddDownstreamRule(ruleA);
+        resetNetdAndBpfMaps();
+
+        recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+        final Ipv6DownstreamRule ruleB = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_B, MAC_B);
+        verifyAddDownstreamRule(ruleB);
+        resetNetdAndBpfMaps();
+
+        // Link-local and multicast neighbors are ignored.
+        recvNewNeigh(myIfindex, NEIGH_LL, NUD_REACHABLE, MAC_A);
+        verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+        recvNewNeigh(myIfindex, NEIGH_MC, NUD_REACHABLE, MAC_A);
+        verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+        // A neighbor that is no longer valid causes the rule to be removed.
+        // NUD_FAILED events do not have a MAC address.
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_FAILED, null);
+        final Ipv6DownstreamRule ruleANull = buildTestDownstreamRule(
+                UPSTREAM_IFINDEX, NEIGH_A, MAC_NULL);
+        verifyRemoveDownstreamRule(ruleANull);
+        resetNetdAndBpfMaps();
+
+        // A neighbor that is deleted causes the rule to be removed.
+        recvDelNeigh(myIfindex, NEIGH_B, NUD_STALE, MAC_B);
+        final Ipv6DownstreamRule ruleBNull = buildTestDownstreamRule(
+                UPSTREAM_IFINDEX, NEIGH_B, MAC_NULL);
+        verifyRemoveDownstreamRule(ruleBNull);
+        resetNetdAndBpfMaps();
+
+        // Upstream interface changes result in updating the rules.
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+        resetNetdAndBpfMaps();
+
+        InOrder inOrder = inOrder(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+        LinkProperties lp = new LinkProperties();
+        lp.setInterfaceName(UPSTREAM_IFACE2);
+        lp.setLinkAddresses(UPSTREAM_ADDRESSES);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp, -1);
+        final Ipv6DownstreamRule ruleA2 = buildTestDownstreamRule(
+                UPSTREAM_IFINDEX2, NEIGH_A, MAC_A);
+        final Ipv6DownstreamRule ruleB2 = buildTestDownstreamRule(
+                UPSTREAM_IFINDEX2, NEIGH_B, MAC_B);
+        verifyRemoveDownstreamRule(inOrder, ruleA);
+        verifyRemoveDownstreamRule(inOrder, ruleB);
+        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
+        verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
+        verifyAddDownstreamRule(inOrder, ruleA2);
+        verifyAddDownstreamRule(inOrder, ruleB2);
+        verifyNoUpstreamIpv6ForwardingChange(inOrder);
+        resetNetdAndBpfMaps();
+
+        // Upstream link addresses change result in updating the rules.
+        LinkProperties lp2 = new LinkProperties();
+        lp2.setInterfaceName(UPSTREAM_IFACE2);
+        lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp2, -1);
+        verifyRemoveDownstreamRule(inOrder, ruleA2);
+        verifyRemoveDownstreamRule(inOrder, ruleB2);
+        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
+        verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
+        verifyAddDownstreamRule(inOrder, ruleA2);
+        verifyAddDownstreamRule(inOrder, ruleB2);
+        resetNetdAndBpfMaps();
+
+        // When the upstream is lost, rules are removed.
+        dispatchTetherConnectionChanged(ipServer, null, null, 0);
+        verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES2);
+        verifyRemoveDownstreamRule(ruleA2);
+        verifyRemoveDownstreamRule(ruleB2);
+        // Upstream lost doesn't clear the downstream rules from the maps.
+        // Do that here.
+        recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+        recvDelNeigh(myIfindex, NEIGH_B, NUD_STALE, MAC_B);
+        resetNetdAndBpfMaps();
+
+        // If the upstream is IPv4-only, no IPv6 rules are added to BPF map.
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE);
+        resetNetdAndBpfMaps();
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        verifyNoUpstreamIpv6ForwardingChange(null);
+        // Downstream rules are only added to BpfCoordinator but not BPF map.
+        verifyNeverAddDownstreamRule();
+        verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+        // Rules can be added again once upstream IPv6 connectivity is available. The existing rules
+        // with an upstream of NO_UPSTREAM are reapplied.
+        lp.setInterfaceName(UPSTREAM_IFACE);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, -1);
+        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+        verifyAddDownstreamRule(ruleA);
+        recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+        verifyAddDownstreamRule(ruleB);
+
+        // If upstream IPv6 connectivity is lost, rules are removed.
+        resetNetdAndBpfMaps();
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, null, 0);
+        verifyRemoveDownstreamRule(ruleA);
+        verifyRemoveDownstreamRule(ruleB);
+        verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+
+        // When upstream IPv6 connectivity comes back, upstream rules are added and downstream rules
+        // are reapplied.
+        lp.setInterfaceName(UPSTREAM_IFACE);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, -1);
+        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+        verifyAddDownstreamRule(ruleA);
+        verifyAddDownstreamRule(ruleB);
+        resetNetdAndBpfMaps();
+
+        // When the downstream interface goes down, rules are removed.
+        ipServer.stop();
+        mTestLooper.dispatchAll();
+        verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+        verifyRemoveDownstreamRule(ruleA);
+        verifyRemoveDownstreamRule(ruleB);
+        verify(mIpNeighborMonitor).stop();
+        resetNetdAndBpfMaps();
+    }
+
+    @Test
+    public void enableDisableUsingBpfOffload() throws Exception {
+        final int myIfindex = DOWNSTREAM_IFINDEX;
+
+        // Expect that rules can be only added/removed when the BPF offload config is enabled.
+        // Note that the BPF offload disabled case is not a realistic test case. Because IP
+        // neighbor monitor doesn't start if BPF offload is disabled, there should have no
+        // neighbor event listening. This is used for testing the protection check just in case.
+        // TODO: Perhaps remove the BPF offload disabled case test once this check isn't needed
+        // anymore.
+
+        // [1] Enable BPF offload.
+        // A neighbor that is added or deleted causes the rule to be added or removed.
+        final BpfCoordinator coordinator = makeBpfCoordinator();
+        final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+        resetNetdAndBpfMaps();
+
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        final Ipv6DownstreamRule rule = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
+        verifyAddDownstreamRule(rule);
+        resetNetdAndBpfMaps();
+
+        recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+        final Ipv6DownstreamRule ruleNull = buildTestDownstreamRule(
+                UPSTREAM_IFINDEX, NEIGH_A, MAC_NULL);
+        verifyRemoveDownstreamRule(ruleNull);
+        resetNetdAndBpfMaps();
+
+        // Upstream IPv6 connectivity change causes upstream rules change.
+        LinkProperties lp2 = new LinkProperties();
+        lp2.setInterfaceName(UPSTREAM_IFACE2);
+        lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
+        dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp2, 0);
+        verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
+        resetNetdAndBpfMaps();
+
+        // [2] Disable BPF offload.
+        // A neighbor that is added or deleted doesn’t cause the rule to be added or removed.
+        when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(false);
+        final BpfCoordinator coordinator2 = makeBpfCoordinator();
+        final IpServer ipServer2 = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator2);
+        verifyNoUpstreamIpv6ForwardingChange(null);
+        resetNetdAndBpfMaps();
+
+        recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+        verifyNeverAddDownstreamRule();
+        resetNetdAndBpfMaps();
+
+        recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+        verifyNeverRemoveDownstreamRule();
+        resetNetdAndBpfMaps();
+
+        // Upstream IPv6 connectivity change doesn't cause the rule to be added or removed.
+        dispatchTetherConnectionChanged(ipServer2, UPSTREAM_IFACE2, lp2, 0);
+        verifyNoUpstreamIpv6ForwardingChange(null);
+        verifyNeverRemoveDownstreamRule();
+        resetNetdAndBpfMaps();
+    }
+
+    @Test
+    public void doesNotStartIpNeighborMonitorIfBpfOffloadDisabled() throws Exception {
+        when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(false);
+        final BpfCoordinator coordinator = makeBpfCoordinator();
+        final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+
+        // IP neighbor monitor doesn't start if BPF offload is disabled.
+        verify(mIpNeighborMonitor, never()).start();
+    }
+
+    @Test
+    public void testSkipVirtualNetworkInBpf() throws Exception {
+        final BpfCoordinator coordinator = makeBpfCoordinator();
+        final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+        final LinkProperties v6Only = new LinkProperties();
+        v6Only.setInterfaceName(IPSEC_IFACE);
+        v6Only.setLinkAddresses(UPSTREAM_ADDRESSES);
+
+        resetNetdAndBpfMaps();
+        dispatchTetherConnectionChanged(ipServer, IPSEC_IFACE, v6Only, 0);
+        verify(mNetd).tetherAddForward(DOWNSTREAM_IFACE, IPSEC_IFACE);
+        verify(mNetd).ipfwdAddInterfaceForward(DOWNSTREAM_IFACE, IPSEC_IFACE);
+        verifyNeverAddUpstreamRule();
+
+        recvNewNeigh(DOWNSTREAM_IFINDEX, NEIGH_A, NUD_REACHABLE, MAC_A);
+        verifyNeverAddDownstreamRule();
+    }
+
+    @Test
+    public void addRemoveTetherClient() throws Exception {
+        final BpfCoordinator coordinator = makeBpfCoordinator();
+        final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+        final int myIfindex = DOWNSTREAM_IFINDEX;
+        final int notMyIfindex = myIfindex - 1;
+
+        final InetAddress neighA = InetAddresses.parseNumericAddress("192.168.80.1");
+        final InetAddress neighB = InetAddresses.parseNumericAddress("192.168.80.2");
+        final InetAddress neighLL = InetAddresses.parseNumericAddress("169.254.0.1");
+        final InetAddress neighMC = InetAddresses.parseNumericAddress("224.0.0.1");
+
+        // Events on other interfaces are ignored.
+        recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, MAC_A);
+        assertNull(mTetherClients.get(ipServer));
+
+        // Events on this interface are received and sent to BpfCoordinator.
+        recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, MAC_A);
+        assertClientInfoExists(ipServer,
+                new ClientInfo(myIfindex, DOWNSTREAM_MAC, (Inet4Address) neighA, MAC_A));
+
+        recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, MAC_B);
+        assertClientInfoExists(ipServer,
+                new ClientInfo(myIfindex, DOWNSTREAM_MAC, (Inet4Address) neighB, MAC_B));
+
+        // Link-local and multicast neighbors are ignored.
+        recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, MAC_A);
+        assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighLL);
+        recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, MAC_A);
+        assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighMC);
+
+        // A neighbor that is no longer valid causes the client to be removed.
+        // NUD_FAILED events do not have a MAC address.
+        recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
+        assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighA);
+
+        // A neighbor that is deleted causes the client to be removed.
+        recvDelNeigh(myIfindex, neighB, NUD_STALE, MAC_B);
+        // When last client information is deleted, IpServer will be removed from mTetherClients
+        assertNull(mTetherClients.get(ipServer));
+    }
 }
diff --git a/bpf_progs/netd.h b/bpf_progs/netd.h
index d1fc58d..64ed633 100644
--- a/bpf_progs/netd.h
+++ b/bpf_progs/netd.h
@@ -192,6 +192,7 @@
     OEM_DENY_1_MATCH = (1 << 9),
     OEM_DENY_2_MATCH = (1 << 10),
     OEM_DENY_3_MATCH = (1 << 11),
+    BACKGROUND_MATCH = (1 << 12)
 };
 // LINT.ThenChange(../framework/src/android/net/BpfNetMapsConstants.java)
 
@@ -244,7 +245,8 @@
 // DROP_IF_SET is set of rules that DROP if rule is globally enabled, and per-uid bit is set
 #define DROP_IF_SET (STANDBY_MATCH | OEM_DENY_1_MATCH | OEM_DENY_2_MATCH | OEM_DENY_3_MATCH)
 // DROP_IF_UNSET is set of rules that should DROP if globally enabled, and per-uid bit is NOT set
-#define DROP_IF_UNSET (DOZABLE_MATCH | POWERSAVE_MATCH | RESTRICTED_MATCH | LOW_POWER_STANDBY_MATCH)
+#define DROP_IF_UNSET (DOZABLE_MATCH | POWERSAVE_MATCH | RESTRICTED_MATCH \
+                        | LOW_POWER_STANDBY_MATCH | BACKGROUND_MATCH)
 
 // Warning: funky bit-wise arithmetic: in parallel, for all DROP_IF_SET/UNSET rules
 // check whether the rules are globally enabled, and if so whether the rules are
diff --git a/common/flags.aconfig b/common/flags.aconfig
index 0c46b48..b85c2fe 100644
--- a/common/flags.aconfig
+++ b/common/flags.aconfig
@@ -34,3 +34,10 @@
   description: "This flag controls whether isUidNetworkingBlocked is supported"
   bug: "297836825"
 }
+
+flag {
+  name: "basic_background_restrictions_enabled"
+  namespace: "android_core_networking"
+  description: "Block network access for apps in a low importance background state"
+  bug: "304347838"
+}
diff --git a/framework-t/api/OWNERS b/framework-t/api/OWNERS
index 607f85a..8ef735c 100644
--- a/framework-t/api/OWNERS
+++ b/framework-t/api/OWNERS
@@ -1,2 +1,3 @@
 file:platform/packages/modules/Connectivity:main:/nearby/OWNERS
 file:platform/packages/modules/Connectivity:main:/remoteauth/OWNERS
+file:platform/packages/modules/Connectivity:main:/thread/OWNERS
diff --git a/framework-t/api/module-lib-lint-baseline.txt b/framework-t/api/module-lib-lint-baseline.txt
index 3158bd4..6f954df 100644
--- a/framework-t/api/module-lib-lint-baseline.txt
+++ b/framework-t/api/module-lib-lint-baseline.txt
@@ -5,3 +5,17 @@
     Methods must not mention RuntimeException subclasses in throws clauses (was `java.lang.SecurityException`)
 BannedThrow: android.app.usage.NetworkStatsManager#queryTaggedSummary(android.net.NetworkTemplate, long, long):
     Methods must not mention RuntimeException subclasses in throws clauses (was `java.lang.SecurityException`)
+
+
+MissingPermission: android.net.IpSecManager#startTunnelModeTransformMigration(android.net.IpSecTransform, java.net.InetAddress, java.net.InetAddress):
+    Feature field FEATURE_IPSEC_TUNNEL_MIGRATION required by method android.net.IpSecManager.startTunnelModeTransformMigration(android.net.IpSecTransform, java.net.InetAddress, java.net.InetAddress) is hidden or removed
+
+
+RequiresPermission: android.app.usage.NetworkStatsManager#registerUsageCallback(android.net.NetworkTemplate, long, java.util.concurrent.Executor, android.app.usage.NetworkStatsManager.UsageCallback):
+    Method 'registerUsageCallback' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.EthernetManager#disableInterface(String, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'disableInterface' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.EthernetManager#enableInterface(String, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'enableInterface' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.EthernetManager#updateConfiguration(String, android.net.EthernetNetworkUpdateRequest, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'updateConfiguration' documentation mentions permissions already declared by @RequiresPermission
diff --git a/framework-t/api/system-current.txt b/framework-t/api/system-current.txt
index 23510e1..b285d85 100644
--- a/framework-t/api/system-current.txt
+++ b/framework-t/api/system-current.txt
@@ -418,7 +418,6 @@
 package android.net.thread {
 
   @FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ActiveOperationalDataset implements android.os.Parcelable {
-    method @NonNull public static android.net.thread.ActiveOperationalDataset createRandomDataset();
     method public int describeContents();
     method @NonNull public static android.net.thread.ActiveOperationalDataset fromThreadTlvs(@NonNull byte[]);
     method @NonNull public android.net.thread.OperationalDatasetTimestamp getActiveTimestamp();
@@ -493,10 +492,49 @@
   }
 
   @FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ThreadNetworkController {
+    method public void createRandomizedDataset(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.net.thread.ActiveOperationalDataset,android.net.thread.ThreadNetworkException>);
     method public int getThreadVersion();
+    method public static boolean isAttached(int);
+    method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void join(@NonNull android.net.thread.ActiveOperationalDataset, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+    method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void leave(@NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+    method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_NETWORK_STATE, "android.permission.THREAD_NETWORK_PRIVILEGED"}) public void registerOperationalDatasetCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.thread.ThreadNetworkController.OperationalDatasetCallback);
+    method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void registerStateCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.thread.ThreadNetworkController.StateCallback);
+    method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void scheduleMigration(@NonNull android.net.thread.PendingOperationalDataset, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+    method public void unregisterOperationalDatasetCallback(@NonNull android.net.thread.ThreadNetworkController.OperationalDatasetCallback);
+    method public void unregisterStateCallback(@NonNull android.net.thread.ThreadNetworkController.StateCallback);
+    field public static final int DEVICE_ROLE_CHILD = 2; // 0x2
+    field public static final int DEVICE_ROLE_DETACHED = 1; // 0x1
+    field public static final int DEVICE_ROLE_LEADER = 4; // 0x4
+    field public static final int DEVICE_ROLE_ROUTER = 3; // 0x3
+    field public static final int DEVICE_ROLE_STOPPED = 0; // 0x0
     field public static final int THREAD_VERSION_1_3 = 4; // 0x4
   }
 
+  public static interface ThreadNetworkController.OperationalDatasetCallback {
+    method public void onActiveOperationalDatasetChanged(@Nullable android.net.thread.ActiveOperationalDataset);
+    method public default void onPendingOperationalDatasetChanged(@Nullable android.net.thread.PendingOperationalDataset);
+  }
+
+  public static interface ThreadNetworkController.StateCallback {
+    method public void onDeviceRoleChanged(int);
+    method public default void onPartitionIdChanged(long);
+  }
+
+  @FlaggedApi("com.android.net.thread.flags.thread_enabled") public class ThreadNetworkException extends java.lang.Exception {
+    ctor public ThreadNetworkException(int, @NonNull String);
+    method public int getErrorCode();
+    field public static final int ERROR_ABORTED = 2; // 0x2
+    field public static final int ERROR_BUSY = 5; // 0x5
+    field public static final int ERROR_FAILED_PRECONDITION = 6; // 0x6
+    field public static final int ERROR_INTERNAL_ERROR = 1; // 0x1
+    field public static final int ERROR_REJECTED_BY_PEER = 8; // 0x8
+    field public static final int ERROR_RESOURCE_EXHAUSTED = 10; // 0xa
+    field public static final int ERROR_RESPONSE_BAD_FORMAT = 9; // 0x9
+    field public static final int ERROR_TIMEOUT = 3; // 0x3
+    field public static final int ERROR_UNAVAILABLE = 4; // 0x4
+    field public static final int ERROR_UNSUPPORTED_CHANNEL = 7; // 0x7
+  }
+
   @FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ThreadNetworkManager {
     method @NonNull public java.util.List<android.net.thread.ThreadNetworkController> getAllThreadNetworkControllers();
   }
diff --git a/framework-t/api/system-lint-baseline.txt b/framework-t/api/system-lint-baseline.txt
index 9baf991..4f7af87 100644
--- a/framework-t/api/system-lint-baseline.txt
+++ b/framework-t/api/system-lint-baseline.txt
@@ -5,3 +5,161 @@
 
 GenericException: android.net.IpSecManager.IpSecTunnelInterface#finalize():
     Methods must not throw generic exceptions (`java.lang.Throwable`)
+
+
+MissingPermission: android.net.IpSecManager#startTunnelModeTransformMigration(android.net.IpSecTransform, java.net.InetAddress, java.net.InetAddress):
+    Feature field FEATURE_IPSEC_TUNNEL_MIGRATION required by method android.net.IpSecManager.startTunnelModeTransformMigration(android.net.IpSecTransform, java.net.InetAddress, java.net.InetAddress) is hidden or removed
+
+
+RequiresPermission: android.net.EthernetManager#disableInterface(String, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'disableInterface' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.EthernetManager#enableInterface(String, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'enableInterface' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.EthernetManager#updateConfiguration(String, android.net.EthernetNetworkUpdateRequest, java.util.concurrent.Executor, android.os.OutcomeReceiver<java.lang.String,android.net.EthernetNetworkManagementException>):
+    Method 'updateConfiguration' documentation mentions permissions already declared by @RequiresPermission
+
+
+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/api/lint-baseline.txt b/framework/api/lint-baseline.txt
index 2f4004a..4465bcb 100644
--- a/framework/api/lint-baseline.txt
+++ b/framework/api/lint-baseline.txt
@@ -1,4 +1,19 @@
 // Baseline format: 1.0
+BroadcastBehavior: android.net.ConnectivityManager#ACTION_BACKGROUND_DATA_SETTING_CHANGED:
+    Field 'ACTION_BACKGROUND_DATA_SETTING_CHANGED' is missing @BroadcastBehavior
+
+
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.app.PendingIntent):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities#getOwnerUid():
+    Method 'getOwnerUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.http.BidirectionalStream.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.http.UrlRequest.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
+
+
 VisiblySynchronized: android.net.NetworkInfo#toString():
     Internal locks must not be exposed (synchronizing on this or class is still
-    externally observable): method android.net.NetworkInfo.toString()
diff --git a/framework/api/module-lib-current.txt b/framework/api/module-lib-current.txt
index 4d55067..026d8a9 100644
--- a/framework/api/module-lib-current.txt
+++ b/framework/api/module-lib-current.txt
@@ -45,6 +45,7 @@
     field public static final int BLOCKED_METERED_REASON_DATA_SAVER = 65536; // 0x10000
     field public static final int BLOCKED_METERED_REASON_MASK = -65536; // 0xffff0000
     field public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 131072; // 0x20000
+    field @FlaggedApi("com.android.net.flags.basic_background_restrictions_enabled") public static final int BLOCKED_REASON_APP_BACKGROUND = 64; // 0x40
     field public static final int BLOCKED_REASON_APP_STANDBY = 4; // 0x4
     field public static final int BLOCKED_REASON_BATTERY_SAVER = 1; // 0x1
     field public static final int BLOCKED_REASON_DOZE = 2; // 0x2
@@ -52,6 +53,7 @@
     field public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 32; // 0x20
     field public static final int BLOCKED_REASON_NONE = 0; // 0x0
     field public static final int BLOCKED_REASON_RESTRICTED_MODE = 8; // 0x8
+    field @FlaggedApi("com.android.net.flags.basic_background_restrictions_enabled") public static final int FIREWALL_CHAIN_BACKGROUND = 6; // 0x6
     field public static final int FIREWALL_CHAIN_DOZABLE = 1; // 0x1
     field public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5; // 0x5
     field public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7; // 0x7
@@ -233,6 +235,7 @@
 
   public final class VpnTransportInfo implements android.os.Parcelable android.net.TransportInfo {
     ctor @Deprecated public VpnTransportInfo(int, @Nullable String);
+    method public long getApplicableRedactions();
     method @Nullable public String getSessionId();
     method @NonNull public android.net.VpnTransportInfo makeCopy(long);
   }
diff --git a/framework/api/module-lib-lint-baseline.txt b/framework/api/module-lib-lint-baseline.txt
new file mode 100644
index 0000000..53a8c5e
--- /dev/null
+++ b/framework/api/module-lib-lint-baseline.txt
@@ -0,0 +1,33 @@
+// Baseline format: 1.0
+BroadcastBehavior: android.net.ConnectivityManager#ACTION_BACKGROUND_DATA_SETTING_CHANGED:
+    Field 'ACTION_BACKGROUND_DATA_SETTING_CHANGED' is missing @BroadcastBehavior
+
+
+RequiresPermission: android.net.ConnectivityManager#isTetheringSupported():
+    Method 'isTetheringSupported' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.app.PendingIntent):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestRouteToHostAddress(int, java.net.InetAddress):
+    Method 'requestRouteToHostAddress' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.LinkProperties#getCaptivePortalApiUrl():
+    Method 'getCaptivePortalApiUrl' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.LinkProperties#getCaptivePortalData():
+    Method 'getCaptivePortalData' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities#getOwnerUid():
+    Method 'getOwnerUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities#getUnderlyingNetworks():
+    Method 'getUnderlyingNetworks' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities.Builder#setAllowedUids(java.util.Set<java.lang.Integer>):
+    Method 'setAllowedUids' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities.Builder#setSignalStrength(int):
+    Method 'setSignalStrength' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities.Builder#setUnderlyingNetworks(java.util.List<android.net.Network>):
+    Method 'setUnderlyingNetworks' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.NetworkRequest.Builder#setSignalStrength(int):
+    Method 'setSignalStrength' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.http.BidirectionalStream.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.http.UrlRequest.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
diff --git a/framework/api/system-lint-baseline.txt b/framework/api/system-lint-baseline.txt
index 9a97707..3ac97c0 100644
--- a/framework/api/system-lint-baseline.txt
+++ b/framework/api/system-lint-baseline.txt
@@ -1 +1,29 @@
 // Baseline format: 1.0
+BroadcastBehavior: android.net.ConnectivityManager#ACTION_BACKGROUND_DATA_SETTING_CHANGED:
+    Field 'ACTION_BACKGROUND_DATA_SETTING_CHANGED' is missing @BroadcastBehavior
+
+
+RequiresPermission: android.net.ConnectivityManager#isTetheringSupported():
+    Method 'isTetheringSupported' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.app.PendingIntent):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback):
+    Method 'requestNetwork' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.LinkProperties#getCaptivePortalApiUrl():
+    Method 'getCaptivePortalApiUrl' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.LinkProperties#getCaptivePortalData():
+    Method 'getCaptivePortalData' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities#getOwnerUid():
+    Method 'getOwnerUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities#getUnderlyingNetworks():
+    Method 'getUnderlyingNetworks' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities.Builder#setSignalStrength(int):
+    Method 'setSignalStrength' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.NetworkCapabilities.Builder#setUnderlyingNetworks(java.util.List<android.net.Network>):
+    Method 'setUnderlyingNetworks' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.NetworkRequest.Builder#setSignalStrength(int):
+    Method 'setSignalStrength' documentation mentions permissions already declared by @RequiresPermission
+RequiresPermission: android.net.http.BidirectionalStream.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
+RequiresPermission: android.net.http.UrlRequest.Builder#setTrafficStatsUid(int):
+    Method 'setTrafficStatsUid' documentation mentions permissions without declaring @RequiresPermission
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/BpfNetMapsConstants.java b/framework/src/android/net/BpfNetMapsConstants.java
index c784597..5d0fe73 100644
--- a/framework/src/android/net/BpfNetMapsConstants.java
+++ b/framework/src/android/net/BpfNetMapsConstants.java
@@ -16,6 +16,7 @@
 
 package android.net;
 
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
 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;
@@ -77,6 +78,7 @@
     public static final long OEM_DENY_1_MATCH = (1 << 9);
     public static final long OEM_DENY_2_MATCH = (1 << 10);
     public static final long OEM_DENY_3_MATCH = (1 << 11);
+    public static final long BACKGROUND_MATCH = (1 << 12);
 
     public static final List<Pair<Long, String>> MATCH_LIST = Arrays.asList(
             Pair.create(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"),
@@ -90,7 +92,8 @@
             Pair.create(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"),
             Pair.create(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"),
             Pair.create(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"),
-            Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH")
+            Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH"),
+            Pair.create(BACKGROUND_MATCH, "BACKGROUND_MATCH")
     );
 
     /**
@@ -102,7 +105,8 @@
             FIREWALL_CHAIN_DOZABLE,
             FIREWALL_CHAIN_POWERSAVE,
             FIREWALL_CHAIN_RESTRICTED,
-            FIREWALL_CHAIN_LOW_POWER_STANDBY
+            FIREWALL_CHAIN_LOW_POWER_STANDBY,
+            FIREWALL_CHAIN_BACKGROUND
     );
 
     /**
diff --git a/framework/src/android/net/BpfNetMapsUtils.java b/framework/src/android/net/BpfNetMapsUtils.java
index e9c9137..11d610c 100644
--- a/framework/src/android/net/BpfNetMapsUtils.java
+++ b/framework/src/android/net/BpfNetMapsUtils.java
@@ -17,6 +17,7 @@
 package android.net;
 
 import static android.net.BpfNetMapsConstants.ALLOW_CHAINS;
+import static android.net.BpfNetMapsConstants.BACKGROUND_MATCH;
 import static android.net.BpfNetMapsConstants.DENY_CHAINS;
 import static android.net.BpfNetMapsConstants.DOZABLE_MATCH;
 import static android.net.BpfNetMapsConstants.LOW_POWER_STANDBY_MATCH;
@@ -28,6 +29,7 @@
 import static android.net.BpfNetMapsConstants.POWERSAVE_MATCH;
 import static android.net.BpfNetMapsConstants.RESTRICTED_MATCH;
 import static android.net.BpfNetMapsConstants.STANDBY_MATCH;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
 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;
@@ -70,6 +72,8 @@
                 return POWERSAVE_MATCH;
             case FIREWALL_CHAIN_RESTRICTED:
                 return RESTRICTED_MATCH;
+            case FIREWALL_CHAIN_BACKGROUND:
+                return BACKGROUND_MATCH;
             case FIREWALL_CHAIN_LOW_POWER_STANDBY:
                 return LOW_POWER_STANDBY_MATCH;
             case FIREWALL_CHAIN_OEM_DENY_1:
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index eb8f8c3..57ecf49 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -135,6 +135,8 @@
                 "com.android.net.flags.set_data_saver_via_cm";
         static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
                 "com.android.net.flags.support_is_uid_networking_blocked";
+        static final String BASIC_BACKGROUND_RESTRICTIONS_ENABLED =
+                "com.android.net.flags.basic_background_restrictions_enabled";
     }
 
     /**
@@ -908,6 +910,16 @@
     public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
 
     /**
+     * Flag to indicate that an app is subject to default background restrictions that would
+     * result in its network access being blocked.
+     *
+     * @hide
+     */
+    @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
+    @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+    public static final int BLOCKED_REASON_APP_BACKGROUND = 1 << 6;
+
+    /**
      * Flag to indicate that an app is subject to Data saver restrictions that would
      * result in its metered network access being blocked.
      *
@@ -946,6 +958,7 @@
             BLOCKED_REASON_RESTRICTED_MODE,
             BLOCKED_REASON_LOCKDOWN_VPN,
             BLOCKED_REASON_LOW_POWER_STANDBY,
+            BLOCKED_REASON_APP_BACKGROUND,
             BLOCKED_METERED_REASON_DATA_SAVER,
             BLOCKED_METERED_REASON_USER_RESTRICTED,
             BLOCKED_METERED_REASON_ADMIN_DISABLED,
@@ -963,7 +976,6 @@
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
     private final IConnectivityManager mService;
 
-    // LINT.IfChange(firewall_chain)
     /**
      * Firewall chain for device idle (doze mode).
      * Allowlist of apps that have network access in device idle.
@@ -1005,6 +1017,16 @@
     public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
 
     /**
+     * Firewall chain used for always-on default background restrictions.
+     * Allowlist of apps that have access because either they are in the foreground or they are
+     * exempted for specific situations while in the background.
+     * @hide
+     */
+    @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
+    @SystemApi(client = MODULE_LIBRARIES)
+    public static final int FIREWALL_CHAIN_BACKGROUND = 6;
+
+    /**
      * Firewall chain used for OEM-specific application restrictions.
      *
      * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
@@ -1063,12 +1085,12 @@
         FIREWALL_CHAIN_POWERSAVE,
         FIREWALL_CHAIN_RESTRICTED,
         FIREWALL_CHAIN_LOW_POWER_STANDBY,
+        FIREWALL_CHAIN_BACKGROUND,
         FIREWALL_CHAIN_OEM_DENY_1,
         FIREWALL_CHAIN_OEM_DENY_2,
         FIREWALL_CHAIN_OEM_DENY_3
     })
     public @interface FirewallChain {}
-    // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
 
     /**
      * A firewall rule which allows or drops packets depending on existing policy.
@@ -3963,16 +3985,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 +4016,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 +4144,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 +4250,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 +4288,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 +4343,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 +4369,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/LocalNetworkConfig.java b/framework/src/android/net/LocalNetworkConfig.java
index fca7fd1..17b1064 100644
--- a/framework/src/android/net/LocalNetworkConfig.java
+++ b/framework/src/android/net/LocalNetworkConfig.java
@@ -62,11 +62,19 @@
         return mUpstreamSelector;
     }
 
-    public @NonNull MulticastRoutingConfig getUpstreamMulticastRoutingConfig() {
+    /**
+     * Get the upstream multicast routing config
+     */
+    @NonNull
+    public MulticastRoutingConfig getUpstreamMulticastRoutingConfig() {
         return mUpstreamMulticastRoutingConfig;
     }
 
-    public @NonNull MulticastRoutingConfig getDownstreamMulticastRoutingConfig() {
+    /**
+     * Get the downstream multicast routing config
+     */
+    @NonNull
+    public MulticastRoutingConfig getDownstreamMulticastRoutingConfig() {
         return mDownstreamMulticastRoutingConfig;
     }
 
@@ -82,6 +90,15 @@
         dest.writeParcelable(mDownstreamMulticastRoutingConfig, flags);
     }
 
+    @Override
+    public String toString() {
+        return "LocalNetworkConfig{"
+                + "UpstreamSelector=" + mUpstreamSelector
+                + ", UpstreamMulticastConfig=" + mUpstreamMulticastRoutingConfig
+                + ", DownstreamMulticastConfig=" + mDownstreamMulticastRoutingConfig
+                + '}';
+    }
+
     public static final @NonNull Creator<LocalNetworkConfig> CREATOR = new Creator<>() {
         public LocalNetworkConfig createFromParcel(Parcel in) {
             final NetworkRequest upstreamSelector = in.readParcelable(null);
@@ -100,13 +117,13 @@
 
     public static final class Builder {
         @Nullable
-        NetworkRequest mUpstreamSelector;
+        private NetworkRequest mUpstreamSelector;
 
         @Nullable
-        MulticastRoutingConfig mUpstreamMulticastRoutingConfig;
+        private MulticastRoutingConfig mUpstreamMulticastRoutingConfig;
 
         @Nullable
-        MulticastRoutingConfig mDownstreamMulticastRoutingConfig;
+        private MulticastRoutingConfig mDownstreamMulticastRoutingConfig;
 
         /**
          * Create a Builder
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/MulticastRoutingConfig.java b/framework/src/android/net/MulticastRoutingConfig.java
index ebd9fc5..1f4071c 100644
--- a/framework/src/android/net/MulticastRoutingConfig.java
+++ b/framework/src/android/net/MulticastRoutingConfig.java
@@ -38,8 +38,8 @@
  * Internal usage to Connectivity
  * @hide
  */
-// TODO : @SystemApi
-public class MulticastRoutingConfig implements Parcelable {
+// @SystemApi(client = MODULE_LIBRARIES)
+public final class MulticastRoutingConfig implements Parcelable {
     private static final String TAG = MulticastRoutingConfig.class.getSimpleName();
 
     /** Do not forward any multicast packets. */
@@ -55,6 +55,7 @@
      */
     public static final int FORWARD_WITH_MIN_SCOPE = 2;
 
+    /** @hide */
     @Retention(RetentionPolicy.SOURCE)
     @IntDef(prefix = { "FORWARD_" }, value = {
             FORWARD_NONE,
@@ -68,6 +69,7 @@
      */
     public static final int MULTICAST_SCOPE_NONE = -1;
 
+    /** @hide */
     public static final MulticastRoutingConfig CONFIG_FORWARD_NONE =
             new MulticastRoutingConfig(FORWARD_NONE, MULTICAST_SCOPE_NONE, null);
 
@@ -102,7 +104,7 @@
      * Returns the minimal group address scope that is allowed for forwarding.
      * If the forwarding mode is not FORWARD_WITH_MIN_SCOPE, will be MULTICAST_SCOPE_NONE.
      */
-    public int getMinScope() {
+    public int getMinimumScope() {
         return mMinScope;
     }
 
@@ -111,7 +113,7 @@
      * The list will be empty if the forwarding mode is not FORWARD_SELECTED.
      */
     @NonNull
-    public Set<Inet6Address> getMulticastListeningAddresses() {
+    public Set<Inet6Address> getListeningAddresses() {
         return mListeningAddresses;
     }
 
@@ -133,7 +135,7 @@
     }
 
     @Override
-    public void writeToParcel(Parcel dest, int flags) {
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
         dest.writeInt(mForwardingMode);
         dest.writeInt(mMinScope);
         dest.writeInt(mListeningAddresses.size());
@@ -147,9 +149,10 @@
         return 0;
     }
 
+    @NonNull
     public static final Creator<MulticastRoutingConfig> CREATOR = new Creator<>() {
         @Override
-        public MulticastRoutingConfig createFromParcel(Parcel in) {
+        public MulticastRoutingConfig createFromParcel(@NonNull Parcel in) {
             return new MulticastRoutingConfig(in);
         }
 
@@ -159,43 +162,76 @@
         }
     };
 
-    public static class Builder {
+    @Override
+    public String toString() {
+        return "MulticastRoutingConfig{"
+                + "ForwardingMode=" + forwardingModeToString(mForwardingMode)
+                + ", MinScope=" + mMinScope
+                + ", ListeningAddresses=" + mListeningAddresses
+                + '}';
+    }
+
+    private static String forwardingModeToString(final int forwardingMode) {
+        switch (forwardingMode) {
+            case FORWARD_NONE: return "NONE";
+            case FORWARD_SELECTED: return "SELECTED";
+            case FORWARD_WITH_MIN_SCOPE: return "WITH_MIN_SCOPE";
+            default: return "UNKNOWN";
+        }
+    }
+
+    public static final class Builder {
         @MulticastForwardingMode
         private final int mForwardingMode;
         private int mMinScope;
         private final ArraySet<Inet6Address> mListeningAddresses;
 
-        private Builder(@MulticastForwardingMode final int mode, int scope) {
+        // The two constructors with runtime checks for the mode and scope are arguably
+        // less convenient than three static factory methods, but API guidelines mandates
+        // that Builders are built with a constructor and not factory methods.
+        /**
+         * Create a new builder for forwarding mode FORWARD_NONE or FORWARD_SELECTED.
+         *
+         * <p>On a Builder for FORWARD_NONE, no properties can be set.
+         * <p>On a Builder for FORWARD_SELECTED, listening addresses can be added and removed
+         * but the minimum scope can't be set.
+         *
+         * @param mode {@link #FORWARD_NONE} or {@link #FORWARD_SELECTED}. Any other
+         *             value will result in IllegalArgumentException.
+         * @see #Builder(int, int)
+         */
+        public Builder(@MulticastForwardingMode final int mode) {
+            if (FORWARD_NONE != mode && FORWARD_SELECTED != mode) {
+                if (FORWARD_WITH_MIN_SCOPE == mode) {
+                    throw new IllegalArgumentException("FORWARD_WITH_MIN_SCOPE requires "
+                            + "passing the scope as a second argument");
+                } else {
+                    throw new IllegalArgumentException("Unknown forwarding mode : " + mode);
+                }
+            }
             mForwardingMode = mode;
-            mMinScope = scope;
+            mMinScope = MULTICAST_SCOPE_NONE;
             mListeningAddresses = new ArraySet<>();
         }
 
         /**
-         * Create a builder that forwards nothing.
-         * No properties can be set on such a builder.
-         */
-        public static Builder newBuilderForwardingNone() {
-            return new Builder(FORWARD_NONE, MULTICAST_SCOPE_NONE);
-        }
-
-        /**
-         * Create a builder that forwards packets above a certain scope
+         * Create a new builder for forwarding mode FORWARD_WITH_MIN_SCOPE.
          *
-         * The scope can be changed on this builder, but not the listening addresses.
-         * @param scope the initial scope
-         */
-        public static Builder newBuilderWithMinScope(final int scope) {
-            return new Builder(FORWARD_WITH_MIN_SCOPE, scope);
-        }
-
-        /**
-         * Create a builder that forwards a specified list of listening addresses.
+         * <p>On this Builder the scope can be set with {@link #setMinimumScope}, but
+         * listening addresses can't be added or removed.
          *
-         * Addresses can be added and removed from this builder, but the scope can't be set.
+         * @param mode Must be {@link #FORWARD_WITH_MIN_SCOPE}.
+         * @param scope the minimum scope for this multicast routing config.
+         * @see Builder#Builder(int)
          */
-        public static Builder newBuilderWithListeningAddresses() {
-            return new Builder(FORWARD_SELECTED, MULTICAST_SCOPE_NONE);
+        public Builder(@MulticastForwardingMode final int mode, int scope) {
+            if (FORWARD_WITH_MIN_SCOPE != mode) {
+                throw new IllegalArgumentException("Forwarding with a min scope must "
+                        + "use forward mode FORWARD_WITH_MIN_SCOPE");
+            }
+            mForwardingMode = mode;
+            mMinScope = scope;
+            mListeningAddresses = new ArraySet<>();
         }
 
         /**
@@ -203,6 +239,7 @@
          * This is only meaningful (indeed, allowed) for configs in FORWARD_WITH_MIN_SCOPE mode.
          * @return this builder
          */
+        @NonNull
         public Builder setMinimumScope(final int scope) {
             if (FORWARD_WITH_MIN_SCOPE != mForwardingMode) {
                 throw new IllegalArgumentException("Can't set the scope on a builder in mode "
@@ -219,6 +256,7 @@
          * If this address was already added, this is a no-op.
          * @return this builder
          */
+        @NonNull
         public Builder addListeningAddress(@NonNull final Inet6Address address) {
             if (FORWARD_SELECTED != mForwardingMode) {
                 throw new IllegalArgumentException("Can't add an address on a builder in mode "
@@ -236,7 +274,8 @@
          * If this address was not added, or was already removed, this is a no-op.
          * @return this builder
          */
-        public Builder removeListeningAddress(@NonNull final Inet6Address address) {
+        @NonNull
+        public Builder clearListeningAddress(@NonNull final Inet6Address address) {
             if (FORWARD_SELECTED != mForwardingMode) {
                 throw new IllegalArgumentException("Can't remove an address on a builder in mode "
                         + modeToString(mForwardingMode));
@@ -248,6 +287,7 @@
         /**
          * Build the config.
          */
+        @NonNull
         public MulticastRoutingConfig build() {
             return new MulticastRoutingConfig(mForwardingMode, mMinScope, mListeningAddresses);
         }
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/NsdService.java b/service-t/src/com/android/server/NsdService.java
index c74f229..43357e4 100644
--- a/service-t/src/com/android/server/NsdService.java
+++ b/service-t/src/com/android/server/NsdService.java
@@ -1647,10 +1647,12 @@
                         mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
                 .setIsExpiredServicesRemovalEnabled(mDeps.isTrunkStableFeatureEnabled(
                         MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
+                .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
+                        mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
                 .build();
         mMdnsSocketClient =
                 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
-                        LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
+                        LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
         mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
                 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
         handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsFeatureFlags.java b/service-t/src/com/android/server/connectivity/mdns/MdnsFeatureFlags.java
index 6f7645e..738c151 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsFeatureFlags.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsFeatureFlags.java
@@ -36,6 +36,11 @@
     public static final String NSD_EXPIRED_SERVICES_REMOVAL =
             "nsd_expired_services_removal";
 
+    /**
+     * A feature flag to control whether the label count limit should be enabled.
+     */
+    public static final String NSD_LIMIT_LABEL_COUNT = "nsd_limit_label_count";
+
     // Flag for offload feature
     public final boolean mIsMdnsOffloadFeatureEnabled;
 
@@ -45,14 +50,20 @@
     // Flag for expired services removal
     public final boolean mIsExpiredServicesRemovalEnabled;
 
+    // Flag for label count limit
+    public final boolean mIsLabelCountLimitEnabled;
+
     /**
      * The constructor for {@link MdnsFeatureFlags}.
      */
     public MdnsFeatureFlags(boolean isOffloadFeatureEnabled,
-            boolean includeInetAddressRecordsInProbing, boolean isExpiredServicesRemovalEnabled) {
+            boolean includeInetAddressRecordsInProbing,
+            boolean isExpiredServicesRemovalEnabled,
+            boolean isLabelCountLimitEnabled) {
         mIsMdnsOffloadFeatureEnabled = isOffloadFeatureEnabled;
         mIncludeInetAddressRecordsInProbing = includeInetAddressRecordsInProbing;
         mIsExpiredServicesRemovalEnabled = isExpiredServicesRemovalEnabled;
+        mIsLabelCountLimitEnabled = isLabelCountLimitEnabled;
     }
 
 
@@ -67,6 +78,7 @@
         private boolean mIsMdnsOffloadFeatureEnabled;
         private boolean mIncludeInetAddressRecordsInProbing;
         private boolean mIsExpiredServicesRemovalEnabled;
+        private boolean mIsLabelCountLimitEnabled;
 
         /**
          * The constructor for {@link Builder}.
@@ -75,6 +87,7 @@
             mIsMdnsOffloadFeatureEnabled = false;
             mIncludeInetAddressRecordsInProbing = false;
             mIsExpiredServicesRemovalEnabled = true; // Default enabled.
+            mIsLabelCountLimitEnabled = true; // Default enabled.
         }
 
         /**
@@ -109,11 +122,23 @@
         }
 
         /**
+         * Set whether the label count limit is enabled.
+         *
+         * @see #NSD_LIMIT_LABEL_COUNT
+         */
+        public Builder setIsLabelCountLimitEnabled(boolean isLabelCountLimitEnabled) {
+            mIsLabelCountLimitEnabled = isLabelCountLimitEnabled;
+            return this;
+        }
+
+        /**
          * Builds a {@link MdnsFeatureFlags} with the arguments supplied to this builder.
          */
         public MdnsFeatureFlags build() {
             return new MdnsFeatureFlags(mIsMdnsOffloadFeatureEnabled,
-                    mIncludeInetAddressRecordsInProbing, mIsExpiredServicesRemovalEnabled);
+                    mIncludeInetAddressRecordsInProbing,
+                    mIsExpiredServicesRemovalEnabled,
+                    mIsLabelCountLimitEnabled);
         }
     }
 }
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java b/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
index 42a6b0d..62c37ad 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
@@ -65,11 +65,12 @@
     private final MdnsProber mProber;
     @NonNull
     private final MdnsReplySender mReplySender;
-
     @NonNull
     private final SharedLog mSharedLog;
     @NonNull
     private final byte[] mPacketCreationBuffer;
+    @NonNull
+    private final MdnsFeatureFlags mMdnsFeatureFlags;
 
     /**
      * Callbacks called by {@link MdnsInterfaceAdvertiser} to report status updates.
@@ -213,6 +214,7 @@
         mProber = deps.makeMdnsProber(sharedLog.getTag(), looper, mReplySender, mProbingCallback,
                 sharedLog);
         mSharedLog = sharedLog;
+        mMdnsFeatureFlags = mdnsFeatureFlags;
     }
 
     /**
@@ -351,7 +353,7 @@
     public void handlePacket(byte[] recvbuf, int length, InetSocketAddress src) {
         final MdnsPacket packet;
         try {
-            packet = MdnsPacket.parse(new MdnsPacketReader(recvbuf, length));
+            packet = MdnsPacket.parse(new MdnsPacketReader(recvbuf, length, mMdnsFeatureFlags));
         } catch (MdnsPacket.ParseException e) {
             mSharedLog.e("Error parsing mDNS packet", e);
             if (DBG) {
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClient.java b/service-t/src/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClient.java
index 4ba6912..e7b0eaa 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClient.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClient.java
@@ -50,6 +50,7 @@
     @NonNull private final Handler mHandler;
     @NonNull private final MdnsSocketProvider mSocketProvider;
     @NonNull private final SharedLog mSharedLog;
+    @NonNull private final MdnsFeatureFlags mMdnsFeatureFlags;
 
     private final ArrayMap<MdnsServiceBrowserListener, InterfaceSocketCallback> mSocketRequests =
             new ArrayMap<>();
@@ -58,11 +59,12 @@
     private int mReceivedPacketNumber = 0;
 
     public MdnsMultinetworkSocketClient(@NonNull Looper looper,
-            @NonNull MdnsSocketProvider provider,
-            @NonNull SharedLog sharedLog) {
+            @NonNull MdnsSocketProvider provider, @NonNull SharedLog sharedLog,
+            @NonNull MdnsFeatureFlags mdnsFeatureFlags) {
         mHandler = new Handler(looper);
         mSocketProvider = provider;
         mSharedLog = sharedLog;
+        mMdnsFeatureFlags = mdnsFeatureFlags;
     }
 
     private class InterfaceSocketCallback implements MdnsSocketProvider.SocketCallback {
@@ -239,7 +241,7 @@
 
         final MdnsPacket response;
         try {
-            response = MdnsResponseDecoder.parseResponse(recvbuf, length);
+            response = MdnsResponseDecoder.parseResponse(recvbuf, length, mMdnsFeatureFlags);
         } catch (MdnsPacket.ParseException e) {
             if (e.code != MdnsResponseErrorCode.ERROR_NOT_RESPONSE_MESSAGE) {
                 mSharedLog.e(e.getMessage(), e);
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsPacketReader.java b/service-t/src/com/android/server/connectivity/mdns/MdnsPacketReader.java
index aa38844..4917188 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsPacketReader.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsPacketReader.java
@@ -16,6 +16,7 @@
 
 package com.android.server.connectivity.mdns;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.util.SparseArray;
 
@@ -33,21 +34,23 @@
     private final byte[] buf;
     private final int count;
     private final SparseArray<LabelEntry> labelDictionary;
+    private final MdnsFeatureFlags mMdnsFeatureFlags;
     private int pos;
     private int limit;
 
     /** Constructs a reader for the given packet. */
     public MdnsPacketReader(DatagramPacket packet) {
-        this(packet.getData(), packet.getLength());
+        this(packet.getData(), packet.getLength(), MdnsFeatureFlags.newBuilder().build());
     }
 
     /** Constructs a reader for the given packet. */
-    public MdnsPacketReader(byte[] buffer, int length) {
+    public MdnsPacketReader(byte[] buffer, int length, @NonNull MdnsFeatureFlags mdnsFeatureFlags) {
         buf = buffer;
         count = length;
         pos = 0;
         limit = -1;
         labelDictionary = new SparseArray<>(16);
+        mMdnsFeatureFlags = mdnsFeatureFlags;
     }
 
     /**
@@ -269,4 +272,4 @@
             this.label = label;
         }
     }
-}
\ No newline at end of file
+}
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsResponseDecoder.java b/service-t/src/com/android/server/connectivity/mdns/MdnsResponseDecoder.java
index 050913f..b812bb4 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsResponseDecoder.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsResponseDecoder.java
@@ -84,9 +84,9 @@
      * @throws MdnsPacket.ParseException if a response packet could not be parsed.
      */
     @NonNull
-    public static MdnsPacket parseResponse(@NonNull byte[] recvbuf, int length)
-            throws MdnsPacket.ParseException {
-        MdnsPacketReader reader = new MdnsPacketReader(recvbuf, length);
+    public static MdnsPacket parseResponse(@NonNull byte[] recvbuf, int length,
+            @NonNull MdnsFeatureFlags mdnsFeatureFlags) throws MdnsPacket.ParseException {
+        final MdnsPacketReader reader = new MdnsPacketReader(recvbuf, length, mdnsFeatureFlags);
 
         final MdnsPacket mdnsPacket;
         try {
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsSocketClient.java b/service-t/src/com/android/server/connectivity/mdns/MdnsSocketClient.java
index d18a19b..82c8c5b 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsSocketClient.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsSocketClient.java
@@ -105,9 +105,10 @@
     private AtomicInteger packetsCount;
     @Nullable private Timer checkMulticastResponseTimer;
     private final SharedLog sharedLog;
+    @NonNull private final MdnsFeatureFlags mdnsFeatureFlags;
 
     public MdnsSocketClient(@NonNull Context context, @NonNull MulticastLock multicastLock,
-            SharedLog sharedLog) {
+            SharedLog sharedLog, @NonNull MdnsFeatureFlags mdnsFeatureFlags) {
         this.sharedLog = sharedLog;
         this.context = context;
         this.multicastLock = multicastLock;
@@ -116,6 +117,7 @@
         } else {
             unicastReceiverBuffer = null;
         }
+        this.mdnsFeatureFlags = mdnsFeatureFlags;
     }
 
     @Override
@@ -454,7 +456,8 @@
 
         final MdnsPacket response;
         try {
-            response = MdnsResponseDecoder.parseResponse(packet.getData(), packet.getLength());
+            response = MdnsResponseDecoder.parseResponse(
+                    packet.getData(), packet.getLength(), mdnsFeatureFlags);
         } catch (MdnsPacket.ParseException e) {
             sharedLog.w(String.format("Error while decoding %s packet (%d): %d",
                     responseType, packetNumber, e.code));
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..82f64ba 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -107,11 +107,15 @@
         "-Werror",
         "-Wno-unused-parameter",
         "-Wthread-safety",
+
+        // AServiceManager_waitForService is available on only 31+, but it's still safe for Thread
+        // service because it's enabled on only 34+
+        "-Wno-unguarded-availability",
     ],
     srcs: [
         ":services.connectivity-netstats-jni-sources",
-        "jni/com_android_server_BpfNetMaps.cpp",
         "jni/com_android_server_connectivity_ClatCoordinator.cpp",
+        "jni/com_android_server_ServiceManagerWrapper.cpp",
         "jni/com_android_server_TestNetworkService.cpp",
         "jni/onload.cpp",
     ],
@@ -124,11 +128,11 @@
         "libmodules-utils-build",
         "libnetjniutils",
         "libnet_utils_device_common_bpfjni",
-        "libtraffic_controller",
         "netd_aidl_interface-lateststable-ndk",
     ],
     shared_libs: [
         "libbase",
+        "libbinder_ndk",
         "libcutils",
         "libnetdutils",
         "liblog",
@@ -204,6 +208,8 @@
     visibility: [
         "//packages/modules/Connectivity/service-t",
         "//packages/modules/Connectivity/tests:__subpackages__",
+        "//packages/modules/Connectivity/thread/service:__subpackages__",
+        "//packages/modules/Connectivity/thread/tests:__subpackages__",
     ],
 }
 
diff --git a/service/jni/com_android_server_BpfNetMaps.cpp b/service/jni/com_android_server_BpfNetMaps.cpp
deleted file mode 100644
index 50a0635..0000000
--- a/service/jni/com_android_server_BpfNetMaps.cpp
+++ /dev/null
@@ -1,236 +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 "TrafficControllerJni"
-
-#include "TrafficController.h"
-
-#include "netd.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();
-}
-
-/*
- * JNI registration.
- */
-// 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},
-};
-// clang-format on
-
-int register_com_android_server_BpfNetMaps(JNIEnv* env) {
-    return jniRegisterNativeMethods(env, "android/net/connectivity/com/android/server/BpfNetMaps",
-                                    gMethods, NELEM(gMethods));
-}
-
-}; // namespace android
diff --git a/service/jni/com_android_server_ServiceManagerWrapper.cpp b/service/jni/com_android_server_ServiceManagerWrapper.cpp
new file mode 100644
index 0000000..0cd58f4
--- /dev/null
+++ b/service/jni/com_android_server_ServiceManagerWrapper.cpp
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+
+#include <android/binder_ibinder_jni.h>
+#include <android/binder_manager.h>
+#include <jni.h>
+#include "nativehelper/JNIHelp.h"
+#include <nativehelper/ScopedUtfChars.h>
+#include <private/android_filesystem_config.h>
+
+namespace android {
+static jobject com_android_server_ServiceManagerWrapper_waitForService(
+        JNIEnv* env, jobject clazz, jstring serviceName) {
+    ScopedUtfChars name(env, serviceName);
+    return AIBinder_toJavaBinder(env, AServiceManager_waitForService(name.c_str()));
+}
+
+/*
+ * JNI registration.
+ */
+
+static const JNINativeMethod gMethods[] = {
+        /* name, signature, funcPtr */
+        {"nativeWaitForService",
+         "(Ljava/lang/String;)Landroid/os/IBinder;",
+         (void*)com_android_server_ServiceManagerWrapper_waitForService},
+};
+
+int register_com_android_server_ServiceManagerWrapper(JNIEnv* env) {
+    return jniRegisterNativeMethods(env,
+            "android/net/connectivity/com/android/server/ServiceManagerWrapper",
+            gMethods, NELEM(gMethods));
+}
+
+};  // namespace android
diff --git a/service/jni/onload.cpp b/service/jni/onload.cpp
index ed74430..bb70d4f 100644
--- a/service/jni/onload.cpp
+++ b/service/jni/onload.cpp
@@ -22,10 +22,10 @@
 namespace android {
 
 int register_com_android_server_TestNetworkService(JNIEnv* env);
-int register_com_android_server_BpfNetMaps(JNIEnv* env);
 int register_com_android_server_connectivity_ClatCoordinator(JNIEnv* env);
 int register_android_server_net_NetworkStatsFactory(JNIEnv* env);
 int register_android_server_net_NetworkStatsService(JNIEnv* env);
+int register_com_android_server_ServiceManagerWrapper(JNIEnv* env);
 
 extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
     JNIEnv *env;
@@ -38,11 +38,11 @@
         return JNI_ERR;
     }
 
-    if (android::modules::sdklevel::IsAtLeastT()) {
-        if (register_com_android_server_BpfNetMaps(env) < 0) {
-            return JNI_ERR;
-        }
+    if (register_com_android_server_ServiceManagerWrapper(env) < 0) {
+        return JNI_ERR;
+    }
 
+    if (android::modules::sdklevel::IsAtLeastT()) {
         if (register_com_android_server_connectivity_ClatCoordinator(env) < 0) {
             return JNI_ERR;
         }
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/Common.h b/service/native/include/Common.h
deleted file mode 100644
index 03f449a..0000000
--- a/service/native/include/Common.h
+++ /dev/null
@@ -1,46 +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
-// TODO: deduplicate with the constants in NetdConstants.h.
-#include <aidl/android/net/INetd.h>
-#include "clat_mark.h"
-
-using aidl::android::net::INetd;
-
-static_assert(INetd::CLAT_MARK == CLAT_MARK, "must be 0xDEADC1A7");
-
-enum FirewallRule { ALLOW = INetd::FIREWALL_RULE_ALLOW, DENY = INetd::FIREWALL_RULE_DENY };
-
-// ALLOWLIST means the firewall denies all by default, uids must be explicitly ALLOWed
-// DENYLIST means the firewall allows all by default, uids must be explicitly DENYed
-
-enum FirewallType { ALLOWLIST = INetd::FIREWALL_ALLOWLIST, DENYLIST = INetd::FIREWALL_DENYLIST };
-
-// LINT.IfChange(firewall_chain)
-enum ChildChain {
-    NONE = 0,
-    DOZABLE = 1,
-    STANDBY = 2,
-    POWERSAVE = 3,
-    RESTRICTED = 4,
-    LOW_POWER_STANDBY = 5,
-    OEM_DENY_1 = 7,
-    OEM_DENY_2 = 8,
-    OEM_DENY_3 = 9,
-    INVALID_CHAIN
-};
-// LINT.ThenChange(packages/modules/Connectivity/framework/src/android/net/ConnectivityManager.java)
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/native/libs/libclat/Android.bp b/service/native/libs/libclat/Android.bp
index 996706e..5c6b123 100644
--- a/service/native/libs/libclat/Android.bp
+++ b/service/native/libs/libclat/Android.bp
@@ -43,11 +43,15 @@
     srcs: [
         "clatutils_test.cpp",
     ],
+    header_libs: [
+        "bpf_connectivity_headers",
+    ],
     static_libs: [
         "libbase",
         "libclat",
         "libip_checksum",
         "libnetd_test_tun_interface",
+        "netd_aidl_interface-lateststable-ndk",
     ],
     shared_libs: [
         "liblog",
diff --git a/service/native/libs/libclat/clatutils_test.cpp b/service/native/libs/libclat/clatutils_test.cpp
index f4f97db..cf6492f 100644
--- a/service/native/libs/libclat/clatutils_test.cpp
+++ b/service/native/libs/libclat/clatutils_test.cpp
@@ -26,6 +26,10 @@
 #include "checksum.h"
 }
 
+#include <aidl/android/net/INetd.h>
+#include "clat_mark.h"
+static_assert(aidl::android::net::INetd::CLAT_MARK == CLAT_MARK, "must be 0xDEADC1A7");
+
 // Default translation parameters.
 static const char kIPv4LocalAddr[] = "192.0.0.4";
 
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index f20159c..ad9cfbe 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,10 +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";
-
     // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
     // This entry is not accessed by others.
     // BpfNetMaps acquires this lock while sequence of read, modify, and write.
@@ -149,14 +135,6 @@
     );
 
     /**
-     * Set sEnableJavaBpfMap for test.
-     */
-    @VisibleForTesting
-    public static void setEnableJavaBpfMapForTest(boolean enable) {
-        sEnableJavaBpfMap = enable;
-    }
-
-    /**
      * Set configurationMap for test.
      */
     @VisibleForTesting
@@ -319,22 +297,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.
      */
@@ -355,10 +321,16 @@
         }
 
         /**
-         * Call synchronize_rcu()
+         * Synchronously call in to kernel to synchronize_rcu()
          */
+        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
         public int synchronizeKernelRCU() {
-            return native_synchronizeKernelRCU();
+            try {
+                BpfMap.synchronizeKernelRCU();
+            } catch (ErrnoException e) {
+                return -e.errno;
+            }
+            return 0;
         }
 
         /**
@@ -476,12 +448,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 +462,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 +476,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 +490,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 +506,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 +558,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 +606,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 +717,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 +755,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 +776,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 +794,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 +834,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 +1028,6 @@
         pw.println("TrafficController");  // required by CTS testDumpBpfNetMaps
 
         pw.println();
-        pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
         if (verbose) {
             pw.println();
             pw.println("BPF map content:");
@@ -1184,46 +1064,4 @@
             pw.decreaseIndent();
         }
     }
-
-    @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..7d1644e 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()) {
@@ -8996,6 +9006,9 @@
             return;
         }
 
+        if (VDBG) {
+            Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
+        }
         final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
         // TODO : apply the diff for multicast routing.
         configBuilder.setUpstreamMulticastRoutingConfig(
@@ -9021,6 +9034,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 +9061,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 +9399,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 +9449,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 +9484,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 +10125,7 @@
                     loge("Can't update forwarding rules", e);
                 }
             }
+            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
         }
 
         updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
@@ -12838,6 +12887,7 @@
             case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
             case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
             case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
+            case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
                 defaultRule = FIREWALL_RULE_DENY;
                 break;
             default:
diff --git a/service/src/com/android/server/ServiceManagerWrapper.java b/service/src/com/android/server/ServiceManagerWrapper.java
new file mode 100644
index 0000000..6d99f33
--- /dev/null
+++ b/service/src/com/android/server/ServiceManagerWrapper.java
@@ -0,0 +1,46 @@
+/*
+ * 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 com.android.server;
+
+import android.annotation.RequiresApi;
+import android.os.IBinder;
+import android.os.Build;
+import android.os.ServiceManager;
+
+/** Provides a way to access {@link ServiceManager#waitForService} API. */
+@RequiresApi(Build.VERSION_CODES.S)
+public final class ServiceManagerWrapper {
+    static {
+        System.loadLibrary("service-connectivity");
+    }
+
+    private ServiceManagerWrapper() {}
+
+    /**
+     * Returns the specified service from the service manager.
+     *
+     * If the service is not running, service manager will attempt to start it, and this function
+     * will wait for it to be ready.
+     *
+     * @return {@code null} only if there are permission problems or fatal errors
+     */
+    public static IBinder waitForService(String serviceName) {
+        return nativeWaitForService(serviceName);
+    }
+
+    private static native IBinder nativeWaitForService(String serviceName);
+}
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index 0bcb757..6325b46 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -96,12 +96,17 @@
     srcs: [
     "framework/**/DnsPacket.java",
     "framework/**/DnsPacketUtils.java",
+    "framework/**/DnsSvcbPacket.java",
+    "framework/**/DnsSvcbRecord.java",
+    "framework/**/HexDump.java",
+    "framework/**/NetworkStackConstants.java",
     ],
     sdk_version: "module_current",
     visibility: [
         "//packages/services/Iwlan:__subpackages__",
     ],
     libs: [
+        "androidx.annotation_annotation",
         "framework-annotations-lib",
         "framework-connectivity.stubs.module_lib",
     ],
diff --git a/staticlibs/device/com/android/net/module/util/BpfMap.java b/staticlibs/device/com/android/net/module/util/BpfMap.java
index 595ac74..d622427 100644
--- a/staticlibs/device/com/android/net/module/util/BpfMap.java
+++ b/staticlibs/device/com/android/net/module/util/BpfMap.java
@@ -239,6 +239,11 @@
         return Struct.parse(mValueClass, buffer);
     }
 
+    /** Synchronize Kernel RCU */
+    public static void synchronizeKernelRCU() throws ErrnoException {
+        nativeSynchronizeKernelRCU();
+    }
+
     private static native int nativeBpfFdGet(String path, int mode, int keySize, int valueSize)
             throws ErrnoException, NullPointerException;
 
@@ -260,4 +265,6 @@
 
     private native boolean nativeFindMapEntry(int fd, byte[] key, byte[] value)
             throws ErrnoException;
+
+    private static native void nativeSynchronizeKernelRCU() throws ErrnoException;
 }
diff --git a/staticlibs/framework/com/android/net/module/util/DnsPacket.java b/staticlibs/framework/com/android/net/module/util/DnsPacket.java
index 0dcdf1e..63106a1 100644
--- a/staticlibs/framework/com/android/net/module/util/DnsPacket.java
+++ b/staticlibs/framework/com/android/net/module/util/DnsPacket.java
@@ -56,6 +56,7 @@
      */
     // TODO: Define the constant as a public constant in DnsResolver since it can never change.
     private static final int TYPE_CNAME = 5;
+    public static final int TYPE_SVCB = 64;
 
     /**
      * Thrown when parsing packet failed.
@@ -282,7 +283,7 @@
          * @param buf ByteBuffer input of record, must be in network byte order
          *         (which is the default).
          */
-        private DnsRecord(@RecordType int rType, @NonNull ByteBuffer buf)
+        protected DnsRecord(@RecordType int rType, @NonNull ByteBuffer buf)
                 throws BufferUnderflowException, ParseException {
             Objects.requireNonNull(buf);
             this.rType = rType;
@@ -326,6 +327,8 @@
             // Return a DnsRecord instance by default for backward compatibility, this is useful
             // when a partner supports new type of DnsRecord but does not inherit DnsRecord.
             switch (nsType) {
+                case TYPE_SVCB:
+                    return new DnsSvcbRecord(rType, buf);
                 default:
                     return new DnsRecord(rType, buf);
             }
diff --git a/staticlibs/framework/com/android/net/module/util/DnsSvcbPacket.java b/staticlibs/framework/com/android/net/module/util/DnsSvcbPacket.java
new file mode 100644
index 0000000..c7ed3e6
--- /dev/null
+++ b/staticlibs/framework/com/android/net/module/util/DnsSvcbPacket.java
@@ -0,0 +1,182 @@
+/*
+ * 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 com.android.net.module.util;
+
+import static android.net.DnsResolver.TYPE_A;
+import static android.net.DnsResolver.TYPE_AAAA;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.StringJoiner;
+
+/**
+ * A class for a DNS SVCB response packet.
+ *
+ * @hide
+ */
+public class DnsSvcbPacket extends DnsPacket {
+    public static final int TYPE_SVCB = 64;
+
+    private static final String TAG = DnsSvcbPacket.class.getSimpleName();
+
+    /**
+     * Creates a DnsSvcbPacket object from the given wire-format DNS packet.
+     */
+    private DnsSvcbPacket(@NonNull byte[] data) throws DnsPacket.ParseException {
+        // If data is null, ParseException will be thrown.
+        super(data);
+
+        final int questions = mHeader.getRecordCount(QDSECTION);
+        if (questions != 1) {
+            throw new DnsPacket.ParseException("Unexpected question count " + questions);
+        }
+        final int nsType = mRecords[QDSECTION].get(0).nsType;
+        if (nsType != TYPE_SVCB) {
+            throw new DnsPacket.ParseException("Unexpected query type " + nsType);
+        }
+    }
+
+    /**
+     * Returns true if the DnsSvcbPacket is a DNS response.
+     */
+    public boolean isResponse() {
+        return mHeader.isResponse();
+    }
+
+    /**
+     * Returns whether the given protocol alpn is supported.
+     */
+    public boolean isSupported(@NonNull String alpn) {
+        return findSvcbRecord(alpn) != null;
+    }
+
+    /**
+     * Returns the TargetName associated with the given protocol alpn.
+     * If the alpn is not supported, a null is returned.
+     */
+    @Nullable
+    public String getTargetName(@NonNull String alpn) {
+        final DnsSvcbRecord record = findSvcbRecord(alpn);
+        return (record != null) ? record.getTargetName() : null;
+    }
+
+    /**
+     * Returns the TargetName that associated with the given protocol alpn.
+     * If the alpn is not supported, -1 is returned.
+     */
+    public int getPort(@NonNull String alpn) {
+        final DnsSvcbRecord record = findSvcbRecord(alpn);
+        return (record != null) ? record.getPort() : -1;
+    }
+
+    /**
+     * Returns the IP addresses that support the given protocol alpn.
+     * If the alpn is not supported, an empty list is returned.
+     */
+    @NonNull
+    public List<InetAddress> getAddresses(@NonNull String alpn) {
+        final DnsSvcbRecord record = findSvcbRecord(alpn);
+        if (record == null) return Collections.EMPTY_LIST;
+
+        // As per draft-ietf-dnsop-svcb-https-10#section-7.4 and draft-ietf-add-ddr-10#section-4,
+        // if A/AAAA records are available in the Additional section, use the IP addresses in
+        // those records instead of the IP addresses in ipv4hint/ipv6hint.
+        final List<InetAddress> out = getAddressesFromAdditionalSection();
+        if (out.size() > 0) return out;
+
+        return record.getAddresses();
+    }
+
+    /**
+     * Returns the value of SVCB key dohpath that associated with the given protocol alpn.
+     * If the alpn is not supported, a null is returned.
+     */
+    @Nullable
+    public String getDohPath(@NonNull String alpn) {
+        final DnsSvcbRecord record = findSvcbRecord(alpn);
+        return (record != null) ? record.getDohPath() : null;
+    }
+
+    /**
+     * Returns the DnsSvcbRecord associated with the given protocol alpn.
+     * If the alpn is not supported, a null is returned.
+     */
+    @Nullable
+    private DnsSvcbRecord findSvcbRecord(@NonNull String alpn) {
+        for (final DnsRecord record : mRecords[ANSECTION]) {
+            if (record instanceof DnsSvcbRecord) {
+                final DnsSvcbRecord svcbRecord = (DnsSvcbRecord) record;
+                if (svcbRecord.getAlpns().contains(alpn)) {
+                    return svcbRecord;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns the IP addresses in additional section.
+     */
+    @NonNull
+    private List<InetAddress> getAddressesFromAdditionalSection() {
+        final List<InetAddress> out = new ArrayList<InetAddress>();
+        if (mHeader.getRecordCount(ARSECTION) == 0) {
+            return out;
+        }
+        for (final DnsRecord record : mRecords[ARSECTION]) {
+            if (record.nsType != TYPE_A && record.nsType != TYPE_AAAA) {
+                Log.d(TAG, "Found type other than A/AAAA in Additional section: " + record.nsType);
+                continue;
+            }
+            try {
+                out.add(InetAddress.getByAddress(record.getRR()));
+            } catch (UnknownHostException e) {
+                Log.w(TAG, "Failed to parse address");
+            }
+        }
+        return out;
+    }
+
+    @Override
+    public String toString() {
+        final StringJoiner out = new StringJoiner(" ");
+        out.add("QUERY: [" + TextUtils.join(", ", mRecords[QDSECTION]) + "]");
+        out.add("ANSWER: [" + TextUtils.join(", ", mRecords[ANSECTION]) + "]");
+        out.add("AUTHORITY: [" + TextUtils.join(", ", mRecords[NSSECTION]) + "]");
+        out.add("ADDITIONAL: [" + TextUtils.join(", ", mRecords[ARSECTION]) + "]");
+        return out.toString();
+    }
+
+    /**
+     * Creates a DnsSvcbPacket object from the given wire-format DNS answer.
+     */
+    public static DnsSvcbPacket fromResponse(@NonNull byte[] data) throws DnsPacket.ParseException {
+        DnsSvcbPacket out = new DnsSvcbPacket(data);
+        if (!out.isResponse()) {
+            throw new DnsPacket.ParseException("Not an answer packet");
+        }
+        return out;
+    }
+}
diff --git a/staticlibs/framework/com/android/net/module/util/DnsSvcbRecord.java b/staticlibs/framework/com/android/net/module/util/DnsSvcbRecord.java
new file mode 100644
index 0000000..669725c
--- /dev/null
+++ b/staticlibs/framework/com/android/net/module/util/DnsSvcbRecord.java
@@ -0,0 +1,516 @@
+/*
+ * 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 com.android.net.module.util;
+
+import static android.net.DnsResolver.CLASS_IN;
+
+import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
+import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
+import static com.android.net.module.util.DnsPacket.ParseException;
+
+import android.annotation.NonNull;
+import android.text.TextUtils;
+import android.util.SparseArray;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.ShortBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.StringJoiner;
+
+/**
+ * A class for an SVCB record.
+ * https://www.iana.org/assignments/dns-svcb/dns-svcb.xhtml
+ * @hide
+ */
+@VisibleForTesting(visibility = PACKAGE)
+public final class DnsSvcbRecord extends DnsPacket.DnsRecord {
+    /**
+     * The following SvcParamKeys KEY_* are defined in
+     * https://www.iana.org/assignments/dns-svcb/dns-svcb.xhtml.
+     */
+
+    // The SvcParamKey "mandatory". The associated implementation of SvcParam is SvcParamMandatory.
+    private static final int KEY_MANDATORY = 0;
+
+    // The SvcParamKey "alpn". The associated implementation of SvcParam is SvcParamAlpn.
+    private static final int KEY_ALPN = 1;
+
+    // The SvcParamKey "no-default-alpn". The associated implementation of SvcParam is
+    // SvcParamNoDefaultAlpn.
+    private static final int KEY_NO_DEFAULT_ALPN = 2;
+
+    // The SvcParamKey "port". The associated implementation of SvcParam is SvcParamPort.
+    private static final int KEY_PORT = 3;
+
+    // The SvcParamKey "ipv4hint". The associated implementation of SvcParam is SvcParamIpv4Hint.
+    private static final int KEY_IPV4HINT = 4;
+
+    // The SvcParamKey "ech". The associated implementation of SvcParam is SvcParamEch.
+    private static final int KEY_ECH = 5;
+
+    // The SvcParamKey "ipv6hint". The associated implementation of SvcParam is SvcParamIpv6Hint.
+    private static final int KEY_IPV6HINT = 6;
+
+    // The SvcParamKey "dohpath". The associated implementation of SvcParam is SvcParamDohPath.
+    private static final int KEY_DOHPATH = 7;
+
+    // The minimal size of a SvcParam.
+    // https://www.ietf.org/archive/id/draft-ietf-dnsop-svcb-https-12.html#name-rdata-wire-format
+    private static final int MINSVCPARAMSIZE = 4;
+
+    private static final String TAG = DnsSvcbRecord.class.getSimpleName();
+
+    private final int mSvcPriority;
+
+    @NonNull
+    private final String mTargetName;
+
+    @NonNull
+    private final SparseArray<SvcParam> mAllSvcParams = new SparseArray<>();
+
+    @VisibleForTesting(visibility = PACKAGE)
+    public DnsSvcbRecord(@DnsPacket.RecordType int rType, @NonNull ByteBuffer buff)
+            throws IllegalStateException, ParseException {
+        super(rType, buff);
+        if (nsType != DnsPacket.TYPE_SVCB) {
+            throw new IllegalStateException("incorrect nsType: " + nsType);
+        }
+        if (nsClass != CLASS_IN) {
+            throw new ParseException("incorrect nsClass: " + nsClass);
+        }
+
+        // DNS Record in Question Section doesn't have Rdata.
+        if (rType == DnsPacket.QDSECTION) {
+            mSvcPriority = 0;
+            mTargetName = "";
+            return;
+        }
+
+        final byte[] rdata = getRR();
+        if (rdata == null) {
+            throw new ParseException("SVCB rdata is empty");
+        }
+
+        final ByteBuffer buf = ByteBuffer.wrap(rdata).asReadOnlyBuffer();
+        mSvcPriority = Short.toUnsignedInt(buf.getShort());
+        mTargetName = DnsPacketUtils.DnsRecordParser.parseName(buf, 0 /* Parse depth */,
+                false /* isNameCompressionSupported */);
+
+        if (mTargetName.length() > DnsPacket.DnsRecord.MAXNAMESIZE) {
+            throw new ParseException(
+                    "Failed to parse SVCB target name, name size is too long: "
+                            + mTargetName.length());
+        }
+        while (buf.remaining() >= MINSVCPARAMSIZE) {
+            final SvcParam svcParam = parseSvcParam(buf);
+            final int key = svcParam.getKey();
+            if (mAllSvcParams.get(key) != null) {
+                throw new ParseException("Invalid DnsSvcbRecord, key " + key + " is repeated");
+            }
+            mAllSvcParams.put(key, svcParam);
+        }
+        if (buf.hasRemaining()) {
+            throw new ParseException("Invalid DnsSvcbRecord. Got "
+                    + buf.remaining() + " remaining bytes after parsing");
+        }
+    }
+
+    /**
+     * Returns the TargetName.
+     */
+    @VisibleForTesting(visibility = PACKAGE)
+    @NonNull
+    public String getTargetName() {
+        return mTargetName;
+    }
+
+    /**
+     * Returns an unmodifiable list of alpns from SvcParam alpn.
+     */
+    @VisibleForTesting(visibility = PACKAGE)
+    @NonNull
+    public List<String> getAlpns() {
+        final SvcParamAlpn sp = (SvcParamAlpn) mAllSvcParams.get(KEY_ALPN);
+        final List<String> list = (sp != null) ? sp.getValue() : Collections.EMPTY_LIST;
+        return Collections.unmodifiableList(list);
+    }
+
+    /**
+     * Returns the port number from SvcParam port.
+     */
+    @VisibleForTesting(visibility = PACKAGE)
+    public int getPort() {
+        final SvcParamPort sp = (SvcParamPort) mAllSvcParams.get(KEY_PORT);
+        return (sp != null) ? sp.getValue() : -1;
+    }
+
+    /**
+     * Returns a list of the IP addresses from both of SvcParam ipv4hint and ipv6hint.
+     */
+    @VisibleForTesting(visibility = PACKAGE)
+    @NonNull
+    public List<InetAddress> getAddresses() {
+        final List<InetAddress> out = new ArrayList<>();
+        final SvcParamIpHint sp4 = (SvcParamIpHint) mAllSvcParams.get(KEY_IPV4HINT);
+        if (sp4 != null) {
+            out.addAll(sp4.getValue());
+        }
+        final SvcParamIpHint sp6 = (SvcParamIpHint) mAllSvcParams.get(KEY_IPV6HINT);
+        if (sp6 != null) {
+            out.addAll(sp6.getValue());
+        }
+        return out;
+    }
+
+    /**
+     * Returns the doh path from SvcParam dohPath.
+     */
+    @VisibleForTesting(visibility = PACKAGE)
+    @NonNull
+    public String getDohPath() {
+        final SvcParamDohPath sp = (SvcParamDohPath) mAllSvcParams.get(KEY_DOHPATH);
+        return (sp != null) ? sp.getValue() : "";
+    }
+
+    @Override
+    public String toString() {
+        if (rType == DnsPacket.QDSECTION) {
+            return dName + " IN SVCB";
+        }
+
+        final StringJoiner sj = new StringJoiner(" ");
+        for (int i = 0; i < mAllSvcParams.size(); i++) {
+            sj.add(mAllSvcParams.valueAt(i).toString());
+        }
+        return dName + " " + ttl + " IN SVCB " + mSvcPriority + " " + mTargetName + " "
+                + sj.toString();
+    }
+
+    private static SvcParam parseSvcParam(@NonNull ByteBuffer buf) throws ParseException {
+        try {
+            final int key = Short.toUnsignedInt(buf.getShort());
+            switch (key) {
+                case KEY_MANDATORY: return new SvcParamMandatory(buf);
+                case KEY_ALPN: return new SvcParamAlpn(buf);
+                case KEY_NO_DEFAULT_ALPN: return new SvcParamNoDefaultAlpn(buf);
+                case KEY_PORT: return new SvcParamPort(buf);
+                case KEY_IPV4HINT: return new SvcParamIpv4Hint(buf);
+                case KEY_ECH: return new SvcParamEch(buf);
+                case KEY_IPV6HINT: return new SvcParamIpv6Hint(buf);
+                case KEY_DOHPATH: return new SvcParamDohPath(buf);
+                default: return new SvcParamGeneric(key, buf);
+            }
+        } catch (BufferUnderflowException e) {
+            throw new ParseException("Malformed packet", e);
+        }
+    }
+
+    /**
+     * The base class for all SvcParam.
+     */
+    private abstract static class SvcParam {
+        private final int mKey;
+
+        SvcParam(int key) {
+            mKey = key;
+        }
+
+        int getKey() {
+            return mKey;
+        }
+    }
+
+    private static class SvcParamMandatory extends SvcParam {
+        private final short[] mValue;
+
+        private SvcParamMandatory(@NonNull ByteBuffer buf) throws BufferUnderflowException,
+                ParseException {
+            super(KEY_MANDATORY);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = Short.toUnsignedInt(buf.getShort());
+            final ByteBuffer svcParamValue = sliceAndAdvance(buf, len);
+            mValue = SvcParamValueUtil.toShortArray(svcParamValue);
+            if (mValue.length == 0) {
+                throw new ParseException("mandatory value must be non-empty");
+            }
+        }
+
+        @Override
+        public String toString() {
+            final StringJoiner valueJoiner = new StringJoiner(",");
+            for (short key : mValue) {
+                valueJoiner.add(toKeyName(key));
+            }
+            return toKeyName(getKey()) + "=" + valueJoiner.toString();
+        }
+    }
+
+    private static class SvcParamAlpn extends SvcParam {
+        private final List<String> mValue;
+
+        SvcParamAlpn(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_ALPN);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = Short.toUnsignedInt(buf.getShort());
+            final ByteBuffer svcParamValue = sliceAndAdvance(buf, len);
+            mValue = SvcParamValueUtil.toStringList(svcParamValue);
+            if (mValue.isEmpty()) {
+                throw new ParseException("alpn value must be non-empty");
+            }
+        }
+
+        List<String> getValue() {
+            return Collections.unmodifiableList(mValue);
+        }
+
+        @Override
+        public String toString() {
+            return toKeyName(getKey()) + "=" + TextUtils.join(",", mValue);
+        }
+    }
+
+    private static class SvcParamNoDefaultAlpn extends SvcParam {
+        SvcParamNoDefaultAlpn(@NonNull ByteBuffer buf) throws BufferUnderflowException,
+                ParseException {
+            super(KEY_NO_DEFAULT_ALPN);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = buf.getShort();
+            if (len != 0) {
+                throw new ParseException("no-default-alpn value must be empty");
+            }
+        }
+
+        @Override
+        public String toString() {
+            return toKeyName(getKey());
+        }
+    }
+
+    private static class SvcParamPort extends SvcParam {
+        private final int mValue;
+
+        SvcParamPort(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_PORT);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = buf.getShort();
+            if (len != Short.BYTES) {
+                throw new ParseException("key port len is not 2 but " + len);
+            }
+            mValue = Short.toUnsignedInt(buf.getShort());
+        }
+
+        int getValue() {
+            return mValue;
+        }
+
+        @Override
+        public String toString() {
+            return toKeyName(getKey()) + "=" + mValue;
+        }
+    }
+
+    private static class SvcParamIpHint extends SvcParam {
+        private final List<InetAddress> mValue;
+
+        private SvcParamIpHint(int key, @NonNull ByteBuffer buf, int addrLen) throws
+                BufferUnderflowException, ParseException {
+            super(key);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = Short.toUnsignedInt(buf.getShort());
+            final ByteBuffer svcParamValue = sliceAndAdvance(buf, len);
+            mValue = SvcParamValueUtil.toInetAddressList(svcParamValue, addrLen);
+            if (mValue.isEmpty()) {
+                throw new ParseException(toKeyName(getKey()) + " value must be non-empty");
+            }
+        }
+
+        List<InetAddress> getValue() {
+            return Collections.unmodifiableList(mValue);
+        }
+
+        @Override
+        public String toString() {
+            final StringJoiner valueJoiner = new StringJoiner(",");
+            for (InetAddress ip : mValue) {
+                valueJoiner.add(ip.getHostAddress());
+            }
+            return toKeyName(getKey()) + "=" + valueJoiner.toString();
+        }
+    }
+
+    private static class SvcParamIpv4Hint extends SvcParamIpHint {
+        SvcParamIpv4Hint(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_IPV4HINT, buf, NetworkStackConstants.IPV4_ADDR_LEN);
+        }
+    }
+
+    private static class SvcParamIpv6Hint extends SvcParamIpHint {
+        SvcParamIpv6Hint(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_IPV6HINT, buf, NetworkStackConstants.IPV6_ADDR_LEN);
+        }
+    }
+
+    private static class SvcParamEch extends SvcParamGeneric {
+        SvcParamEch(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_ECH, buf);
+        }
+    }
+
+    private static class SvcParamDohPath extends SvcParam {
+        private final String mValue;
+
+        SvcParamDohPath(@NonNull ByteBuffer buf) throws BufferUnderflowException, ParseException {
+            super(KEY_DOHPATH);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = Short.toUnsignedInt(buf.getShort());
+            final byte[] value = new byte[len];
+            buf.get(value);
+            mValue = new String(value, StandardCharsets.UTF_8);
+        }
+
+        String getValue() {
+            return mValue;
+        }
+
+        @Override
+        public String toString() {
+            return toKeyName(getKey()) + "=" + mValue;
+        }
+    }
+
+    // For other unrecognized and unimplemented SvcParams, they are stored as SvcParamGeneric.
+    private static class SvcParamGeneric extends SvcParam {
+        private final byte[] mValue;
+
+        SvcParamGeneric(int key, @NonNull ByteBuffer buf) throws BufferUnderflowException,
+                ParseException {
+            super(key);
+            // The caller already read 2 bytes for SvcParamKey.
+            final int len = Short.toUnsignedInt(buf.getShort());
+            mValue = new byte[len];
+            buf.get(mValue);
+        }
+
+        @Override
+        public String toString() {
+            final StringBuilder out = new StringBuilder();
+            out.append(toKeyName(getKey()));
+            if (mValue != null && mValue.length > 0) {
+                out.append("=");
+                out.append(HexDump.toHexString(mValue));
+            }
+            return out.toString();
+        }
+    }
+
+    private static String toKeyName(int key) {
+        switch (key) {
+            case KEY_MANDATORY: return "mandatory";
+            case KEY_ALPN: return "alpn";
+            case KEY_NO_DEFAULT_ALPN: return "no-default-alpn";
+            case KEY_PORT: return "port";
+            case KEY_IPV4HINT: return "ipv4hint";
+            case KEY_ECH: return "ech";
+            case KEY_IPV6HINT: return "ipv6hint";
+            case KEY_DOHPATH: return "dohpath";
+            default: return "key" + key;
+        }
+    }
+
+    /**
+     * Returns a read-only ByteBuffer (with position = 0, limit = `length`, and capacity = `length`)
+     * sliced from `buf`'s current position, and moves the position of `buf` by `length`.
+     */
+    @VisibleForTesting(visibility = PRIVATE)
+    public static ByteBuffer sliceAndAdvance(@NonNull ByteBuffer buf, int length)
+            throws BufferUnderflowException {
+        if (buf.remaining() < length) {
+            throw new BufferUnderflowException();
+        }
+        final int pos = buf.position();
+
+        // `out` equals to `buf.slice(pos, length)` that is supported in API level 34.
+        final ByteBuffer out = ((ByteBuffer) buf.slice().limit(length)).slice();
+
+        buf.position(pos + length);
+        return out.asReadOnlyBuffer();
+    }
+
+    // A utility to convert the byte array of SvcParamValue to other types.
+    private static class SvcParamValueUtil {
+        // Refer to draft-ietf-dnsop-svcb-https-10#section-7.1 for the wire format of alpn.
+        @NonNull
+        private static List<String> toStringList(@NonNull ByteBuffer buf)
+                throws BufferUnderflowException, ParseException {
+            final List<String> out = new ArrayList<>();
+            while (buf.hasRemaining()) {
+                final int alpnLen = Byte.toUnsignedInt(buf.get());
+                if (alpnLen == 0) {
+                    throw new ParseException("alpn should not be an empty string");
+                }
+                final byte[] alpn = new byte[alpnLen];
+                buf.get(alpn);
+                out.add(new String(alpn, StandardCharsets.UTF_8));
+            }
+            return out;
+        }
+
+        // Refer to draft-ietf-dnsop-svcb-https-10#section-7.5 for the wire format of SvcParamKey
+        // "mandatory".
+        @NonNull
+        private static short[] toShortArray(@NonNull ByteBuffer buf)
+                throws BufferUnderflowException, ParseException {
+            if (buf.remaining() % Short.BYTES != 0) {
+                throw new ParseException("Can't parse whole byte array");
+            }
+            final ShortBuffer sb = buf.asShortBuffer();
+            final short[] out = new short[sb.remaining()];
+            sb.get(out);
+            return out;
+        }
+
+        // Refer to draft-ietf-dnsop-svcb-https-10#section-7.4 for the wire format of ipv4hint and
+        // ipv6hint.
+        @NonNull
+        private static List<InetAddress> toInetAddressList(@NonNull ByteBuffer buf, int addrLen)
+                throws BufferUnderflowException, ParseException {
+            if (buf.remaining() % addrLen != 0) {
+                throw new ParseException("Can't parse whole byte array");
+            }
+
+            final List<InetAddress> out = new ArrayList<>();
+            final byte[] addr = new byte[addrLen];
+            while (buf.remaining() >= addrLen) {
+                buf.get(addr);
+                try {
+                    out.add(InetAddress.getByAddress(addr));
+                } catch (UnknownHostException e) {
+                    throw new ParseException("Can't parse byte array as an IP address");
+                }
+            }
+            return out;
+        }
+    }
+}
diff --git a/staticlibs/native/bpf_headers/BpfRingbufTest.cpp b/staticlibs/native/bpf_headers/BpfRingbufTest.cpp
index 6c0841c..e4de812 100644
--- a/staticlibs/native/bpf_headers/BpfRingbufTest.cpp
+++ b/staticlibs/native/bpf_headers/BpfRingbufTest.cpp
@@ -72,12 +72,15 @@
 
     auto result = BpfRingbuf<uint64_t>::Create(mRingbufPath.c_str());
     ASSERT_RESULT_OK(result);
+    EXPECT_TRUE(result.value()->isEmpty());
 
     for (int i = 0; i < n; i++) {
       RunProgram();
     }
 
+    EXPECT_FALSE(result.value()->isEmpty());
     EXPECT_THAT(result.value()->ConsumeAll(callback), HasValue(n));
+    EXPECT_TRUE(result.value()->isEmpty());
     EXPECT_EQ(output, TEST_RINGBUF_MAGIC_NUM);
     EXPECT_EQ(run_count, n);
   }
diff --git a/staticlibs/native/bpf_headers/include/bpf/BpfMap.h b/staticlibs/native/bpf_headers/include/bpf/BpfMap.h
index 5d7eb0d..3fede3c 100644
--- a/staticlibs/native/bpf_headers/include/bpf/BpfMap.h
+++ b/staticlibs/native/bpf_headers/include/bpf/BpfMap.h
@@ -78,7 +78,7 @@
     Result<Key> getFirstKey() const {
         Key firstKey;
         if (getFirstMapKey(mMapFd, &firstKey)) {
-            return ErrnoErrorf("Get firstKey map {} failed", mMapFd.get());
+            return ErrnoErrorf("BpfMap::getFirstKey() failed");
         }
         return firstKey;
     }
@@ -86,7 +86,7 @@
     Result<Key> getNextKey(const Key& key) const {
         Key nextKey;
         if (getNextMapKey(mMapFd, &key, &nextKey)) {
-            return ErrnoErrorf("Get next key of map {} failed", mMapFd.get());
+            return ErrnoErrorf("BpfMap::getNextKey() failed");
         }
         return nextKey;
     }
@@ -94,7 +94,7 @@
     Result<Value> readValue(const Key key) const {
         Value value;
         if (findMapEntry(mMapFd, &key, &value)) {
-            return ErrnoErrorf("Read value of map {} failed", mMapFd.get());
+            return ErrnoErrorf("BpfMap::readValue() failed");
         }
         return value;
     }
@@ -243,14 +243,14 @@
 
     Result<void> writeValue(const Key& key, const Value& value, uint64_t flags) {
         if (writeToMapEntry(mMapFd, &key, &value, flags)) {
-            return ErrnoErrorf("Write to map {} failed", mMapFd.get());
+            return ErrnoErrorf("BpfMap::writeValue() failed");
         }
         return {};
     }
 
     Result<void> deleteValue(const Key& key) {
         if (deleteMapEntry(mMapFd, &key)) {
-            return ErrnoErrorf("Delete entry from map {} failed", mMapFd.get());
+            return ErrnoErrorf("BpfMap::deleteValue() failed");
         }
         return {};
     }
@@ -280,7 +280,7 @@
         if (map_flags & BPF_F_RDONLY) abort();
         mMapFd.reset(createMap(map_type, sizeof(Key), sizeof(Value), max_entries,
                                map_flags));
-        if (!mMapFd.ok()) return ErrnoErrorf("Unable to create map.");
+        if (!mMapFd.ok()) return ErrnoErrorf("BpfMap::resetMap() failed");
         abortOnMismatch(/* writable */ true);
         return {};
     }
diff --git a/staticlibs/native/bpf_headers/include/bpf/BpfRingbuf.h b/staticlibs/native/bpf_headers/include/bpf/BpfRingbuf.h
index dd1504c..9aff790 100644
--- a/staticlibs/native/bpf_headers/include/bpf/BpfRingbuf.h
+++ b/staticlibs/native/bpf_headers/include/bpf/BpfRingbuf.h
@@ -39,6 +39,8 @@
     mProducerPos = nullptr;
   }
 
+  bool isEmpty(void);
+
  protected:
   // Non-initializing constructor, used by Create.
   BpfRingbufBase(size_t value_size) : mValueSize(value_size) {}
@@ -197,6 +199,13 @@
   return {};
 }
 
+inline bool BpfRingbufBase::isEmpty(void) {
+  uint32_t prod_pos = mProducerPos->load(std::memory_order_acquire);
+  // Only userspace writes to mConsumerPos, so no need to use std::memory_order_acquire
+  uint64_t cons_pos = mConsumerPos->load(std::memory_order_relaxed);
+  return (cons_pos & 0xFFFFFFFF) == prod_pos;
+}
+
 inline base::Result<int> BpfRingbufBase::ConsumeAll(
     const std::function<void(const void*)>& callback) {
   int64_t count = 0;
diff --git a/staticlibs/native/bpfmapjni/com_android_net_module_util_BpfMap.cpp b/staticlibs/native/bpfmapjni/com_android_net_module_util_BpfMap.cpp
index f93d6e1..b92f107 100644
--- a/staticlibs/native/bpfmapjni/com_android_net_module_util_BpfMap.cpp
+++ b/staticlibs/native/bpfmapjni/com_android_net_module_util_BpfMap.cpp
@@ -15,6 +15,8 @@
  */
 
 #include <errno.h>
+#include <linux/pfkeyv2.h>
+#include <sys/socket.h>
 #include <jni.h>
 #include <nativehelper/JNIHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
@@ -117,6 +119,22 @@
     return throwIfNotEnoent(env, "nativeFindMapEntry", ret, errno);
 }
 
+static void com_android_net_module_util_BpfMap_nativeSynchronizeKernelRCU(JNIEnv *env,
+                                                                          jclass clazz) {
+    const int pfSocket = socket(AF_KEY, SOCK_RAW | SOCK_CLOEXEC, PF_KEY_V2);
+
+    if (pfSocket < 0) {
+        jniThrowErrnoException(env, "nativeSynchronizeKernelRCU:socket", errno);
+        return;
+    }
+
+    if (close(pfSocket)) {
+        jniThrowErrnoException(env, "nativeSynchronizeKernelRCU:close", errno);
+        return;
+    }
+    return;
+}
+
 /*
  * JNI registration.
  */
@@ -132,6 +150,8 @@
         (void*) com_android_net_module_util_BpfMap_nativeGetNextMapKey },
     { "nativeFindMapEntry", "(I[B[B)Z",
         (void*) com_android_net_module_util_BpfMap_nativeFindMapEntry },
+    { "nativeSynchronizeKernelRCU", "()V",
+        (void*) com_android_net_module_util_BpfMap_nativeSynchronizeKernelRCU },
 
 };
 
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/DnsPacketTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/DnsPacketTest.java
index 28e183a..88d9e1e 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/DnsPacketTest.java
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/DnsPacketTest.java
@@ -203,6 +203,30 @@
                 "test.com", CLASS_IN, 0 /* ttl */, "example.com"));
     }
 
+    /** Verifies that the type of implementation returned from DnsRecord#parse is correct */
+    @Test
+    public void testDnsRecordParse() throws IOException {
+        final byte[] svcbQuestionRecord = new byte[] {
+                0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c', 'o', 'm', 0x00, /* Name */
+                0x00, 0x40, /* Type */
+                0x00, 0x01, /* Class */
+        };
+        assertTrue(DnsPacket.DnsRecord.parse(DnsPacket.QDSECTION,
+                ByteBuffer.wrap(svcbQuestionRecord)) instanceof DnsSvcbRecord);
+
+        final byte[] svcbAnswerRecord = new byte[] {
+                0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c', 'o', 'm', 0x00, /* Name */
+                0x00, 0x40, /* Type */
+                0x00, 0x01, /* Class */
+                0x00, 0x00, 0x01, 0x2b, /* TTL */
+                0x00, 0x0b, /* Data length */
+                0x00, 0x01, /* SvcPriority */
+                0x03, 'd', 'o', 't', 0x03, 'c', 'o', 'm', 0x00, /* TargetName */
+        };
+        assertTrue(DnsPacket.DnsRecord.parse(DnsPacket.ANSECTION,
+                ByteBuffer.wrap(svcbAnswerRecord)) instanceof DnsSvcbRecord);
+    }
+
     /**
      * Verifies ttl/rData error handling when parsing
      * {@link DnsPacket.DnsRecord} from bytes.
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/DnsSvcbPacketTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/DnsSvcbPacketTest.java
new file mode 100644
index 0000000..6778f8a
--- /dev/null
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/DnsSvcbPacketTest.java
@@ -0,0 +1,606 @@
+/*
+ * 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 com.android.net.module.util;
+
+import static android.net.DnsResolver.CLASS_IN;
+import static android.net.DnsResolver.TYPE_A;
+import static android.net.DnsResolver.TYPE_AAAA;
+
+import static com.android.net.module.util.DnsPacket.TYPE_SVCB;
+import static com.android.testutils.MiscAsserts.assertThrows;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.annotation.NonNull;
+import android.net.InetAddresses;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@RunWith(JUnit4.class)
+public class DnsSvcbPacketTest {
+    private static final short TEST_TRANSACTION_ID = 0x4321;
+    private static final byte[] TEST_DNS_RESPONSE_HEADER_FLAG =  new byte[] { (byte) 0x81, 0x00 };
+
+    // A common DNS SVCB Question section with Name = "_dns.resolver.arpa".
+    private static final byte[] TEST_DNS_SVCB_QUESTION_SECTION = new byte[] {
+            0x04, '_', 'd', 'n', 's', 0x08, 'r', 'e', 's', 'o', 'l', 'v', 'e', 'r',
+            0x04, 'a', 'r', 'p', 'a', 0x00, 0x00, 0x40, 0x00, 0x01,
+    };
+
+    // mandatory=ipv4hint,alpn,key333
+    private static final byte[] TEST_SVC_PARAM_MANDATORY = new byte[] {
+            0x00, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00, 0x01, 0x01, 0x4d,
+    };
+
+    // alpn=doq
+    private static final byte[] TEST_SVC_PARAM_ALPN_DOQ = new byte[] {
+            0x00, 0x01, 0x00, 0x04, 0x03, 'd', 'o', 'q'
+    };
+
+    // alpn=h2,http/1.1
+    private static final byte[] TEST_SVC_PARAM_ALPN_HTTPS = new byte[] {
+            0x00, 0x01, 0x00, 0x0c, 0x02, 'h', '2',
+            0x08, 'h', 't', 't', 'p', '/', '1', '.', '1',
+    };
+
+    // no-default-alpn
+    private static final byte[] TEST_SVC_PARAM_NO_DEFAULT_ALPN = new byte[] {
+            0x00, 0x02, 0x00, 0x00,
+    };
+
+    // port=5353
+    private static final byte[] TEST_SVC_PARAM_PORT = new byte[] {
+            0x00, 0x03, 0x00, 0x02, 0x14, (byte) 0xe9,
+    };
+
+    // ipv4hint=1.2.3.4,6.7.8.9
+    private static final byte[] TEST_SVC_PARAM_IPV4HINT_1 = new byte[] {
+            0x00, 0x04, 0x00, 0x08, 0x01, 0x02, 0x03, 0x04, 0x06, 0x07, 0x08, 0x09,
+    };
+
+    // ipv4hint=4.3.2.1
+    private static final byte[] TEST_SVC_PARAM_IPV4HINT_2 = new byte[] {
+            0x00, 0x04, 0x00, 0x04, 0x04, 0x03, 0x02, 0x01,
+    };
+
+    // ech=aBcDe
+    private static final byte[] TEST_SVC_PARAM_ECH = new byte[] {
+            0x00, 0x05, 0x00, 0x05, 'a', 'B', 'c', 'D', 'e',
+    };
+
+    // ipv6hint=2001:db8::1
+    private static final byte[] TEST_SVC_PARAM_IPV6HINT = new byte[] {
+            0x00, 0x06, 0x00, 0x10, 0x20, 0x01, 0x0d, (byte) 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00,
+            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+    };
+
+    // dohpath=/some-path{?dns}
+    private static final byte[] TEST_SVC_PARAM_DOHPATH = new byte[] {
+            0x00, 0x07, 0x00, 0x10,
+            '/', 's', 'o', 'm', 'e', '-', 'p', 'a', 't', 'h', '{', '?', 'd', 'n', 's', '}',
+    };
+
+    // key12345=1A2B0C
+    private static final byte[] TEST_SVC_PARAM_GENERIC_WITH_VALUE = new byte[] {
+            0x30, 0x39, 0x00, 0x03, 0x1a, 0x2b, 0x0c,
+    };
+
+    // key12346
+    private static final byte[] TEST_SVC_PARAM_GENERIC_WITHOUT_VALUE = new byte[] {
+            0x30, 0x3a, 0x00, 0x00,
+    };
+
+    private static byte[] makeDnsResponseHeaderAsByteArray(int qdcount, int ancount, int nscount,
+                int arcount) {
+        final ByteBuffer buffer = ByteBuffer.wrap(new byte[12]);
+        buffer.putShort(TEST_TRANSACTION_ID); /* Transaction ID */
+        buffer.put(TEST_DNS_RESPONSE_HEADER_FLAG); /* Flags */
+        buffer.putShort((short) qdcount);
+        buffer.putShort((short) ancount);
+        buffer.putShort((short) nscount);
+        buffer.putShort((short) arcount);
+        return buffer.array();
+    }
+
+    private static DnsSvcbRecord makeDnsSvcbRecordFromByteArray(@NonNull byte[] data)
+                throws IOException {
+        return new DnsSvcbRecord(DnsPacket.ANSECTION, ByteBuffer.wrap(data));
+    }
+
+    private static DnsSvcbRecord makeDnsSvcbRecordWithSingleSvcParam(@NonNull byte[] svcParam)
+            throws IOException {
+        return makeDnsSvcbRecordFromByteArray(new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_SVCB)
+                .setTargetName("test.com")
+                .addRdata(svcParam)
+                .build());
+    }
+
+    // Converts a Short to a byte array in big endian.
+    private static byte[] shortToByteArray(short value) {
+        return new byte[] { (byte) (value >> 8), (byte) value };
+    }
+
+    private static byte[] getRemainingByteArray(@NonNull ByteBuffer buffer) {
+        final byte[] out = new byte[buffer.remaining()];
+        buffer.get(out);
+        return out;
+    }
+
+    // A utility to make a DNS record as byte array.
+    private static class TestDnsRecordByteArrayBuilder {
+        private static final byte[] NAME_COMPRESSION_POINTER = new byte[] { (byte) 0xc0, 0x0c };
+
+        private final String mRRName = "dns.com";
+        private short mRRType = 0;
+        private final short mRRClass = CLASS_IN;
+        private final int mRRTtl = 10;
+        private int mRdataLen = 0;
+        private final ArrayList<byte[]> mRdata = new ArrayList<>();
+        private String mTargetName = null;
+        private short mSvcPriority = 1;
+        private boolean mNameCompression = false;
+
+        TestDnsRecordByteArrayBuilder setNameCompression(boolean value) {
+            mNameCompression = value;
+            return this;
+        }
+
+        TestDnsRecordByteArrayBuilder setRRType(int value) {
+            mRRType = (short) value;
+            return this;
+        }
+
+        TestDnsRecordByteArrayBuilder setTargetName(@NonNull String value) throws IOException {
+            mTargetName = value;
+            return this;
+        }
+
+        TestDnsRecordByteArrayBuilder setSvcPriority(int value) {
+            mSvcPriority = (short) value;
+            return this;
+        }
+
+        TestDnsRecordByteArrayBuilder addRdata(@NonNull byte[] value) {
+            mRdata.add(value);
+            mRdataLen += value.length;
+            return this;
+        }
+
+        byte[] build() throws IOException {
+            final ByteArrayOutputStream os = new ByteArrayOutputStream();
+            final byte[] name = mNameCompression ? NAME_COMPRESSION_POINTER
+                    : DnsPacketUtils.DnsRecordParser.domainNameToLabels(mRRName);
+            os.write(name);
+            os.write(shortToByteArray(mRRType));
+            os.write(shortToByteArray(mRRClass));
+            os.write(HexDump.toByteArray(mRRTtl));
+            if (mTargetName == null) {
+                os.write(shortToByteArray((short) mRdataLen));
+            } else {
+                final byte[] targetNameLabels =
+                                DnsPacketUtils.DnsRecordParser.domainNameToLabels(mTargetName);
+                mRdataLen += (Short.BYTES + targetNameLabels.length);
+                os.write(shortToByteArray((short) mRdataLen));
+                os.write(shortToByteArray(mSvcPriority));
+                os.write(targetNameLabels);
+            }
+            for (byte[] data : mRdata) {
+                os.write(data);
+            }
+            return os.toByteArray();
+        }
+    }
+
+    @Test
+    public void testSliceAndAdvance() throws Exception {
+        final ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9});
+        final ByteBuffer slice1 = DnsSvcbRecord.sliceAndAdvance(buffer, 3);
+        final ByteBuffer slice2 = DnsSvcbRecord.sliceAndAdvance(buffer, 4);
+        assertEquals(0, slice1.position());
+        assertEquals(3, slice1.capacity());
+        assertEquals(3, slice1.remaining());
+        assertTrue(slice1.isReadOnly());
+        assertArrayEquals(new byte[] {1, 2, 3}, getRemainingByteArray(slice1));
+        assertEquals(0, slice2.position());
+        assertEquals(4, slice2.capacity());
+        assertEquals(4, slice2.remaining());
+        assertTrue(slice2.isReadOnly());
+        assertArrayEquals(new byte[] {4, 5, 6, 7}, getRemainingByteArray(slice2));
+
+        // Nothing is read if out-of-bound access happens.
+        assertThrows(BufferUnderflowException.class,
+                () -> DnsSvcbRecord.sliceAndAdvance(buffer, 5));
+        assertEquals(7, buffer.position());
+        assertEquals(9, buffer.capacity());
+        assertEquals(2, buffer.remaining());
+        assertArrayEquals(new byte[] {8, 9}, getRemainingByteArray(buffer));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamMandatory() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_MANDATORY);
+        // Check the content returned from toString() for now because the getter function for
+        // this SvcParam hasn't been implemented.
+        // TODO(b/240259333): Consider adding DnsSvcbRecord.isMandatory(String alpn) when needed.
+        assertTrue(record.toString().contains("mandatory=ipv4hint,alpn,key333"));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamAlpn() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_ALPN_HTTPS);
+        assertEquals(Arrays.asList("h2", "http/1.1"), record.getAlpns());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamNoDefaultAlpn() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(
+                TEST_SVC_PARAM_NO_DEFAULT_ALPN);
+        // Check the content returned from toString() for now because the getter function for
+        // this SvcParam hasn't been implemented.
+        // TODO(b/240259333): Consider adding DnsSvcbRecord.hasNoDefaultAlpn() when needed.
+        assertTrue(record.toString().contains("no-default-alpn"));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamPort() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_PORT);
+        assertEquals(5353, record.getPort());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamIpv4Hint() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_IPV4HINT_2);
+        assertEquals(Arrays.asList(InetAddresses.parseNumericAddress("4.3.2.1")),
+                record.getAddresses());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamEch() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_ECH);
+        // Check the content returned from toString() for now because the getter function for
+        // this SvcParam hasn't been implemented.
+        // TODO(b/240259333): Consider adding DnsSvcbRecord.getEch() when needed.
+        assertTrue(record.toString().contains("ech=6142634465"));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamIpv6Hint() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_IPV6HINT);
+        assertEquals(Arrays.asList(InetAddresses.parseNumericAddress("2001:db8::1")),
+                record.getAddresses());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamDohPath() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(TEST_SVC_PARAM_DOHPATH);
+        assertEquals("/some-path{?dns}", record.getDohPath());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamGeneric_withValue() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(
+                TEST_SVC_PARAM_GENERIC_WITH_VALUE);
+        // Check the content returned from toString() for now because the getter function for
+        // generic SvcParam hasn't been implemented.
+        // TODO(b/240259333): Consider adding DnsSvcbRecord.getValueFromGenericSvcParam(int key)
+        // when needed.
+        assertTrue(record.toString().contains("key12345=1A2B0C"));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_svcParamGeneric_withoutValue() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordWithSingleSvcParam(
+                TEST_SVC_PARAM_GENERIC_WITHOUT_VALUE);
+        // Check the content returned from toString() for now because the getter function for
+        // generic SvcParam hasn't been implemented.
+        // TODO(b/240259333): Consider adding DnsSvcbRecord.getValueFromGenericSvcParam(int key)
+        // when needed.
+        assertTrue(record.toString().contains("key12346"));
+    }
+
+    @Test
+    public void testDnsSvcbRecord() throws Exception {
+        final DnsSvcbRecord record = makeDnsSvcbRecordFromByteArray(
+                new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_SVCB)
+                .setTargetName("doh.dns.com")
+                .addRdata(TEST_SVC_PARAM_ALPN_HTTPS)
+                .addRdata(TEST_SVC_PARAM_IPV4HINT_1)
+                .addRdata(TEST_SVC_PARAM_IPV6HINT)
+                .addRdata(TEST_SVC_PARAM_PORT)
+                .addRdata(TEST_SVC_PARAM_DOHPATH)
+                .build());
+        assertEquals("doh.dns.com", record.getTargetName());
+        assertEquals(Arrays.asList("h2", "http/1.1"), record.getAlpns());
+        assertEquals(5353, record.getPort());
+        assertEquals(Arrays.asList(
+                InetAddresses.parseNumericAddress("1.2.3.4"),
+                InetAddresses.parseNumericAddress("6.7.8.9"),
+                InetAddresses.parseNumericAddress("2001:db8::1")), record.getAddresses());
+        assertEquals("/some-path{?dns}", record.getDohPath());
+    }
+
+    @Test
+    public void testDnsSvcbRecord_createdFromNullObject() throws Exception {
+        assertThrows(NullPointerException.class, () -> makeDnsSvcbRecordFromByteArray(null));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_invalidDnsRecord() throws Exception {
+        // The type is not SVCB.
+        final byte[] bytes1 = new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_A)
+                .addRdata(InetAddresses.parseNumericAddress("1.2.3.4").getAddress())
+                .build();
+        assertThrows(IllegalStateException.class, () -> makeDnsSvcbRecordFromByteArray(bytes1));
+
+        // TargetName is missing.
+        final byte[] bytes2 = new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_SVCB)
+                .addRdata(new byte[] { 0x01, 0x01 })
+                .build();
+        assertThrows(BufferUnderflowException.class, () -> makeDnsSvcbRecordFromByteArray(bytes2));
+
+        // Rdata is empty.
+        final byte[] bytes3 = new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_SVCB)
+                .build();
+        assertThrows(BufferUnderflowException.class, () -> makeDnsSvcbRecordFromByteArray(bytes3));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_repeatedKeyIsInvalid() throws Exception {
+        final byte[] bytes = new TestDnsRecordByteArrayBuilder()
+                .setRRType(TYPE_SVCB)
+                .addRdata(TEST_SVC_PARAM_ALPN_HTTPS)
+                .addRdata(TEST_SVC_PARAM_ALPN_DOQ)
+                .build();
+        assertThrows(DnsPacket.ParseException.class, () -> makeDnsSvcbRecordFromByteArray(bytes));
+    }
+
+    @Test
+    public void testDnsSvcbRecord_invalidContent() throws Exception {
+        final List<byte[]> invalidContents = Arrays.asList(
+                // Invalid SvcParamValue for "mandatory":
+                // - SvcParamValue must not be empty.
+                // - SvcParamValue has less data than expected.
+                // - SvcParamValue has more data than expected.
+                // - SvcParamValue must be multiple of 2.
+                new byte[] { 0x00, 0x00, 0x00, 0x00},
+                new byte[] { 0x00, 0x00, 0x00, 0x02, 0x00, 0x04, 0x00, 0x06 },
+                new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, },
+                new byte[] { 0x00, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00 },
+
+                // Invalid SvcParamValue for "alpn":
+                // - SvcParamValue must not be empty.
+                // - SvcParamValue has less data than expected.
+                // - SvcParamValue has more data than expected.
+                // - Alpn length is less than the actual data size.
+                // - Alpn length is more than the actual data size.
+                // - Alpn must be a non-empty string.
+                new byte[] { 0x00, 0x01, 0x00, 0x00},
+                new byte[] { 0x00, 0x01, 0x00, 0x02, 0x02, 'h', '2' },
+                new byte[] { 0x00, 0x01, 0x00, 0x05, 0x02, 'h', '2' },
+                new byte[] { 0x00, 0x01, 0x00, 0x04, 0x02, 'd', 'o', 't' },
+                new byte[] { 0x00, 0x01, 0x00, 0x04, 0x08, 'd', 'o', 't' },
+                new byte[] { 0x00, 0x01, 0x00, 0x08, 0x02, 'h', '2', 0x00 },
+
+                // Invalid SvcParamValue for "no-default-alpn":
+                // - SvcParamValue must be empty.
+                // - SvcParamValue length must be 0.
+                new byte[] { 0x00, 0x02, 0x00, 0x04, 'd', 'a', 't', 'a' },
+                new byte[] { 0x00, 0x02, 0x00, 0x04 },
+
+                // Invalid SvcParamValue for "port":
+                // - SvcParamValue must not be empty.
+                // - SvcParamValue has less data than expected.
+                // - SvcParamValue has more data than expected.
+                // - SvcParamValue length must be multiple of 2.
+                new byte[] { 0x00, 0x03, 0x00, 0x00 },
+                new byte[] { 0x00, 0x03, 0x00, 0x02, 0x01 },
+                new byte[] { 0x00, 0x03, 0x00, 0x02, 0x01, 0x02, 0x03 },
+                new byte[] { 0x00, 0x03, 0x00, 0x03, 0x01, 0x02, 0x03 },
+
+                // Invalid SvcParamValue for "ipv4hint":
+                // - SvcParamValue must not be empty.
+                // - SvcParamValue has less data than expected.
+                // - SvcParamValue has more data than expected.
+                // - SvcParamValue must be multiple of 4.
+                new byte[] { 0x00, 0x04, 0x00, 0x00 },
+                new byte[] { 0x00, 0x04, 0x00, 0x04, 0x08 },
+                new byte[] { 0x00, 0x04, 0x00, 0x04, 0x08, 0x08, 0x08, 0x08, 0x08 },
+                new byte[] { 0x00, 0x04, 0x00, 0x05, 0x08, 0x08, 0x08, 0x08 },
+
+                // Invalid SvcParamValue for "ipv6hint":
+                // - SvcParamValue must not be empty.
+                // - SvcParamValue has less data than expected.
+                // - SvcParamValue has more data than expected.
+                // - SvcParamValue must be multiple of 16.
+                new byte[] { 0x00, 0x06, 0x00, 0x00 },
+                new byte[] { 0x00, 0x06, 0x00, 0x10, 0x01 },
+                new byte[] { 0x00, 0x06, 0x00, 0x10, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+                        0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 },
+                new byte[] { 0x00, 0x06, 0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+                        0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }
+        );
+
+        for (byte[] content : invalidContents) {
+            final byte[] bytes = new TestDnsRecordByteArrayBuilder()
+                        .setRRType(TYPE_SVCB)
+                        .addRdata(content)
+                        .build();
+            assertThrows(DnsPacket.ParseException.class,
+                        () -> makeDnsSvcbRecordFromByteArray(bytes));
+        }
+    }
+
+    @Test
+    public void testDnsSvcbPacket_createdFromNullObject() throws Exception {
+        assertThrows(DnsPacket.ParseException.class, () -> DnsSvcbPacket.fromResponse(null));
+    }
+
+    @Test
+    public void testDnsSvcbPacket() throws Exception {
+        final String dohTargetName = "https.dns.com";
+        final String doqTargetName = "doq.dns.com";
+        final InetAddress[] expectedIpAddressesForHttps = new InetAddress[] {
+                InetAddresses.parseNumericAddress("1.2.3.4"),
+                InetAddresses.parseNumericAddress("6.7.8.9"),
+                InetAddresses.parseNumericAddress("2001:db8::1"),
+        };
+        final InetAddress[] expectedIpAddressesForDoq = new InetAddress[] {
+                InetAddresses.parseNumericAddress("4.3.2.1"),
+        };
+
+        final ByteArrayOutputStream os = new ByteArrayOutputStream();
+        os.write(makeDnsResponseHeaderAsByteArray(1 /* qdcount */, 2 /* ancount */, 0 /* nscount */,
+                0 /* arcount */));
+        os.write(TEST_DNS_SVCB_QUESTION_SECTION);
+        // Add answer for alpn h2 and http/1.1.
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_SVCB)
+                .setTargetName(dohTargetName)
+                .addRdata(TEST_SVC_PARAM_ALPN_HTTPS)
+                .addRdata(TEST_SVC_PARAM_IPV4HINT_1)
+                .addRdata(TEST_SVC_PARAM_IPV6HINT)
+                .addRdata(TEST_SVC_PARAM_PORT)
+                .addRdata(TEST_SVC_PARAM_DOHPATH)
+                .build());
+        // Add answer for alpn doq.
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_SVCB)
+                .setTargetName(doqTargetName)
+                .setSvcPriority(2)
+                .addRdata(TEST_SVC_PARAM_ALPN_DOQ)
+                .addRdata(TEST_SVC_PARAM_IPV4HINT_2)
+                .build());
+        final DnsSvcbPacket pkt = DnsSvcbPacket.fromResponse(os.toByteArray());
+
+        assertTrue(pkt.isSupported("http/1.1"));
+        assertTrue(pkt.isSupported("h2"));
+        assertTrue(pkt.isSupported("doq"));
+        assertFalse(pkt.isSupported("http"));
+        assertFalse(pkt.isSupported("h3"));
+        assertFalse(pkt.isSupported(""));
+
+        assertEquals(dohTargetName, pkt.getTargetName("http/1.1"));
+        assertEquals(dohTargetName, pkt.getTargetName("h2"));
+        assertEquals(doqTargetName, pkt.getTargetName("doq"));
+        assertEquals(null, pkt.getTargetName("http"));
+        assertEquals(null, pkt.getTargetName("h3"));
+        assertEquals(null, pkt.getTargetName(""));
+
+        assertEquals(5353, pkt.getPort("http/1.1"));
+        assertEquals(5353, pkt.getPort("h2"));
+        assertEquals(-1, pkt.getPort("doq"));
+        assertEquals(-1, pkt.getPort("http"));
+        assertEquals(-1, pkt.getPort("h3"));
+        assertEquals(-1, pkt.getPort(""));
+
+        assertArrayEquals(expectedIpAddressesForHttps, pkt.getAddresses("http/1.1").toArray());
+        assertArrayEquals(expectedIpAddressesForHttps, pkt.getAddresses("h2").toArray());
+        assertArrayEquals(expectedIpAddressesForDoq, pkt.getAddresses("doq").toArray());
+        assertTrue(pkt.getAddresses("http").isEmpty());
+        assertTrue(pkt.getAddresses("h3").isEmpty());
+        assertTrue(pkt.getAddresses("").isEmpty());
+
+        assertEquals("/some-path{?dns}", pkt.getDohPath("http/1.1"));
+        assertEquals("/some-path{?dns}", pkt.getDohPath("h2"));
+        assertEquals("", pkt.getDohPath("doq"));
+        assertEquals(null, pkt.getDohPath("http"));
+        assertEquals(null, pkt.getDohPath("h3"));
+        assertEquals(null, pkt.getDohPath(""));
+    }
+
+    @Test
+    public void testDnsSvcbPacket_noIpHint() throws Exception {
+        final String targetName = "doq.dns.com";
+        final ByteArrayOutputStream os = new ByteArrayOutputStream();
+        os.write(makeDnsResponseHeaderAsByteArray(1 /* qdcount */, 1 /* ancount */, 0 /* nscount */,
+                0 /* arcount */));
+        os.write(TEST_DNS_SVCB_QUESTION_SECTION);
+        // Add answer for alpn doq.
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_SVCB)
+                .setTargetName(targetName)
+                .addRdata(TEST_SVC_PARAM_ALPN_DOQ)
+                .build());
+        final DnsSvcbPacket pkt = DnsSvcbPacket.fromResponse(os.toByteArray());
+
+        assertTrue(pkt.isSupported("doq"));
+        assertEquals(targetName, pkt.getTargetName("doq"));
+        assertEquals(-1, pkt.getPort("doq"));
+        assertArrayEquals(new InetAddress[] {}, pkt.getAddresses("doq").toArray());
+        assertEquals("", pkt.getDohPath("doq"));
+    }
+
+    @Test
+    public void testDnsSvcbPacket_hasAnswerInAdditionalSection() throws Exception {
+        final InetAddress[] expectedIpAddresses = new InetAddress[] {
+                InetAddresses.parseNumericAddress("1.2.3.4"),
+                InetAddresses.parseNumericAddress("2001:db8::2"),
+        };
+
+        final ByteArrayOutputStream os = new ByteArrayOutputStream();
+        os.write(makeDnsResponseHeaderAsByteArray(1 /* qdcount */, 1 /* ancount */, 0 /* nscount */,
+                2 /* arcount */));
+        os.write(TEST_DNS_SVCB_QUESTION_SECTION);
+        // Add SVCB record in the Answer section.
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_SVCB)
+                .setTargetName("doq.dns.com")
+                .addRdata(TEST_SVC_PARAM_ALPN_DOQ)
+                .addRdata(TEST_SVC_PARAM_IPV4HINT_2)
+                .addRdata(TEST_SVC_PARAM_IPV6HINT)
+                .build());
+        // Add A/AAAA records in the Additional section.
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_A)
+                .addRdata(InetAddresses.parseNumericAddress("1.2.3.4").getAddress())
+                .build());
+        os.write(new TestDnsRecordByteArrayBuilder()
+                .setNameCompression(true)
+                .setRRType(TYPE_AAAA)
+                .addRdata(InetAddresses.parseNumericAddress("2001:db8::2").getAddress())
+                .build());
+        final DnsSvcbPacket pkt = DnsSvcbPacket.fromResponse(os.toByteArray());
+
+        // If there are A/AAAA records in the Additional section, getAddresses() returns the IP
+        // addresses in those records instead of the IP addresses in ipv4hint/ipv6hint.
+        assertArrayEquals(expectedIpAddresses, pkt.getAddresses("doq").toArray());
+    }
+}
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/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index 62614c1..0a143c5 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -38,6 +38,7 @@
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.net.ConnectivityManager.EXTRA_NETWORK;
 import static android.net.ConnectivityManager.EXTRA_NETWORK_REQUEST;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
 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;
@@ -3538,6 +3539,12 @@
         doTestFirewallBlocking(FIREWALL_CHAIN_DOZABLE, ALLOWLIST);
     }
 
+    @Test @IgnoreUpTo(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) @ConnectivityModuleTest
+    @AppModeFull(reason = "Socket cannot bind in instant app mode")
+    public void testFirewallBlockingBackground() {
+        doTestFirewallBlocking(FIREWALL_CHAIN_BACKGROUND, ALLOWLIST);
+    }
+
     @Test @IgnoreUpTo(SC_V2) @ConnectivityModuleTest
     @AppModeFull(reason = "Socket cannot bind in instant app mode")
     public void testFirewallBlockingPowersave() {
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/ConnectivityServiceTest.java b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
index aae37e5..bafd450 100755
--- a/tests/unit/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
@@ -59,6 +59,7 @@
 import static android.net.ConnectivityManager.EXTRA_NETWORK_INFO;
 import static android.net.ConnectivityManager.EXTRA_NETWORK_TYPE;
 import static android.net.ConnectivityManager.EXTRA_REALTIME_NS;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
 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;
@@ -10475,6 +10476,7 @@
         doTestSetUidFirewallRule(FIREWALL_CHAIN_POWERSAVE, FIREWALL_RULE_DENY);
         doTestSetUidFirewallRule(FIREWALL_CHAIN_RESTRICTED, FIREWALL_RULE_DENY);
         doTestSetUidFirewallRule(FIREWALL_CHAIN_LOW_POWER_STANDBY, FIREWALL_RULE_DENY);
+        doTestSetUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, FIREWALL_RULE_DENY);
         doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_1, FIREWALL_RULE_ALLOW);
         doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_2, FIREWALL_RULE_ALLOW);
         doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_3, FIREWALL_RULE_ALLOW);
@@ -10488,6 +10490,7 @@
                 FIREWALL_CHAIN_POWERSAVE,
                 FIREWALL_CHAIN_RESTRICTED,
                 FIREWALL_CHAIN_LOW_POWER_STANDBY,
+                FIREWALL_CHAIN_BACKGROUND,
                 FIREWALL_CHAIN_OEM_DENY_1,
                 FIREWALL_CHAIN_OEM_DENY_2,
                 FIREWALL_CHAIN_OEM_DENY_3);
@@ -10537,6 +10540,7 @@
         doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_POWERSAVE, allowlist);
         doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_RESTRICTED, allowlist);
         doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_LOW_POWER_STANDBY, allowlist);
+        doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_BACKGROUND, allowlist);
 
         doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_STANDBY, denylist);
         doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_OEM_DENY_1, denylist);
@@ -10558,6 +10562,7 @@
         doTestReplaceFirewallChain(FIREWALL_CHAIN_POWERSAVE);
         doTestReplaceFirewallChain(FIREWALL_CHAIN_RESTRICTED);
         doTestReplaceFirewallChain(FIREWALL_CHAIN_LOW_POWER_STANDBY);
+        doTestReplaceFirewallChain(FIREWALL_CHAIN_BACKGROUND);
         doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_1);
         doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_2);
         doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_3);
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClientTest.java b/tests/unit/java/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClientTest.java
index 8917ed3..ad30ce0 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClientTest.java
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsMultinetworkSocketClientTest.java
@@ -82,8 +82,8 @@
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
         mSocketKey = new SocketKey(1000 /* interfaceIndex */);
-        mSocketClient = new MdnsMultinetworkSocketClient(
-                mHandlerThread.getLooper(), mProvider, mSharedLog);
+        mSocketClient = new MdnsMultinetworkSocketClient(mHandlerThread.getLooper(), mProvider,
+                mSharedLog, MdnsFeatureFlags.newBuilder().build());
         mHandler.post(() -> mSocketClient.setCallback(mCallback));
     }
 
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketReaderTests.java b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketReaderTests.java
index 19d8a00..37588b5 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketReaderTests.java
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketReaderTests.java
@@ -75,7 +75,7 @@
                     + "the packet length");
         } catch (IOException e) {
             // Expected
-        } catch (Exception e) {
+        } catch (RuntimeException e) {
             fail(String.format(
                     Locale.ROOT,
                     "Should not have thrown any other exception except " + "for IOException: %s",
@@ -83,4 +83,4 @@
         }
         assertEquals(data.length, packetReader.getRemaining());
     }
-}
\ No newline at end of file
+}
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketTest.kt b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketTest.kt
index 28ea4b6..0877b68 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketTest.kt
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketTest.kt
@@ -27,6 +27,9 @@
 
 @RunWith(DevSdkIgnoreRunner::class)
 class MdnsPacketTest {
+    private fun makeFlags(isLabelCountLimitEnabled: Boolean = false): MdnsFeatureFlags =
+            MdnsFeatureFlags.newBuilder()
+                    .setIsLabelCountLimitEnabled(isLabelCountLimitEnabled).build()
     @Test
     fun testParseQuery() {
         // Probe packet with 1 question for Android.local, and 4 additionalRecords with 4 addresses
@@ -38,7 +41,7 @@
                 "010db8000000000000000000000789"
 
         val bytes = HexDump.hexStringToByteArray(packetHex)
-        val reader = MdnsPacketReader(bytes, bytes.size)
+        val reader = MdnsPacketReader(bytes, bytes.size, makeFlags())
         val packet = MdnsPacket.parse(reader)
 
         assertEquals(123, packet.transactionId)
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsResponseDecoderTests.java b/tests/unit/java/com/android/server/connectivity/mdns/MdnsResponseDecoderTests.java
index 3fc656a..a22e8c6 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsResponseDecoderTests.java
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsResponseDecoderTests.java
@@ -17,8 +17,10 @@
 package com.android.server.connectivity.mdns;
 
 import static android.net.InetAddresses.parseNumericAddress;
+
 import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
 import static com.android.testutils.DevSdkIgnoreRuleKt.SC_V2;
+
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -337,7 +339,8 @@
         packet.setSocketAddress(
                 new InetSocketAddress(MdnsConstants.getMdnsIPv6Address(), MdnsConstants.MDNS_PORT));
 
-        final MdnsPacket parsedPacket = MdnsResponseDecoder.parseResponse(data6, data6.length);
+        final MdnsPacket parsedPacket = MdnsResponseDecoder.parseResponse(
+                data6, data6.length, MdnsFeatureFlags.newBuilder().build());
         assertNotNull(parsedPacket);
 
         final Network network = mock(Network.class);
@@ -636,7 +639,8 @@
 
     private ArraySet<MdnsResponse> decode(MdnsResponseDecoder decoder, byte[] data,
             Collection<MdnsResponse> existingResponses) throws MdnsPacket.ParseException {
-        final MdnsPacket parsedPacket = MdnsResponseDecoder.parseResponse(data, data.length);
+        final MdnsPacket parsedPacket = MdnsResponseDecoder.parseResponse(
+                data, data.length, MdnsFeatureFlags.newBuilder().build());
         assertNotNull(parsedPacket);
 
         return new ArraySet<>(decoder.augmentResponses(parsedPacket,
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsSocketClientTests.java b/tests/unit/java/com/android/server/connectivity/mdns/MdnsSocketClientTests.java
index 74f1c37..8b7ab71 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsSocketClientTests.java
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsSocketClientTests.java
@@ -78,6 +78,7 @@
     @Mock private SharedLog sharedLog;
 
     private MdnsSocketClient mdnsClient;
+    private MdnsFeatureFlags flags = MdnsFeatureFlags.newBuilder().build();
 
     @Before
     public void setup() throws RuntimeException, IOException {
@@ -86,7 +87,7 @@
         when(mockWifiManager.createMulticastLock(ArgumentMatchers.anyString()))
                 .thenReturn(mockMulticastLock);
 
-        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog) {
+        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog, flags) {
                     @Override
                     MdnsSocket createMdnsSocket(int port, SharedLog sharedLog) throws IOException {
                         if (port == MdnsConstants.MDNS_PORT) {
@@ -515,7 +516,7 @@
         //MdnsConfigsFlagsImpl.allowNetworkInterfaceIndexPropagation.override(true);
 
         when(mockMulticastSocket.getInterfaceIndex()).thenReturn(21);
-        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog) {
+        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog, flags) {
                     @Override
                     MdnsSocket createMdnsSocket(int port, SharedLog sharedLog) {
                         if (port == MdnsConstants.MDNS_PORT) {
@@ -538,7 +539,7 @@
         //MdnsConfigsFlagsImpl.allowNetworkInterfaceIndexPropagation.override(false);
 
         when(mockMulticastSocket.getInterfaceIndex()).thenReturn(21);
-        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog) {
+        mdnsClient = new MdnsSocketClient(mContext, mockMulticastLock, sharedLog, flags) {
                     @Override
                     MdnsSocket createMdnsSocket(int port, SharedLog sharedLog) {
                         if (port == MdnsConstants.MDNS_PORT) {
diff --git a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
index 3a76ad0..1dab548 100644
--- a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
+++ b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
@@ -29,6 +29,7 @@
 import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
 import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED
 import android.net.NetworkCapabilities.TRANSPORT_CELLULAR
+import android.net.NetworkCapabilities.TRANSPORT_THREAD
 import android.net.NetworkCapabilities.TRANSPORT_WIFI
 import android.net.NetworkRequest
 import android.net.NetworkScore
@@ -38,10 +39,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 +112,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 +120,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 +145,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 +158,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 +212,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 +229,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 +264,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 +275,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 +310,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 +324,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 +339,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 +356,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 +395,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 +431,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 +442,86 @@
         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()
+    }
+
+    @Test
+    fun testLocalNetworkUnwanted_withUpstream() {
+        doTestLocalNetworkUnwanted(true)
+    }
+
+    @Test
+    fun testLocalNetworkUnwanted_withoutUpstream() {
+        doTestLocalNetworkUnwanted(false)
+    }
+
+    fun doTestLocalNetworkUnwanted(haveUpstream: Boolean) {
+        deps.setBuildSdk(VERSION_V)
+
+        val nr = NetworkRequest.Builder().addCapability(NET_CAPABILITY_LOCAL_NETWORK).build()
+        val requestCb = TestableNetworkCallback()
+        cm.requestNetwork(nr, requestCb)
+        val listenCb = TestableNetworkCallback()
+        cm.registerNetworkCallback(nr, listenCb)
+
+        val upstream = if (haveUpstream) {
+            Agent(score = keepScore(), lp = lp("wifi0"),
+                    nc = nc(TRANSPORT_WIFI)).also { it.connect() }
+        } else {
+            null
+        }
+
+        // Set up a local agent.
+        val lnc = LocalNetworkConfig.Builder().apply {
+            if (haveUpstream) {
+                setUpstreamSelector(NetworkRequest.Builder()
+                        .addTransportType(TRANSPORT_WIFI)
+                        .build())
+            }
+        }.build()
+        val localAgent = Agent(nc = nc(TRANSPORT_THREAD, NET_CAPABILITY_LOCAL_NETWORK),
+                lp = lp("local0"),
+                lnc = lnc,
+                score = FromS(NetworkScore.Builder().build())
+        )
+        localAgent.connect()
+
+        requestCb.expectAvailableCallbacks(localAgent.network,
+                validated = false, upstream = upstream?.network)
+        listenCb.expectAvailableCallbacks(localAgent.network,
+                validated = false, upstream = upstream?.network)
+
+        cm.unregisterNetworkCallback(requestCb)
+
+        listenCb.expect<Lost>()
     }
 }
diff --git a/thread/TEST_MAPPING b/thread/TEST_MAPPING
index 3eaebfa..30aeca5 100644
--- a/thread/TEST_MAPPING
+++ b/thread/TEST_MAPPING
@@ -3,5 +3,10 @@
     {
       "name": "CtsThreadNetworkTestCases"
     }
+  ],
+  "postsubmit": [
+    {
+      "name": "ThreadNetworkUnitTests"
+    }
   ]
 }
diff --git a/thread/framework/java/android/net/thread/ActiveOperationalDataset.java b/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
index c9b047a..b74a15a 100644
--- a/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
+++ b/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
@@ -16,8 +16,6 @@
 
 package android.net.thread;
 
-import static android.net.thread.ActiveOperationalDataset.SecurityPolicy.DEFAULT_ROTATION_TIME_HOURS;
-
 import static com.android.internal.util.Preconditions.checkArgument;
 import static com.android.internal.util.Preconditions.checkState;
 import static com.android.net.module.util.HexDump.dumpHexString;
@@ -41,26 +39,25 @@
 import java.io.ByteArrayOutputStream;
 import java.net.Inet6Address;
 import java.net.UnknownHostException;
-import java.security.SecureRandom;
-import java.time.Instant;
 import java.util.Arrays;
-import java.util.Random;
 
 /**
  * Data interface for managing a Thread Active Operational Dataset.
  *
- * <p>An example usage of creating an Active Operational Dataset with random parameters:
+ * <p>An example usage of creating an Active Operational Dataset with randomized parameters:
  *
  * <pre>{@code
- * ActiveOperationalDataset activeDataset = ActiveOperationalDataset.createRandomDataset();
+ * ActiveOperationalDataset activeDataset = controller.createRandomizedDataset("MyNet");
  * }</pre>
  *
- * <p>or random Dataset with customized Network Name:
+ * <p>or randomized Dataset with customized channel:
  *
  * <pre>{@code
  * ActiveOperationalDataset activeDataset =
- *         new ActiveOperationalDataset.Builder(ActiveOperationalDataset.createRandomDataset())
- *                 .setNetworkName("MyThreadNet").build();
+ *         new ActiveOperationalDataset.Builder(controller.createRandomizedDataset("MyNet"))
+ *                 .setChannel(CHANNEL_PAGE_24_GHZ, 17)
+ *                 .setActiveTimestamp(OperationalDatasetTimestamp.fromInstant(Instant.now()))
+ *                 .build();
  * }</pre>
  *
  * <p>If the Active Operational Dataset is already known as <a
@@ -116,7 +113,9 @@
     /** @hide */
     @VisibleForTesting public static final int TYPE_CHANNEL_MASK = 53;
 
-    private static final byte MESH_LOCAL_PREFIX_FIRST_BYTE = (byte) 0xfd;
+    /** @hide */
+    public static final byte MESH_LOCAL_PREFIX_FIRST_BYTE = (byte) 0xfd;
+
     private static final int LENGTH_CHANNEL = 3;
     private static final int LENGTH_PAN_ID = 2;
 
@@ -344,86 +343,6 @@
         outputStream.write(entries, 0, entries.length);
     }
 
-    /**
-     * Creates a new {@link ActiveOperationalDataset} object with randomized or default parameters.
-     *
-     * <p>The randomized (or default) value for each parameter:
-     *
-     * <ul>
-     *   <li>{@code Active Timestamp} defaults to {@code new OperationalDatasetTimestamp(1, 0,
-     *       false)}
-     *   <li>{@code Network Name} defaults to "THREAD-PAN-<PAN ID decimal>", for example
-     *       "THREAD-PAN-12345"
-     *   <li>{@code Extended PAN ID} filled with randomly generated bytes
-     *   <li>{@code PAN ID} randomly generated integer in range of [0, 0xfffe]
-     *   <li>{@code Channel Page} defaults to {@link #CHANNEL_PAGE_24_GHZ}
-     *   <li>{@code Channel} randomly selected channel in range of [{@link #CHANNEL_MIN_24_GHZ},
-     *       {@link #CHANNEL_MAX_24_GHZ}]
-     *   <li>{@code Channel Mask} all bits from {@link #CHANNEL_MIN_24_GHZ} to {@link
-     *       #CHANNEL_MAX_24_GHZ} are set to {@code true}
-     *   <li>{@code PSKc} filled with bytes generated by secure random generator
-     *   <li>{@code Network Key} filled with bytes generated by secure random generator
-     *   <li>{@code Mesh-local Prefix} filled with randomly generated bytes except that the first
-     *       byte is always set to {@code 0xfd}
-     *   <li>{@code Security Policy} defaults to {@code new SecurityPolicy(
-     *       DEFAULT_ROTATION_TIME_HOURS, new byte[]{(byte)0xff, (byte)0xf8})}. This is the default
-     *       values required by the Thread 1.2 specification
-     * </ul>
-     *
-     * <p>This method is the recommended way to create a randomized operational dataset for a new
-     * Thread network. It may be desired to change one or more of the generated value(s). For
-     * example, to use a more meaningful Network Name. To do that, create a new {@link Builder}
-     * object from this dataset with {@link Builder#Builder(ActiveOperationalDataset)} and override
-     * the value with the setters of {@link Builder}.
-     *
-     * <p>Note that it's highly discouraged to change the randomly generated Extended PAN ID,
-     * Network Key or PSKc, as it will compromise the security of a Thread network.
-     */
-    @NonNull
-    public static ActiveOperationalDataset createRandomDataset() {
-        return createRandomDataset(new Random(Instant.now().toEpochMilli()), new SecureRandom());
-    }
-
-    /** @hide */
-    @VisibleForTesting
-    public static ActiveOperationalDataset createRandomDataset(
-            Random random, SecureRandom secureRandom) {
-        int panId = random.nextInt(/* bound= */ 0xffff);
-        byte[] meshLocalPrefix = newRandomBytes(random, LENGTH_MESH_LOCAL_PREFIX_BITS / 8);
-        meshLocalPrefix[0] = MESH_LOCAL_PREFIX_FIRST_BYTE;
-
-        SparseArray<byte[]> channelMask = new SparseArray<>(1);
-        channelMask.put(CHANNEL_PAGE_24_GHZ, new byte[] {0x00, 0x1f, (byte) 0xff, (byte) 0xe0});
-
-        return new Builder()
-                .setActiveTimestamp(
-                        new OperationalDatasetTimestamp(
-                                /* seconds= */ 1,
-                                /* ticks= */ 0,
-                                /* isAuthoritativeSource= */ false))
-                .setExtendedPanId(newRandomBytes(random, LENGTH_EXTENDED_PAN_ID))
-                .setPanId(panId)
-                .setNetworkName("THREAD-PAN-" + panId)
-                .setChannel(
-                        CHANNEL_PAGE_24_GHZ,
-                        random.nextInt(CHANNEL_MAX_24_GHZ - CHANNEL_MIN_24_GHZ + 1)
-                                + CHANNEL_MIN_24_GHZ)
-                .setChannelMask(channelMask)
-                .setPskc(newRandomBytes(secureRandom, LENGTH_PSKC))
-                .setNetworkKey(newRandomBytes(secureRandom, LENGTH_NETWORK_KEY))
-                .setMeshLocalPrefix(meshLocalPrefix)
-                .setSecurityPolicy(
-                        new SecurityPolicy(
-                                DEFAULT_ROTATION_TIME_HOURS, new byte[] {(byte) 0xff, (byte) 0xf8}))
-                .build();
-    }
-
-    private static byte[] newRandomBytes(Random random, int length) {
-        byte[] result = new byte[length];
-        random.nextBytes(result);
-        return result;
-    }
-
     private static boolean areByteSparseArraysEqual(
             @NonNull SparseArray<byte[]> first, @NonNull SparseArray<byte[]> second) {
         if (first == second) {
@@ -683,6 +602,20 @@
         return sb.toString();
     }
 
+    static String checkNetworkName(@NonNull String networkName) {
+        requireNonNull(networkName, "networkName cannot be null");
+
+        int nameLength = networkName.getBytes(UTF_8).length;
+        checkArgument(
+                nameLength >= LENGTH_MIN_NETWORK_NAME_BYTES
+                        && nameLength <= LENGTH_MAX_NETWORK_NAME_BYTES,
+                "Invalid network name (length = %d, expectedLengthRange = [%d, %d])",
+                nameLength,
+                LENGTH_MIN_NETWORK_NAME_BYTES,
+                LENGTH_MAX_NETWORK_NAME_BYTES);
+        return networkName;
+    }
+
     /** The builder for creating {@link ActiveOperationalDataset} objects. */
     public static final class Builder {
         private OperationalDatasetTimestamp mActiveTimestamp;
@@ -748,7 +681,7 @@
          * @param networkName the name of the Thread network
          * @throws IllegalArgumentException if length of the UTF-8 representation of {@code
          *     networkName} isn't in range of [{@link #LENGTH_MIN_NETWORK_NAME_BYTES}, {@link
-         *     #LENGTH_MAX_NETWORK_NAME_BYTES}].
+         *     #LENGTH_MAX_NETWORK_NAME_BYTES}]
          */
         @NonNull
         public Builder setNetworkName(
@@ -757,26 +690,16 @@
                                 min = LENGTH_MIN_NETWORK_NAME_BYTES,
                                 max = LENGTH_MAX_NETWORK_NAME_BYTES)
                         String networkName) {
-            requireNonNull(networkName, "networkName cannot be null");
-
-            int nameLength = networkName.getBytes(UTF_8).length;
-            checkArgument(
-                    nameLength >= LENGTH_MIN_NETWORK_NAME_BYTES
-                            && nameLength <= LENGTH_MAX_NETWORK_NAME_BYTES,
-                    "Invalid network name (length = %d, expectedLengthRange = [%d, %d])",
-                    nameLength,
-                    LENGTH_MIN_NETWORK_NAME_BYTES,
-                    LENGTH_MAX_NETWORK_NAME_BYTES);
-            this.mNetworkName = networkName;
+            this.mNetworkName = checkNetworkName(networkName);
             return this;
         }
 
         /**
          * Sets the Extended PAN ID.
          *
-         * <p>Use with caution. A randomly generated Extended PAN ID should be used for real Thread
+         * <p>Use with caution. A randomized Extended PAN ID should be used for real Thread
          * networks. It's discouraged to call this method to override the default value created by
-         * {@link ActiveOperationalDataset#createRandomDataset} in production.
+         * {@link ThreadNetworkController#createRandomizedDataset} in production.
          *
          * @throws IllegalArgumentException if length of {@code extendedPanId} is not {@link
          *     #LENGTH_EXTENDED_PAN_ID}.
@@ -867,7 +790,7 @@
          *
          * <p>Use with caution. A randomly generated PSKc should be used for real Thread networks.
          * It's discouraged to call this method to override the default value created by {@link
-         * ActiveOperationalDataset#createRandomDataset} in production.
+         * ThreadNetworkController#createRandomizedDataset} in production.
          *
          * @param pskc the key stretched version of the Commissioning Credential for the network
          * @throws IllegalArgumentException if length of {@code pskc} is not {@link #LENGTH_PSKC}
@@ -889,7 +812,7 @@
          *
          * <p>Use with caution, randomly generated Network Key should be used for real Thread
          * networks. It's discouraged to call this method to override the default value created by
-         * {@link ActiveOperationalDataset#createRandomDataset} in production.
+         * {@link ThreadNetworkController#createRandomizedDataset} in production.
          *
          * @param networkKey a 128-bit security key-derivation key for the Thread Network
          * @throws IllegalArgumentException if length of {@code networkKey} is not {@link
@@ -930,8 +853,16 @@
             return this;
         }
 
+        /**
+         * Sets the Mesh-Local Prefix.
+         *
+         * @param meshLocalPrefix the prefix used for realm-local traffic within the mesh
+         * @throws IllegalArgumentException if {@code meshLocalPrefix} doesn't start with {@code
+         *     0xfd} or has length other than {@code LENGTH_MESH_LOCAL_PREFIX_BITS / 8}
+         * @hide
+         */
         @NonNull
-        private Builder setMeshLocalPrefix(byte[] meshLocalPrefix) {
+        public Builder setMeshLocalPrefix(byte[] meshLocalPrefix) {
             final int prefixLength = meshLocalPrefix.length * 8;
             checkArgument(
                     prefixLength == LENGTH_MESH_LOCAL_PREFIX_BITS,
diff --git a/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl b/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl
new file mode 100644
index 0000000..aba54eb
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright 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.thread;
+
+import android.net.thread.ActiveOperationalDataset;
+
+/** Receives the result of an operation which returns an Active Operational Dataset. @hide */
+oneway interface IActiveOperationalDatasetReceiver {
+    void onSuccess(in ActiveOperationalDataset dataset);
+    void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IOperationReceiver.aidl b/thread/framework/java/android/net/thread/IOperationReceiver.aidl
new file mode 100644
index 0000000..42e157b
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IOperationReceiver.aidl
@@ -0,0 +1,23 @@
+/*
+ * Copyright 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.thread;
+
+/** Receives the result of a Thread network operation. @hide */
+oneway interface IOperationReceiver {
+    void onSuccess();
+    void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl b/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl
new file mode 100644
index 0000000..b576b33
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright 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.thread;
+
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.PendingOperationalDataset;
+
+/**
+ * @hide
+ */
+oneway interface IOperationalDatasetCallback {
+    void onActiveOperationalDatasetChanged(in @nullable ActiveOperationalDataset activeOpDataset);
+    void onPendingOperationalDatasetChanged(in @nullable PendingOperationalDataset pendingOpDataset);
+}
diff --git a/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl b/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl
new file mode 100644
index 0000000..c45d463
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl
@@ -0,0 +1,24 @@
+/*
+ * Copyright 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.thread;
+
+/** Receives the result of {@link ThreadNetworkManager#scheduleMigration}. @hide */
+oneway interface IScheduleMigrationReceiver {
+    void onScheduled(long delayTimerMillis);
+    void onMigrated();
+    void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IStateCallback.aidl b/thread/framework/java/android/net/thread/IStateCallback.aidl
new file mode 100644
index 0000000..d7cbda9
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IStateCallback.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright 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.thread;
+
+/**
+ * @hide
+ */
+oneway interface IStateCallback {
+    void onDeviceRoleChanged(int deviceRole);
+    void onPartitionIdChanged(long partitionId);
+}
diff --git a/thread/framework/java/android/net/thread/IThreadNetworkController.aidl b/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
index 0219beb..51e4d88 100644
--- a/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
+++ b/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
@@ -16,10 +16,29 @@
 
 package android.net.thread;
 
+import android.net.Network;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.IActiveOperationalDatasetReceiver;
+import android.net.thread.IOperationalDatasetCallback;
+import android.net.thread.IOperationReceiver;
+import android.net.thread.IScheduleMigrationReceiver;
+import android.net.thread.IStateCallback;
+import android.net.thread.PendingOperationalDataset;
+
 /**
 * Interface for communicating with ThreadNetworkControllerService.
 * @hide
 */
 interface IThreadNetworkController {
+    void registerStateCallback(in IStateCallback callback);
+    void unregisterStateCallback(in IStateCallback callback);
+    void registerOperationalDatasetCallback(in IOperationalDatasetCallback callback);
+    void unregisterOperationalDatasetCallback(in IOperationalDatasetCallback callback);
+
+    void join(in ActiveOperationalDataset activeOpDataset, in IOperationReceiver receiver);
+    void scheduleMigration(in PendingOperationalDataset pendingOpDataset, in IOperationReceiver receiver);
+    void leave(in IOperationReceiver receiver);
+
     int getThreadVersion();
+    void createRandomizedDataset(String networkName, IActiveOperationalDatasetReceiver receiver);
 }
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/PendingOperationalDataset.java b/thread/framework/java/android/net/thread/PendingOperationalDataset.java
index 4762d7f..9cfd0b8 100644
--- a/thread/framework/java/android/net/thread/PendingOperationalDataset.java
+++ b/thread/framework/java/android/net/thread/PendingOperationalDataset.java
@@ -69,7 +69,15 @@
     @NonNull private final OperationalDatasetTimestamp mPendingTimestamp;
     @NonNull private final Duration mDelayTimer;
 
-    /** Creates a new {@link PendingOperationalDataset} object. */
+    /**
+     * Creates a new {@link PendingOperationalDataset} object.
+     *
+     * @param activeOpDataset the included Active Operational Dataset
+     * @param pendingTimestamp the Pending Timestamp which represents the version of this Pending
+     *     Dataset
+     * @param delayTimer the delay after when {@code activeOpDataset} will be committed on this
+     *     device
+     */
     public PendingOperationalDataset(
             @NonNull ActiveOperationalDataset activeOpDataset,
             @NonNull OperationalDatasetTimestamp pendingTimestamp,
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkController.java b/thread/framework/java/android/net/thread/ThreadNetworkController.java
index 7575757..ec39db4 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkController.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkController.java
@@ -18,23 +18,64 @@
 
 import static java.util.Objects.requireNonNull;
 
+import android.Manifest.permission;
+import android.annotation.CallbackExecutor;
 import android.annotation.FlaggedApi;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
+import android.os.OutcomeReceiver;
 import android.os.RemoteException;
 
+import com.android.internal.annotations.GuardedBy;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Executor;
 
 /**
- * Provides the primary API for controlling all aspects of a Thread network.
+ * Provides the primary APIs for controlling all aspects of a Thread network.
+ *
+ * <p>For example, join this device to a Thread network with given Thread Operational Dataset, or
+ * migrate an existing network.
  *
  * @hide
-*/
+ */
 @FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
 @SystemApi
 public final class ThreadNetworkController {
+    private static final String TAG = "ThreadNetworkController";
+
+    /** The Thread stack is stopped. */
+    public static final int DEVICE_ROLE_STOPPED = 0;
+
+    /** The device is not currently participating in a Thread network/partition. */
+    public static final int DEVICE_ROLE_DETACHED = 1;
+
+    /** The device is a Thread Child. */
+    public static final int DEVICE_ROLE_CHILD = 2;
+
+    /** The device is a Thread Router. */
+    public static final int DEVICE_ROLE_ROUTER = 3;
+
+    /** The device is a Thread Leader. */
+    public static final int DEVICE_ROLE_LEADER = 4;
+
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({
+        DEVICE_ROLE_STOPPED,
+        DEVICE_ROLE_DETACHED,
+        DEVICE_ROLE_CHILD,
+        DEVICE_ROLE_ROUTER,
+        DEVICE_ROLE_LEADER
+    })
+    public @interface DeviceRole {}
 
     /** Thread standard version 1.3. */
     public static final int THREAD_VERSION_1_3 = 4;
@@ -46,9 +87,19 @@
 
     private final IThreadNetworkController mControllerService;
 
+    private final Object mStateCallbackMapLock = new Object();
+
+    @GuardedBy("mStateCallbackMapLock")
+    private final Map<StateCallback, StateCallbackProxy> mStateCallbackMap = new HashMap<>();
+
+    private final Object mOpDatasetCallbackMapLock = new Object();
+
+    @GuardedBy("mOpDatasetCallbackMapLock")
+    private final Map<OperationalDatasetCallback, OperationalDatasetCallbackProxy>
+            mOpDatasetCallbackMap = new HashMap<>();
+
     ThreadNetworkController(@NonNull IThreadNetworkController controllerService) {
         requireNonNull(controllerService, "controllerService cannot be null");
-
         mControllerService = controllerService;
     }
 
@@ -61,4 +112,412 @@
             throw e.rethrowFromSystemServer();
         }
     }
+
+    /**
+     * Creates a new Active Operational Dataset with randomized parameters.
+     *
+     * <p>This method is the recommended way to create a randomized dataset which can be used with
+     * {@link #join} to securely join this device to the specified network . It's highly discouraged
+     * to change the randomly generated Extended PAN ID, Network Key or PSKc, as it will compromise
+     * the security of a Thread network.
+     *
+     * @throws IllegalArgumentException if length of the UTF-8 representation of {@code networkName}
+     *     isn't in range of [{@link #LENGTH_MIN_NETWORK_NAME_BYTES}, {@link
+     *     #LENGTH_MAX_NETWORK_NAME_BYTES}]
+     */
+    public void createRandomizedDataset(
+            @NonNull String networkName,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> receiver) {
+        ActiveOperationalDataset.checkNetworkName(networkName);
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(receiver, "receiver cannot be null");
+        try {
+            mControllerService.createRandomizedDataset(
+                    networkName, new ActiveDatasetReceiverProxy(executor, receiver));
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /** Returns {@code true} if {@code deviceRole} indicates an attached state. */
+    public static boolean isAttached(@DeviceRole int deviceRole) {
+        return deviceRole == DEVICE_ROLE_CHILD
+                || deviceRole == DEVICE_ROLE_ROUTER
+                || deviceRole == DEVICE_ROLE_LEADER;
+    }
+
+    /**
+     * Callback to receive notifications when the Thread network states are changed.
+     *
+     * <p>Applications which are interested in monitoring Thread network states should implement
+     * this interface and register the callback with {@link #registerStateCallback}.
+     */
+    public interface StateCallback {
+        /**
+         * The Thread device role has changed.
+         *
+         * @param deviceRole the new Thread device role
+         */
+        void onDeviceRoleChanged(@DeviceRole int deviceRole);
+
+        /**
+         * The Thread network partition ID has changed.
+         *
+         * @param partitionId the new Thread partition ID
+         */
+        default void onPartitionIdChanged(long partitionId) {}
+    }
+
+    private static final class StateCallbackProxy extends IStateCallback.Stub {
+        private final Executor mExecutor;
+        private final StateCallback mCallback;
+
+        StateCallbackProxy(@CallbackExecutor Executor executor, StateCallback callback) {
+            mExecutor = executor;
+            mCallback = callback;
+        }
+
+        @Override
+        public void onDeviceRoleChanged(@DeviceRole int deviceRole) {
+            mExecutor.execute(() -> mCallback.onDeviceRoleChanged(deviceRole));
+        }
+
+        @Override
+        public void onPartitionIdChanged(long partitionId) {
+            mExecutor.execute(() -> mCallback.onPartitionIdChanged(partitionId));
+        }
+    }
+
+    /**
+     * Registers a callback to be called when Thread network states are changed.
+     *
+     * <p>Upon return of this method, methods of {@code callback} will be invoked immediately with
+     * existing states.
+     *
+     * @param executor the executor to execute the {@code callback}
+     * @param callback the callback to receive Thread network state changes
+     * @throws IllegalArgumentException if {@code callback} has already been registered
+     */
+    @RequiresPermission(permission.ACCESS_NETWORK_STATE)
+    public void registerStateCallback(
+            @NonNull @CallbackExecutor Executor executor, @NonNull StateCallback callback) {
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(callback, "callback cannot be null");
+        synchronized (mStateCallbackMapLock) {
+            if (mStateCallbackMap.containsKey(callback)) {
+                throw new IllegalArgumentException("callback has already been registered");
+            }
+            StateCallbackProxy callbackProxy = new StateCallbackProxy(executor, callback);
+            mStateCallbackMap.put(callback, callbackProxy);
+
+            try {
+                mControllerService.registerStateCallback(callbackProxy);
+            } catch (RemoteException e) {
+                mStateCallbackMap.remove(callback);
+                e.rethrowFromSystemServer();
+            }
+        }
+    }
+
+    /**
+     * Unregisters the Thread state changed callback.
+     *
+     * @param callback the callback which has been registered with {@link #registerStateCallback}
+     * @throws IllegalArgumentException if {@code callback} hasn't been registered
+     */
+    public void unregisterStateCallback(@NonNull StateCallback callback) {
+        requireNonNull(callback, "callback cannot be null");
+        synchronized (mStateCallbackMapLock) {
+            StateCallbackProxy callbackProxy = mStateCallbackMap.remove(callback);
+            if (callbackProxy == null) {
+                throw new IllegalArgumentException("callback hasn't been registered");
+            }
+            try {
+                mControllerService.unregisterStateCallback(callbackProxy);
+            } catch (RemoteException e) {
+                e.rethrowFromSystemServer();
+            }
+        }
+    }
+
+    /**
+     * Callback to receive notifications when the Thread Operational Datasets are changed.
+     *
+     * <p>Applications which are interested in monitoring Thread network datasets should implement
+     * this interface and register the callback with {@link #registerOperationalDatasetCallback}.
+     */
+    public interface OperationalDatasetCallback {
+        /**
+         * Called when the Active Operational Dataset is changed.
+         *
+         * @param activeDataset the new Active Operational Dataset or {@code null} if the dataset is
+         *     absent
+         */
+        void onActiveOperationalDatasetChanged(@Nullable ActiveOperationalDataset activeDataset);
+
+        /**
+         * Called when the Pending Operational Dataset is changed.
+         *
+         * @param pendingDataset the new Pending Operational Dataset or {@code null} if the dataset
+         *     has been committed and removed
+         */
+        default void onPendingOperationalDatasetChanged(
+                @Nullable PendingOperationalDataset pendingDataset) {}
+    }
+
+    private static final class OperationalDatasetCallbackProxy
+            extends IOperationalDatasetCallback.Stub {
+        private final Executor mExecutor;
+        private final OperationalDatasetCallback mCallback;
+
+        OperationalDatasetCallbackProxy(
+                @CallbackExecutor Executor executor, OperationalDatasetCallback callback) {
+            mExecutor = executor;
+            mCallback = callback;
+        }
+
+        @Override
+        public void onActiveOperationalDatasetChanged(
+                @Nullable ActiveOperationalDataset activeDataset) {
+            mExecutor.execute(() -> mCallback.onActiveOperationalDatasetChanged(activeDataset));
+        }
+
+        @Override
+        public void onPendingOperationalDatasetChanged(
+                @Nullable PendingOperationalDataset pendingDataset) {
+            mExecutor.execute(() -> mCallback.onPendingOperationalDatasetChanged(pendingDataset));
+        }
+    }
+
+    /**
+     * Registers a callback to be called when Thread Operational Datasets are changed.
+     *
+     * <p>Upon return of this method, methods of {@code callback} will be invoked immediately with
+     * existing Operational Datasets.
+     *
+     * @param executor the executor to execute {@code callback}
+     * @param callback the callback to receive Operational Dataset changes
+     * @throws IllegalArgumentException if {@code callback} has already been registered
+     */
+    @RequiresPermission(
+            allOf = {
+                permission.ACCESS_NETWORK_STATE,
+                "android.permission.THREAD_NETWORK_PRIVILEGED"
+            })
+    public void registerOperationalDatasetCallback(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OperationalDatasetCallback callback) {
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(callback, "callback cannot be null");
+        synchronized (mOpDatasetCallbackMapLock) {
+            if (mOpDatasetCallbackMap.containsKey(callback)) {
+                throw new IllegalArgumentException("callback has already been registered");
+            }
+            OperationalDatasetCallbackProxy callbackProxy =
+                    new OperationalDatasetCallbackProxy(executor, callback);
+            mOpDatasetCallbackMap.put(callback, callbackProxy);
+
+            try {
+                mControllerService.registerOperationalDatasetCallback(callbackProxy);
+            } catch (RemoteException e) {
+                mOpDatasetCallbackMap.remove(callback);
+                e.rethrowFromSystemServer();
+            }
+        }
+    }
+
+    /**
+     * Unregisters the Thread Operational Dataset callback.
+     *
+     * @param callback the callback which has been registered with {@link
+     *     #registerOperationalDatasetCallback}
+     * @throws IllegalArgumentException if {@code callback} hasn't been registered
+     */
+    public void unregisterOperationalDatasetCallback(@NonNull OperationalDatasetCallback callback) {
+        requireNonNull(callback, "callback cannot be null");
+        synchronized (mOpDatasetCallbackMapLock) {
+            OperationalDatasetCallbackProxy callbackProxy = mOpDatasetCallbackMap.remove(callback);
+            if (callbackProxy == null) {
+                throw new IllegalArgumentException("callback hasn't been registered");
+            }
+            try {
+                mControllerService.unregisterOperationalDatasetCallback(callbackProxy);
+            } catch (RemoteException e) {
+                e.rethrowFromSystemServer();
+            }
+        }
+    }
+
+    /**
+     * Joins to a Thread network with given Active Operational Dataset.
+     *
+     * <p>This method does nothing if this device has already joined to the same network specified
+     * by {@code activeDataset}. If this device has already joined to a different network, this
+     * device will first leave from that network and then join the new network. This method changes
+     * only this device and all other connected devices will stay in the old network. To change the
+     * network for all connected devices together, use {@link #scheduleMigration}.
+     *
+     * <p>On success, {@link OutcomeReceiver#onResult} of {@code receiver} is called and the Dataset
+     * will be persisted on this device; this device will try to attach to the Thread network and
+     * the state changes can be observed by {@link #registerStateCallback}. On failure, {@link
+     * OutcomeReceiver#onError} of {@code receiver} will be invoked with a specific error:
+     *
+     * <ul>
+     *   <li>{@link ThreadNetworkException#ERROR_UNSUPPORTED_CHANNEL} {@code activeDataset}
+     *       specifies a channel which is not supported in the current country or region; the {@code
+     *       activeDataset} is rejected and not persisted so this device won't auto re-join the next
+     *       time
+     *   <li>{@link ThreadNetworkException#ERROR_ABORTED} this operation is aborted by another
+     *       {@code join} or {@code leave} operation
+     * </ul>
+     *
+     * @param activeDataset the Active Operational Dataset represents the Thread network to join
+     * @param executor the executor to execute {@code receiver}
+     * @param receiver the receiver to receive result of this operation
+     */
+    @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+    public void join(
+            @NonNull ActiveOperationalDataset activeDataset,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+        requireNonNull(activeDataset, "activeDataset cannot be null");
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(receiver, "receiver cannot be null");
+        try {
+            mControllerService.join(activeDataset, new OperationReceiverProxy(executor, receiver));
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Schedules a network migration which moves all devices in the current connected network to a
+     * new network or updates parameters of the current connected network.
+     *
+     * <p>The migration doesn't happen immediately but is registered to the Leader device so that
+     * all devices in the current Thread network can be scheduled to apply the new dataset together.
+     *
+     * <p>On success, the Pending Dataset is successfully registered and persisted on the Leader and
+     * {@link OutcomeReceiver#onResult} of {@code receiver} will be called; Operational Dataset
+     * changes will be asynchronously delivered via {@link OperationalDatasetCallback} if a callback
+     * has been registered with {@link #registerOperationalDatasetCallback}. When failed, {@link
+     * OutcomeReceiver#onError} will be called with a specific error:
+     *
+     * <ul>
+     *   <li>{@link ThreadNetworkException#ERROR_FAILED_PRECONDITION} the migration is rejected
+     *       because this device is not attached
+     *   <li>{@link ThreadNetworkException#ERROR_UNSUPPORTED_CHANNEL} {@code pendingDataset}
+     *       specifies a channel which is not supported in the current country or region; the {@code
+     *       pendingDataset} is rejected and not persisted
+     *   <li>{@link ThreadNetworkException#ERROR_REJECTED_BY_PEER} the Pending Dataset is rejected
+     *       by the Leader device
+     *   <li>{@link ThreadNetworkException#ERROR_BUSY} another {@code scheduleMigration} request is
+     *       being processed
+     *   <li>{@link ThreadNetworkException#ERROR_TIMEOUT} response from the Leader device hasn't
+     *       been received before deadline
+     * </ul>
+     *
+     * <p>The Delay Timer of {@code pendingDataset} can vary from several minutes to a few days.
+     * It's important to select a proper value to safely migrate all devices in the network without
+     * leaving sleepy end devices orphaned. Apps are not suggested to specify the Delay Timer value
+     * if it's unclear how long it can take to propagate the {@code pendingDataset} to the whole
+     * network. Instead, use {@link Duration#ZERO} to use the default value suggested by the system.
+     *
+     * @param pendingDataset the Pending Operational Dataset
+     * @param executor the executor to execute {@code receiver}
+     * @param receiver the receiver to receive result of this operation
+     */
+    @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+    public void scheduleMigration(
+            @NonNull PendingOperationalDataset pendingDataset,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+        requireNonNull(pendingDataset, "pendingDataset cannot be null");
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(receiver, "receiver cannot be null");
+        try {
+            mControllerService.scheduleMigration(
+                    pendingDataset, new OperationReceiverProxy(executor, receiver));
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Leaves from the Thread network.
+     *
+     * <p>This undoes a {@link join} operation. On success, this device is disconnected from the
+     * joined network and will not automatically join a network before {@link #join} is called
+     * again. Active and Pending Operational Dataset configured and persisted on this device will be
+     * removed too.
+     *
+     * @param executor the executor to execute {@code receiver}
+     * @param receiver the receiver to receive result of this operation
+     */
+    @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+    public void leave(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+        requireNonNull(executor, "executor cannot be null");
+        requireNonNull(receiver, "receiver cannot be null");
+        try {
+            mControllerService.leave(new OperationReceiverProxy(executor, receiver));
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    private static <T> void propagateError(
+            Executor executor,
+            OutcomeReceiver<T, ThreadNetworkException> receiver,
+            int errorCode,
+            String errorMsg) {
+        executor.execute(() -> receiver.onError(new ThreadNetworkException(errorCode, errorMsg)));
+    }
+
+    private static final class ActiveDatasetReceiverProxy
+            extends IActiveOperationalDatasetReceiver.Stub {
+        final Executor mExecutor;
+        final OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> mResultReceiver;
+
+        ActiveDatasetReceiverProxy(
+                @CallbackExecutor Executor executor,
+                OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> resultReceiver) {
+            this.mExecutor = executor;
+            this.mResultReceiver = resultReceiver;
+        }
+
+        @Override
+        public void onSuccess(ActiveOperationalDataset dataset) {
+            mExecutor.execute(() -> mResultReceiver.onResult(dataset));
+        }
+
+        @Override
+        public void onError(int errorCode, String errorMessage) {
+            propagateError(mExecutor, mResultReceiver, errorCode, errorMessage);
+        }
+    }
+
+    private static final class OperationReceiverProxy extends IOperationReceiver.Stub {
+        final Executor mExecutor;
+        final OutcomeReceiver<Void, ThreadNetworkException> mResultReceiver;
+
+        OperationReceiverProxy(
+                @CallbackExecutor Executor executor,
+                OutcomeReceiver<Void, ThreadNetworkException> resultReceiver) {
+            this.mExecutor = executor;
+            this.mResultReceiver = resultReceiver;
+        }
+
+        @Override
+        public void onSuccess() {
+            mExecutor.execute(() -> mResultReceiver.onResult(null));
+        }
+
+        @Override
+        public void onError(int errorCode, String errorMessage) {
+            propagateError(mExecutor, mResultReceiver, errorCode, errorMessage);
+        }
+    }
 }
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkException.java b/thread/framework/java/android/net/thread/ThreadNetworkException.java
new file mode 100644
index 0000000..c5e1e97
--- /dev/null
+++ b/thread/framework/java/android/net/thread/ThreadNetworkException.java
@@ -0,0 +1,137 @@
+/*
+ * 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.thread;
+
+import static java.util.Objects.requireNonNull;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Represents a Thread network specific failure.
+ *
+ * @hide
+ */
+@FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
+@SystemApi
+public class ThreadNetworkException extends Exception {
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({
+        ERROR_INTERNAL_ERROR,
+        ERROR_ABORTED,
+        ERROR_TIMEOUT,
+        ERROR_UNAVAILABLE,
+        ERROR_BUSY,
+        ERROR_FAILED_PRECONDITION,
+        ERROR_UNSUPPORTED_CHANNEL,
+        ERROR_REJECTED_BY_PEER,
+        ERROR_RESPONSE_BAD_FORMAT,
+        ERROR_RESOURCE_EXHAUSTED,
+    })
+    public @interface ErrorCode {}
+
+    /**
+     * The operation failed because some invariants expected by the underlying system have been
+     * broken. This error code is reserved for serious errors. The caller can do nothing to recover
+     * from this error. A bugreport should be created and sent to the Android community if this
+     * error is ever returned.
+     */
+    public static final int ERROR_INTERNAL_ERROR = 1;
+
+    /**
+     * The operation failed because concurrent operations are overriding this one. Retrying an
+     * aborted operation has the risk of aborting another ongoing operation again. So the caller
+     * should retry at a higher level where it knows there won't be race conditions.
+     */
+    public static final int ERROR_ABORTED = 2;
+
+    /**
+     * The operation failed because a deadline expired before the operation could complete. This may
+     * be caused by connectivity unavailability and the caller can retry the same operation when the
+     * connectivity issue is fixed.
+     */
+    public static final int ERROR_TIMEOUT = 3;
+
+    /**
+     * The operation failed because the service is currently unavailable and that this is most
+     * likely a transient condition. The caller can recover from this error by retrying with a
+     * back-off scheme. Note that it is not always safe to retry non-idempotent operations.
+     */
+    public static final int ERROR_UNAVAILABLE = 4;
+
+    /**
+     * The operation failed because this device is currently busy processing concurrent requests.
+     * The caller may recover from this error when the current operations has been finished.
+     */
+    public static final int ERROR_BUSY = 5;
+
+    /**
+     * The operation failed because required preconditions were not satisfied. For example, trying
+     * to schedule a network migration when this device is not attached will receive this error. The
+     * caller should not retry the same operation before the precondition is satisfied.
+     */
+    public static final int ERROR_FAILED_PRECONDITION = 6;
+
+    /**
+     * The operation was rejected because the specified channel is currently not supported by this
+     * device in this country. For example, trying to join or migrate to a network with channel
+     * which is not supported. The caller should should change the channel or return an error to the
+     * user if the channel cannot be changed.
+     */
+    public static final int ERROR_UNSUPPORTED_CHANNEL = 7;
+
+    /**
+     * The operation failed because a request is rejected by the peer device. This happens because
+     * the peer device is not capable of processing the request, or a request from another device
+     * has already been accepted by the peer device. The caller may not be able to recover from this
+     * error by retrying the same operation.
+     */
+    public static final int ERROR_REJECTED_BY_PEER = 8;
+
+    /**
+     * The operation failed because the received response is malformed. This is typically because
+     * the peer device is misbehaving. The caller may only recover from this error by retrying with
+     * a different peer device.
+     */
+    public static final int ERROR_RESPONSE_BAD_FORMAT = 9;
+
+    /**
+     * The operation failed because some resource has been exhausted. For example, no enough
+     * allocated memory buffers, or maximum number of supported operations has been exceeded. The
+     * caller may retry and recover from this error when the resource has been freed.
+     */
+    public static final int ERROR_RESOURCE_EXHAUSTED = 10;
+
+    private final int mErrorCode;
+
+    /** Creates a new {@link ThreadNetworkException} object with given error code and message. */
+    public ThreadNetworkException(@ErrorCode int errorCode, @NonNull String errorMessage) {
+        super(requireNonNull(errorMessage, "errorMessage cannot be null"));
+        this.mErrorCode = errorCode;
+    }
+
+    /** Returns the error code. */
+    public @ErrorCode int getErrorCode() {
+        return mErrorCode;
+    }
+}
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkManager.java b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
index c3bdbd7..28012a7 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkManager.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
@@ -66,6 +66,19 @@
      */
     public static final String FEATURE_NAME = "android.hardware.thread_network";
 
+    /**
+     * Permission allows changing Thread network state and access to Thread network credentials such
+     * as Network Key and PSKc.
+     *
+     * <p>This is the same value as android.Manifest.permission.THREAD_NETWORK_PRIVILEGED. That
+     * symbol is not available on U while this feature needs to support Android U TV devices, so
+     * here is making a copy of android.Manifest.permission.THREAD_NETWORK_PRIVILEGED.
+     *
+     * @hide
+     */
+    public static final String PERMISSION_THREAD_NETWORK_PRIVILEGED =
+            "android.permission.THREAD_NETWORK_PRIVILEGED";
+
     @NonNull private final Context mContext;
     @NonNull private final List<ThreadNetworkController> mUnmodifiableControllerServices;
 
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/service/Android.bp b/thread/service/Android.bp
index f1af653..bd265e6 100644
--- a/thread/service/Android.bp
+++ b/thread/service/Android.bp
@@ -33,10 +33,35 @@
     min_sdk_version: "30",
     srcs: [":service-thread-sources"],
     libs: [
+        "framework-connectivity-pre-jarjar",
         "framework-connectivity-t-pre-jarjar",
+        "service-connectivity-pre-jarjar",
     ],
     static_libs: [
         "net-utils-device-common",
+        "net-utils-device-common-netlink",
+        "ot-daemon-aidl-java",
+    ],
+    apex_available: ["com.android.tethering"],
+}
+
+cc_library_shared {
+    name: "libservice-thread-jni",
+    min_sdk_version: "30",
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-unused-parameter",
+        "-Wthread-safety",
+    ],
+    srcs: [
+        "jni/**/*.cpp",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+        "libnativehelper",
     ],
     apex_available: ["com.android.tethering"],
 }
diff --git a/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java b/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java
new file mode 100644
index 0000000..a8909bc
--- /dev/null
+++ b/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java
@@ -0,0 +1,82 @@
+/*
+ * 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 com.android.server.thread;
+
+import static android.net.thread.ThreadNetworkException.ERROR_UNAVAILABLE;
+
+import android.net.thread.IOperationReceiver;
+import android.os.RemoteException;
+
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/** A {@link IOperationReceiver} wrapper which makes it easier to invoke the callbacks. */
+final class OperationReceiverWrapper {
+    private final IOperationReceiver mReceiver;
+
+    private static final Object sPendingReceiversLock = new Object();
+
+    @GuardedBy("sPendingReceiversLock")
+    private static final Set<OperationReceiverWrapper> sPendingReceivers = new HashSet<>();
+
+    public OperationReceiverWrapper(IOperationReceiver receiver) {
+        this.mReceiver = receiver;
+
+        synchronized (sPendingReceiversLock) {
+            sPendingReceivers.add(this);
+        }
+    }
+
+    public static void onOtDaemonDied() {
+        synchronized (sPendingReceiversLock) {
+            for (OperationReceiverWrapper receiver : sPendingReceivers) {
+                try {
+                    receiver.mReceiver.onError(ERROR_UNAVAILABLE, "Thread daemon died");
+                } catch (RemoteException e) {
+                    // The client is dead, do nothing
+                }
+            }
+            sPendingReceivers.clear();
+        }
+    }
+
+    public void onSuccess() {
+        synchronized (sPendingReceiversLock) {
+            sPendingReceivers.remove(this);
+        }
+
+        try {
+            mReceiver.onSuccess();
+        } catch (RemoteException e) {
+            // The client is dead, do nothing
+        }
+    }
+
+    public void onError(int errorCode, String errorMessage, Object... messageArgs) {
+        synchronized (sPendingReceiversLock) {
+            sPendingReceivers.remove(this);
+        }
+
+        try {
+            mReceiver.onError(errorCode, String.format(errorMessage, messageArgs));
+        } catch (RemoteException e) {
+            // The client is dead, do nothing
+        }
+    }
+}
diff --git a/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java b/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
index e8b95bc..6c9a775 100644
--- a/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
+++ b/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
@@ -1,31 +1,833 @@
 /*
  * 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
+ * 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
+ * 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.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
  */
 
 package com.android.server.thread;
 
+import static android.net.thread.ActiveOperationalDataset.CHANNEL_PAGE_24_GHZ;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_EXTENDED_PAN_ID;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_MESH_LOCAL_PREFIX_BITS;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_NETWORK_KEY;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_PSKC;
+import static android.net.thread.ActiveOperationalDataset.MESH_LOCAL_PREFIX_FIRST_BYTE;
+import static android.net.thread.ActiveOperationalDataset.SecurityPolicy.DEFAULT_ROTATION_TIME_HOURS;
+import static android.net.thread.ThreadNetworkController.DEVICE_ROLE_DETACHED;
 import static android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3;
+import static android.net.thread.ThreadNetworkException.ERROR_ABORTED;
+import static android.net.thread.ThreadNetworkException.ERROR_BUSY;
+import static android.net.thread.ThreadNetworkException.ERROR_FAILED_PRECONDITION;
+import static android.net.thread.ThreadNetworkException.ERROR_INTERNAL_ERROR;
+import static android.net.thread.ThreadNetworkException.ERROR_REJECTED_BY_PEER;
+import static android.net.thread.ThreadNetworkException.ERROR_RESOURCE_EXHAUSTED;
+import static android.net.thread.ThreadNetworkException.ERROR_RESPONSE_BAD_FORMAT;
+import static android.net.thread.ThreadNetworkException.ERROR_TIMEOUT;
+import static android.net.thread.ThreadNetworkException.ERROR_UNSUPPORTED_CHANNEL;
+import static android.net.thread.ThreadNetworkException.ErrorCode;
+import static android.net.thread.ThreadNetworkManager.PERMISSION_THREAD_NETWORK_PRIVILEGED;
 
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_ABORT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_BUSY;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_DETACHED;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_INVALID_STATE;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_NO_BUFS;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_PARSE;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_REASSEMBLY_TIMEOUT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_REJECTED;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_RESPONSE_TIMEOUT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_UNSUPPORTED_CHANNEL;
+import static com.android.server.thread.openthread.IOtDaemon.TUN_IF_NAME;
+
+import android.Manifest.permission;
+import android.annotation.NonNull;
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.LinkAddress;
+import android.net.LinkProperties;
+import android.net.NetworkAgent;
+import android.net.NetworkAgentConfig;
+import android.net.NetworkCapabilities;
+import android.net.NetworkProvider;
+import android.net.NetworkScore;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
+import android.net.thread.IActiveOperationalDatasetReceiver;
+import android.net.thread.IOperationReceiver;
+import android.net.thread.IOperationalDatasetCallback;
+import android.net.thread.IStateCallback;
 import android.net.thread.IThreadNetworkController;
+import android.net.thread.OperationalDatasetTimestamp;
+import android.net.thread.PendingOperationalDataset;
 import android.net.thread.ThreadNetworkController;
+import android.net.thread.ThreadNetworkController.DeviceRole;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.os.SystemClock;
+import android.util.Log;
+import android.util.SparseArray;
 
-/** Implementation of the {@link ThreadNetworkController} API. */
-public final class ThreadNetworkControllerService extends IThreadNetworkController.Stub {
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.ServiceManagerWrapper;
+import com.android.server.thread.openthread.IOtDaemon;
+import com.android.server.thread.openthread.IOtDaemonCallback;
+import com.android.server.thread.openthread.IOtStatusReceiver;
+import com.android.server.thread.openthread.Ipv6AddressInfo;
+import com.android.server.thread.openthread.OtDaemonState;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.SecureRandom;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Random;
+import java.util.function.Supplier;
+
+/**
+ * Implementation of the {@link ThreadNetworkController} API.
+ *
+ * <p>Threading model: This class is not Thread-safe and should only be accessed from the
+ * ThreadNetworkService class. Additional attention should be paid to handle the threading code
+ * correctly: 1. All member fields other than `mHandler` and `mContext` MUST be accessed from
+ * `mHandlerThread` 2. In the @Override methods, the actual work MUST be dispatched to the
+ * HandlerThread except for arguments or permissions checking
+ */
+final class ThreadNetworkControllerService extends IThreadNetworkController.Stub {
+    private static final String TAG = "ThreadNetworkService";
+
+    // Below member fields can be accessed from both the binder and handler threads
+
+    private final Context mContext;
+    private final Handler mHandler;
+
+    // Below member fields can only be accessed from the handler thread (`mHandlerThread`). In
+    // particular, the constructor does not run on the handler thread, so it must not touch any of
+    // the non-final fields, nor must it mutate any of the non-final fields inside these objects.
+
+    private final HandlerThread mHandlerThread;
+    private final NetworkProvider mNetworkProvider;
+    private final Supplier<IOtDaemon> mOtDaemonSupplier;
+    private final ConnectivityManager mConnectivityManager;
+    private final TunInterfaceController mTunIfController;
+    private final LinkProperties mLinkProperties = new LinkProperties();
+    private final OtDaemonCallbackProxy mOtDaemonCallbackProxy = new OtDaemonCallbackProxy();
+
+    // TODO(b/308310823): read supported channel from Thread dameon
+    private final int mSupportedChannelMask = 0x07FFF800; // from channel 11 to 26
+
+    private IOtDaemon mOtDaemon;
+    private NetworkAgent mNetworkAgent;
+
+    @VisibleForTesting
+    ThreadNetworkControllerService(
+            Context context,
+            HandlerThread handlerThread,
+            NetworkProvider networkProvider,
+            Supplier<IOtDaemon> otDaemonSupplier,
+            ConnectivityManager connectivityManager,
+            TunInterfaceController tunIfController) {
+        mContext = context;
+        mHandlerThread = handlerThread;
+        mHandler = new Handler(handlerThread.getLooper());
+        mNetworkProvider = networkProvider;
+        mOtDaemonSupplier = otDaemonSupplier;
+        mConnectivityManager = connectivityManager;
+        mTunIfController = tunIfController;
+    }
+
+    public static ThreadNetworkControllerService newInstance(Context context) {
+        HandlerThread handlerThread = new HandlerThread("ThreadHandlerThread");
+        handlerThread.start();
+        NetworkProvider networkProvider =
+                new NetworkProvider(context, handlerThread.getLooper(), "ThreadNetworkProvider");
+
+        return new ThreadNetworkControllerService(
+                context,
+                handlerThread,
+                networkProvider,
+                () -> IOtDaemon.Stub.asInterface(ServiceManagerWrapper.waitForService("ot_daemon")),
+                context.getSystemService(ConnectivityManager.class),
+                new TunInterfaceController(TUN_IF_NAME));
+    }
+
+    private static NetworkCapabilities newNetworkCapabilities() {
+        return new NetworkCapabilities.Builder()
+                .addTransportType(NetworkCapabilities.TRANSPORT_THREAD)
+                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
+                .build();
+    }
+
+    private static InetAddress addressInfoToInetAddress(Ipv6AddressInfo addressInfo) {
+        try {
+            return InetAddress.getByAddress(addressInfo.address);
+        } catch (UnknownHostException e) {
+            // This is impossible unless the Thread daemon is critically broken
+            return null;
+        }
+    }
+
+    private static LinkAddress newLinkAddress(Ipv6AddressInfo addressInfo) {
+        long deprecationTimeMillis =
+                addressInfo.isPreferred
+                        ? LinkAddress.LIFETIME_PERMANENT
+                        : SystemClock.elapsedRealtime();
+
+        InetAddress address = addressInfoToInetAddress(addressInfo);
+
+        // flags and scope will be adjusted automatically depending on the address and
+        // its lifetimes.
+        return new LinkAddress(
+                address,
+                addressInfo.prefixLength,
+                0 /* flags */,
+                0 /* scope */,
+                deprecationTimeMillis,
+                LinkAddress.LIFETIME_PERMANENT /* expirationTime */);
+    }
+
+    private void initializeOtDaemon() {
+        try {
+            getOtDaemon();
+        } catch (RemoteException e) {
+            Log.e(TAG, "Failed to initialize ot-daemon");
+        }
+    }
+
+    private IOtDaemon getOtDaemon() throws RemoteException {
+        if (mOtDaemon != null) {
+            return mOtDaemon;
+        }
+
+        IOtDaemon otDaemon = mOtDaemonSupplier.get();
+        if (otDaemon == null) {
+            throw new RemoteException("Internal error: failed to start OT daemon");
+        }
+        otDaemon.asBinder().linkToDeath(() -> mHandler.post(this::onOtDaemonDied), 0);
+        otDaemon.initialize(mTunIfController.getTunFd());
+        otDaemon.registerStateCallback(mOtDaemonCallbackProxy, -1);
+        mOtDaemon = otDaemon;
+        return mOtDaemon;
+    }
+
+    private void onOtDaemonDied() {
+        Log.w(TAG, "OT daemon became dead, clean up...");
+        OperationReceiverWrapper.onOtDaemonDied();
+        mOtDaemonCallbackProxy.onOtDaemonDied();
+        mOtDaemon = null;
+    }
+
+    public void initialize() {
+        mHandler.post(
+                () -> {
+                    Log.d(TAG, "Initializing Thread system service...");
+                    try {
+                        mTunIfController.createTunInterface();
+                    } catch (IOException e) {
+                        throw new IllegalStateException(
+                                "Failed to create Thread tunnel interface", e);
+                    }
+                    mLinkProperties.setInterfaceName(TUN_IF_NAME);
+                    mLinkProperties.setMtu(TunInterfaceController.MTU);
+                    mConnectivityManager.registerNetworkProvider(mNetworkProvider);
+
+                    initializeOtDaemon();
+                });
+    }
+
+    private void registerThreadNetwork() {
+        if (mNetworkAgent != null) {
+            return;
+        }
+        NetworkCapabilities netCaps = newNetworkCapabilities();
+        NetworkScore score =
+                new NetworkScore.Builder()
+                        .setKeepConnectedReason(NetworkScore.KEEP_CONNECTED_LOCAL_NETWORK)
+                        .build();
+        mNetworkAgent =
+                new NetworkAgent(
+                        mContext,
+                        mHandlerThread.getLooper(),
+                        TAG,
+                        netCaps,
+                        mLinkProperties,
+                        score,
+                        new NetworkAgentConfig.Builder().build(),
+                        mNetworkProvider) {};
+        mNetworkAgent.register();
+        mNetworkAgent.markConnected();
+        Log.i(TAG, "Registered Thread network");
+    }
+
+    private void unregisterThreadNetwork() {
+        if (mNetworkAgent == null) {
+            // unregisterThreadNetwork can be called every time this device becomes detached or
+            // disabled and the mNetworkAgent may not be created in this cases
+            return;
+        }
+
+        Log.d(TAG, "Unregistering Thread network agent");
+
+        mNetworkAgent.unregister();
+        mNetworkAgent = null;
+    }
+
+    private void updateTunInterfaceAddress(LinkAddress linkAddress, boolean isAdded) {
+        try {
+            if (isAdded) {
+                mTunIfController.addAddress(linkAddress);
+            } else {
+                mTunIfController.removeAddress(linkAddress);
+            }
+        } catch (IOException e) {
+            Log.e(
+                    TAG,
+                    String.format(
+                            "Failed to %s Thread tun interface address %s",
+                            (isAdded ? "add" : "remove"), linkAddress),
+                    e);
+        }
+    }
+
+    private void updateNetworkLinkProperties(LinkAddress linkAddress, boolean isAdded) {
+        if (isAdded) {
+            mLinkProperties.addLinkAddress(linkAddress);
+        } else {
+            mLinkProperties.removeLinkAddress(linkAddress);
+        }
+
+        // The Thread daemon can send link property updates before the networkAgent is
+        // registered
+        if (mNetworkAgent != null) {
+            mNetworkAgent.sendLinkProperties(mLinkProperties);
+        }
+    }
 
     @Override
     public int getThreadVersion() {
         return THREAD_VERSION_1_3;
     }
+
+    @Override
+    public void createRandomizedDataset(
+            String networkName, IActiveOperationalDatasetReceiver receiver) {
+        mHandler.post(
+                () -> {
+                    ActiveOperationalDataset dataset =
+                            createRandomizedDatasetInternal(
+                                    networkName,
+                                    mSupportedChannelMask,
+                                    Instant.now(),
+                                    new Random(),
+                                    new SecureRandom());
+                    try {
+                        receiver.onSuccess(dataset);
+                    } catch (RemoteException e) {
+                        // The client is dead, do nothing
+                    }
+                });
+    }
+
+    private static ActiveOperationalDataset createRandomizedDatasetInternal(
+            String networkName,
+            int supportedChannelMask,
+            Instant now,
+            Random random,
+            SecureRandom secureRandom) {
+        int panId = random.nextInt(/* bound= */ 0xffff);
+        final byte[] meshLocalPrefix = newRandomBytes(random, LENGTH_MESH_LOCAL_PREFIX_BITS / 8);
+        meshLocalPrefix[0] = MESH_LOCAL_PREFIX_FIRST_BYTE;
+
+        final SparseArray<byte[]> channelMask = new SparseArray<>(1);
+        channelMask.put(CHANNEL_PAGE_24_GHZ, channelMaskToByteArray(supportedChannelMask));
+
+        final byte[] securityFlags = new byte[] {(byte) 0xff, (byte) 0xf8};
+
+        return new ActiveOperationalDataset.Builder()
+                .setActiveTimestamp(
+                        new OperationalDatasetTimestamp(
+                                now.getEpochSecond() & 0xffffffffffffL, 0, false))
+                .setExtendedPanId(newRandomBytes(random, LENGTH_EXTENDED_PAN_ID))
+                .setPanId(panId)
+                .setNetworkName(networkName)
+                .setChannel(CHANNEL_PAGE_24_GHZ, selectRandomChannel(supportedChannelMask, random))
+                .setChannelMask(channelMask)
+                .setPskc(newRandomBytes(secureRandom, LENGTH_PSKC))
+                .setNetworkKey(newRandomBytes(secureRandom, LENGTH_NETWORK_KEY))
+                .setMeshLocalPrefix(meshLocalPrefix)
+                .setSecurityPolicy(new SecurityPolicy(DEFAULT_ROTATION_TIME_HOURS, securityFlags))
+                .build();
+    }
+
+    private static byte[] newRandomBytes(Random random, int length) {
+        byte[] result = new byte[length];
+        random.nextBytes(result);
+        return result;
+    }
+
+    private static byte[] channelMaskToByteArray(int channelMask) {
+        // Per Thread spec, a Channel Mask is:
+        // A variable-length bit mask that identifies the channels within the channel page
+        // (1 = selected, 0 = unselected). The channels are represented in most significant bit
+        // order. For example, the most significant bit of the left-most byte indicates channel 0.
+        // If channel 0 and channel 10 are selected, the mask would be: 80 20 00 00. For IEEE
+        // 802.15.4-2006 2.4 GHz PHY, the ChannelMask is 27 bits and MaskLength is 4.
+        //
+        // The pass-in channelMask represents a channel K by (channelMask & (1 << K)), so here
+        // needs to do bit-wise reverse to convert it to the Thread spec format in bytes.
+        channelMask = Integer.reverse(channelMask);
+        return new byte[] {
+            (byte) (channelMask >>> 24),
+            (byte) (channelMask >>> 16),
+            (byte) (channelMask >>> 8),
+            (byte) channelMask
+        };
+    }
+
+    private static int selectRandomChannel(int supportedChannelMask, Random random) {
+        int num = random.nextInt(Integer.bitCount(supportedChannelMask));
+        for (int i = 0; i < 32; i++) {
+            if ((supportedChannelMask & 1) == 1 && (num--) == 0) {
+                return i;
+            }
+            supportedChannelMask >>>= 1;
+        }
+        return -1;
+    }
+
+    private void enforceAllCallingPermissionsGranted(String... permissions) {
+        for (String permission : permissions) {
+            mContext.enforceCallingPermission(
+                    permission, "Permission " + permission + " is missing");
+        }
+    }
+
+    @Override
+    public void registerStateCallback(IStateCallback stateCallback) throws RemoteException {
+        enforceAllCallingPermissionsGranted(permission.ACCESS_NETWORK_STATE);
+
+        mHandler.post(() -> mOtDaemonCallbackProxy.registerStateCallback(stateCallback));
+    }
+
+    @Override
+    public void unregisterStateCallback(IStateCallback stateCallback) throws RemoteException {
+        mHandler.post(() -> mOtDaemonCallbackProxy.unregisterStateCallback(stateCallback));
+    }
+
+    @Override
+    public void registerOperationalDatasetCallback(IOperationalDatasetCallback callback)
+            throws RemoteException {
+        enforceAllCallingPermissionsGranted(
+                permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+        mHandler.post(() -> mOtDaemonCallbackProxy.registerDatasetCallback(callback));
+    }
+
+    @Override
+    public void unregisterOperationalDatasetCallback(IOperationalDatasetCallback callback)
+            throws RemoteException {
+        mHandler.post(() -> mOtDaemonCallbackProxy.unregisterDatasetCallback(callback));
+    }
+
+    private void checkOnHandlerThread() {
+        if (Looper.myLooper() != mHandlerThread.getLooper()) {
+            Log.wtf(TAG, "Must be on the handler thread!");
+        }
+    }
+
+    private IOtStatusReceiver newOtStatusReceiver(OperationReceiverWrapper receiver) {
+        return new IOtStatusReceiver.Stub() {
+            @Override
+            public void onSuccess() {
+                receiver.onSuccess();
+            }
+
+            @Override
+            public void onError(int otError, String message) {
+                receiver.onError(otErrorToAndroidError(otError), message);
+            }
+        };
+    }
+
+    @ErrorCode
+    private static int otErrorToAndroidError(int otError) {
+        // See external/openthread/include/openthread/error.h for OT error definition
+        switch (otError) {
+            case OT_ERROR_ABORT:
+                return ERROR_ABORTED;
+            case OT_ERROR_BUSY:
+                return ERROR_BUSY;
+            case OT_ERROR_DETACHED:
+            case OT_ERROR_INVALID_STATE:
+                return ERROR_FAILED_PRECONDITION;
+            case OT_ERROR_NO_BUFS:
+                return ERROR_RESOURCE_EXHAUSTED;
+            case OT_ERROR_PARSE:
+                return ERROR_RESPONSE_BAD_FORMAT;
+            case OT_ERROR_REASSEMBLY_TIMEOUT:
+            case OT_ERROR_RESPONSE_TIMEOUT:
+                return ERROR_TIMEOUT;
+            case OT_ERROR_REJECTED:
+                return ERROR_REJECTED_BY_PEER;
+            case OT_ERROR_UNSUPPORTED_CHANNEL:
+                return ERROR_UNSUPPORTED_CHANNEL;
+            default:
+                return ERROR_INTERNAL_ERROR;
+        }
+    }
+
+    @Override
+    public void join(
+            @NonNull ActiveOperationalDataset activeDataset, @NonNull IOperationReceiver receiver) {
+        enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        OperationReceiverWrapper receiverWrapper = new OperationReceiverWrapper(receiver);
+        mHandler.post(() -> joinInternal(activeDataset, receiverWrapper));
+    }
+
+    private void joinInternal(
+            @NonNull ActiveOperationalDataset activeDataset,
+            @NonNull OperationReceiverWrapper receiver) {
+        checkOnHandlerThread();
+
+        try {
+            // The otDaemon.join() will leave first if this device is currently attached
+            getOtDaemon().join(activeDataset.toThreadTlvs(), newOtStatusReceiver(receiver));
+        } catch (RemoteException e) {
+            Log.e(TAG, "otDaemon.join failed", e);
+            receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+        }
+    }
+
+    @Override
+    public void scheduleMigration(
+            @NonNull PendingOperationalDataset pendingDataset,
+            @NonNull IOperationReceiver receiver) {
+        enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        OperationReceiverWrapper receiverWrapper = new OperationReceiverWrapper(receiver);
+        mHandler.post(() -> scheduleMigrationInternal(pendingDataset, receiverWrapper));
+    }
+
+    public void scheduleMigrationInternal(
+            @NonNull PendingOperationalDataset pendingDataset,
+            @NonNull OperationReceiverWrapper receiver) {
+        checkOnHandlerThread();
+
+        try {
+            getOtDaemon()
+                    .scheduleMigration(
+                            pendingDataset.toThreadTlvs(), newOtStatusReceiver(receiver));
+        } catch (RemoteException e) {
+            Log.e(TAG, "otDaemon.scheduleMigration failed", e);
+            receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+        }
+    }
+
+    @Override
+    public void leave(@NonNull IOperationReceiver receiver) throws RemoteException {
+        enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        mHandler.post(() -> leaveInternal(new OperationReceiverWrapper(receiver)));
+    }
+
+    private void leaveInternal(@NonNull OperationReceiverWrapper receiver) {
+        checkOnHandlerThread();
+
+        try {
+            getOtDaemon().leave(newOtStatusReceiver(receiver));
+        } catch (RemoteException e) {
+            // Oneway AIDL API should never throw?
+            receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+        }
+    }
+
+    private void handleThreadInterfaceStateChanged(boolean isUp) {
+        try {
+            mTunIfController.setInterfaceUp(isUp);
+            Log.d(TAG, "Thread network interface becomes " + (isUp ? "up" : "down"));
+        } catch (IOException e) {
+            Log.e(TAG, "Failed to handle Thread interface state changes", e);
+        }
+    }
+
+    private void handleDeviceRoleChanged(@DeviceRole int deviceRole) {
+        if (ThreadNetworkController.isAttached(deviceRole)) {
+            Log.d(TAG, "Attached to the Thread network");
+            registerThreadNetwork();
+        } else {
+            Log.d(TAG, "Detached from the Thread network");
+            unregisterThreadNetwork();
+        }
+    }
+
+    private void handleAddressChanged(Ipv6AddressInfo addressInfo, boolean isAdded) {
+        checkOnHandlerThread();
+        InetAddress address = addressInfoToInetAddress(addressInfo);
+        if (address.isMulticastAddress()) {
+            Log.i(TAG, "Ignoring multicast address " + address.getHostAddress());
+            return;
+        }
+
+        LinkAddress linkAddress = newLinkAddress(addressInfo);
+        Log.d(TAG, (isAdded ? "Adding" : "Removing") + " address " + linkAddress);
+
+        updateTunInterfaceAddress(linkAddress, isAdded);
+        updateNetworkLinkProperties(linkAddress, isAdded);
+    }
+
+    private static final class CallbackMetadata {
+        private static long gId = 0;
+
+        // The unique ID
+        final long id;
+
+        final IBinder.DeathRecipient deathRecipient;
+
+        CallbackMetadata(IBinder.DeathRecipient deathRecipient) {
+            this.id = allocId();
+            this.deathRecipient = deathRecipient;
+        }
+
+        private static long allocId() {
+            if (gId == Long.MAX_VALUE) {
+                gId = 0;
+            }
+            return gId++;
+        }
+    }
+
+    /**
+     * Handles and forwards Thread daemon callbacks. This class must be accessed from the {@code
+     * mHandlerThread}.
+     */
+    private final class OtDaemonCallbackProxy extends IOtDaemonCallback.Stub {
+        private final Map<IStateCallback, CallbackMetadata> mStateCallbacks = new HashMap<>();
+        private final Map<IOperationalDatasetCallback, CallbackMetadata> mOpDatasetCallbacks =
+                new HashMap<>();
+
+        private OtDaemonState mState;
+        private ActiveOperationalDataset mActiveDataset;
+        private PendingOperationalDataset mPendingDataset;
+
+        public void registerStateCallback(IStateCallback callback) {
+            checkOnHandlerThread();
+            if (mStateCallbacks.containsKey(callback)) {
+                return;
+            }
+
+            IBinder.DeathRecipient deathRecipient =
+                    () -> mHandler.post(() -> unregisterStateCallback(callback));
+            CallbackMetadata callbackMetadata = new CallbackMetadata(deathRecipient);
+            mStateCallbacks.put(callback, callbackMetadata);
+            try {
+                callback.asBinder().linkToDeath(deathRecipient, 0);
+            } catch (RemoteException e) {
+                mStateCallbacks.remove(callback);
+                // This is thrown when the client is dead, do nothing
+            }
+
+            try {
+                getOtDaemon().registerStateCallback(this, callbackMetadata.id);
+            } catch (RemoteException e) {
+                // oneway operation should never fail
+            }
+        }
+
+        public void unregisterStateCallback(IStateCallback callback) {
+            checkOnHandlerThread();
+            if (!mStateCallbacks.containsKey(callback)) {
+                return;
+            }
+            callback.asBinder().unlinkToDeath(mStateCallbacks.remove(callback).deathRecipient, 0);
+        }
+
+        public void registerDatasetCallback(IOperationalDatasetCallback callback) {
+            checkOnHandlerThread();
+            if (mOpDatasetCallbacks.containsKey(callback)) {
+                return;
+            }
+
+            IBinder.DeathRecipient deathRecipient =
+                    () -> mHandler.post(() -> unregisterDatasetCallback(callback));
+            CallbackMetadata callbackMetadata = new CallbackMetadata(deathRecipient);
+            mOpDatasetCallbacks.put(callback, callbackMetadata);
+            try {
+                callback.asBinder().linkToDeath(deathRecipient, 0);
+            } catch (RemoteException e) {
+                mOpDatasetCallbacks.remove(callback);
+            }
+
+            try {
+                getOtDaemon().registerStateCallback(this, callbackMetadata.id);
+            } catch (RemoteException e) {
+                // oneway operation should never fail
+            }
+        }
+
+        public void unregisterDatasetCallback(IOperationalDatasetCallback callback) {
+            checkOnHandlerThread();
+            if (!mOpDatasetCallbacks.containsKey(callback)) {
+                return;
+            }
+            callback.asBinder()
+                    .unlinkToDeath(mOpDatasetCallbacks.remove(callback).deathRecipient, 0);
+        }
+
+        public void onOtDaemonDied() {
+            checkOnHandlerThread();
+            if (mState == null) {
+                return;
+            }
+
+            // If this device is already STOPPED or DETACHED, do nothing
+            if (!ThreadNetworkController.isAttached(mState.deviceRole)) {
+                return;
+            }
+
+            // The Thread device role is considered DETACHED when the OT daemon process is dead
+            handleDeviceRoleChanged(DEVICE_ROLE_DETACHED);
+            for (IStateCallback callback : mStateCallbacks.keySet()) {
+                try {
+                    callback.onDeviceRoleChanged(DEVICE_ROLE_DETACHED);
+                } catch (RemoteException ignored) {
+                    // do nothing if the client is dead
+                }
+            }
+        }
+
+        @Override
+        public void onStateChanged(OtDaemonState newState, long listenerId) {
+            mHandler.post(() -> onStateChangedInternal(newState, listenerId));
+        }
+
+        private void onStateChangedInternal(OtDaemonState newState, long listenerId) {
+            checkOnHandlerThread();
+            onInterfaceStateChanged(newState.isInterfaceUp);
+            onDeviceRoleChanged(newState.deviceRole, listenerId);
+            onPartitionIdChanged(newState.partitionId, listenerId);
+            mState = newState;
+
+            ActiveOperationalDataset newActiveDataset;
+            try {
+                if (newState.activeDatasetTlvs.length != 0) {
+                    newActiveDataset =
+                            ActiveOperationalDataset.fromThreadTlvs(newState.activeDatasetTlvs);
+                } else {
+                    newActiveDataset = null;
+                }
+                onActiveOperationalDatasetChanged(newActiveDataset, listenerId);
+                mActiveDataset = newActiveDataset;
+            } catch (IllegalArgumentException e) {
+                // Is unlikely that OT will generate invalid Operational Dataset
+                Log.w(TAG, "Ignoring invalid Active Operational Dataset changes", e);
+            }
+
+            PendingOperationalDataset newPendingDataset;
+            try {
+                if (newState.pendingDatasetTlvs.length != 0) {
+                    newPendingDataset =
+                            PendingOperationalDataset.fromThreadTlvs(newState.pendingDatasetTlvs);
+                } else {
+                    newPendingDataset = null;
+                }
+                onPendingOperationalDatasetChanged(newPendingDataset, listenerId);
+                mPendingDataset = newPendingDataset;
+            } catch (IllegalArgumentException e) {
+                Log.w(TAG, "Ignoring invalid Pending Operational Dataset changes", e);
+            }
+        }
+
+        private void onInterfaceStateChanged(boolean isUp) {
+            checkOnHandlerThread();
+            if (mState == null || mState.isInterfaceUp != isUp) {
+                handleThreadInterfaceStateChanged(isUp);
+            }
+        }
+
+        private void onDeviceRoleChanged(@DeviceRole int deviceRole, long listenerId) {
+            checkOnHandlerThread();
+            boolean hasChange = (mState == null || mState.deviceRole != deviceRole);
+            if (hasChange) {
+                handleDeviceRoleChanged(deviceRole);
+            }
+
+            for (var callbackEntry : mStateCallbacks.entrySet()) {
+                if (!hasChange && callbackEntry.getValue().id != listenerId) {
+                    continue;
+                }
+                try {
+                    callbackEntry.getKey().onDeviceRoleChanged(deviceRole);
+                } catch (RemoteException ignored) {
+                    // do nothing if the client is dead
+                }
+            }
+        }
+
+        private void onPartitionIdChanged(long partitionId, long listenerId) {
+            checkOnHandlerThread();
+            boolean hasChange = (mState == null || mState.partitionId != partitionId);
+
+            for (var callbackEntry : mStateCallbacks.entrySet()) {
+                if (!hasChange && callbackEntry.getValue().id != listenerId) {
+                    continue;
+                }
+                try {
+                    callbackEntry.getKey().onPartitionIdChanged(partitionId);
+                } catch (RemoteException ignored) {
+                    // do nothing if the client is dead
+                }
+            }
+        }
+
+        private void onActiveOperationalDatasetChanged(
+                ActiveOperationalDataset activeDataset, long listenerId) {
+            checkOnHandlerThread();
+            boolean hasChange = !Objects.equals(mActiveDataset, activeDataset);
+
+            for (var callbackEntry : mOpDatasetCallbacks.entrySet()) {
+                if (!hasChange && callbackEntry.getValue().id != listenerId) {
+                    continue;
+                }
+                try {
+                    callbackEntry.getKey().onActiveOperationalDatasetChanged(activeDataset);
+                } catch (RemoteException ignored) {
+                    // do nothing if the client is dead
+                }
+            }
+        }
+
+        private void onPendingOperationalDatasetChanged(
+                PendingOperationalDataset pendingDataset, long listenerId) {
+            checkOnHandlerThread();
+            boolean hasChange = !Objects.equals(mPendingDataset, pendingDataset);
+            for (var callbackEntry : mOpDatasetCallbacks.entrySet()) {
+                if (!hasChange && callbackEntry.getValue().id != listenerId) {
+                    continue;
+                }
+                try {
+                    callbackEntry.getKey().onPendingOperationalDatasetChanged(pendingDataset);
+                } catch (RemoteException ignored) {
+                    // do nothing if the client is dead
+                }
+            }
+        }
+
+        @Override
+        public void onAddressChanged(Ipv6AddressInfo addressInfo, boolean isAdded) {
+            mHandler.post(() -> handleAddressChanged(addressInfo, isAdded));
+        }
+    }
 }
diff --git a/thread/service/java/com/android/server/thread/ThreadNetworkService.java b/thread/service/java/com/android/server/thread/ThreadNetworkService.java
index c6d47df..cc694a1 100644
--- a/thread/service/java/com/android/server/thread/ThreadNetworkService.java
+++ b/thread/service/java/com/android/server/thread/ThreadNetworkService.java
@@ -16,6 +16,7 @@
 
 package com.android.server.thread;
 
+import android.annotation.Nullable;
 import android.content.Context;
 import android.net.thread.IThreadNetworkController;
 import android.net.thread.IThreadNetworkManager;
@@ -29,16 +30,12 @@
  * Implementation of the Thread network service. This is the entry point of Android Thread feature.
  */
 public class ThreadNetworkService extends IThreadNetworkManager.Stub {
-    private final ThreadNetworkControllerService mControllerService;
+    private final Context mContext;
+    @Nullable private ThreadNetworkControllerService mControllerService;
 
     /** Creates a new {@link ThreadNetworkService} object. */
     public ThreadNetworkService(Context context) {
-        this(context, new ThreadNetworkControllerService());
-    }
-
-    private ThreadNetworkService(
-            Context context, ThreadNetworkControllerService controllerService) {
-        mControllerService = controllerService;
+        mContext = context;
     }
 
     /**
@@ -48,12 +45,16 @@
      */
     public void onBootPhase(int phase) {
         if (phase == SystemService.PHASE_BOOT_COMPLETED) {
-            // TODO: initialize ThreadNetworkManagerService
+            mControllerService = ThreadNetworkControllerService.newInstance(mContext);
+            mControllerService.initialize();
         }
     }
 
     @Override
     public List<IThreadNetworkController> getAllThreadNetworkControllers() {
+        if (mControllerService == null) {
+            return Collections.emptyList();
+        }
         return Collections.singletonList(mControllerService);
     }
 }
diff --git a/thread/service/java/com/android/server/thread/TunInterfaceController.java b/thread/service/java/com/android/server/thread/TunInterfaceController.java
new file mode 100644
index 0000000..ac65b11
--- /dev/null
+++ b/thread/service/java/com/android/server/thread/TunInterfaceController.java
@@ -0,0 +1,140 @@
+/*
+ * 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 com.android.server.thread;
+
+import android.net.LinkAddress;
+import android.net.util.SocketUtils;
+import android.os.ParcelFileDescriptor;
+import android.os.SystemClock;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import android.util.Log;
+
+import com.android.net.module.util.netlink.NetlinkUtils;
+import com.android.net.module.util.netlink.RtNetlinkAddressMessage;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+
+/** Controller for virtual/tunnel network interfaces. */
+public class TunInterfaceController {
+    private static final String TAG = "TunIfController";
+    static final int MTU = 1280;
+
+    static {
+        System.loadLibrary("service-thread-jni");
+    }
+
+    private final String mIfName;
+    private ParcelFileDescriptor mParcelTunFd;
+    private FileDescriptor mNetlinkSocket;
+    private static int sNetlinkSeqNo = 0;
+
+    /** Creates a new {@link TunInterfaceController} instance for given interface. */
+    public TunInterfaceController(String interfaceName) {
+        this.mIfName = interfaceName;
+    }
+
+    /**
+     * Creates the tunnel interface.
+     *
+     * @throws IOException if failed to create the interface
+     */
+    public void createTunInterface() throws IOException {
+        mParcelTunFd = ParcelFileDescriptor.adoptFd(nativeCreateTunInterface(mIfName, MTU));
+        try {
+            mNetlinkSocket = NetlinkUtils.netlinkSocketForProto(OsConstants.NETLINK_ROUTE);
+        } catch (ErrnoException e) {
+            throw new IOException("Failed to create netlink socket", e);
+        }
+    }
+
+    public void destroyTunInterface() {
+        try {
+            mParcelTunFd.close();
+            SocketUtils.closeSocket(mNetlinkSocket);
+        } catch (IOException e) {
+            // Should never fail
+        }
+        mParcelTunFd = null;
+        mNetlinkSocket = null;
+    }
+
+    /** Returns the FD of the tunnel interface. */
+    public ParcelFileDescriptor getTunFd() {
+        return mParcelTunFd;
+    }
+
+    private native int nativeCreateTunInterface(String interfaceName, int mtu) throws IOException;
+
+    /** Sets the interface up or down according to {@code isUp}. */
+    public void setInterfaceUp(boolean isUp) throws IOException {
+        nativeSetInterfaceUp(mIfName, isUp);
+    }
+
+    private native void nativeSetInterfaceUp(String interfaceName, boolean isUp) throws IOException;
+
+    /** Adds a new address to the interface. */
+    public void addAddress(LinkAddress address) throws IOException {
+        Log.d(TAG, "Adding address " + address + " with flags: " + address.getFlags());
+
+        long validLifetimeSeconds;
+        long preferredLifetimeSeconds;
+
+        if (address.getDeprecationTime() == LinkAddress.LIFETIME_PERMANENT
+                || address.getDeprecationTime() == LinkAddress.LIFETIME_UNKNOWN) {
+            validLifetimeSeconds = 0xffffffffL;
+        } else {
+            validLifetimeSeconds =
+                    Math.max(
+                            (address.getDeprecationTime() - SystemClock.elapsedRealtime()) / 1000L,
+                            0L);
+        }
+
+        if (address.getExpirationTime() == LinkAddress.LIFETIME_PERMANENT
+                || address.getExpirationTime() == LinkAddress.LIFETIME_UNKNOWN) {
+            preferredLifetimeSeconds = 0xffffffffL;
+        } else {
+            preferredLifetimeSeconds =
+                    Math.max(
+                            (address.getExpirationTime() - SystemClock.elapsedRealtime()) / 1000L,
+                            0L);
+        }
+
+        byte[] message =
+                RtNetlinkAddressMessage.newRtmNewAddressMessage(
+                        sNetlinkSeqNo,
+                        address.getAddress(),
+                        (short) address.getPrefixLength(),
+                        address.getFlags(),
+                        (byte) address.getScope(),
+                        Os.if_nametoindex(mIfName),
+                        validLifetimeSeconds,
+                        preferredLifetimeSeconds);
+        try {
+            Os.write(mNetlinkSocket, message, 0, message.length);
+        } catch (ErrnoException e) {
+            throw new IOException("Failed to send netlink message", e);
+        }
+    }
+
+    /** Removes an address from the interface. */
+    public void removeAddress(LinkAddress address) throws IOException {
+        // TODO(b/263222068): remove address with netlink
+    }
+}
diff --git a/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp b/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp
new file mode 100644
index 0000000..ed39fab
--- /dev/null
+++ b/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp
@@ -0,0 +1,124 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "jniThreadTun"
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <linux/if_arp.h>
+#include <linux/if_tun.h>
+#include <linux/ioctl.h>
+#include <log/log.h>
+#include <net/if.h>
+#include <spawn.h>
+#include <sys/wait.h>
+#include <string>
+
+#include <private/android_filesystem_config.h>
+
+#include "jni.h"
+#include "nativehelper/JNIHelp.h"
+#include "nativehelper/scoped_utf_chars.h"
+
+namespace android {
+static jint com_android_server_thread_TunInterfaceController_createTunInterface(
+        JNIEnv* env, jobject clazz, jstring interfaceName, jint mtu) {
+    ScopedUtfChars ifName(env, interfaceName);
+
+    int fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
+    if (fd == -1) {
+        jniThrowExceptionFmt(env, "java/io/IOException", "open tun device failed (%s)",
+                             strerror(errno));
+        return -1;
+    }
+
+    struct ifreq ifr = {
+            .ifr_flags = IFF_TUN | IFF_NO_PI | static_cast<short>(IFF_TUN_EXCL),
+    };
+    strlcpy(ifr.ifr_name, ifName.c_str(), sizeof(ifr.ifr_name));
+
+    if (ioctl(fd, TUNSETIFF, &ifr, sizeof(ifr)) != 0) {
+        close(fd);
+        jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(TUNSETIFF) failed (%s)",
+                             strerror(errno));
+        return -1;
+    }
+
+    int inet6 = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_IP);
+    if (inet6 == -1) {
+        close(fd);
+        jniThrowExceptionFmt(env, "java/io/IOException", "create inet6 socket failed (%s)",
+                             strerror(errno));
+        return -1;
+    }
+    ifr.ifr_mtu = mtu;
+    if (ioctl(inet6, SIOCSIFMTU, &ifr) != 0) {
+        close(fd);
+        close(inet6);
+        jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(SIOCSIFMTU) failed (%s)",
+                             strerror(errno));
+        return -1;
+    }
+
+    close(inet6);
+    return fd;
+}
+
+static void com_android_server_thread_TunInterfaceController_setInterfaceUp(
+        JNIEnv* env, jobject clazz, jstring interfaceName, jboolean isUp) {
+    struct ifreq ifr;
+    ScopedUtfChars ifName(env, interfaceName);
+
+    ifr.ifr_flags = isUp ? IFF_UP : 0;
+    strlcpy(ifr.ifr_name, ifName.c_str(), sizeof(ifr.ifr_name));
+
+    int inet6 = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_IP);
+    if (inet6 == -1) {
+        jniThrowExceptionFmt(env, "java/io/IOException", "create inet6 socket failed (%s)",
+                             strerror(errno));
+    }
+
+    if (ioctl(inet6, SIOCSIFFLAGS, &ifr) != 0) {
+        close(inet6);
+        jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(SIOCSIFFLAGS) failed (%s)",
+                             strerror(errno));
+    }
+
+    close(inet6);
+}
+
+/*
+ * JNI registration.
+ */
+
+static const JNINativeMethod gMethods[] = {
+        /* name, signature, funcPtr */
+        {"nativeCreateTunInterface",
+         "(Ljava/lang/String;I)I",
+         (void*)com_android_server_thread_TunInterfaceController_createTunInterface},
+        {"nativeSetInterfaceUp",
+         "(Ljava/lang/String;Z)V",
+         (void*)com_android_server_thread_TunInterfaceController_setInterfaceUp},
+};
+
+int register_com_android_server_thread_TunInterfaceController(JNIEnv* env) {
+    return jniRegisterNativeMethods(env, "com/android/server/thread/TunInterfaceController",
+                                    gMethods, NELEM(gMethods));
+}
+
+};  // namespace android
diff --git a/thread/service/jni/onload.cpp b/thread/service/jni/onload.cpp
new file mode 100644
index 0000000..5081664
--- /dev/null
+++ b/thread/service/jni/onload.cpp
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+#include "jni.h"
+#include "utils/Log.h"
+
+namespace android {
+int register_com_android_server_thread_TunInterfaceController(JNIEnv* env);
+}
+
+using namespace android;
+
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) {
+    JNIEnv* env = NULL;
+
+    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
+        ALOGE("GetEnv failed!");
+        return -1;
+    }
+    ALOG_ASSERT(env != NULL, "Could not retrieve the env!");
+
+    register_com_android_server_thread_TunInterfaceController(env);
+    return JNI_VERSION_1_4;
+}
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/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java b/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
index 39df21b..0e76930 100644
--- a/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
@@ -70,7 +70,7 @@
     // PAN ID: 0xD9A0
     // PSKc: A245479C836D551B9CA557F7B9D351B4
     // Security Policy: 672 onrcb
-    private static final byte[] VALID_DATASET =
+    private static final byte[] VALID_DATASET_TLVS =
             base16().decode(
                             "0E080000000000010000000300001335060004001FFFE002"
                                     + "08ACC214689BC40BDF0708FD64DB1225F47E0B0510F26B31"
@@ -78,6 +78,9 @@
                                     + "642D643961300102D9A00410A245479C836D551B9CA557F7"
                                     + "B9D351B40C0402A0FFF8");
 
+    private static final ActiveOperationalDataset DEFAULT_DATASET =
+            ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
+
     private static byte[] removeTlv(byte[] dataset, int type) {
         ByteArrayOutputStream os = new ByteArrayOutputStream(dataset.length);
         int i = 0;
@@ -105,7 +108,8 @@
 
     @Test
     public void parcelable_parcelingIsLossLess() {
-        ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET);
+        ActiveOperationalDataset dataset =
+                ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
 
         assertParcelingIsLossless(dataset);
     }
@@ -126,7 +130,8 @@
 
     @Test
     public void fromThreadTlvs_invalidNetworkKeyTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_NETWORK_KEY, "05080000000000000000");
+        byte[] invalidTlv =
+                replaceTlv(VALID_DATASET_TLVS, TYPE_NETWORK_KEY, "05080000000000000000");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -135,7 +140,7 @@
 
     @Test
     public void fromThreadTlvs_noNetworkKeyTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_NETWORK_KEY);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_NETWORK_KEY);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -144,7 +149,8 @@
 
     @Test
     public void fromThreadTlvs_invalidActiveTimestampTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_ACTIVE_TIMESTAMP, "0E0700000000010000");
+        byte[] invalidTlv =
+                replaceTlv(VALID_DATASET_TLVS, TYPE_ACTIVE_TIMESTAMP, "0E0700000000010000");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -153,7 +159,7 @@
 
     @Test
     public void fromThreadTlvs_noActiveTimestampTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_ACTIVE_TIMESTAMP);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_ACTIVE_TIMESTAMP);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -162,7 +168,7 @@
 
     @Test
     public void fromThreadTlvs_invalidNetworkNameTlv_emptyName_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_NETWORK_NAME, "0300");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_NETWORK_NAME, "0300");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -173,7 +179,9 @@
     public void fromThreadTlvs_invalidNetworkNameTlv_tooLongName_throwsIllegalArgument() {
         byte[] invalidTlv =
                 replaceTlv(
-                        VALID_DATASET, TYPE_NETWORK_NAME, "03114142434445464748494A4B4C4D4E4F5051");
+                        VALID_DATASET_TLVS,
+                        TYPE_NETWORK_NAME,
+                        "03114142434445464748494A4B4C4D4E4F5051");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -182,7 +190,7 @@
 
     @Test
     public void fromThreadTlvs_noNetworkNameTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_NETWORK_NAME);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_NETWORK_NAME);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -191,7 +199,7 @@
 
     @Test
     public void fromThreadTlvs_invalidChannelTlv_channelMissing_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000100");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000100");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -200,7 +208,7 @@
 
     @Test
     public void fromThreadTlvs_undefinedChannelPage_success() {
-        byte[] datasetTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "0003010020");
+        byte[] datasetTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "0003010020");
 
         ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(datasetTlv);
 
@@ -210,8 +218,8 @@
 
     @Test
     public void fromThreadTlvs_invalid2P4GhzChannel_throwsIllegalArgument() {
-        byte[] invalidTlv1 = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000300000A");
-        byte[] invalidTlv2 = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000300001B");
+        byte[] invalidTlv1 = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000300000A");
+        byte[] invalidTlv2 = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000300001B");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -223,7 +231,7 @@
 
     @Test
     public void fromThreadTlvs_valid2P4GhzChannelTlv_success() {
-        byte[] validTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "0003000010");
+        byte[] validTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "0003000010");
 
         ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(validTlv);
 
@@ -232,7 +240,7 @@
 
     @Test
     public void fromThreadTlvs_noChannelTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_CHANNEL);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_CHANNEL);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -241,7 +249,7 @@
 
     @Test
     public void fromThreadTlvs_prematureEndOfChannelMaskEntry_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "350100");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "350100");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -250,7 +258,7 @@
 
     @Test
     public void fromThreadTlvs_inconsistentChannelMaskLength_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "3506000500010000");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "3506000500010000");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -261,7 +269,7 @@
     public void fromThreadTlvs_unsupportedChannelMaskLength_success() {
         ActiveOperationalDataset dataset =
                 ActiveOperationalDataset.fromThreadTlvs(
-                        replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "350700050001000000"));
+                        replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "350700050001000000"));
 
         SparseArray<byte[]> channelMask = dataset.getChannelMask();
         assertThat(channelMask.size()).isEqualTo(1);
@@ -271,7 +279,7 @@
 
     @Test
     public void fromThreadTlvs_noChannelMaskTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_CHANNEL_MASK);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -280,7 +288,7 @@
 
     @Test
     public void fromThreadTlvs_invalidPanIdTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_PAN_ID, "010101");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_PAN_ID, "010101");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -289,7 +297,7 @@
 
     @Test
     public void fromThreadTlvs_noPanIdTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_PAN_ID);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_PAN_ID);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -298,7 +306,8 @@
 
     @Test
     public void fromThreadTlvs_invalidExtendedPanIdTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_EXTENDED_PAN_ID, "020700010203040506");
+        byte[] invalidTlv =
+                replaceTlv(VALID_DATASET_TLVS, TYPE_EXTENDED_PAN_ID, "020700010203040506");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -307,7 +316,7 @@
 
     @Test
     public void fromThreadTlvs_noExtendedPanIdTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_EXTENDED_PAN_ID);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_EXTENDED_PAN_ID);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -317,7 +326,7 @@
     @Test
     public void fromThreadTlvs_invalidPskcTlv_throwsIllegalArgument() {
         byte[] invalidTlv =
-                replaceTlv(VALID_DATASET, TYPE_PSKC, "0411000102030405060708090A0B0C0D0E0F10");
+                replaceTlv(VALID_DATASET_TLVS, TYPE_PSKC, "0411000102030405060708090A0B0C0D0E0F10");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -326,7 +335,7 @@
 
     @Test
     public void fromThreadTlvs_noPskcTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_PSKC);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_PSKC);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -336,7 +345,7 @@
     @Test
     public void fromThreadTlvs_invalidMeshLocalPrefixTlv_throwsIllegalArgument() {
         byte[] invalidTlv =
-                replaceTlv(VALID_DATASET, TYPE_MESH_LOCAL_PREFIX, "0709FD0001020304050607");
+                replaceTlv(VALID_DATASET_TLVS, TYPE_MESH_LOCAL_PREFIX, "0709FD0001020304050607");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -345,7 +354,7 @@
 
     @Test
     public void fromThreadTlvs_noMeshLocalPrefixTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_MESH_LOCAL_PREFIX);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_MESH_LOCAL_PREFIX);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -354,7 +363,7 @@
 
     @Test
     public void fromThreadTlvs_tooShortSecurityPolicyTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_SECURITY_POLICY, "0C0101");
+        byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_SECURITY_POLICY, "0C0101");
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -363,7 +372,7 @@
 
     @Test
     public void fromThreadTlvs_noSecurityPolicyTlv_throwsIllegalArgument() {
-        byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_SECURITY_POLICY);
+        byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_SECURITY_POLICY);
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -429,7 +438,7 @@
 
     @Test
     public void fromThreadTlvs_containsUnknownTlvs_unknownTlvsRetained() {
-        final byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET, "AA01FFBB020102");
+        final byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET_TLVS, "AA01FFBB020102");
 
         ActiveOperationalDataset dataset =
                 ActiveOperationalDataset.fromThreadTlvs(datasetWithUnknownTlvs);
@@ -443,7 +452,7 @@
 
     @Test
     public void toThreadTlvs_conversionIsLossLess() {
-        ActiveOperationalDataset dataset1 = ActiveOperationalDataset.createRandomDataset();
+        ActiveOperationalDataset dataset1 = DEFAULT_DATASET;
 
         ActiveOperationalDataset dataset2 =
                 ActiveOperationalDataset.fromThreadTlvs(dataset1.toThreadTlvs());
@@ -465,9 +474,7 @@
                 };
 
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setNetworkKey(networkKey)
-                        .build();
+                new Builder(DEFAULT_DATASET).setNetworkKey(networkKey).build();
 
         assertThat(dataset.getNetworkKey()).isEqualTo(networkKey);
     }
@@ -475,7 +482,7 @@
     @Test
     public void builder_setInvalidNetworkKey_throwsIllegalArgument() {
         byte[] invalidNetworkKey = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(
                 IllegalArgumentException.class, () -> builder.setNetworkKey(invalidNetworkKey));
@@ -486,9 +493,7 @@
         byte[] extendedPanId = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
 
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setExtendedPanId(extendedPanId)
-                        .build();
+                new Builder(DEFAULT_DATASET).setExtendedPanId(extendedPanId).build();
 
         assertThat(dataset.getExtendedPanId()).isEqualTo(extendedPanId);
     }
@@ -496,31 +501,28 @@
     @Test
     public void builder_setInvalidExtendedPanId_throwsIllegalArgument() {
         byte[] extendedPanId = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(IllegalArgumentException.class, () -> builder.setExtendedPanId(extendedPanId));
     }
 
     @Test
     public void builder_setValidPanId_success() {
-        ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setPanId(0xfffe)
-                        .build();
+        ActiveOperationalDataset dataset = new Builder(DEFAULT_DATASET).setPanId(0xfffe).build();
 
         assertThat(dataset.getPanId()).isEqualTo(0xfffe);
     }
 
     @Test
     public void builder_setInvalidPanId_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(IllegalArgumentException.class, () -> builder.setPanId(0xffff));
     }
 
     @Test
     public void builder_setInvalidChannel_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(IllegalArgumentException.class, () -> builder.setChannel(0, 0));
         assertThrows(IllegalArgumentException.class, () -> builder.setChannel(0, 27));
@@ -529,9 +531,7 @@
     @Test
     public void builder_setValid2P4GhzChannel_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setChannel(CHANNEL_PAGE_24_GHZ, 16)
-                        .build();
+                new Builder(DEFAULT_DATASET).setChannel(CHANNEL_PAGE_24_GHZ, 16).build();
 
         assertThat(dataset.getChannel()).isEqualTo(16);
         assertThat(dataset.getChannelPage()).isEqualTo(CHANNEL_PAGE_24_GHZ);
@@ -540,23 +540,21 @@
     @Test
     public void builder_setValidNetworkName_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setNetworkName("ot-network")
-                        .build();
+                new Builder(DEFAULT_DATASET).setNetworkName("ot-network").build();
 
         assertThat(dataset.getNetworkName()).isEqualTo("ot-network");
     }
 
     @Test
     public void builder_setEmptyNetworkName_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(IllegalArgumentException.class, () -> builder.setNetworkName(""));
     }
 
     @Test
     public void builder_setTooLongNetworkName_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(
                 IllegalArgumentException.class, () -> builder.setNetworkName("openthread-network"));
@@ -564,7 +562,7 @@
 
     @Test
     public void builder_setTooLongUtf8NetworkName_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         // UTF-8 encoded length of "我的线程网络" is 18 bytes which exceeds the max length
         assertThrows(IllegalArgumentException.class, () -> builder.setNetworkName("我的线程网络"));
@@ -573,9 +571,7 @@
     @Test
     public void builder_setValidUtf8NetworkName_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setNetworkName("我的网络")
-                        .build();
+                new Builder(DEFAULT_DATASET).setNetworkName("我的网络").build();
 
         assertThat(dataset.getNetworkName()).isEqualTo("我的网络");
     }
@@ -584,8 +580,7 @@
     public void builder_setValidPskc_success() {
         byte[] pskc = base16().decode("A245479C836D551B9CA557F7B9D351B4");
 
-        ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset()).setPskc(pskc).build();
+        ActiveOperationalDataset dataset = new Builder(DEFAULT_DATASET).setPskc(pskc).build();
 
         assertThat(dataset.getPskc()).isEqualTo(pskc);
     }
@@ -593,18 +588,18 @@
     @Test
     public void builder_setTooLongPskc_throwsIllegalArgument() {
         byte[] tooLongPskc = base16().decode("A245479C836D551B9CA557F7B9D351B400");
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(IllegalArgumentException.class, () -> builder.setPskc(tooLongPskc));
     }
 
     @Test
     public void builder_setValidChannelMask_success() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
         SparseArray<byte[]> channelMask = new SparseArray<byte[]>(1);
         channelMask.put(0, new byte[] {0x00, 0x00, 0x01, 0x00});
 
-        ActiveOperationalDataset dataset = builder.setChannelMask(channelMask).build();
+        ActiveOperationalDataset dataset =
+                new Builder(DEFAULT_DATASET).setChannelMask(channelMask).build();
 
         SparseArray<byte[]> resultChannelMask = dataset.getChannelMask();
         assertThat(resultChannelMask.size()).isEqualTo(1);
@@ -613,7 +608,7 @@
 
     @Test
     public void builder_setEmptyChannelMask_throwsIllegalArgument() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -623,7 +618,7 @@
     @Test
     public void builder_setValidActiveTimestamp_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
+                new Builder(DEFAULT_DATASET)
                         .setActiveTimestamp(
                                 new OperationalDatasetTimestamp(
                                         /* seconds= */ 1,
@@ -638,7 +633,7 @@
 
     @Test
     public void builder_wrongMeshLocalPrefixLength_throwsIllegalArguments() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         // The Mesh-Local Prefix length must be 64 bits
         assertThrows(
@@ -656,7 +651,7 @@
 
     @Test
     public void builder_meshLocalPrefixNotStartWith0xfd_throwsIllegalArguments() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder();
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -666,9 +661,7 @@
     @Test
     public void builder_setValidMeshLocalPrefix_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
-                        .setMeshLocalPrefix(new IpPrefix("fd00::/64"))
-                        .build();
+                new Builder(DEFAULT_DATASET).setMeshLocalPrefix(new IpPrefix("fd00::/64")).build();
 
         assertThat(dataset.getMeshLocalPrefix()).isEqualTo(new IpPrefix("fd00::/64"));
     }
@@ -676,7 +669,7 @@
     @Test
     public void builder_setValid1P2SecurityPolicy_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
+                new Builder(DEFAULT_DATASET)
                         .setSecurityPolicy(
                                 new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}))
                         .build();
@@ -689,7 +682,7 @@
     @Test
     public void builder_setValid1P1SecurityPolicy_success() {
         ActiveOperationalDataset dataset =
-                new Builder(ActiveOperationalDataset.createRandomDataset())
+                new Builder(DEFAULT_DATASET)
                         .setSecurityPolicy(new SecurityPolicy(672, new byte[] {(byte) 0xff}))
                         .build();
 
diff --git a/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java b/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
index 7a49957..0bb18ce 100644
--- a/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
@@ -25,8 +25,10 @@
 
 import android.net.IpPrefix;
 import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
 import android.net.thread.OperationalDatasetTimestamp;
 import android.net.thread.PendingOperationalDataset;
+import android.util.SparseArray;
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 import androidx.test.filters.SmallTest;
@@ -37,20 +39,36 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.net.InetAddress;
 import java.time.Duration;
 
 /** Tests for {@link PendingOperationalDataset}. */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public final class PendingOperationalDatasetTest {
-    private static final ActiveOperationalDataset DEFAULT_ACTIVE_DATASET =
-            ActiveOperationalDataset.createRandomDataset();
+    private static ActiveOperationalDataset createActiveDataset() throws Exception {
+        SparseArray<byte[]> channelMask = new SparseArray<>(1);
+        channelMask.put(0, new byte[] {0x00, 0x1f, (byte) 0xff, (byte) 0xe0});
+
+        return new ActiveOperationalDataset.Builder()
+                .setActiveTimestamp(new OperationalDatasetTimestamp(100, 10, false))
+                .setExtendedPanId(new byte[] {0, 1, 2, 3, 4, 5, 6, 7})
+                .setPanId(12345)
+                .setNetworkName("defaultNet")
+                .setChannel(0, 18)
+                .setChannelMask(channelMask)
+                .setPskc(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})
+                .setNetworkKey(new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})
+                .setMeshLocalPrefix(new IpPrefix(InetAddress.getByName("fd00::1"), 64))
+                .setSecurityPolicy(new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}))
+                .build();
+    }
 
     @Test
-    public void parcelable_parcelingIsLossLess() {
+    public void parcelable_parcelingIsLossLess() throws Exception {
         PendingOperationalDataset dataset =
                 new PendingOperationalDataset(
-                        DEFAULT_ACTIVE_DATASET,
+                        createActiveDataset(),
                         new OperationalDatasetTimestamp(31536000, 200, false),
                         Duration.ofHours(100));
 
@@ -58,9 +76,15 @@
     }
 
     @Test
-    public void equalityTests() {
-        ActiveOperationalDataset activeDataset1 = ActiveOperationalDataset.createRandomDataset();
-        ActiveOperationalDataset activeDataset2 = ActiveOperationalDataset.createRandomDataset();
+    public void equalityTests() throws Exception {
+        ActiveOperationalDataset activeDataset1 =
+                new ActiveOperationalDataset.Builder(createActiveDataset())
+                        .setNetworkName("net1")
+                        .build();
+        ActiveOperationalDataset activeDataset2 =
+                new ActiveOperationalDataset.Builder(createActiveDataset())
+                        .setNetworkName("net2")
+                        .build();
 
         new EqualsTester()
                 .addEqualityGroup(
@@ -103,14 +127,15 @@
     }
 
     @Test
-    public void constructor_correctValuesAreSet() {
+    public void constructor_correctValuesAreSet() throws Exception {
+        final ActiveOperationalDataset activeDataset = createActiveDataset();
         PendingOperationalDataset dataset =
                 new PendingOperationalDataset(
-                        DEFAULT_ACTIVE_DATASET,
+                        activeDataset,
                         new OperationalDatasetTimestamp(31536000, 200, false),
                         Duration.ofHours(100));
 
-        assertThat(dataset.getActiveOperationalDataset()).isEqualTo(DEFAULT_ACTIVE_DATASET);
+        assertThat(dataset.getActiveOperationalDataset()).isEqualTo(activeDataset);
         assertThat(dataset.getPendingTimestamp())
                 .isEqualTo(new OperationalDatasetTimestamp(31536000, 200, false));
         assertThat(dataset.getDelayTimer()).isEqualTo(Duration.ofHours(100));
@@ -166,33 +191,35 @@
     }
 
     @Test
-    public void fromThreadTlvs_completePendingDatasetTlvs_success() {
+    public void fromThreadTlvs_completePendingDatasetTlvs_success() throws Exception {
+        final ActiveOperationalDataset activeDataset = createActiveDataset();
+
         // Type Length Value
         // 0x33 0x08 0x0000000000010000 (Pending Timestamp TLV)
         // 0x34 0x04 0x0000012C (Delay Timer TLV)
         final byte[] pendingTimestampAndDelayTimerTlvs =
                 base16().decode("3308000000000001000034040000012C");
         final byte[] pendingDatasetTlvs =
-                Bytes.concat(
-                        pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+                Bytes.concat(pendingTimestampAndDelayTimerTlvs, activeDataset.toThreadTlvs());
 
         PendingOperationalDataset dataset =
                 PendingOperationalDataset.fromThreadTlvs(pendingDatasetTlvs);
 
-        assertThat(dataset.getActiveOperationalDataset()).isEqualTo(DEFAULT_ACTIVE_DATASET);
+        assertThat(dataset.getActiveOperationalDataset()).isEqualTo(activeDataset);
         assertThat(dataset.getPendingTimestamp())
                 .isEqualTo(new OperationalDatasetTimestamp(1, 0, false));
         assertThat(dataset.getDelayTimer()).isEqualTo(Duration.ofMillis(300));
     }
 
     @Test
-    public void fromThreadTlvs_PendingTimestampTlvIsMissing_throwsIllegalArgument() {
+    public void fromThreadTlvs_PendingTimestampTlvIsMissing_throwsIllegalArgument()
+            throws Exception {
         // Type Length Value
         // 0x34 0x04 0x00000064 (Delay Timer TLV)
         final byte[] pendingTimestampAndDelayTimerTlvs = base16().decode("34040000012C");
         final byte[] pendingDatasetTlvs =
                 Bytes.concat(
-                        pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+                        pendingTimestampAndDelayTimerTlvs, createActiveDataset().toThreadTlvs());
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -200,13 +227,13 @@
     }
 
     @Test
-    public void fromThreadTlvs_delayTimerTlvIsMissing_throwsIllegalArgument() {
+    public void fromThreadTlvs_delayTimerTlvIsMissing_throwsIllegalArgument() throws Exception {
         // Type Length Value
         // 0x33 0x08 0x0000000000010000 (Pending Timestamp TLV)
         final byte[] pendingTimestampAndDelayTimerTlvs = base16().decode("33080000000000010000");
         final byte[] pendingDatasetTlvs =
                 Bytes.concat(
-                        pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+                        pendingTimestampAndDelayTimerTlvs, createActiveDataset().toThreadTlvs());
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -214,8 +241,8 @@
     }
 
     @Test
-    public void fromThreadTlvs_activeDatasetTlvs_throwsIllegalArgument() {
-        final byte[] activeDatasetTlvs = DEFAULT_ACTIVE_DATASET.toThreadTlvs();
+    public void fromThreadTlvs_activeDatasetTlvs_throwsIllegalArgument() throws Exception {
+        final byte[] activeDatasetTlvs = createActiveDataset().toThreadTlvs();
 
         assertThrows(
                 IllegalArgumentException.class,
@@ -232,10 +259,10 @@
     }
 
     @Test
-    public void toThreadTlvs_conversionIsLossLess() {
+    public void toThreadTlvs_conversionIsLossLess() throws Exception {
         PendingOperationalDataset dataset1 =
                 new PendingOperationalDataset(
-                        DEFAULT_ACTIVE_DATASET,
+                        createActiveDataset(),
                         new OperationalDatasetTimestamp(31536000, 200, false),
                         Duration.ofHours(100));
 
diff --git a/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java b/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
index b3118f4..e17dd02 100644
--- a/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
@@ -16,58 +16,612 @@
 
 package android.net.thread.cts;
 
+import static android.net.thread.ThreadNetworkController.DEVICE_ROLE_STOPPED;
 import static android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3;
+import static android.net.thread.ThreadNetworkException.ERROR_ABORTED;
+import static android.net.thread.ThreadNetworkException.ERROR_FAILED_PRECONDITION;
+import static android.net.thread.ThreadNetworkException.ERROR_REJECTED_BY_PEER;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
 
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assume.assumeNotNull;
 
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
+import android.Manifest.permission;
 import android.content.Context;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.OperationalDatasetTimestamp;
+import android.net.thread.PendingOperationalDataset;
 import android.net.thread.ThreadNetworkController;
+import android.net.thread.ThreadNetworkController.OperationalDatasetCallback;
+import android.net.thread.ThreadNetworkController.StateCallback;
+import android.net.thread.ThreadNetworkException;
 import android.net.thread.ThreadNetworkManager;
 import android.os.Build;
+import android.os.OutcomeReceiver;
 
 import androidx.test.core.app.ApplicationProvider;
-import androidx.test.filters.SmallTest;
+import androidx.test.filters.LargeTest;
 
 import com.android.testutils.DevSdkIgnoreRule;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
 import com.android.testutils.DevSdkIgnoreRunner;
 
+import com.google.common.util.concurrent.SettableFuture;
+
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 
 /** CTS tests for {@link ThreadNetworkController}. */
-@SmallTest
+@LargeTest
 @RunWith(DevSdkIgnoreRunner.class)
 @IgnoreUpTo(Build.VERSION_CODES.TIRAMISU) // Thread is available on only U+
 public class ThreadNetworkControllerTest {
+    private static final int CALLBACK_TIMEOUT_MILLIS = 1000;
+    private static final String PERMISSION_THREAD_NETWORK_PRIVILEGED =
+            "android.permission.THREAD_NETWORK_PRIVILEGED";
+
     @Rule public DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
 
     private final Context mContext = ApplicationProvider.getApplicationContext();
+    private ExecutorService mExecutor;
     private ThreadNetworkManager mManager;
 
+    private Set<String> mGrantedPermissions;
+
     @Before
     public void setUp() {
+        mExecutor = Executors.newSingleThreadExecutor();
         mManager = mContext.getSystemService(ThreadNetworkManager.class);
+        mGrantedPermissions = new HashSet<String>();
 
         // TODO: we will also need it in tearDown(), it's better to have a Rule to skip
         // tests if a feature is not available.
         assumeNotNull(mManager);
     }
 
+    @After
+    public void tearDown() throws Exception {
+        if (mManager != null) {
+            leaveAndWait();
+            dropPermissions();
+        }
+    }
+
     private List<ThreadNetworkController> getAllControllers() {
         return mManager.getAllThreadNetworkControllers();
     }
 
+    private void leaveAndWait() throws Exception {
+        grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Void> future = SettableFuture.create();
+            controller.leave(mExecutor, future::set);
+            future.get();
+        }
+    }
+
+    private void grantPermissions(String... permissions) {
+        for (String permission : permissions) {
+            mGrantedPermissions.add(permission);
+        }
+        String[] allPermissions = new String[mGrantedPermissions.size()];
+        mGrantedPermissions.toArray(allPermissions);
+        getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(allPermissions);
+    }
+
+    private static void dropPermissions() {
+        getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
+    }
+
+    private static ActiveOperationalDataset newRandomizedDataset(
+            String networkName, ThreadNetworkController controller) throws Exception {
+        SettableFuture<ActiveOperationalDataset> future = SettableFuture.create();
+        controller.createRandomizedDataset(networkName, directExecutor(), future::set);
+        return future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+    }
+
+    private static boolean isAttached(ThreadNetworkController controller) throws Exception {
+        return ThreadNetworkController.isAttached(getDeviceRole(controller));
+    }
+
+    private static int getDeviceRole(ThreadNetworkController controller) throws Exception {
+        SettableFuture<Integer> future = SettableFuture.create();
+        StateCallback callback = future::set;
+        controller.registerStateCallback(directExecutor(), callback);
+        int role = future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+        controller.unregisterStateCallback(callback);
+        return role;
+    }
+
+    private static int waitForStateAnyOf(
+            ThreadNetworkController controller, List<Integer> deviceRoles) throws Exception {
+        SettableFuture<Integer> future = SettableFuture.create();
+        StateCallback callback =
+                newRole -> {
+                    if (deviceRoles.contains(newRole)) {
+                        future.set(newRole);
+                    }
+                };
+        controller.registerStateCallback(directExecutor(), callback);
+        int role = future.get();
+        controller.unregisterStateCallback(callback);
+        return role;
+    }
+
+    private static ActiveOperationalDataset getActiveOperationalDataset(
+            ThreadNetworkController controller) throws Exception {
+        SettableFuture<ActiveOperationalDataset> future = SettableFuture.create();
+        OperationalDatasetCallback callback = future::set;
+        controller.registerOperationalDatasetCallback(directExecutor(), callback);
+        ActiveOperationalDataset dataset = future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+        controller.unregisterOperationalDatasetCallback(callback);
+        return dataset;
+    }
+
+    private static PendingOperationalDataset getPendingOperationalDataset(
+            ThreadNetworkController controller) throws Exception {
+        SettableFuture<ActiveOperationalDataset> activeFuture = SettableFuture.create();
+        SettableFuture<PendingOperationalDataset> pendingFuture = SettableFuture.create();
+        controller.registerOperationalDatasetCallback(
+                directExecutor(), newDatasetCallback(activeFuture, pendingFuture));
+        return pendingFuture.get();
+    }
+
+    private static OperationalDatasetCallback newDatasetCallback(
+            SettableFuture<ActiveOperationalDataset> activeFuture,
+            SettableFuture<PendingOperationalDataset> pendingFuture) {
+        return new OperationalDatasetCallback() {
+            @Override
+            public void onActiveOperationalDatasetChanged(
+                    ActiveOperationalDataset activeOpDataset) {
+                activeFuture.set(activeOpDataset);
+            }
+
+            @Override
+            public void onPendingOperationalDatasetChanged(
+                    PendingOperationalDataset pendingOpDataset) {
+                pendingFuture.set(pendingOpDataset);
+            }
+        };
+    }
+
     @Test
     public void getThreadVersion_returnsAtLeastThreadVersion1P3() {
         for (ThreadNetworkController controller : getAllControllers()) {
             assertThat(controller.getThreadVersion()).isAtLeast(THREAD_VERSION_1_3);
         }
     }
+
+    @Test
+    public void registerStateCallback_permissionsGranted_returnsCurrentStates() throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Integer> deviceRole = SettableFuture.create();
+
+            controller.registerStateCallback(mExecutor, role -> deviceRole.set(role));
+
+            assertThat(deviceRole.get()).isEqualTo(DEVICE_ROLE_STOPPED);
+        }
+    }
+
+    @Test
+    public void registerStateCallback_noPermissions_throwsSecurityException() throws Exception {
+        dropPermissions();
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            assertThrows(
+                    SecurityException.class,
+                    () -> controller.registerStateCallback(mExecutor, role -> {}));
+        }
+    }
+
+    @Test
+    public void registerStateCallback_alreadyRegistered_throwsIllegalArgumentException()
+            throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Integer> deviceRole = SettableFuture.create();
+            StateCallback callback = role -> deviceRole.set(role);
+            controller.registerStateCallback(mExecutor, callback);
+
+            assertThrows(
+                    IllegalArgumentException.class,
+                    () -> controller.registerStateCallback(mExecutor, callback));
+        }
+    }
+
+    @Test
+    public void unregisterStateCallback_callbackRegistered_success() throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE);
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Integer> deviceRole = SettableFuture.create();
+            StateCallback callback = role -> deviceRole.set(role);
+            controller.registerStateCallback(mExecutor, callback);
+
+            controller.unregisterStateCallback(callback);
+        }
+    }
+
+    @Test
+    public void unregisterStateCallback_callbackNotRegistered_throwsIllegalArgumentException()
+            throws Exception {
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Integer> deviceRole = SettableFuture.create();
+            StateCallback callback = role -> deviceRole.set(role);
+
+            assertThrows(
+                    IllegalArgumentException.class,
+                    () -> controller.unregisterStateCallback(callback));
+        }
+    }
+
+    @Test
+    public void unregisterStateCallback_alreadyUnregistered_throwsIllegalArgumentException()
+            throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE);
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<Integer> deviceRole = SettableFuture.create();
+            StateCallback callback = role -> deviceRole.set(role);
+            controller.registerStateCallback(mExecutor, callback);
+            controller.unregisterStateCallback(callback);
+
+            assertThrows(
+                    IllegalArgumentException.class,
+                    () -> controller.unregisterStateCallback(callback));
+        }
+    }
+
+    @Test
+    public void registerOperationalDatasetCallback_permissionsGranted_returnsCurrentStates()
+            throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            SettableFuture<ActiveOperationalDataset> activeFuture = SettableFuture.create();
+            SettableFuture<PendingOperationalDataset> pendingFuture = SettableFuture.create();
+
+            controller.registerOperationalDatasetCallback(
+                    mExecutor, newDatasetCallback(activeFuture, pendingFuture));
+
+            assertThat(activeFuture.get()).isNull();
+            assertThat(pendingFuture.get()).isNull();
+        }
+    }
+
+    private static <V> OutcomeReceiver<V, ThreadNetworkException> newOutcomeReceiver(
+            SettableFuture<V> future) {
+        return new OutcomeReceiver<V, ThreadNetworkException>() {
+            @Override
+            public void onResult(V result) {
+                future.set(result);
+            }
+
+            @Override
+            public void onError(ThreadNetworkException e) {
+                future.setException(e);
+            }
+        };
+    }
+
+    @Test
+    public void join_withPrivilegedPermission_success() throws Exception {
+        grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+
+            controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            grantPermissions(permission.ACCESS_NETWORK_STATE);
+            assertThat(isAttached(controller)).isTrue();
+            assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset);
+        }
+    }
+
+    @Test
+    public void join_withoutPrivilegedPermission_throwsSecurityException() throws Exception {
+        dropPermissions();
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+
+            assertThrows(
+                    SecurityException.class,
+                    () -> controller.join(activeDataset, mExecutor, v -> {}));
+        }
+    }
+
+    @Test
+    public void join_concurrentRequests_firstOneIsAborted() throws Exception {
+        grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        final byte[] KEY_1 = new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
+        final byte[] KEY_2 = new byte[] {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset1 =
+                    new ActiveOperationalDataset.Builder(
+                                    newRandomizedDataset("TestNet", controller))
+                            .setNetworkKey(KEY_1)
+                            .build();
+            ActiveOperationalDataset activeDataset2 =
+                    new ActiveOperationalDataset.Builder(activeDataset1)
+                            .setNetworkKey(KEY_2)
+                            .build();
+            SettableFuture<Void> joinFuture1 = SettableFuture.create();
+            SettableFuture<Void> joinFuture2 = SettableFuture.create();
+
+            controller.join(activeDataset1, mExecutor, newOutcomeReceiver(joinFuture1));
+            controller.join(activeDataset2, mExecutor, newOutcomeReceiver(joinFuture2));
+
+            ThreadNetworkException thrown =
+                    (ThreadNetworkException)
+                            assertThrows(ExecutionException.class, joinFuture1::get).getCause();
+            assertThat(thrown.getErrorCode()).isEqualTo(ERROR_ABORTED);
+            joinFuture2.get();
+            grantPermissions(permission.ACCESS_NETWORK_STATE);
+            assertThat(isAttached(controller)).isTrue();
+            assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+        }
+    }
+
+    @Test
+    public void leave_withPrivilegedPermission_success() throws Exception {
+        grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+            SettableFuture<Void> leaveFuture = SettableFuture.create();
+            controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            controller.leave(mExecutor, newOutcomeReceiver(leaveFuture));
+            leaveFuture.get();
+
+            grantPermissions(permission.ACCESS_NETWORK_STATE);
+            assertThat(getDeviceRole(controller)).isEqualTo(DEVICE_ROLE_STOPPED);
+        }
+    }
+
+    @Test
+    public void leave_withoutPrivilegedPermission_throwsSecurityException() {
+        dropPermissions();
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            assertThrows(SecurityException.class, () -> controller.leave(mExecutor, v -> {}));
+        }
+    }
+
+    @Test
+    public void leave_concurrentRequests_bothSuccess() throws Exception {
+        grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+            SettableFuture<Void> leaveFuture1 = SettableFuture.create();
+            SettableFuture<Void> leaveFuture2 = SettableFuture.create();
+            controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            controller.leave(mExecutor, newOutcomeReceiver(leaveFuture1));
+            controller.leave(mExecutor, newOutcomeReceiver(leaveFuture2));
+
+            leaveFuture1.get();
+            leaveFuture2.get();
+            grantPermissions(permission.ACCESS_NETWORK_STATE);
+            assertThat(getDeviceRole(controller)).isEqualTo(DEVICE_ROLE_STOPPED);
+        }
+    }
+
+    @Test
+    public void scheduleMigration_withPrivilegedPermission_success() throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset activeDataset1 =
+                    new ActiveOperationalDataset.Builder(
+                                    newRandomizedDataset("TestNet", controller))
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+                            .setExtendedPanId(new byte[] {1, 1, 1, 1, 1, 1, 1, 1})
+                            .build();
+            ActiveOperationalDataset activeDataset2 =
+                    new ActiveOperationalDataset.Builder(activeDataset1)
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+                            .setNetworkName("ThreadNet2")
+                            .build();
+            PendingOperationalDataset pendingDataset2 =
+                    new PendingOperationalDataset(
+                            activeDataset2,
+                            OperationalDatasetTimestamp.fromInstant(Instant.now()),
+                            Duration.ofSeconds(30));
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+            SettableFuture<Void> migrateFuture = SettableFuture.create();
+            controller.join(activeDataset1, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            controller.scheduleMigration(
+                    pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture));
+
+            migrateFuture.get();
+            Thread.sleep(35 * 1000);
+            assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+            assertThat(getPendingOperationalDataset(controller)).isNull();
+        }
+    }
+
+    @Test
+    public void scheduleMigration_whenNotAttached_failWithPreconditionError() throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            PendingOperationalDataset pendingDataset =
+                    new PendingOperationalDataset(
+                            newRandomizedDataset("TestNet", controller),
+                            OperationalDatasetTimestamp.fromInstant(Instant.now()),
+                            Duration.ofSeconds(30));
+            SettableFuture<Void> migrateFuture = SettableFuture.create();
+
+            controller.scheduleMigration(
+                    pendingDataset, mExecutor, newOutcomeReceiver(migrateFuture));
+
+            ThreadNetworkException thrown =
+                    (ThreadNetworkException)
+                            assertThrows(ExecutionException.class, migrateFuture::get).getCause();
+            assertThat(thrown.getErrorCode()).isEqualTo(ERROR_FAILED_PRECONDITION);
+        }
+    }
+
+    @Test
+    public void scheduleMigration_secondRequestHasSmallerTimestamp_rejectedByLeader()
+            throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            final ActiveOperationalDataset activeDataset =
+                    new ActiveOperationalDataset.Builder(
+                                    newRandomizedDataset("testNet", controller))
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+                            .build();
+            ActiveOperationalDataset activeDataset1 =
+                    new ActiveOperationalDataset.Builder(activeDataset)
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+                            .setNetworkName("testNet1")
+                            .build();
+            PendingOperationalDataset pendingDataset1 =
+                    new PendingOperationalDataset(
+                            activeDataset1,
+                            new OperationalDatasetTimestamp(100, 0, false),
+                            Duration.ofSeconds(30));
+            ActiveOperationalDataset activeDataset2 =
+                    new ActiveOperationalDataset.Builder(activeDataset)
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(3L, 0, false))
+                            .setNetworkName("testNet2")
+                            .build();
+            PendingOperationalDataset pendingDataset2 =
+                    new PendingOperationalDataset(
+                            activeDataset2,
+                            new OperationalDatasetTimestamp(20, 0, false),
+                            Duration.ofSeconds(30));
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+            SettableFuture<Void> migrateFuture1 = SettableFuture.create();
+            SettableFuture<Void> migrateFuture2 = SettableFuture.create();
+            controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            controller.scheduleMigration(
+                    pendingDataset1, mExecutor, newOutcomeReceiver(migrateFuture1));
+            migrateFuture1.get();
+            controller.scheduleMigration(
+                    pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture2));
+
+            ThreadNetworkException thrown =
+                    (ThreadNetworkException)
+                            assertThrows(ExecutionException.class, migrateFuture2::get).getCause();
+            assertThat(thrown.getErrorCode()).isEqualTo(ERROR_REJECTED_BY_PEER);
+        }
+    }
+
+    @Test
+    public void scheduleMigration_secondRequestHasLargerTimestamp_success() throws Exception {
+        grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+        for (ThreadNetworkController controller : getAllControllers()) {
+            final ActiveOperationalDataset activeDataset =
+                    new ActiveOperationalDataset.Builder(
+                                    newRandomizedDataset("validName", controller))
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+                            .build();
+            ActiveOperationalDataset activeDataset1 =
+                    new ActiveOperationalDataset.Builder(activeDataset)
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+                            .setNetworkName("testNet1")
+                            .build();
+            PendingOperationalDataset pendingDataset1 =
+                    new PendingOperationalDataset(
+                            activeDataset1,
+                            new OperationalDatasetTimestamp(100, 0, false),
+                            Duration.ofSeconds(30));
+            ActiveOperationalDataset activeDataset2 =
+                    new ActiveOperationalDataset.Builder(activeDataset)
+                            .setActiveTimestamp(new OperationalDatasetTimestamp(3L, 0, false))
+                            .setNetworkName("testNet2")
+                            .build();
+            PendingOperationalDataset pendingDataset2 =
+                    new PendingOperationalDataset(
+                            activeDataset2,
+                            new OperationalDatasetTimestamp(200, 0, false),
+                            Duration.ofSeconds(30));
+            SettableFuture<Void> joinFuture = SettableFuture.create();
+            SettableFuture<Void> migrateFuture1 = SettableFuture.create();
+            SettableFuture<Void> migrateFuture2 = SettableFuture.create();
+            controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+            joinFuture.get();
+
+            controller.scheduleMigration(
+                    pendingDataset1, mExecutor, newOutcomeReceiver(migrateFuture1));
+            migrateFuture1.get();
+            controller.scheduleMigration(
+                    pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture2));
+
+            migrateFuture2.get();
+            Thread.sleep(35 * 1000);
+            assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+            assertThat(getPendingOperationalDataset(controller)).isNull();
+        }
+    }
+
+    @Test
+    public void createRandomizedDataset_wrongNetworkNameLength_throwsIllegalArgumentException() {
+        for (ThreadNetworkController controller : getAllControllers()) {
+            assertThrows(
+                    IllegalArgumentException.class,
+                    () -> controller.createRandomizedDataset("", mExecutor, dataset -> {}));
+
+            assertThrows(
+                    IllegalArgumentException.class,
+                    () ->
+                            controller.createRandomizedDataset(
+                                    "ANetNameIs17Bytes", mExecutor, dataset -> {}));
+        }
+    }
+
+    @Test
+    public void createRandomizedDataset_validNetworkName_success() throws Exception {
+        for (ThreadNetworkController controller : getAllControllers()) {
+            ActiveOperationalDataset dataset = newRandomizedDataset("validName", controller);
+
+            assertThat(dataset.getNetworkName()).isEqualTo("validName");
+            assertThat(dataset.getPanId()).isLessThan(0xffff);
+            assertThat(dataset.getChannelMask().size()).isAtLeast(1);
+            assertThat(dataset.getExtendedPanId()).hasLength(8);
+            assertThat(dataset.getNetworkKey()).hasLength(16);
+            assertThat(dataset.getPskc()).hasLength(16);
+            assertThat(dataset.getMeshLocalPrefix().getPrefixLength()).isEqualTo(64);
+            assertThat(dataset.getMeshLocalPrefix().getRawAddress()[0]).isEqualTo((byte) 0xfd);
+        }
+    }
 }
diff --git a/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java b/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
index 78eb3d0..7284968 100644
--- a/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
+++ b/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
@@ -20,14 +20,7 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.assertThrows;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
 
-import android.net.IpPrefix;
 import android.net.thread.ActiveOperationalDataset.Builder;
 import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
 import android.util.SparseArray;
@@ -61,7 +54,7 @@
     // PAN ID: 0xD9A0
     // PSKc: A245479C836D551B9CA557F7B9D351B4
     // Security Policy: 672 onrcb
-    private static final byte[] VALID_DATASET =
+    private static final byte[] VALID_DATASET_TLVS =
             base16().decode(
                             "0E080000000000010000000300001335060004001FFFE002"
                                     + "08ACC214689BC40BDF0708FD64DB1225F47E0B0510F26B31"
@@ -83,7 +76,7 @@
 
     @Test
     public void fromThreadTlvs_containsUnknownTlvs_unknownTlvsRetained() {
-        byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET, "AA01FFBB020102");
+        byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET_TLVS, "AA01FFBB020102");
 
         ActiveOperationalDataset dataset1 =
                 ActiveOperationalDataset.fromThreadTlvs(datasetWithUnknownTlvs);
@@ -98,66 +91,8 @@
     }
 
     @Test
-    public void createRandomDataset_fieldsAreRandomized() {
-        // Always return the max bounded value
-        doAnswer(invocation -> (int) invocation.getArgument(0) - 1)
-                .when(mockRandom)
-                .nextInt(anyInt());
-        doAnswer(
-                        invocation -> {
-                            byte[] output = invocation.getArgument(0);
-                            for (int i = 0; i < output.length; ++i) {
-                                output[i] = (byte) (i + 10);
-                            }
-                            return null;
-                        })
-                .when(mockRandom)
-                .nextBytes(any(byte[].class));
-        doAnswer(
-                        invocation -> {
-                            byte[] output = invocation.getArgument(0);
-                            for (int i = 0; i < output.length; ++i) {
-                                output[i] = (byte) (i + 30);
-                            }
-                            return null;
-                        })
-                .when(mockSecureRandom)
-                .nextBytes(any(byte[].class));
-
-        ActiveOperationalDataset dataset =
-                ActiveOperationalDataset.createRandomDataset(mockRandom, mockSecureRandom);
-
-        assertThat(dataset.getActiveTimestamp())
-                .isEqualTo(new OperationalDatasetTimestamp(1, 0, false));
-        assertThat(dataset.getExtendedPanId())
-                .isEqualTo(new byte[] {10, 11, 12, 13, 14, 15, 16, 17});
-        assertThat(dataset.getMeshLocalPrefix())
-                .isEqualTo(new IpPrefix("fd0b:0c0d:0e0f:1011::/64"));
-        verify(mockRandom, times(2)).nextBytes(any(byte[].class));
-        assertThat(dataset.getPanId()).isEqualTo(0xfffe); // PAN ID <= 0xfffe
-        verify(mockRandom, times(1)).nextInt(eq(0xffff));
-        assertThat(dataset.getChannel()).isEqualTo(26);
-        verify(mockRandom, times(1)).nextInt(eq(16));
-        assertThat(dataset.getChannelPage()).isEqualTo(0);
-        assertThat(dataset.getChannelMask().size()).isEqualTo(1);
-        assertThat(dataset.getPskc())
-                .isEqualTo(
-                        new byte[] {
-                            30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45
-                        });
-        assertThat(dataset.getNetworkKey())
-                .isEqualTo(
-                        new byte[] {
-                            30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45
-                        });
-        verify(mockSecureRandom, times(2)).nextBytes(any(byte[].class));
-        assertThat(dataset.getSecurityPolicy())
-                .isEqualTo(new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}));
-    }
-
-    @Test
     public void builder_buildWithTooLongTlvs_throwsIllegalState() {
-        Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+        Builder builder = new Builder(ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS));
         for (int i = 0; i < 10; i++) {
             builder.addUnknownTlv(i, new byte[20]);
         }
@@ -167,7 +102,8 @@
 
     @Test
     public void builder_setUnknownTlvs_success() {
-        ActiveOperationalDataset dataset1 = ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET);
+        ActiveOperationalDataset dataset1 =
+                ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
         SparseArray<byte[]> unknownTlvs = new SparseArray<>(2);
         unknownTlvs.put(0x33, new byte[] {1, 2, 3});
         unknownTlvs.put(0x44, new byte[] {1, 2, 3, 4});
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);
+    }
 }