Snap for 9550355 from 3b5211804f5bce62eb3e3d5d8a83e335b54c997c to sdk-release

Change-Id: I42aae0ced749d511c3ee98a6922a0315e6d26c5a
diff --git a/Android.bp b/Android.bp
index b0c00e5..49c011e 100644
--- a/Android.bp
+++ b/Android.bp
@@ -45,10 +45,6 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-// In some branches, this may be module_current instead of module_33 if the SDK prebuilts are not
-// yet dropped there, meaning module_33 cannot be used yet.
-module_33_version = "module_current"
-
 // TODO: remove this default and replace with ConnectivityNextEnableDefaults. This will need to be
 // done separately in each branch due to merge conflicts.
 // Defaults to enable/disable java targets that depend on
@@ -67,6 +63,7 @@
     min_sdk_version: "29",
     sdk_version: "module_current",
     libs: [
+        "framework-configinfrastructure",
         "framework-connectivity",
         "framework-connectivity-t",
         "framework-statsd",
@@ -74,11 +71,18 @@
     ]
 }
 
+// Common defaults for NetworkStack integration tests, root tests and coverage tests
+// to keep tests always running against the same target sdk version with NetworkStack.
 java_defaults {
-    name: "NetworkStackReleaseApiLevel",
-    sdk_version: module_33_version,
+    name: "NetworkStackReleaseTargetSdk",
     min_sdk_version: "29",
     target_sdk_version: "33",
+}
+
+java_defaults {
+    name: "NetworkStackReleaseApiLevel",
+    defaults:["NetworkStackReleaseTargetSdk"],
+    sdk_version: "module_33",
     libs: [
         "framework-connectivity",
         "framework-connectivity-t",
@@ -153,6 +157,12 @@
     srcs: [
         "apishim/31/**/*.java",
     ],
+    static_libs: [
+        // Libs building against module API can only be linked against when building against
+        // module API (so NetworkStackApi30Shims or NetworkStackApi29Shims can't use it, since they
+        // use system_30 and system_29 respectively).
+        "net-utils-framework-common",
+    ],
     libs: [
         "NetworkStackShimsCommon",
         "NetworkStackApi29Shims",
@@ -165,13 +175,10 @@
 
 java_library {
     name: "NetworkStackApi33Shims",
-    defaults: ["NetworkStackShimsDefaults", "ConnectivityNextEnableDefaults"],
+    defaults: ["NetworkStackShimsDefaults"],
     srcs: [
         "apishim/33/**/*.java",
     ],
-    static_libs: [
-        "net-utils-framework-common",
-    ],
     libs: [
         "NetworkStackShimsCommon",
         "NetworkStackApi29Shims",
@@ -182,22 +189,23 @@
         "framework-connectivity-t.stubs.module_lib",
         "framework-tethering",
     ],
-    sdk_version: module_33_version,
+    sdk_version: "module_33",
     visibility: ["//visibility:private"],
 }
 
 // Shims for APIs being added to the current development version of Android. These APIs are not
 // stable and have no defined version number. These could be called 10000, but they use the next
 // integer so if the next SDK release happens to use that integer, we don't need to rename them.
+// Jarjar rules are generated based on the stable shims, which do not contain this library. As a
+// result, no static_lib that needs jarjar should be used here. In general, static_libs should not
+// be used in this library at all; instead they can be in one of the earlier, shim libraries which
+// are part of the stable shims and scanned when generating jarjar rules.
 java_library {
     name: "NetworkStackApi34Shims",
     defaults: ["NetworkStackShimsDefaults", "ConnectivityNextEnableDefaults"],
     srcs: [
         "apishim/34/**/*.java",
     ],
-    static_libs: [
-        "net-utils-framework-common",
-    ],
     libs: [
         "NetworkStackShimsCommon",
         "NetworkStackApi29Shims",
@@ -286,7 +294,6 @@
         "net-utils-device-common-ip",
         "net-utils-device-common-netlink",
     ],
-    plugins: ["java_api_finder"],
 }
 
 // The versions of the android library containing network stack code compiled for each SDK variant.
@@ -353,15 +360,31 @@
     visibility: ["//packages/modules/Connectivity/tests/cts/net"],
 }
 
-filegroup {
+java_genrule {
     name: "NetworkStackJarJarRules",
-    srcs: ["jarjar-rules-shared.txt"],
+    tool_files: [
+        // com.android.networkstack.apishim is already in the target package that is not jarjared,
+        // so it does not matter whether ApiStable or ApiCurrent is used to generate the jarjar
+        // rules. Use ApiStable to be based on most stable release configuration and be buildable
+        // in all branches.
+        ":NetworkStackApiStableLib{.jar}",
+        "jarjar-excludes.txt",
+    ],
+    tools: [
+        "jarjar-rules-generator",
+    ],
+    out: ["NetworkStackJarJarRules.txt"],
+    cmd: "$(location jarjar-rules-generator) " +
+        "$(location :NetworkStackApiStableLib{.jar}) " +
+        "--prefix com.android.networkstack " +
+        "--excludes $(location jarjar-excludes.txt) " +
+        "--output $(out)",
     visibility: [
         "//packages/modules/NetworkStack/tests/unit",
         "//packages/modules/NetworkStack/tests/integration",
         "//packages/modules/Connectivity/tests:__subpackages__",
         "//packages/modules/Connectivity/Tethering/tests/integration",
-    ]
+    ],
 }
 
 // Common defaults for compiling the actual APK, based on the NetworkStackApiXBase android libraries
@@ -377,6 +400,7 @@
     jarjar_rules: ":NetworkStackJarJarRules",
     use_embedded_native_libs: true,
     optimize: {
+        ignore_warnings: false,
         proguard_flags_files: ["proguard.flags"],
     },
 }
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index d616750..9fe8b1d 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -58,14 +58,15 @@
              The service is protected by NETWORK_SETTINGS permissions as there is no better
              networking-related permission that exists on Q, is sufficiently protected (signature),
              and can be obtained via shell permissions. -->
-        <service android:name="com.android.server.TestNetworkStackService"
+        <!-- (The name starting with a dot means the package prefix is the APK package name) -->
+        <service android:name=".TestNetworkStackService"
                  android:permission="android.permission.NETWORK_SETTINGS"
                  android:exported="true">
             <intent-filter>
                 <action android:name="android.net.INetworkStackConnector.Test"/>
             </intent-filter>
         </service>
-        <service android:name="com.android.server.connectivity.ipmemorystore.RegularMaintenanceJobService"
+        <service android:name=".ipmemorystore.RegularMaintenanceJobService"
                  android:permission="android.permission.BIND_JOB_SERVICE" >
         </service>
     </application>
diff --git a/AndroidManifest_InProcess.xml b/AndroidManifest_InProcess.xml
index 7934826..40d74a5 100644
--- a/AndroidManifest_InProcess.xml
+++ b/AndroidManifest_InProcess.xml
@@ -33,7 +33,7 @@
                 <action android:name="android.net.INetworkStackConnector.InProcess"/>
             </intent-filter>
         </service>
-        <service android:name="com.android.server.connectivity.ipmemorystore.RegularMaintenanceJobService"
+        <service android:name="com.android.networkstack.ipmemorystore.RegularMaintenanceJobService"
                  android:process="system"
                  android:permission="android.permission.BIND_JOB_SERVICE" >
         </service>
diff --git a/TEST_MAPPING b/TEST_MAPPING
index f7dc8f0..3869fc9 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -8,6 +8,9 @@
     },
     {
       "name": "NetworkStackIntegrationTests"
+    },
+    {
+      "name": "NetworkStackRootTests"
     }
   ],
   "mainline-presubmit": [
@@ -16,11 +19,17 @@
     // so in theory the infra would not need to reinstall/reboot devices to run both.
     {
       "name": "NetworkStackTests[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
-    }
-  ],
-  "mainline-postsubmit": [
+    },
+    // This is used to verify NetworkStackRootTests with all latest modules listed below on
+    // preivous OS platforms.
     {
-      "name": "NetworkStackIntegrationTests[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
+      "name": "NetworkStackRootTests[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
+    },
+    // This is used to verify NetworkStackRootTests with latest CaptivePortalLoginGoogle.apk
+    // but with other modules on different version(e.g. an older tethering module to verify
+    // backwards compatibility of APIs).
+    {
+      "name": "NetworkStackRootTests[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk]"
     }
   ],
   "imports": [
diff --git a/apishim/29/com/android/networkstack/apishim/api29/BroadcastOptionsShimImpl.java b/apishim/29/com/android/networkstack/apishim/api29/BroadcastOptionsShimImpl.java
new file mode 100644
index 0000000..ab58dc2
--- /dev/null
+++ b/apishim/29/com/android/networkstack/apishim/api29/BroadcastOptionsShimImpl.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.android.networkstack.apishim.api29;
+
+import android.app.BroadcastOptions;
+import android.os.Build;
+import android.os.Bundle;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.BroadcastOptionsShim;
+
+/**
+ * Implementation of {@link BroadcastOptionsShim} for API 29.
+ */
+@RequiresApi(Build.VERSION_CODES.Q)
+public class BroadcastOptionsShimImpl implements BroadcastOptionsShim {
+    protected final BroadcastOptions mOptions;
+
+    protected BroadcastOptionsShimImpl(@NonNull BroadcastOptions options) {
+        mOptions = options;
+    }
+
+    /**
+     * Get a new instance of {@link BroadcastOptionsShim}.
+     */
+    public static BroadcastOptionsShim newInstance(@NonNull BroadcastOptions options) {
+        return new BroadcastOptionsShimImpl(options);
+    }
+
+    /** See android.app.BroadcastOptions#toBundle */
+    @Override
+    @NonNull
+    public Bundle toBundle() {
+        return mOptions.toBundle();
+    }
+}
diff --git a/apishim/29/com/android/networkstack/apishim/api29/NsdShimImpl.java b/apishim/29/com/android/networkstack/apishim/api29/NsdShimImpl.java
index 51cb2ba..ac0c69a 100644
--- a/apishim/29/com/android/networkstack/apishim/api29/NsdShimImpl.java
+++ b/apishim/29/com/android/networkstack/apishim/api29/NsdShimImpl.java
@@ -86,4 +86,11 @@
             throws UnsupportedApiLevelException {
         throw new UnsupportedApiLevelException("Resolve with executor is only supported on T+");
     }
+
+    @Override
+    public void stopServiceResolution(@NonNull NsdManager nsdManager,
+            @NonNull NsdManager.ResolveListener resolveListener)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Stop service resolution is only supported on U+");
+    }
 }
diff --git a/apishim/29/com/android/networkstack/apishim/api29/VpnProfileStateShimImpl.java b/apishim/29/com/android/networkstack/apishim/api29/VpnProfileStateShimImpl.java
deleted file mode 100644
index 10eb8b9..0000000
--- a/apishim/29/com/android/networkstack/apishim/api29/VpnProfileStateShimImpl.java
+++ /dev/null
@@ -1,27 +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 com.android.networkstack.apishim.api29;
-
-import android.os.Build;
-
-import androidx.annotation.RequiresApi;
-
-import com.android.networkstack.apishim.common.VpnProfileStateShim;
-
-/** Implementation of {@link VpnProfileStateShim} for API 29. */
-@RequiresApi(Build.VERSION_CODES.Q)
-public class VpnProfileStateShimImpl implements VpnProfileStateShim {
-}
diff --git a/apishim/31/com/android/networkstack/apishim/api31/VpnProfileStateShimImpl.java b/apishim/31/com/android/networkstack/apishim/api31/VpnProfileStateShimImpl.java
deleted file mode 100644
index 0bdd157..0000000
--- a/apishim/31/com/android/networkstack/apishim/api31/VpnProfileStateShimImpl.java
+++ /dev/null
@@ -1,28 +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 com.android.networkstack.apishim.api31;
-
-import android.os.Build;
-
-import androidx.annotation.RequiresApi;
-
-import com.android.networkstack.apishim.common.VpnProfileStateShim;
-
-/** Implementation of {@link VpnProfileStateShim} for API 31. */
-@RequiresApi(Build.VERSION_CODES.S)
-public class VpnProfileStateShimImpl
-        extends com.android.networkstack.apishim.api29.VpnProfileStateShimImpl {
-}
diff --git a/apishim/33/com/android/networkstack/apishim/api33/BroadcastOptionsShimImpl.java b/apishim/33/com/android/networkstack/apishim/api33/BroadcastOptionsShimImpl.java
new file mode 100644
index 0000000..5e38766
--- /dev/null
+++ b/apishim/33/com/android/networkstack/apishim/api33/BroadcastOptionsShimImpl.java
@@ -0,0 +1,50 @@
+/*
+ * 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 com.android.networkstack.apishim.api33;
+
+import static com.android.modules.utils.build.SdkLevel.isAtLeastT;
+
+import android.app.BroadcastOptions;
+import android.os.Build;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.BroadcastOptionsShim;
+
+/**
+ * Compatibility implementation of {@link BroadcastOptionsShim}.
+ */
+@RequiresApi(Build.VERSION_CODES.TIRAMISU)
+public class BroadcastOptionsShimImpl
+        extends com.android.networkstack.apishim.api29.BroadcastOptionsShimImpl {
+    protected BroadcastOptionsShimImpl(@NonNull BroadcastOptions options) {
+        super(options);
+    }
+
+    /**
+     * Get a new instance of {@link BroadcastOptionsShimImpl}.
+     */
+    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
+    public static BroadcastOptionsShim newInstance(@NonNull BroadcastOptions options) {
+        if (!isAtLeastT()) {
+            return com.android.networkstack.apishim.api29.BroadcastOptionsShimImpl.newInstance(
+                    options);
+        }
+        return new BroadcastOptionsShimImpl(options);
+    }
+}
diff --git a/apishim/33/com/android/networkstack/apishim/api33/ConstantsShim.java b/apishim/33/com/android/networkstack/apishim/api33/ConstantsShim.java
index 227b60c..66714c9 100644
--- a/apishim/33/com/android/networkstack/apishim/api33/ConstantsShim.java
+++ b/apishim/33/com/android/networkstack/apishim/api33/ConstantsShim.java
@@ -30,4 +30,7 @@
      */
     @VisibleForTesting
     public static final int VERSION = 33;
+
+    // Constants defined in android.app.BroadcastOptions.
+    public static final int DELIVERY_GROUP_POLICY_MOST_RECENT = 1;
 }
diff --git a/apishim/33/com/android/networkstack/apishim/api33/TelephonyManagerShimImpl.java b/apishim/33/com/android/networkstack/apishim/api33/TelephonyManagerShimImpl.java
index 473db91..fceb19a 100644
--- a/apishim/33/com/android/networkstack/apishim/api33/TelephonyManagerShimImpl.java
+++ b/apishim/33/com/android/networkstack/apishim/api33/TelephonyManagerShimImpl.java
@@ -23,6 +23,7 @@
 import android.telephony.TelephonyManager;
 import android.telephony.TelephonyManager.CarrierPrivilegesCallback;
 
+import androidx.annotation.Nullable;
 import androidx.annotation.RequiresApi;
 
 import com.android.networkstack.apishim.common.TelephonyManagerShim;
@@ -72,6 +73,12 @@
                 int[] pkgUids = toIntArray(privilegedUids);
                 listener.onCarrierPrivilegesChanged(pkgNames, pkgUids);
             }
+
+            @Override
+            public void onCarrierServiceChanged(@Nullable final String carrierServicePackageName,
+                    final int carrierServiceUid) {
+                listener.onCarrierServiceChanged(carrierServicePackageName, carrierServiceUid);
+            }
         };
         mTm.registerCarrierPrivilegesCallback(logicalSlotIndex, executor,
                 carrierPrivilegesCallback);
@@ -86,6 +93,7 @@
         mListenerMap.remove(listener);
     }
 
+    // TODO : remove this method when all changes are in
     /** See android.telephony.TelephonyManager#getCarrierServicePackageNameForLogicalSlot */
     public String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex) {
         return mTm.getCarrierServicePackageNameForLogicalSlot(logicalSlotIndex);
diff --git a/apishim/34/com/android/networkstack/apishim/BroadcastOptionsShimImpl.java b/apishim/34/com/android/networkstack/apishim/BroadcastOptionsShimImpl.java
new file mode 100644
index 0000000..a6c2c44
--- /dev/null
+++ b/apishim/34/com/android/networkstack/apishim/BroadcastOptionsShimImpl.java
@@ -0,0 +1,74 @@
+/*
+ * 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 com.android.networkstack.apishim;
+
+import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
+
+import android.app.BroadcastOptions;
+import android.os.Build;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.BroadcastOptionsShim;
+import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
+
+/**
+ * Implementation of {@link BroadcastOptionsShim} for API 34.
+ */
+// TODO: when available in all active branches: @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+@RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
+public class BroadcastOptionsShimImpl extends
+        com.android.networkstack.apishim.api33.BroadcastOptionsShimImpl {
+    protected BroadcastOptionsShimImpl(@NonNull BroadcastOptions options) {
+        super(options);
+    }
+
+    /** Get a new instance of {@link BroadcastOptionsShim}. */
+    @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
+    public static BroadcastOptionsShim newInstance(@NonNull BroadcastOptions options) {
+        if (!isAtLeastU()) {
+            return com.android.networkstack.apishim.api33.BroadcastOptionsShimImpl.newInstance(
+                    options);
+        }
+        return new BroadcastOptionsShimImpl(options);
+    }
+
+    /** See android.app.BroadcastOptions#setDeliveryGroupPolicy */
+    @Override
+    public BroadcastOptionsShim setDeliveryGroupPolicy(int policy)
+            throws UnsupportedApiLevelException {
+        mOptions.setDeliveryGroupPolicy(policy);
+        return this;
+    }
+
+    /** See android.app.BroadcastOptions#setDeliveryGroupMatchingKey */
+    @Override
+    public BroadcastOptionsShim setDeliveryGroupMatchingKey(@NonNull String namespace,
+            @NonNull String key) throws UnsupportedApiLevelException {
+        mOptions.setDeliveryGroupMatchingKey(namespace, key);
+        return this;
+    }
+
+    /** See android.app.BroadcastOptions#setDeferUntilActive */
+    @Override
+    public BroadcastOptionsShim setDeferUntilActive(boolean shouldDefer)
+            throws UnsupportedApiLevelException {
+        mOptions.setDeferUntilActive(shouldDefer);
+        return this;
+    }
+}
diff --git a/apishim/34/com/android/networkstack/apishim/NsdShimImpl.java b/apishim/34/com/android/networkstack/apishim/NsdShimImpl.java
index c7b2b7a..1fbc41e 100644
--- a/apishim/34/com/android/networkstack/apishim/NsdShimImpl.java
+++ b/apishim/34/com/android/networkstack/apishim/NsdShimImpl.java
@@ -16,11 +16,24 @@
 
 package com.android.networkstack.apishim;
 
+import android.net.nsd.NsdManager;
+import android.net.nsd.NsdServiceInfo;
 import android.os.Build;
+import android.util.ArrayMap;
 
+import androidx.annotation.NonNull;
 import androidx.annotation.RequiresApi;
 
+import com.android.modules.utils.build.SdkLevel;
 import com.android.networkstack.apishim.common.NsdShim;
+import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
+
+import java.net.InetAddress;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.Executor;
 
 /**
  * Implementation of {@link NsdShim}.
@@ -28,5 +41,88 @@
 // TODO: when available in all active branches: @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
 public class NsdShimImpl extends com.android.networkstack.apishim.api33.NsdShimImpl {
-    protected NsdShimImpl() {}
+    private final Map<ServiceInfoCallbackShim, ServiceInfoCallbackWrapper> mCbWrappers =
+            Collections.synchronizedMap(new ArrayMap<>());
+
+    /**
+     * Get a new instance of {@link NsdShim}.
+     */
+    @RequiresApi(Build.VERSION_CODES.Q)
+    public static NsdShim newInstance() {
+        if (SdkLevel.isAtLeastU()) {
+            return new NsdShimImpl();
+        } else {
+            return new com.android.networkstack.apishim.api33.NsdShimImpl();
+        }
+    }
+
+    @Override
+    public void stopServiceResolution(@NonNull NsdManager nsdManager,
+            @NonNull NsdManager.ResolveListener resolveListener)
+            throws UnsupportedApiLevelException {
+        nsdManager.stopServiceResolution(resolveListener);
+    }
+
+    private static class ServiceInfoCallbackWrapper implements NsdManager.ServiceInfoCallback {
+        @NonNull
+        final ServiceInfoCallbackShim mListener;
+
+        ServiceInfoCallbackWrapper(@NonNull ServiceInfoCallbackShim listener) {
+            mListener = listener;
+        }
+
+        @Override
+        public void onServiceInfoCallbackRegistrationFailed(int errorCode) {
+            mListener.onServiceInfoCallbackRegistrationFailed(errorCode);
+        }
+
+        @Override
+        public void onServiceUpdated(@NonNull NsdServiceInfo serviceInfo) {
+            mListener.onServiceUpdated(serviceInfo);
+        }
+
+        @Override
+        public void onServiceLost() {
+            mListener.onServiceLost();
+        }
+
+        @Override
+        public void onServiceInfoCallbackUnregistered() {
+            mListener.onServiceInfoCallbackUnregistered();
+        }
+    };
+
+    @Override
+    public void registerServiceInfoCallback(@NonNull NsdManager nsdManager,
+            @NonNull NsdServiceInfo serviceInfo, @NonNull Executor executor,
+            @NonNull ServiceInfoCallbackShim listener) throws UnsupportedApiLevelException {
+        Objects.requireNonNull(listener);
+        final ServiceInfoCallbackWrapper wrapper = new ServiceInfoCallbackWrapper(listener);
+        if (null != mCbWrappers.put(listener, wrapper)) {
+            throw new IllegalArgumentException("Listener shims must not be reused");
+        }
+        nsdManager.registerServiceInfoCallback(serviceInfo, executor, wrapper);
+    }
+
+    @Override
+    public void unregisterServiceInfoCallback(@NonNull NsdManager nsdManager,
+            @NonNull ServiceInfoCallbackShim listener) throws UnsupportedApiLevelException {
+        final ServiceInfoCallbackWrapper wrapper = mCbWrappers.remove(listener);
+        if (wrapper == null) {
+            throw new IllegalArgumentException("Listener was not registered");
+        }
+        nsdManager.unregisterServiceInfoCallback(wrapper);
+    }
+
+    @NonNull
+    @Override
+    public List<InetAddress> getHostAddresses(@NonNull NsdServiceInfo serviceInfo) {
+        return serviceInfo.getHostAddresses();
+    }
+
+    @Override
+    public void setHostAddresses(@NonNull NsdServiceInfo serviceInfo,
+            @NonNull List<InetAddress> addresses) {
+        serviceInfo.setHostAddresses(addresses);
+    }
 }
diff --git a/apishim/common/com/android/networkstack/apishim/common/BroadcastOptionsShim.java b/apishim/common/com/android/networkstack/apishim/common/BroadcastOptionsShim.java
new file mode 100644
index 0000000..097270d
--- /dev/null
+++ b/apishim/common/com/android/networkstack/apishim/common/BroadcastOptionsShim.java
@@ -0,0 +1,49 @@
+/*
+ * 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 com.android.networkstack.apishim.common;
+
+import android.os.Bundle;
+
+import androidx.annotation.NonNull;
+
+/**
+ * Interface for accessing API methods in {@link android.app.BroadcastOptions} by different SDK
+ * level.
+ */
+public interface BroadcastOptionsShim {
+    /** See android.app.BroadcastOptions#setDeliveryGroupPolicy */
+    default BroadcastOptionsShim setDeliveryGroupPolicy(int policy)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 34");
+    }
+
+    /** See android.app.BroadcastOptions#setDeliveryGroupMatchingKey */
+    default BroadcastOptionsShim setDeliveryGroupMatchingKey(@NonNull String namespace,
+            @NonNull String key) throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 34");
+    }
+
+    /** See android.app.BroadcastOptions#setDeferUntilActive */
+    default BroadcastOptionsShim setDeferUntilActive(boolean shouldDefer)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 34");
+    }
+
+    /** See android.app.BroadcastOptions#toBundle */
+    @NonNull
+    Bundle toBundle();
+}
diff --git a/apishim/common/com/android/networkstack/apishim/common/NsdShim.java b/apishim/common/com/android/networkstack/apishim/common/NsdShim.java
index 9e067ee..7281022 100644
--- a/apishim/common/com/android/networkstack/apishim/common/NsdShim.java
+++ b/apishim/common/com/android/networkstack/apishim/common/NsdShim.java
@@ -27,6 +27,8 @@
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
+import java.net.InetAddress;
+import java.util.List;
 import java.util.concurrent.Executor;
 
 /** Shim for NSD APIs, including {@link android.net.nsd.NsdManager} and
@@ -72,4 +74,56 @@
             int protocolType, @Nullable NetworkRequest request,
             @NonNull Executor executor, @NonNull DiscoveryListener listener)
             throws UnsupportedApiLevelException;
+
+    /**
+     * @see NsdManager#stopServiceResolution(ResolveListener)
+     */
+    void stopServiceResolution(@NonNull NsdManager nsdManager,
+            @NonNull ResolveListener resolveListener) throws UnsupportedApiLevelException;
+
+    /**
+     * @see NsdManager#ServiceInfoCallback
+     */
+    interface ServiceInfoCallbackShim {
+        default void onServiceInfoCallbackRegistrationFailed(int errorCode) {}
+        default void onServiceUpdated(@NonNull NsdServiceInfo serviceInfo) {}
+        default void onServiceLost() {}
+        default void onServiceInfoCallbackUnregistered() {}
+    }
+
+    /**
+     * @see NsdManager#registerServiceInfoCallback
+     */
+    default void registerServiceInfoCallback(@NonNull NsdManager nsdManager,
+            @NonNull NsdServiceInfo serviceInfo, @NonNull Executor executor,
+            @NonNull ServiceInfoCallbackShim listener)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Service callback is only supported on U+");
+    }
+
+    /**
+     * @see NsdManager#unregisterServiceInfoCallback
+     */
+    default void unregisterServiceInfoCallback(@NonNull NsdManager nsdManager,
+            @NonNull ServiceInfoCallbackShim listener)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Service callback is only supported on U+");
+    }
+
+    /**
+     * @see NsdServiceInfo#getHostAddresses()
+     */
+    @NonNull
+    default List<InetAddress> getHostAddresses(@NonNull NsdServiceInfo serviceInfo)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("getHostAddresses is only supported on U+");
+    }
+
+    /**
+     * @see NsdServiceInfo#setHostAddresses(List<InetAddress>)
+     */
+    default void setHostAddresses(@NonNull NsdServiceInfo serviceInfo,
+            @NonNull List<InetAddress> addresses) throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("setHostAddresses is only supported on U+");
+    }
 }
diff --git a/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java b/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java
index 492624a..6fec190 100644
--- a/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java
+++ b/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java
@@ -16,6 +16,8 @@
 
 package com.android.networkstack.apishim.common;
 
+import androidx.annotation.Nullable;
+
 import java.util.List;
 import java.util.concurrent.Executor;
 
@@ -30,12 +32,17 @@
  */
 public interface TelephonyManagerShim {
     /** See android.telephony.TelephonyManager.CarrierPrivilegesListener */
-    public interface CarrierPrivilegesListenerShim {
+    interface CarrierPrivilegesListenerShim {
         /** See android.telephony.TelephonyManager
-         * .CarrierPrivilegesListener#onCarrierPrivilegesChanged */
-        void onCarrierPrivilegesChanged(
+         * .CarrierPrivilegesCallback#onCarrierPrivilegesChanged */
+        default void onCarrierPrivilegesChanged(
                 List<String> privilegedPackageNames,
-                int[] privilegedUids);
+                int[] privilegedUids) {}
+        // TODO : remove the default implementation of this method once all changes are in
+        /** See CarrierPrivilegesCallback#onCarrierServiceChanged */
+        default void onCarrierServiceChanged(
+                @Nullable String carrierServicePackageName,
+                int carrierServiceUid) {}
     }
 
     /** See android.telephony.TelephonyManager#addCarrierPrivilegesListener */
@@ -54,6 +61,7 @@
         throw new UnsupportedApiLevelException("Only supported starting from API 33");
     }
 
+    // TODO : remove this method when all changes are in
     /** See android.telephony.TelephonyManager#getCarrierServicePackageNameForLogicalSlot */
     default String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex)
             throws UnsupportedApiLevelException {
diff --git a/common/moduleutils/Android.bp b/common/moduleutils/Android.bp
deleted file mode 100644
index 11b3d6d..0000000
--- a/common/moduleutils/Android.bp
+++ /dev/null
@@ -1,44 +0,0 @@
-//
-// Copyright (C) 2019 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.
-//
-
-// Shared utility sources to be used by multiple network modules
-// TODO: remove all frameworks/base dependencies on packages/modules/NetworkStack and
-// frameworks/base/packages/Tethering by moving these files to frameworks/libs/net.
-package {
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-filegroup {
-    name: "connectivity-module-utils-srcs",
-    srcs: [
-        "src/android/net/shared/NetdUtils.java",
-    ],
-    visibility: [
-        "//packages/modules/Connectivity/service",
-    ]
-}
-
-// Shared utility sources to be used by tethering modules
-filegroup {
-    name: "tethering-module-utils-srcs",
-    srcs: [
-        "src/android/net/shared/NetdUtils.java",
-    ],
-    visibility: [
-        "//frameworks/base/packages/Tethering",
-        "//packages/modules/Connectivity/Tethering"
-    ],
-}
diff --git a/common/moduleutils/src/android/net/shared/LinkPropertiesParcelableUtil.java b/common/moduleutils/src/android/net/shared/LinkPropertiesParcelableUtil.java
deleted file mode 100644
index 1729da6..0000000
--- a/common/moduleutils/src/android/net/shared/LinkPropertiesParcelableUtil.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import android.annotation.Nullable;
-import android.net.LinkProperties;
-import android.net.ProxyInfo;
-
-/**
- * Collection of utility methods to convert to and from stable AIDL parcelables for LinkProperties
- * and its attributes.
- * @hide
- */
-public final class LinkPropertiesParcelableUtil {
-    // Temporary methods to facilitate migrating clients away from LinkPropertiesParcelable
-    // TODO: remove the following methods after migrating clients.
-
-    /**
-     * @deprecated conversion to stable parcelable is no longer necessary.
-     */
-    @Deprecated
-    public static LinkProperties toStableParcelable(@Nullable LinkProperties lp) {
-        return lp;
-    }
-
-    /**
-     * @deprecated conversion to stable parcelable is no longer necessary.
-     */
-    @Deprecated
-    public static ProxyInfo toStableParcelable(@Nullable ProxyInfo info) {
-        return info;
-    }
-}
diff --git a/common/moduleutils/src/android/net/shared/NetdUtils.java b/common/moduleutils/src/android/net/shared/NetdUtils.java
deleted file mode 100644
index f801e16..0000000
--- a/common/moduleutils/src/android/net/shared/NetdUtils.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.system.OsConstants.EBUSY;
-
-import android.net.INetd;
-import android.net.TetherConfigParcel;
-import android.os.RemoteException;
-import android.os.ServiceSpecificException;
-import android.os.SystemClock;
-import android.util.Log;
-
-/**
- * Implements common operations on INetd
- * @hide
- */
-public class NetdUtils {
-    private static final String TAG = NetdUtils.class.getSimpleName();
-
-    /** Start tethering. */
-    public static void tetherStart(final INetd netd, final boolean usingLegacyDnsProxy,
-            final String[] dhcpRange) throws RemoteException, ServiceSpecificException {
-        final TetherConfigParcel config = new TetherConfigParcel();
-        config.usingLegacyDnsProxy = usingLegacyDnsProxy;
-        config.dhcpRanges = dhcpRange;
-        netd.tetherStartWithConfiguration(config);
-    }
-
-    /**
-     * Retry Netd#networkAddInterface for EBUSY error code.
-     * If the same interface (e.g., wlan0) is in client mode and then switches to tethered mode.
-     * There can be a race where puts the interface into the local network but interface is still
-     * in use in netd because the ConnectivityService thread hasn't processed the disconnect yet.
-     * See b/158269544 for detail.
-     */
-    private static void networkAddInterface(final INetd netd, final String iface,
-            int maxAttempts, int pollingIntervalMs)
-            throws ServiceSpecificException, RemoteException {
-        for (int i = 1; i <= maxAttempts; i++) {
-            try {
-                netd.networkAddInterface(INetd.LOCAL_NET_ID, iface);
-                return;
-            } catch (ServiceSpecificException e) {
-                if (e.errorCode == EBUSY && i < maxAttempts) {
-                    SystemClock.sleep(pollingIntervalMs);
-                    continue;
-                }
-
-                Log.e(TAG, "Retry Netd#networkAddInterface failure: " + e);
-                throw e;
-            }
-        }
-    }
-
-    /** Reset interface for tethering. */
-    public static void untetherInterface(final INetd netd, String iface)
-            throws RemoteException, ServiceSpecificException {
-        try {
-            netd.tetherInterfaceRemove(iface);
-        } finally {
-            netd.networkRemoveInterface(INetd.LOCAL_NET_ID, iface);
-        }
-    }
-}
diff --git a/common/networkstackclient/Android.bp b/common/networkstackclient/Android.bp
index 038caad..89de36b 100644
--- a/common/networkstackclient/Android.bp
+++ b/common/networkstackclient/Android.bp
@@ -34,7 +34,7 @@
         java: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.bluetooth",
+                "com.android.btservices",
                 "com.android.wifi",
                 "com.android.tethering",
             ],
@@ -110,7 +110,7 @@
         java: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.bluetooth",
+                "com.android.btservices",
                 "com.android.wifi",
                 "com.android.tethering",
             ],
@@ -144,6 +144,7 @@
         "13",
         "14",
         "15",
+        "16",
     ],
     // TODO: have tethering depend on networkstack-client and set visibility to private
     visibility: [
@@ -159,12 +160,12 @@
     min_sdk_version: "29",
     static_libs: [
         "ipmemorystore-aidl-interfaces-V10-java",
-        "networkstack-aidl-interfaces-V15-java",
+        "networkstack-aidl-interfaces-V16-java",
     ],
     visibility: ["//packages/modules/NetworkStack:__subpackages__"],
     apex_available: [
         "//apex_available:platform",
-        "com.android.bluetooth",
+        "com.android.btservices",
         "com.android.tethering",
         "com.android.wifi",
     ],
@@ -208,7 +209,7 @@
     ],
     apex_available: [
         "//apex_available:platform",
-        "com.android.bluetooth",
+        "com.android.btservices",
         "com.android.tethering",
         "com.android.wifi",
     ],
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/.hash b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/.hash
new file mode 100644
index 0000000..1b0fdc0
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/.hash
@@ -0,0 +1 @@
+a7ed197af8532361170ac44595771304b7f04034
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DataStallReportParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DataStallReportParcelable.aidl
new file mode 100644
index 0000000..771deda
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DataStallReportParcelable.aidl
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) 2020, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable DataStallReportParcelable {
+  long timestampMillis = 0;
+  int detectionMethod = 1;
+  int tcpPacketFailRate = 2;
+  int tcpMetricsCollectionPeriodMillis = 3;
+  int dnsConsecutiveTimeouts = 4;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DhcpResultsParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DhcpResultsParcelable.aidl
new file mode 100644
index 0000000..31f2194
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/DhcpResultsParcelable.aidl
@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2019, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable DhcpResultsParcelable {
+  android.net.StaticIpConfiguration baseConfiguration;
+  int leaseDuration;
+  int mtu;
+  String serverAddress;
+  String vendorInfo;
+  @nullable String serverHostName;
+  @nullable String captivePortalApiUrl;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitor.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitor.aidl
new file mode 100644
index 0000000..fc6a70e
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitor.aidl
@@ -0,0 +1,60 @@
+/**
+ * Copyright (c) 2018, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+/* @hide */
+interface INetworkMonitor {
+  oneway void start();
+  oneway void launchCaptivePortalApp();
+  oneway void notifyCaptivePortalAppFinished(int response);
+  oneway void setAcceptPartialConnectivity();
+  oneway void forceReevaluation(int uid);
+  oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
+  oneway void notifyDnsResponse(int returnCode);
+  oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
+  oneway void notifyNetworkDisconnected();
+  oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
+  oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
+  oneway void notifyNetworkConnectedParcel(in android.net.networkstack.aidl.NetworkMonitorParameters params);
+  const int NETWORK_TEST_RESULT_VALID = 0;
+  const int NETWORK_TEST_RESULT_INVALID = 1;
+  const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
+  const int NETWORK_VALIDATION_RESULT_VALID = 1;
+  const int NETWORK_VALIDATION_RESULT_PARTIAL = 2;
+  const int NETWORK_VALIDATION_RESULT_SKIPPED = 4;
+  const int NETWORK_VALIDATION_PROBE_DNS = 4;
+  const int NETWORK_VALIDATION_PROBE_HTTP = 8;
+  const int NETWORK_VALIDATION_PROBE_HTTPS = 16;
+  const int NETWORK_VALIDATION_PROBE_FALLBACK = 32;
+  const int NETWORK_VALIDATION_PROBE_PRIVDNS = 64;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitorCallbacks.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitorCallbacks.aidl
new file mode 100644
index 0000000..36eda8e
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkMonitorCallbacks.aidl
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+/* @hide */
+interface INetworkMonitorCallbacks {
+  oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor) = 0;
+  oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl) = 1;
+  oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config) = 2;
+  oneway void showProvisioningNotification(String action, String packageName) = 3;
+  oneway void hideProvisioningNotification() = 4;
+  oneway void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) = 5;
+  oneway void notifyNetworkTestedWithExtras(in android.net.NetworkTestResultParcelable result) = 6;
+  oneway void notifyDataStallSuspected(in android.net.DataStallReportParcelable report) = 7;
+  oneway void notifyCaptivePortalDataChanged(in android.net.CaptivePortalData data) = 8;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackConnector.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackConnector.aidl
new file mode 100644
index 0000000..8120ffc
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackConnector.aidl
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) 2018, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+/* @hide */
+interface INetworkStackConnector {
+  oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
+  oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
+  oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
+  oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
+  oneway void allowTestUid(int uid, in android.net.INetworkStackStatusCallback cb);
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackStatusCallback.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackStatusCallback.aidl
new file mode 100644
index 0000000..0b6b778
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/INetworkStackStatusCallback.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+/* @hide */
+interface INetworkStackStatusCallback {
+  oneway void onStatusAvailable(int statusCode);
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InformationElementParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InformationElementParcelable.aidl
new file mode 100644
index 0000000..6103774
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InformationElementParcelable.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable InformationElementParcelable {
+  int id;
+  byte[] payload;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InitialConfigurationParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InitialConfigurationParcelable.aidl
new file mode 100644
index 0000000..6a597e6
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/InitialConfigurationParcelable.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable InitialConfigurationParcelable {
+  android.net.LinkAddress[] ipAddresses;
+  android.net.IpPrefix[] directlyConnectedRoutes;
+  String[] dnsServers;
+  String gateway;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2InformationParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2InformationParcelable.aidl
new file mode 100644
index 0000000..83796ee
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2InformationParcelable.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable Layer2InformationParcelable {
+  String l2Key;
+  String cluster;
+  android.net.MacAddress bssid;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2PacketParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2PacketParcelable.aidl
new file mode 100644
index 0000000..4b3fff5
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/Layer2PacketParcelable.aidl
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2019, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable Layer2PacketParcelable {
+  android.net.MacAddress dstMacAddress;
+  byte[] payload;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NattKeepalivePacketDataParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NattKeepalivePacketDataParcelable.aidl
new file mode 100644
index 0000000..18cf954
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NattKeepalivePacketDataParcelable.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable NattKeepalivePacketDataParcelable {
+  byte[] srcAddress;
+  int srcPort;
+  byte[] dstAddress;
+  int dstPort;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NetworkTestResultParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NetworkTestResultParcelable.aidl
new file mode 100644
index 0000000..4d6d5a2
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/NetworkTestResultParcelable.aidl
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) 2020, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable NetworkTestResultParcelable {
+  long timestampMillis;
+  int result;
+  int probesSucceeded;
+  int probesAttempted;
+  String redirectUrl;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/PrivateDnsConfigParcel.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/PrivateDnsConfigParcel.aidl
new file mode 100644
index 0000000..1457caf
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/PrivateDnsConfigParcel.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable PrivateDnsConfigParcel {
+  String hostname;
+  String[] ips;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ProvisioningConfigurationParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ProvisioningConfigurationParcelable.aidl
new file mode 100644
index 0000000..fba524b
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ProvisioningConfigurationParcelable.aidl
@@ -0,0 +1,63 @@
+/*
+**
+** Copyright (C) 2019 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.
+*/
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable ProvisioningConfigurationParcelable {
+  /**
+   * @deprecated use ipv4ProvisioningMode instead.
+   */
+  boolean enableIPv4;
+  /**
+   * @deprecated use ipv6ProvisioningMode instead.
+   */
+  boolean enableIPv6;
+  boolean usingMultinetworkPolicyTracker;
+  boolean usingIpReachabilityMonitor;
+  int requestedPreDhcpActionMs;
+  android.net.InitialConfigurationParcelable initialConfig;
+  android.net.StaticIpConfiguration staticIpConfig;
+  android.net.apf.ApfCapabilities apfCapabilities;
+  int provisioningTimeoutMs;
+  int ipv6AddrGenMode;
+  android.net.Network network;
+  String displayName;
+  boolean enablePreconnection;
+  @nullable android.net.ScanResultInfoParcelable scanResultInfo;
+  @nullable android.net.Layer2InformationParcelable layer2Info;
+  @nullable List<android.net.networkstack.aidl.dhcp.DhcpOption> options;
+  int ipv4ProvisioningMode;
+  int ipv6ProvisioningMode;
+  boolean uniqueEui64AddressesOnly;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ScanResultInfoParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ScanResultInfoParcelable.aidl
new file mode 100644
index 0000000..94fc27f
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ScanResultInfoParcelable.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable ScanResultInfoParcelable {
+  String ssid;
+  String bssid;
+  android.net.InformationElementParcelable[] informationElements;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/TcpKeepalivePacketDataParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/TcpKeepalivePacketDataParcelable.aidl
new file mode 100644
index 0000000..0e1c21c
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/TcpKeepalivePacketDataParcelable.aidl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net;
+@JavaDerive(toString=true)
+parcelable TcpKeepalivePacketDataParcelable {
+  byte[] srcAddress;
+  int srcPort;
+  byte[] dstAddress;
+  int dstPort;
+  int seq;
+  int ack;
+  int rcvWnd;
+  int rcvWndScale;
+  int tos;
+  int ttl;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpLeaseParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpLeaseParcelable.aidl
new file mode 100644
index 0000000..3cd8860
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpLeaseParcelable.aidl
@@ -0,0 +1,43 @@
+/**
+ * Copyright (c) 2020, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.dhcp;
+@JavaDerive(toString=true)
+parcelable DhcpLeaseParcelable {
+  byte[] clientId;
+  byte[] hwAddr;
+  int netAddr;
+  int prefixLength;
+  long expTime;
+  String hostname;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpServingParamsParcel.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpServingParamsParcel.aidl
new file mode 100644
index 0000000..7997936
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/DhcpServingParamsParcel.aidl
@@ -0,0 +1,49 @@
+/**
+ *
+ * Copyright (C) 2018 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.dhcp;
+@JavaDerive(toString=true)
+parcelable DhcpServingParamsParcel {
+  int serverAddr;
+  int serverAddrPrefixLength;
+  int[] defaultRouters;
+  int[] dnsServers;
+  int[] excludedAddrs;
+  long dhcpLeaseTimeSecs;
+  int linkMtu;
+  boolean metered;
+  int singleClientAddr = 0;
+  boolean changePrefixOnDecline = false;
+  int leasesSubnetPrefixLength = 0;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpEventCallbacks.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpEventCallbacks.aidl
new file mode 100644
index 0000000..9312f47
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpEventCallbacks.aidl
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2020, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.dhcp;
+interface IDhcpEventCallbacks {
+  oneway void onLeasesChanged(in List<android.net.dhcp.DhcpLeaseParcelable> newLeases);
+  oneway void onNewPrefixRequest(in android.net.IpPrefix currentPrefix);
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServer.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServer.aidl
new file mode 100644
index 0000000..1109f35
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServer.aidl
@@ -0,0 +1,45 @@
+/**
+ * Copyright (c) 2018, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.dhcp;
+/* @hide */
+interface IDhcpServer {
+  oneway void start(in android.net.INetworkStackStatusCallback cb) = 0;
+  oneway void startWithCallbacks(in android.net.INetworkStackStatusCallback statusCb, in android.net.dhcp.IDhcpEventCallbacks eventCb) = 3;
+  oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb) = 1;
+  oneway void stop(in android.net.INetworkStackStatusCallback cb) = 2;
+  const int STATUS_UNKNOWN = 0;
+  const int STATUS_SUCCESS = 1;
+  const int STATUS_INVALID_ARGUMENT = 2;
+  const int STATUS_UNKNOWN_ERROR = 3;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServerCallbacks.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServerCallbacks.aidl
new file mode 100644
index 0000000..ab8577c
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/dhcp/IDhcpServerCallbacks.aidl
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2018, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.dhcp;
+/* @hide */
+interface IDhcpServerCallbacks {
+  oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClient.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClient.aidl
new file mode 100644
index 0000000..a97511e
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClient.aidl
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2019, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.ip;
+/* @hide */
+interface IIpClient {
+  oneway void completedPreDhcpAction();
+  oneway void confirmConfiguration();
+  oneway void readPacketFilterComplete(in byte[] data);
+  oneway void shutdown();
+  oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
+  oneway void stop();
+  oneway void setTcpBufferSizes(in String tcpBufferSizes);
+  oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
+  oneway void setMulticastFilter(boolean enabled);
+  oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
+  oneway void removeKeepalivePacketFilter(int slot);
+  oneway void setL2KeyAndGroupHint(in String l2Key, in String cluster);
+  oneway void addNattKeepalivePacketFilter(int slot, in android.net.NattKeepalivePacketDataParcelable pkt);
+  oneway void notifyPreconnectionComplete(boolean success);
+  oneway void updateLayer2Information(in android.net.Layer2InformationParcelable info);
+  const int PROV_IPV4_DISABLED = 0;
+  const int PROV_IPV4_STATIC = 1;
+  const int PROV_IPV4_DHCP = 2;
+  const int PROV_IPV6_DISABLED = 0;
+  const int PROV_IPV6_SLAAC = 1;
+  const int PROV_IPV6_LINKLOCAL = 2;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClientCallbacks.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClientCallbacks.aidl
new file mode 100644
index 0000000..24bbf64
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/ip/IIpClientCallbacks.aidl
@@ -0,0 +1,52 @@
+/**
+ * Copyright (c) 2019, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.ip;
+/* @hide */
+interface IIpClientCallbacks {
+  oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
+  oneway void onPreDhcpAction();
+  oneway void onPostDhcpAction();
+  oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
+  oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
+  oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
+  oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
+  oneway void onReachabilityLost(in String logMsg);
+  oneway void onQuit();
+  oneway void installPacketFilter(in byte[] filter);
+  oneway void startReadPacketFilter();
+  oneway void setFallbackMulticastFilter(boolean enabled);
+  oneway void setNeighborDiscoveryOffload(boolean enable);
+  oneway void onPreconnectionStart(in List<android.net.Layer2PacketParcelable> packets);
+  oneway void onReachabilityFailure(in android.net.networkstack.aidl.ip.ReachabilityLossInfoParcelable lossInfo);
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/NetworkMonitorParameters.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/NetworkMonitorParameters.aidl
new file mode 100644
index 0000000..2ab9db0
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/NetworkMonitorParameters.aidl
@@ -0,0 +1,41 @@
+/**
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.networkstack.aidl;
+@JavaDerive(equals=true, toString=true)
+parcelable NetworkMonitorParameters {
+  android.net.NetworkAgentConfig networkAgentConfig;
+  android.net.NetworkCapabilities networkCapabilities;
+  android.net.LinkProperties linkProperties;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/dhcp/DhcpOption.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/dhcp/DhcpOption.aidl
new file mode 100644
index 0000000..eea3e0d
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/dhcp/DhcpOption.aidl
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2020, 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 perNmissions and
+ * limitations under the License.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.networkstack.aidl.dhcp;
+@JavaDerive(toString=true)
+parcelable DhcpOption {
+  byte type;
+  @nullable byte[] value;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossInfoParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossInfoParcelable.aidl
new file mode 100644
index 0000000..bb88434
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossInfoParcelable.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.networkstack.aidl.ip;
+@JavaDerive(equals=true, toString=true) @JavaOnlyImmutable
+parcelable ReachabilityLossInfoParcelable {
+  String message;
+  android.net.networkstack.aidl.ip.ReachabilityLossReason reason;
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossReason.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossReason.aidl
new file mode 100644
index 0000000..70a7db2
--- /dev/null
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/16/android/net/networkstack/aidl/ip/ReachabilityLossReason.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.net.networkstack.aidl.ip;
+@Backing(type="int")
+enum ReachabilityLossReason {
+  ROAM = 0,
+  CONFIRM = 1,
+  ORGANIC = 2,
+}
diff --git a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/current/android/net/ProvisioningConfigurationParcelable.aidl b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/current/android/net/ProvisioningConfigurationParcelable.aidl
index 9ecd110..fba524b 100644
--- a/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/current/android/net/ProvisioningConfigurationParcelable.aidl
+++ b/common/networkstackclient/aidl_api/networkstack-aidl-interfaces/current/android/net/ProvisioningConfigurationParcelable.aidl
@@ -59,4 +59,5 @@
   @nullable List<android.net.networkstack.aidl.dhcp.DhcpOption> options;
   int ipv4ProvisioningMode;
   int ipv6ProvisioningMode;
+  boolean uniqueEui64AddressesOnly;
 }
diff --git a/common/networkstackclient/src/android/net/ProvisioningConfigurationParcelable.aidl b/common/networkstackclient/src/android/net/ProvisioningConfigurationParcelable.aidl
index 54a5729..c4d7866 100644
--- a/common/networkstackclient/src/android/net/ProvisioningConfigurationParcelable.aidl
+++ b/common/networkstackclient/src/android/net/ProvisioningConfigurationParcelable.aidl
@@ -49,4 +49,5 @@
     @nullable List<DhcpOption> options;
     int ipv4ProvisioningMode;
     int ipv6ProvisioningMode;
+    boolean uniqueEui64AddressesOnly;
 }
diff --git a/common/networkstackclient/src/android/net/shared/ProvisioningConfiguration.java b/common/networkstackclient/src/android/net/shared/ProvisioningConfiguration.java
index 3bf6744..f3631f2 100644
--- a/common/networkstackclient/src/android/net/shared/ProvisioningConfiguration.java
+++ b/common/networkstackclient/src/android/net/shared/ProvisioningConfiguration.java
@@ -270,6 +270,18 @@
         }
 
         /**
+         * Specify that the configuration is for a network that only uses unique EUI-64
+         * addresses (e.g., a link-local-only network where addresses are generated via
+         * EUI-64 and where MAC addresses are guaranteed to be unique).
+         * This will disable duplicate address detection if withLinkLocalOnly() and
+         * withRandomMacAddress are also called.
+         */
+        public Builder withUniqueEui64AddressesOnly() {
+            mConfig.mUniqueEui64AddressesOnly = true;
+            return this;
+        }
+
+        /**
          * Build the configuration using previously specified parameters.
          */
         public ProvisioningConfiguration build() {
@@ -333,7 +345,7 @@
 
             @Override
             public int hashCode() {
-                return Objects.hash(mId, mPayload);
+                return Objects.hash(mId, Arrays.hashCode(mPayload));
             }
 
             @Override
@@ -463,6 +475,7 @@
         }
     }
 
+    public boolean mUniqueEui64AddressesOnly = false;
     public boolean mEnablePreconnection = false;
     public boolean mUsingMultinetworkPolicyTracker = true;
     public boolean mUsingIpReachabilityMonitor = true;
@@ -483,6 +496,7 @@
     public ProvisioningConfiguration() {} // used by Builder
 
     public ProvisioningConfiguration(ProvisioningConfiguration other) {
+        mUniqueEui64AddressesOnly = other.mUniqueEui64AddressesOnly;
         mEnablePreconnection = other.mEnablePreconnection;
         mUsingMultinetworkPolicyTracker = other.mUsingMultinetworkPolicyTracker;
         mUsingIpReachabilityMonitor = other.mUsingIpReachabilityMonitor;
@@ -512,6 +526,7 @@
         p.ipv4ProvisioningMode = mIPv4ProvisioningMode;
         p.enableIPv6 = (mIPv6ProvisioningMode != PROV_IPV6_DISABLED);
         p.ipv6ProvisioningMode = mIPv6ProvisioningMode;
+        p.uniqueEui64AddressesOnly = mUniqueEui64AddressesOnly;
         p.enablePreconnection = mEnablePreconnection;
         p.usingMultinetworkPolicyTracker = mUsingMultinetworkPolicyTracker;
         p.usingIpReachabilityMonitor = mUsingIpReachabilityMonitor;
@@ -543,6 +558,7 @@
             @Nullable ProvisioningConfigurationParcelable p, int interfaceVersion) {
         if (p == null) return null;
         final ProvisioningConfiguration config = new ProvisioningConfiguration();
+        config.mUniqueEui64AddressesOnly = p.uniqueEui64AddressesOnly;
         config.mEnablePreconnection = p.enablePreconnection;
         config.mUsingMultinetworkPolicyTracker = p.usingMultinetworkPolicyTracker;
         config.mUsingIpReachabilityMonitor = p.usingIpReachabilityMonitor;
@@ -602,6 +618,7 @@
         final String ipv4ProvisioningMode = ipv4ProvisioningModeToString(mIPv4ProvisioningMode);
         final String ipv6ProvisioningMode = ipv6ProvisioningModeToString(mIPv6ProvisioningMode);
         return new StringJoiner(", ", getClass().getSimpleName() + "{", "}")
+                .add("mUniqueEui64AddressesOnly: " + mUniqueEui64AddressesOnly)
                 .add("mEnablePreconnection: " + mEnablePreconnection)
                 .add("mUsingMultinetworkPolicyTracker: " + mUsingMultinetworkPolicyTracker)
                 .add("mUsingIpReachabilityMonitor: " + mUsingIpReachabilityMonitor)
@@ -647,7 +664,8 @@
     public boolean equals(Object obj) {
         if (!(obj instanceof ProvisioningConfiguration)) return false;
         final ProvisioningConfiguration other = (ProvisioningConfiguration) obj;
-        return mEnablePreconnection == other.mEnablePreconnection
+        return mUniqueEui64AddressesOnly == other.mUniqueEui64AddressesOnly
+                && mEnablePreconnection == other.mEnablePreconnection
                 && mUsingMultinetworkPolicyTracker == other.mUsingMultinetworkPolicyTracker
                 && mUsingIpReachabilityMonitor == other.mUsingIpReachabilityMonitor
                 && mRequestedPreDhcpActionMs == other.mRequestedPreDhcpActionMs
diff --git a/jarjar-excludes.txt b/jarjar-excludes.txt
new file mode 100644
index 0000000..42a9219
--- /dev/null
+++ b/jarjar-excludes.txt
@@ -0,0 +1,4 @@
+# Services referenced in the manifest. They could be moved to a different package as there are no
+# hardcoded reference to them in AOSP, but it is possible that OEM customizations are relying on
+# the naming.
+com\.android\.server\.NetworkStackService(\$.+)?
diff --git a/jarjar-rules-shared.txt b/jarjar-rules-shared.txt
deleted file mode 100644
index e8c9c19..0000000
--- a/jarjar-rules-shared.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-rule com.android.internal.util.** android.net.networkstack.util.@1
-rule com.google.protobuf.** com.android.networkstack.protobuf.@1
-
-# Classes from net-utils-framework-common
-rule com.android.net.module.util.** com.android.networkstack.util.@1
-
-# Ignore DhcpResultsParcelable, but jarjar DhcpResults
-# TODO: move DhcpResults into services.net and delete from here
-rule android.net.DhcpResultsParcelable* @0
-rule android.net.DhcpResults* android.net.networkstack.DhcpResults@1
-rule android.util.LocalLog* android.net.networkstack.util.LocalLog@1
-
-rule android.util.IndentingPrintWriter* android.net.networkstack.util.AndroidUtilIndentingPrintWriter@1
-
-# Classes from modules-utils-build_system
-rule com.android.modules.utils.build.** com.android.networkstack.utils.build.@1
\ No newline at end of file
diff --git a/jni/network_stack_utils_jni.cpp b/jni/network_stack_utils_jni.cpp
index 63146d8..e63483f 100644
--- a/jni/network_stack_utils_jni.cpp
+++ b/jni/network_stack_utils_jni.cpp
@@ -38,7 +38,8 @@
 #include <android/log.h>
 
 namespace android {
-constexpr const char NETWORKSTACKUTILS_PKG_NAME[] = "android/net/util/NetworkStackUtils";
+constexpr const char NETWORKSTACKUTILS_PKG_NAME[] =
+    "com/android/networkstack/util/NetworkStackUtils";
 
 static const uint32_t kEtherTypeOffset = offsetof(ether_header, ether_type);
 static const uint32_t kEtherHeaderLen = sizeof(ether_header);
@@ -59,7 +60,7 @@
     return true;
 }
 
-static void network_stack_utils_addArpEntry(JNIEnv *env, jobject thiz, jbyteArray ethAddr,
+static void network_stack_utils_addArpEntry(JNIEnv *env, jclass clazz, jbyteArray ethAddr,
         jbyteArray ipv4Addr, jstring ifname, jobject javaFd) {
     arpreq req = {};
     sockaddr_in& netAddrStruct = *reinterpret_cast<sockaddr_in*>(&req.arp_pa);
@@ -98,15 +99,17 @@
     }
 }
 
-static void network_stack_utils_attachDhcpFilter(JNIEnv *env, jobject clazz, jobject javaFd) {
-    static sock_filter filter_code[] = {
+static void network_stack_utils_attachDhcpFilter(JNIEnv *env, jclass clazz, jobject javaFd, jboolean dropMF) {
+    const __u32 frag_mask = static_cast<__u32>((dropMF ? IP_MF : 0) | IP_OFFMASK);
+
+    sock_filter filter_code[] = {
         // Check the protocol is UDP.
         BPF_STMT(BPF_LD  | BPF_B    | BPF_ABS, kIPv4Protocol),
         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   IPPROTO_UDP, 0, 6),
 
         // Check this is not a fragment.
         BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS, kIPv4FlagsOffset),
-        BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   IP_OFFMASK, 4, 0),
+        BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   frag_mask, 4, 0),
 
         // Get the IP header length.
         BPF_STMT(BPF_LDX | BPF_B    | BPF_MSH, kEtherHeaderLen),
@@ -115,11 +118,13 @@
         BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPDstPortIndirectOffset),
         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 0, 1),
 
-        // Accept or reject.
+        // Accept.
         BPF_STMT(BPF_RET | BPF_K,              0xffff),
+
+        // Reject.
         BPF_STMT(BPF_RET | BPF_K,              0)
     };
-    static const sock_fprog filter = {
+    const sock_fprog filter = {
         sizeof(filter_code) / sizeof(filter_code[0]),
         filter_code,
     };
@@ -130,7 +135,7 @@
     }
 }
 
-static void network_stack_utils_attachRaFilter(JNIEnv *env, jobject clazz, jobject javaFd,
+static void network_stack_utils_attachRaFilter(JNIEnv *env, jclass clazz, jobject javaFd,
         jint hardwareAddressType) {
     if (hardwareAddressType != ARPHRD_ETHER) {
         jniThrowExceptionFmt(env, "java/net/SocketException",
@@ -147,8 +152,10 @@
         BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kICMPv6TypeOffset),
         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    ND_ROUTER_ADVERT, 0, 1),
 
-        // Accept or reject.
+        // Accept.
         BPF_STMT(BPF_RET | BPF_K,              0xffff),
+
+        // Reject.
         BPF_STMT(BPF_RET | BPF_K,              0)
     };
     static const sock_fprog filter = {
@@ -165,7 +172,7 @@
 
 // TODO: Move all this filter code into libnetutils.
 static void network_stack_utils_attachControlPacketFilter(
-        JNIEnv *env, jobject clazz, jobject javaFd, jint hardwareAddressType) {
+        JNIEnv *env, jclass clazz, jobject javaFd, jint hardwareAddressType) {
     if (hardwareAddressType != ARPHRD_ETHER) {
         jniThrowExceptionFmt(env, "java/net/SocketException",
                 "attachControlPacketFilter only supports ARPHRD_ETHER");
@@ -222,8 +229,10 @@
         BPF_JUMP(BPF_JMP | BPF_JGE  | BPF_K,   ND_ROUTER_SOLICIT, 0, 2),
         BPF_JUMP(BPF_JMP | BPF_JGT  | BPF_K,   ND_NEIGHBOR_ADVERT, 1, 0),
 
-        // Accept or reject.
+        // Accept.
         BPF_STMT(BPF_RET | BPF_K,              0xffff),
+
+        // Reject.
         BPF_STMT(BPF_RET | BPF_K,              0)
     };
     static const sock_fprog filter = {
@@ -244,7 +253,7 @@
 static const JNINativeMethod gNetworkStackUtilsMethods[] = {
     /* name, signature, funcPtr */
     { "addArpEntry", "([B[BLjava/lang/String;Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_addArpEntry },
-    { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_attachDhcpFilter },
+    { "attachDhcpFilter", "(Ljava/io/FileDescriptor;Z)V", (void*) network_stack_utils_attachDhcpFilter },
     { "attachRaFilter", "(Ljava/io/FileDescriptor;I)V", (void*) network_stack_utils_attachRaFilter },
     { "attachControlPacketFilter", "(Ljava/io/FileDescriptor;I)V", (void*) network_stack_utils_attachControlPacketFilter },
 };
diff --git a/proguard.flags b/proguard.flags
index 7f8f207..511a6b3 100644
--- a/proguard.flags
+++ b/proguard.flags
@@ -1,14 +1,14 @@
--keepclassmembers class android.net.ip.IpClient {
+-keepclassmembers class com.android.networkstack.android.net.ip.IpClient {
     static final int CMD_*;
     static final int EVENT_*;
 }
 
--keepclassmembers class android.net.dhcp.DhcpClient {
+-keepclassmembers class com.android.networkstack.android.net.dhcp.DhcpClient {
     static final int CMD_*;
     static final int EVENT_*;
 }
 
--keepclassmembers public class * extends com.android.networkstack.util.Struct {
+-keepclassmembers public class * extends com.android.networkstack.com.android.net.module.util.Struct {
     *;
 }
 
@@ -17,4 +17,4 @@
 # This replicates the base proguard rule used by the build by default
 # (proguard_basic_keeps.flags), but needs to be specified here because the
 # com.google.protobuf package is jarjared to the below package.
--keepclassmembers class * extends com.android.networkstack.protobuf.MessageLite { <fields>; }
+-keepclassmembers class * extends com.android.networkstack.com.google.protobuf.MessageLite { <fields>; }
diff --git a/res/values-en-rCA/strings.xml b/res/values-en-rCA/strings.xml
index d9f3843..71db3ab 100644
--- a/res/values-en-rCA/strings.xml
+++ b/res/values-en-rCA/strings.xml
@@ -19,8 +19,8 @@
     <string name="notification_channel_name_connected" msgid="1795068343200033922">"Captive portal authentication"</string>
     <string name="notification_channel_description_connected" msgid="7239184168268014518">"Notifications shown when the device has successfully authenticated to a captive portal network"</string>
     <string name="notification_channel_name_network_venue_info" msgid="6526543187249265733">"Network venue information"</string>
-    <string name="notification_channel_description_network_venue_info" msgid="5131499595382733605">"Notifications shown to indicate that the network has a venue information page"</string>
+    <string name="notification_channel_description_network_venue_info" msgid="5131499595382733605">"Notifications shown to indicate the network has a venue information page"</string>
     <string name="connected" msgid="4563643884927480998">"Connected"</string>
-    <string name="tap_for_info" msgid="6849746325626883711">"Connected/Tap to view website"</string>
+    <string name="tap_for_info" msgid="6849746325626883711">"Connected / Tap to view website"</string>
     <string name="application_label" msgid="1322847171305285454">"Network manager"</string>
 </resources>
diff --git a/res/values-ro/strings.xml b/res/values-ro/strings.xml
index feda547..61a7149 100644
--- a/res/values-ro/strings.xml
+++ b/res/values-ro/strings.xml
@@ -21,6 +21,6 @@
     <string name="notification_channel_name_network_venue_info" msgid="6526543187249265733">"Informații despre locația rețelei"</string>
     <string name="notification_channel_description_network_venue_info" msgid="5131499595382733605">"Notificări afișate pentru a indica faptul că o rețea are o pagină cu informații despre locație"</string>
     <string name="connected" msgid="4563643884927480998">"Conectată"</string>
-    <string name="tap_for_info" msgid="6849746325626883711">"Conectat / atingeți pentru a vedea site-ul"</string>
+    <string name="tap_for_info" msgid="6849746325626883711">"Conectat / atinge pentru a vedea site-ul"</string>
     <string name="application_label" msgid="1322847171305285454">"Manager de rețea"</string>
 </resources>
diff --git a/res/values/config.xml b/res/values/config.xml
index 805ca04..15152e3 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -113,12 +113,16 @@
 
     <!-- An array of Denylisted EtherType, packets with EtherTypes within this array
          will be dropped
-         TODO: need to put proper values, these are for testing purposes only -->
+         TODO: are these proper values? -->
     <integer-array name="config_apfEthTypeDenyList">
         <item>0x88A2</item>
         <item>0x88A4</item>
         <item>0x88B8</item>
         <item>0x88CD</item>
+        <item>0x88E1</item>
         <item>0x88E3</item>
     </integer-array>
+
+    <!-- Whether to validate DUN networks. This is unused and always true on U+. -->
+    <bool name="config_validate_dun_networks">false</bool>
 </resources>
diff --git a/res/values/overlayable.xml b/res/values/overlayable.xml
index a8b31cc..20ee593 100644
--- a/res/values/overlayable.xml
+++ b/res/values/overlayable.xml
@@ -88,6 +88,8 @@
             notifying that internet access is now available or that a venue info page is
             available, for example. -->
             <item type="drawable" name="icon_wifi"/>
+            <!-- Whether to validate DUN networks. This is unused and always true on U+. -->
+            <item type="bool" name="config_validate_dun_networks"/>
         </policy>
     </overlayable>
 </resources>
diff --git a/src/android/net/NetworkStackIpMemoryStore.java b/src/android/net/NetworkStackIpMemoryStore.java
index 850faaf..5426db0 100644
--- a/src/android/net/NetworkStackIpMemoryStore.java
+++ b/src/android/net/NetworkStackIpMemoryStore.java
@@ -20,13 +20,15 @@
 
 import androidx.annotation.NonNull;
 
+import com.android.networkstack.ipmemorystore.IpMemoryStoreService;
+
 import java.util.concurrent.ExecutionException;
 import java.util.function.Consumer;
 
 /**
  * service used to communicate with the ip memory store service in network stack,
  * which is running in the same module.
- * @see com.android.server.connectivity.ipmemorystore.IpMemoryStoreService
+ * @see IpMemoryStoreService
  * @hide
  */
 public class NetworkStackIpMemoryStore extends IpMemoryStoreClient {
diff --git a/src/android/net/apf/ApfFilter.java b/src/android/net/apf/ApfFilter.java
index 4d98568..70fa673 100644
--- a/src/android/net/apf/ApfFilter.java
+++ b/src/android/net/apf/ApfFilter.java
@@ -49,7 +49,6 @@
 import android.net.metrics.ApfStats;
 import android.net.metrics.IpConnectivityLog;
 import android.net.metrics.RaEvent;
-import android.net.util.NetworkStackUtils;
 import android.os.PowerManager;
 import android.os.SystemClock;
 import android.system.ErrnoException;
@@ -67,6 +66,8 @@
 import com.android.net.module.util.CollectionUtils;
 import com.android.net.module.util.ConnectivityUtils;
 import com.android.net.module.util.InterfaceParams;
+import com.android.net.module.util.SocketUtils;
+import com.android.networkstack.util.NetworkStackUtils;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
@@ -191,7 +192,7 @@
 
     // Thread to listen for RAs.
     @VisibleForTesting
-    class ReceiveThread extends Thread {
+    public class ReceiveThread extends Thread {
         private final byte[] mPacket = new byte[1514];
         private final FileDescriptor mSocket;
         private final long mStart = SystemClock.elapsedRealtime();
@@ -212,7 +213,7 @@
         public void halt() {
             mStopped = true;
             // Interrupts the read() call the thread is blocked in.
-            NetworkStackUtils.closeSocketQuietly(mSocket);
+            SocketUtils.closeSocketQuietly(mSocket);
         }
 
         @Override
@@ -348,9 +349,9 @@
     private final IpConnectivityLog mMetricsLog;
 
     @VisibleForTesting
-    byte[] mHardwareAddress;
+    public byte[] mHardwareAddress;
     @VisibleForTesting
-    ReceiveThread mReceiveThread;
+    public ReceiveThread mReceiveThread;
     @GuardedBy("this")
     private long mUniqueCounter;
     @GuardedBy("this")
@@ -386,7 +387,7 @@
     private int mIPv4PrefixLength;
 
     @VisibleForTesting
-    ApfFilter(Context context, ApfConfiguration config, InterfaceParams ifParams,
+    public ApfFilter(Context context, ApfConfiguration config, InterfaceParams ifParams,
             IpClientCallbacksWrapper ipClientCallback, IpConnectivityLog log) {
         mApfCapabilities = config.apfCapabilities;
         mIpClientCallback = ipClientCallback;
@@ -466,7 +467,7 @@
      * filters to ignore useless RAs.
      */
     @VisibleForTesting
-    void maybeStartFilter() {
+    public void maybeStartFilter() {
         FileDescriptor socket;
         try {
             mHardwareAddress = mInterfaceParams.macAddr.toByteArray();
@@ -546,7 +547,7 @@
 
     // A class to hold information about an RA.
     @VisibleForTesting
-    class Ra {
+    public class Ra {
         // From RFC4861:
         private static final int ICMP6_RA_HEADER_LEN = 16;
         private static final int ICMP6_RA_CHECKSUM_OFFSET =
@@ -771,7 +772,8 @@
         // Buffer.position(int) or due to an invalid-length option) or IndexOutOfBoundsException
         // (from ByteBuffer.get(int) ) if parsing encounters something non-compliant with
         // specifications.
-        Ra(byte[] packet, int length) throws InvalidRaException {
+        @VisibleForTesting
+        public Ra(byte[] packet, int length) throws InvalidRaException {
             if (length < ICMP6_RA_OPTION_OFFSET) {
                 throw new InvalidRaException("Not an ICMP6 router advertisement: too short");
             }
@@ -902,13 +904,21 @@
 
         // Append a filter for this RA to {@code gen}. Jump to DROP_LABEL if it should be dropped.
         // Jump to the next filter if packet doesn't match this RA.
+        // Return Long.MAX_VALUE if we don't install any filter program for this RA. As the return
+        // value of this function is used to calculate the program min lifetime (which corresponds
+        // to the smallest generated filter lifetime). Returning Long.MAX_VALUE in the case no
+        // filter gets generated makes sure the program lifetime stays unaffected.
         @GuardedBy("ApfFilter.this")
         long generateFilterLocked(ApfGenerator gen) throws IllegalInstructionException {
+            // Filter for a fraction of the lifetime and adjust for the age of the RA.
+            int filterLifetime = (int) (mMinLifetime / FRACTION_OF_LIFETIME_TO_FILTER)
+                    - (int) (mProgramBaseTime - mLastSeen);
+            if (filterLifetime <= 0) return Long.MAX_VALUE;
+
             String nextFilterLabel = "Ra" + getUniqueNumberLocked();
             // Skip if packet is not the right size
             gen.addLoadFromMemory(Register.R0, gen.PACKET_SIZE_MEMORY_SLOT);
             gen.addJumpIfR0NotEquals(mPacket.capacity(), nextFilterLabel);
-            int filterLifetime = (int)(currentLifetime() / FRACTION_OF_LIFETIME_TO_FILTER);
             // Skip filter if expired
             gen.addLoadFromMemory(Register.R0, gen.FILTER_AGE_MEMORY_SLOT);
             gen.addJumpIfR0GreaterThan(filterLifetime, nextFilterLabel);
@@ -1176,6 +1186,11 @@
     // packets may be dropped, so let's use 6.
     private static final int FRACTION_OF_LIFETIME_TO_FILTER = 6;
 
+    // The base time for this filter program. In seconds since Unix Epoch.
+    // This is the time when the APF program was generated. All filters in the program should use
+    // this base time as their current time for consistency purposes.
+    @GuardedBy("this")
+    private long mProgramBaseTime;
     // When did we last install a filter program? In seconds since Unix Epoch.
     @GuardedBy("this")
     private long mLastTimeInstalledProgram;
@@ -1619,7 +1634,7 @@
      */
     @GuardedBy("this")
     @VisibleForTesting
-    void installNewProgramLocked() {
+    public void installNewProgramLocked() {
         purgeExpiredRasLocked();
         ArrayList<Ra> rasToFilter = new ArrayList<>();
         final byte[] program;
@@ -1630,6 +1645,7 @@
             maximumApfProgramSize -= Counter.totalSize();
         }
 
+        mProgramBaseTime = currentTimeSeconds();
         try {
             // Step 1: Determine how many RA filters we can fit in the program.
             ApfGenerator gen = emitPrologueLocked();
@@ -1666,8 +1682,8 @@
             Log.e(TAG, "Failed to generate APF program.", e);
             return;
         }
-        final long now = currentTimeSeconds();
-        mLastTimeInstalledProgram = now;
+        mIpClientCallback.installPacketFilter(program);
+        mLastTimeInstalledProgram = mProgramBaseTime;
         mLastInstalledProgramMinLifetime = programMinLifetime;
         mLastInstalledProgram = program;
         mNumProgramUpdates++;
@@ -1675,8 +1691,7 @@
         if (VDBG) {
             hexDump("Installing filter: ", program, program.length);
         }
-        mIpClientCallback.installPacketFilter(program);
-        logApfProgramEventLocked(now);
+        logApfProgramEventLocked(mProgramBaseTime);
         mLastInstallEvent = new ApfProgramEvent.Builder()
                 .setLifetime(programMinLifetime)
                 .setFilteredRas(rasToFilter.size())
@@ -1730,7 +1745,7 @@
      * @return a ProcessRaResult enum describing what action was performed.
      */
     @VisibleForTesting
-    synchronized ProcessRaResult processRa(byte[] packet, int length) {
+    public synchronized ProcessRaResult processRa(byte[] packet, int length) {
         if (VDBG) hexDump("Read packet = ", packet, length);
 
         // Have we seen this RA before?
@@ -1951,6 +1966,11 @@
                 mLastInstalledProgram.length, currentTimeSeconds() - mLastTimeInstalledProgram,
                 mLastInstalledProgramMinLifetime));
 
+        pw.print("Denylisted Ethertypes:");
+        for (int p : mEthTypeBlackList) {
+            pw.print(String.format(" %04x", p));
+        }
+        pw.println();
         pw.println("RA filters:");
         pw.increaseIndent();
         for (Ra ra: mRas) {
diff --git a/src/android/net/apf/ApfGenerator.java b/src/android/net/apf/ApfGenerator.java
index bf4d910..db51186 100644
--- a/src/android/net/apf/ApfGenerator.java
+++ b/src/android/net/apf/ApfGenerator.java
@@ -16,6 +16,8 @@
 
 package android.net.apf;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 
@@ -372,7 +374,8 @@
      * {@code version} of the APF interpreter. Throws {@code IllegalInstructionException} if
      * the requested version is unsupported.
      */
-    ApfGenerator(int version) throws IllegalInstructionException {
+    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+    public ApfGenerator(int version) throws IllegalInstructionException {
         mVersion = version;
         requireApfVersion(MIN_APF_VERSION);
     }
diff --git a/src/android/net/dhcp/DhcpClient.java b/src/android/net/dhcp/DhcpClient.java
index 34c37a2..8f59839 100644
--- a/src/android/net/dhcp/DhcpClient.java
+++ b/src/android/net/dhcp/DhcpClient.java
@@ -31,12 +31,6 @@
 import static android.net.dhcp.DhcpPacket.INADDR_ANY;
 import static android.net.dhcp.DhcpPacket.INADDR_BROADCAST;
 import static android.net.dhcp.DhcpPacket.INFINITE_LEASE;
-import static android.net.util.NetworkStackUtils.DHCP_INIT_REBOOT_VERSION;
-import static android.net.util.NetworkStackUtils.DHCP_IPV6_ONLY_PREFERRED_VERSION;
-import static android.net.util.NetworkStackUtils.DHCP_IP_CONFLICT_DETECT_VERSION;
-import static android.net.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
-import static android.net.util.NetworkStackUtils.DHCP_SLOW_RETRANSMISSION_VERSION;
-import static android.net.util.NetworkStackUtils.closeSocketQuietly;
 import static android.net.util.SocketUtils.makePacketSocketAddress;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 import static android.system.OsConstants.AF_INET;
@@ -57,6 +51,13 @@
 import static com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_ANY;
 import static com.android.net.module.util.NetworkStackConstants.IPV4_CONFLICT_ANNOUNCE_NUM;
 import static com.android.net.module.util.NetworkStackConstants.IPV4_CONFLICT_PROBE_NUM;
+import static com.android.net.module.util.SocketUtils.closeSocketQuietly;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_DISABLE_DROP_MF;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_INIT_REBOOT_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_IPV6_ONLY_PREFERRED_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_IP_CONFLICT_DETECT_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_SLOW_RETRANSMISSION_VERSION;
 
 import android.content.Context;
 import android.net.DhcpResults;
@@ -74,7 +75,6 @@
 import android.net.metrics.IpConnectivityLog;
 import android.net.networkstack.aidl.dhcp.DhcpOption;
 import android.net.util.HostnameTransliterator;
-import android.net.util.NetworkStackUtils;
 import android.net.util.SocketUtils;
 import android.os.Build;
 import android.os.Handler;
@@ -108,6 +108,7 @@
 import com.android.networkstack.apishim.common.ShimUtils;
 import com.android.networkstack.arp.ArpPacket;
 import com.android.networkstack.metrics.IpProvisioningMetrics;
+import com.android.networkstack.util.NetworkStackUtils;
 
 import java.io.ByteArrayOutputStream;
 import java.io.FileDescriptor;
@@ -692,9 +693,11 @@
 
         @Override
         protected FileDescriptor createFd() {
+            boolean dropMF = !DeviceConfigUtils.getDeviceConfigPropertyBoolean(
+                    NAMESPACE_CONNECTIVITY, DHCP_DISABLE_DROP_MF, false);
             try {
                 mPacketSock = Os.socket(AF_PACKET, SOCK_RAW | SOCK_NONBLOCK, 0 /* protocol */);
-                NetworkStackUtils.attachDhcpFilter(mPacketSock);
+                NetworkStackUtils.attachDhcpFilter(mPacketSock, dropMF);
                 final SocketAddress addr = makePacketSocketAddress(ETH_P_IP, mIface.index);
                 Os.bind(mPacketSock, addr);
             } catch (SocketException | ErrnoException e) {
diff --git a/src/android/net/dhcp/DhcpLease.java b/src/android/net/dhcp/DhcpLease.java
index 0b9cd7c..d440c42 100644
--- a/src/android/net/dhcp/DhcpLease.java
+++ b/src/android/net/dhcp/DhcpLease.java
@@ -142,7 +142,8 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mClientId, mHwAddr, mNetAddr, mPrefixLength, mHostname, mExpTime);
+        return Objects.hash(Arrays.hashCode(mClientId), mHwAddr, mNetAddr, mPrefixLength,
+                mHostname, mExpTime);
     }
 
     static String clientIdToString(byte[] bytes) {
diff --git a/src/android/net/dhcp/DhcpServer.java b/src/android/net/dhcp/DhcpServer.java
index c700453..3325e74 100644
--- a/src/android/net/dhcp/DhcpServer.java
+++ b/src/android/net/dhcp/DhcpServer.java
@@ -23,7 +23,6 @@
 import static android.net.dhcp.IDhcpServer.STATUS_INVALID_ARGUMENT;
 import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
 import static android.net.dhcp.IDhcpServer.STATUS_UNKNOWN_ERROR;
-import static android.net.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.IPPROTO_UDP;
@@ -39,6 +38,7 @@
 import static com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_ALL;
 import static com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_ANY;
 import static com.android.net.module.util.NetworkStackConstants.TAG_SYSTEM_DHCP_SERVER;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
 import static com.android.server.util.PermissionUtil.enforceNetworkStackCallingPermission;
 
 import static java.lang.Integer.toUnsignedLong;
@@ -48,7 +48,6 @@
 import android.net.IpPrefix;
 import android.net.MacAddress;
 import android.net.TrafficStats;
-import android.net.util.NetworkStackUtils;
 import android.net.util.SocketUtils;
 import android.os.Handler;
 import android.os.Message;
@@ -68,6 +67,7 @@
 import com.android.internal.util.StateMachine;
 import com.android.net.module.util.DeviceConfigUtils;
 import com.android.net.module.util.SharedLog;
+import com.android.networkstack.util.NetworkStackUtils;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
diff --git a/src/android/net/ip/ConnectivityPacketTracker.java b/src/android/net/ip/ConnectivityPacketTracker.java
index a905315..4b92179 100644
--- a/src/android/net/ip/ConnectivityPacketTracker.java
+++ b/src/android/net/ip/ConnectivityPacketTracker.java
@@ -24,7 +24,6 @@
 import static android.system.OsConstants.SOCK_RAW;
 
 import android.net.util.ConnectivityPacketSummary;
-import android.net.util.NetworkStackUtils;
 import android.os.Handler;
 import android.os.SystemClock;
 import android.system.ErrnoException;
@@ -37,6 +36,7 @@
 import com.android.internal.util.TokenBucket;
 import com.android.net.module.util.InterfaceParams;
 import com.android.net.module.util.PacketReader;
+import com.android.networkstack.util.NetworkStackUtils;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
diff --git a/src/android/net/ip/IpClient.java b/src/android/net/ip/IpClient.java
index ea45851..fa03e08 100644
--- a/src/android/net/ip/IpClient.java
+++ b/src/android/net/ip/IpClient.java
@@ -23,9 +23,6 @@
 import static android.net.ip.IIpClient.PROV_IPV6_LINKLOCAL;
 import static android.net.ip.IpReachabilityMonitor.INVALID_REACHABILITY_LOSS_TYPE;
 import static android.net.ip.IpReachabilityMonitor.nudEventTypeToInt;
-import static android.net.util.NetworkStackUtils.IPCLIENT_DISABLE_ACCEPT_RA_VERSION;
-import static android.net.util.NetworkStackUtils.IPCLIENT_GARP_NA_ROAMING_VERSION;
-import static android.net.util.NetworkStackUtils.IPCLIENT_GRATUITOUS_NA_VERSION;
 import static android.net.util.SocketUtils.makePacketSocketAddress;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 import static android.system.OsConstants.AF_PACKET;
@@ -38,6 +35,10 @@
 import static com.android.net.module.util.NetworkStackConstants.ETHER_BROADCAST;
 import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_ALL_ROUTERS_MULTICAST;
 import static com.android.net.module.util.NetworkStackConstants.VENDOR_SPECIFIC_IE_ID;
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_DISABLE_ACCEPT_RA_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_GARP_NA_ROAMING_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_GRATUITOUS_NA_VERSION;
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_MULTICAST_NS_VERSION;
 import static com.android.server.util.PermissionUtil.enforceNetworkStackCallingPermission;
 
 import android.annotation.SuppressLint;
@@ -73,7 +74,6 @@
 import android.net.shared.ProvisioningConfiguration;
 import android.net.shared.ProvisioningConfiguration.ScanResultInfo;
 import android.net.shared.ProvisioningConfiguration.ScanResultInfo.InformationElement;
-import android.net.util.NetworkStackUtils;
 import android.os.Build;
 import android.os.ConditionVariable;
 import android.os.Handler;
@@ -107,6 +107,7 @@
 import com.android.net.module.util.DeviceConfigUtils;
 import com.android.net.module.util.InterfaceParams;
 import com.android.net.module.util.SharedLog;
+import com.android.net.module.util.SocketUtils;
 import com.android.net.module.util.ip.InterfaceController;
 import com.android.networkstack.R;
 import com.android.networkstack.apishim.NetworkInformationShimImpl;
@@ -117,6 +118,8 @@
 import com.android.networkstack.metrics.IpProvisioningMetrics;
 import com.android.networkstack.metrics.NetworkQuirkMetrics;
 import com.android.networkstack.packets.NeighborAdvertisement;
+import com.android.networkstack.packets.NeighborSolicitation;
+import com.android.networkstack.util.NetworkStackUtils;
 import com.android.server.NetworkObserverRegistry;
 import com.android.server.NetworkStackService.NetworkStackServiceManager;
 
@@ -455,7 +458,7 @@
     private static final int CMD_START                            = 3;
     private static final int CMD_CONFIRM                          = 4;
     private static final int EVENT_PRE_DHCP_ACTION_COMPLETE       = 5;
-    // Triggered by NetlinkTracker to communicate netlink events.
+    // Triggered by IpClientLinkObserver to communicate netlink events.
     private static final int EVENT_NETLINK_LINKPROPERTIES_CHANGED = 6;
     private static final int CMD_UPDATE_TCP_BUFFER_SIZES          = 7;
     private static final int CMD_UPDATE_HTTP_PROXY                = 8;
@@ -507,18 +510,17 @@
 
     // Specific vendor OUI(3 bytes)/vendor specific type(1 byte) pattern for upstream hotspot
     // device detection. Add new byte array pattern below in turn.
-    private static final List<byte[]> METERED_IE_PATTERN_LIST = Collections.unmodifiableList(
-            Arrays.asList(
-                    new byte[] { (byte) 0x00, (byte) 0x17, (byte) 0xf2, (byte) 0x06 }
-    ));
+    private static final List<byte[]> METERED_IE_PATTERN_LIST = Collections.singletonList(
+            new byte[] { (byte) 0x00, (byte) 0x17, (byte) 0xf2, (byte) 0x06 }
+    );
 
     // Allows Wi-Fi to pass in DHCP options when particular vendor-specific IEs are present.
     // Maps each DHCP option code to a list of IEs, any of which will allow that option.
     private static final Map<Byte, List<byte[]>> DHCP_OPTIONS_ALLOWED = Map.of(
-            (byte) 60, Arrays.asList(
+            (byte) 60, Collections.singletonList(
                     // KT OUI: 00:17:C3, type: 17. See b/170928882.
                     new byte[]{ (byte) 0x00, (byte) 0x17, (byte) 0xc3, (byte) 0x11 }),
-            (byte) 77, Arrays.asList(
+            (byte) 77, Collections.singletonList(
                     // KT OUI: 00:17:C3, type: 17. See b/170928882.
                     new byte[]{ (byte) 0x00, (byte) 0x17, (byte) 0xc3, (byte) 0x11 })
     );
@@ -558,6 +560,8 @@
     private final InterfaceController mInterfaceCtrl;
     // Set of IPv6 addresses for which unsolicited gratuitous NA packets have been sent.
     private final Set<Inet6Address> mGratuitousNaTargetAddresses = new HashSet<>();
+    // Set of IPv6 addresses from which multicast NS packets have been sent.
+    private final Set<Inet6Address> mMulticastNsSourceAddresses = new HashSet<>();
 
     // Ignore nonzero RDNSS option lifetimes below this value. 0 = disabled.
     private final int mMinRdnssLifetimeSec;
@@ -581,6 +585,7 @@
     private long mStartTimeMillis;
     private MacAddress mCurrentBssid;
     private boolean mHasDisabledIpv6OrAcceptRaOnProvLoss;
+    private Integer mDadTransmits = null;
 
     /**
      * Reading the snapshot is an asynchronous operation initiated by invoking
@@ -697,7 +702,7 @@
     }
 
     @VisibleForTesting
-    IpClient(Context context, String ifName, IIpClientCallbacks callback,
+    public IpClient(Context context, String ifName, IIpClientCallbacks callback,
             NetworkObserverRegistry observerRegistry, NetworkStackServiceManager nssManager,
             Dependencies deps) {
         super(IpClient.class.getSimpleName() + "." + ifName);
@@ -746,15 +751,19 @@
                     }
 
                     @Override
-                    public void onIpv6AddressRemoved(final Inet6Address targetIp) {
-                        // The update of Gratuitous NA target addresses set should be only accessed
-                        // from the handler thread of IpClient StateMachine, keeping the behaviour
+                    public void onIpv6AddressRemoved(final Inet6Address address) {
+                        // The update of Gratuitous NA target addresses set or unsolicited
+                        // multicast NS source addresses set should be only accessed from the
+                        // handler thread of IpClient StateMachine, keeping the behaviour
                         // consistent with relying on the non-blocking NetworkObserver callbacks,
                         // see {@link registerObserverForNonblockingCallback}. This can be done
                         // by either sending a message to StateMachine or posting a handler.
+                        if (address.isLinkLocalAddress()) return;
                         getHandler().post(() -> {
-                            if (!mGratuitousNaTargetAddresses.contains(targetIp)) return;
-                            updateGratuitousNaTargetSet(targetIp, false /* remove address */);
+                            mLog.log("Remove IPv6 GUA " + address
+                                    + " from both Gratuituous NA and Multicast NS sets");
+                            mGratuitousNaTargetAddresses.remove(address);
+                            mMulticastNsSourceAddresses.remove(address);
                         });
                     }
 
@@ -923,6 +932,11 @@
                 false /* defaultEnabled */);
     }
 
+    private boolean isMulticastNsEnabled() {
+        return mDependencies.isFeatureEnabled(mContext, IPCLIENT_MULTICAST_NS_VERSION,
+                false /* defaultEnabled */);
+    }
+
     @VisibleForTesting
     static MacAddress getInitialBssid(final Layer2Information layer2Info,
             final ScanResultInfo scanResultInfo, boolean isAtLeastS) {
@@ -1322,6 +1336,25 @@
         }
     }
 
+    private Integer getIpv6DadTransmits() {
+        try {
+            return Integer.parseUnsignedInt(mNetd.getProcSysNet(INetd.IPV6, INetd.CONF,
+                    mInterfaceName, "dad_transmits"));
+        } catch (RemoteException | ServiceSpecificException e) {
+            logError("Couldn't read dad_transmits on " + mInterfaceName, e);
+            return null;
+        }
+    }
+
+    private void setIpv6DadTransmits(int dadTransmits) {
+        try {
+            mNetd.setProcSysNet(INetd.IPV6, INetd.CONF, mInterfaceParams.name,
+                    "dad_transmits", Integer.toString(dadTransmits));
+        } catch (Exception e) {
+            Log.e(mTag, "Failed to set dad_transmits to " + dadTransmits + ": " + e);
+        }
+    }
+
     private void restartIpv6WithAcceptRaDisabled() {
         mInterfaceCtrl.disableIPv6();
         startIPv6(0 /* acceptRa */);
@@ -1607,7 +1640,7 @@
         } catch (SocketException | ErrnoException e) {
             logError(msg, e);
         } finally {
-            NetworkStackUtils.closeSocketQuietly(sock);
+            SocketUtils.closeSocketQuietly(sock);
         }
     }
 
@@ -1637,6 +1670,22 @@
         transmitPacket(packet, sockAddress, "Failed to send GARP");
     }
 
+    private void sendMulticastNs(final Inet6Address srcIp, final Inet6Address dstIp,
+            final Inet6Address targetIp) {
+        final MacAddress dstMac = NetworkStackUtils.ipv6MulticastToEthernetMulticast(dstIp);
+        final ByteBuffer packet = NeighborSolicitation.build(mInterfaceParams.macAddr, dstMac,
+                srcIp, dstIp, targetIp);
+        final SocketAddress sockAddress =
+                SocketUtilsShimImpl.newInstance().makePacketSocketAddress(ETH_P_IPV6,
+                        mInterfaceParams.index, dstMac.toByteArray());
+
+        if (DBG) {
+            mLog.log("send multicast NS from " + srcIp.getHostAddress() + " to "
+                    + dstIp.getHostAddress() + " , target IP: " + targetIp.getHostAddress());
+        }
+        transmitPacket(packet, sockAddress, "Failed to send multicast Neighbor Solicitation");
+    }
+
     @Nullable
     private static Inet6Address getIpv6LinkLocalAddress(final LinkProperties newLp) {
         for (LinkAddress la : newLp.getLinkAddresses()) {
@@ -1647,16 +1696,6 @@
         return null;
     }
 
-    private void updateGratuitousNaTargetSet(@NonNull final Inet6Address targetIp, boolean add) {
-        if (add) {
-            mGratuitousNaTargetAddresses.add(targetIp);
-        } else {
-            mGratuitousNaTargetAddresses.remove(targetIp);
-        }
-        mLog.log((add ? "Add" : "Remove") + " global IPv6 address " + targetIp
-                + (add ? " to" : " from") + " the set of gratuitous NA target address.");
-    }
-
     private void maybeSendGratuitousNAs(final LinkProperties lp, boolean afterRoaming) {
         if (!lp.hasGlobalIpv6Address()) return;
 
@@ -1666,7 +1705,7 @@
         // TODO: add experiment with sending only one gratuitous NA packet instead of one
         // packet per address.
         for (LinkAddress la : lp.getLinkAddresses()) {
-            if (!la.isIpv6() || !la.isGlobalPreferred()) continue;
+            if (!NetworkStackUtils.isIPv6GUA(la)) continue;
             final Inet6Address targetIp = (Inet6Address) la.getAddress();
             // Already sent gratuitous NA with this target global IPv6 address. But for
             // the L2 roaming case, device should always (re)transmit Gratuitous NA for
@@ -1677,7 +1716,9 @@
                         + targetIp.getHostAddress() + (afterRoaming ? " after roaming" : ""));
             }
             sendGratuitousNA(srcIp, targetIp);
-            if (!afterRoaming) updateGratuitousNaTargetSet(targetIp, true /* add address */);
+            if (!afterRoaming) {
+                mGratuitousNaTargetAddresses.add(targetIp);
+            }
         }
     }
 
@@ -1694,6 +1735,39 @@
         }
     }
 
+    @Nullable
+    private static Inet6Address getIPv6DefaultGateway(final LinkProperties lp) {
+        for (RouteInfo r : lp.getRoutes()) {
+            // TODO: call {@link RouteInfo#isIPv6Default} directly after core networking modules
+            // are consolidated.
+            if (r.getType() == RTN_UNICAST && r.getDestination().getPrefixLength() == 0
+                    && r.getDestination().getAddress() instanceof Inet6Address) {
+                // Check if it's IPv6 default route, if yes, return the gateway address
+                // (i.e. default router's IPv6 link-local address)
+                return (Inet6Address) r.getGateway();
+            }
+        }
+        return null;
+    }
+
+    private void maybeSendMulticastNSes(final LinkProperties lp) {
+        if (!(lp.hasGlobalIpv6Address() && lp.hasIpv6DefaultRoute())) return;
+
+        // Get the default router's IPv6 link-local address.
+        final Inet6Address targetIp = getIPv6DefaultGateway(lp);
+        if (targetIp == null) return;
+        final Inet6Address dstIp = NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(targetIp);
+        if (dstIp == null) return;
+
+        for (LinkAddress la : lp.getLinkAddresses()) {
+            if (!NetworkStackUtils.isIPv6GUA(la)) continue;
+            final Inet6Address srcIp = (Inet6Address) la.getAddress();
+            if (mMulticastNsSourceAddresses.contains(srcIp)) continue;
+            sendMulticastNs(srcIp, dstIp, targetIp);
+            mMulticastNsSourceAddresses.add(srcIp);
+        }
+    }
+
     // Returns false if we have lost provisioning, true otherwise.
     private boolean handleLinkPropertiesUpdate(boolean sendCallbacks) {
         final LinkProperties newLp = assembleLinkProperties();
@@ -1708,6 +1782,17 @@
             maybeSendGratuitousNAs(newLp, false /* isGratuitousNaAfterRoaming */);
         }
 
+        // Sending multicast NS from each new assigned IPv6 GUAs to the solicited-node multicast
+        // address based on the default router's IPv6 link-local address should trigger default
+        // router response with NA, and update the neighbor cache entry immediately, that would
+        // help speed up the connection to an IPv6-only network.
+        //
+        // TODO: stop sending this multicast NS after deployment of RFC9131 in the field, leverage
+        // the gratuitous NA to update the first-hop router's neighbor cache entry.
+        if (isMulticastNsEnabled()) {
+            maybeSendMulticastNSes(newLp);
+        }
+
         // Either success IPv4 or IPv6 provisioning triggers new LinkProperties update,
         // wait for the provisioning completion and record the latency.
         mIpProvisioningMetrics.setIPv4ProvisionedLatencyOnFirstTime(newLp.isIpv4Provisioned());
@@ -1862,8 +1947,22 @@
         return true;
     }
 
+    private boolean shouldDisableDad() {
+        return mConfiguration.mUniqueEui64AddressesOnly
+                && mConfiguration.mIPv6ProvisioningMode == PROV_IPV6_LINKLOCAL
+                && mConfiguration.mIPv6AddrGenMode
+                        == ProvisioningConfiguration.IPV6_ADDR_GEN_MODE_EUI64;
+    }
+
     private boolean startIPv6(int acceptRa) {
         setIpv6AcceptRa(acceptRa);
+        if (shouldDisableDad()) {
+            final Integer dadTransmits = getIpv6DadTransmits();
+            if (dadTransmits != null) {
+                mDadTransmits = dadTransmits;
+                setIpv6DadTransmits(0 /* dad_transmits */);
+            }
+        }
         return mInterfaceCtrl.setIPv6PrivacyExtensions(true)
                 && mInterfaceCtrl.setIPv6AddrGenModeIfSupported(mConfiguration.mIPv6AddrGenMode)
                 && mInterfaceCtrl.enableIPv6();
@@ -1955,6 +2054,13 @@
         }
     }
 
+    private void maybeRestoreDadTransmits() {
+        if (mDadTransmits == null) return;
+
+        setIpv6DadTransmits(mDadTransmits);
+        mDadTransmits = null;
+    }
+
     private void handleUpdateL2Information(@NonNull Layer2InformationParcelable info) {
         mL2Key = info.l2Key;
         mCluster = info.cluster;
@@ -2008,6 +2114,7 @@
             stopAllIP();
             mHasDisabledIpv6OrAcceptRaOnProvLoss = false;
             mGratuitousNaTargetAddresses.clear();
+            mMulticastNsSourceAddresses.clear();
 
             resetLinkProperties();
             if (mStartTimeMillis > 0) {
@@ -2087,6 +2194,8 @@
 
             // Restore the interface MTU to initial value if it has changed.
             maybeRestoreInterfaceMtu();
+            // Reset number of dad_transmits to default value if changed.
+            maybeRestoreDadTransmits();
         }
 
         @Override
diff --git a/src/android/net/ip/IpClientLinkObserver.java b/src/android/net/ip/IpClientLinkObserver.java
index 56c5293..0771bff 100644
--- a/src/android/net/ip/IpClientLinkObserver.java
+++ b/src/android/net/ip/IpClientLinkObserver.java
@@ -16,7 +16,6 @@
 
 package android.net.ip;
 
-import static android.net.util.NetworkStackUtils.IPCLIENT_PARSE_NETLINK_EVENTS_VERSION;
 import static android.system.OsConstants.AF_INET6;
 import static android.system.OsConstants.AF_UNSPEC;
 import static android.system.OsConstants.IFF_LOOPBACK;
@@ -29,6 +28,7 @@
 import static com.android.net.module.util.netlink.NetlinkConstants.RTPROT_KERNEL;
 import static com.android.net.module.util.netlink.NetlinkConstants.RTPROT_RA;
 import static com.android.net.module.util.netlink.NetlinkConstants.RT_SCOPE_UNIVERSE;
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_PARSE_NETLINK_EVENTS_VERSION;
 
 import android.app.AlarmManager;
 import android.content.Context;
@@ -45,6 +45,7 @@
 import androidx.annotation.Nullable;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.net.module.util.HexDump;
 import com.android.net.module.util.InterfaceParams;
 import com.android.net.module.util.SharedLog;
 import com.android.net.module.util.ip.NetlinkMonitor;
@@ -156,6 +157,7 @@
     private final IpClient.Dependencies mDependencies;
     private final String mClatInterfaceName;
     private final MyNetlinkMonitor mNetlinkMonitor;
+    private final boolean mNetlinkEventParsingEnabled;
 
     private boolean mClatInterfaceExists;
 
@@ -176,7 +178,7 @@
         mContext = context;
         mInterfaceName = iface;
         mClatInterfaceName = CLAT_PREFIX + iface;
-        mTag = "NetlinkTracker/" + mInterfaceName;
+        mTag = "IpClient/" + mInterfaceName;
         mCallback = callback;
         mLinkProperties = new LinkProperties();
         mLinkProperties.setInterfaceName(mInterfaceName);
@@ -186,6 +188,8 @@
         mDnsServerRepository = new DnsServerRepository(config.minRdnssLifetime);
         mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         mDependencies = deps;
+        mNetlinkEventParsingEnabled = deps.isFeatureEnabled(context,
+                IPCLIENT_PARSE_NETLINK_EVENTS_VERSION, isAtLeastT() /* default value */);
         mNetlinkMonitor = new MyNetlinkMonitor(h, log, mTag);
         mHandler.post(() -> {
             if (!mNetlinkMonitor.start()) {
@@ -201,7 +205,8 @@
     private void maybeLog(String operation, String iface, LinkAddress address) {
         if (DBG) {
             Log.d(mTag, operation + ": " + address + " on " + iface
-                    + " flags " + address.getFlags() + " scope " + address.getScope());
+                    + " flags " + "0x" + HexDump.toHexString(address.getFlags())
+                    + " scope " + address.getScope());
         }
     }
 
@@ -215,11 +220,6 @@
         }
     }
 
-    private boolean isNetlinkEventParsingEnabled() {
-        return mDependencies.isFeatureEnabled(mContext, IPCLIENT_PARSE_NETLINK_EVENTS_VERSION,
-                isAtLeastT() /* default value */);
-    }
-
     private int getSocketReceiveBufferSize() {
         final int size = mDependencies.getDeviceConfigPropertyInt(CONFIG_SOCKET_RECV_BUFSIZE,
                 SOCKET_RECV_BUFSIZE /* default value */);
@@ -231,7 +231,7 @@
 
     @Override
     public void onInterfaceAdded(String iface) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         maybeLog("interfaceAdded", iface);
         if (mClatInterfaceName.equals(iface)) {
             mCallback.onClatInterfaceStateUpdate(true /* add interface */);
@@ -240,7 +240,7 @@
 
     @Override
     public void onInterfaceRemoved(String iface) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         maybeLog("interfaceRemoved", iface);
         if (mClatInterfaceName.equals(iface)) {
             mCallback.onClatInterfaceStateUpdate(false /* remove interface */);
@@ -251,7 +251,7 @@
 
     @Override
     public void onInterfaceLinkStateChanged(String iface, boolean state) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(iface)) return;
         maybeLog("interfaceLinkStateChanged", iface + (state ? " up" : " down"));
         updateInterfaceLinkStateChanged(state);
@@ -259,7 +259,7 @@
 
     @Override
     public void onInterfaceAddressUpdated(LinkAddress address, String iface) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(iface)) return;
         maybeLog("addressUpdated", iface, address);
         updateInterfaceAddress(address, true /* add address */);
@@ -267,7 +267,7 @@
 
     @Override
     public void onInterfaceAddressRemoved(LinkAddress address, String iface) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(iface)) return;
         maybeLog("addressRemoved", iface, address);
         updateInterfaceAddress(address, false /* remove address */);
@@ -275,7 +275,7 @@
 
     @Override
     public void onRouteUpdated(RouteInfo route) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(route.getInterface())) return;
         maybeLog("routeUpdated", route);
         updateInterfaceRoute(route, true /* add route */);
@@ -283,7 +283,7 @@
 
     @Override
     public void onRouteRemoved(RouteInfo route) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(route.getInterface())) return;
         maybeLog("routeRemoved", route);
         updateInterfaceRoute(route, false /* remove route */);
@@ -291,7 +291,7 @@
 
     @Override
     public void onInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
-        if (isNetlinkEventParsingEnabled()) return;
+        if (mNetlinkEventParsingEnabled) return;
         if (!mInterfaceName.equals(iface)) return;
         updateInterfaceDnsServerInfo(lifetime, addresses);
     }
@@ -423,7 +423,7 @@
 
         MyNetlinkMonitor(Handler h, SharedLog log, String tag) {
             super(h, log, tag, OsConstants.NETLINK_ROUTE,
-                    !isNetlinkEventParsingEnabled()
+                    !mNetlinkEventParsingEnabled
                         ? NetlinkConstants.RTMGRP_ND_USEROPT
                         : (NetlinkConstants.RTMGRP_ND_USEROPT | NetlinkConstants.RTMGRP_LINK
                                 | NetlinkConstants.RTMGRP_IPV4_IFADDR
@@ -536,7 +536,7 @@
         }
 
         private void processRdnssOption(StructNdOptRdnss opt) {
-            if (!isNetlinkEventParsingEnabled()) return;
+            if (!mNetlinkEventParsingEnabled) return;
             final String[] addresses = new String[opt.servers.length];
             for (int i = 0; i < opt.servers.length; i++) {
                 addresses[i] = opt.servers[i].getHostAddress();
@@ -587,7 +587,7 @@
         }
 
         private void processRtNetlinkLinkMessage(RtNetlinkLinkMessage msg) {
-            if (!isNetlinkEventParsingEnabled()) return;
+            if (!mNetlinkEventParsingEnabled) return;
 
             // Check if receiving netlink link state update for clat interface.
             final String ifname = msg.getInterfaceName();
@@ -621,7 +621,7 @@
         }
 
         private void processRtNetlinkAddressMessage(RtNetlinkAddressMessage msg) {
-            if (!isNetlinkEventParsingEnabled()) return;
+            if (!mNetlinkEventParsingEnabled) return;
 
             final StructIfaddrMsg ifaddrMsg = msg.getIfaddrHeader();
             if (ifaddrMsg.index != mIfindex) return;
@@ -646,7 +646,7 @@
         }
 
         private void processRtNetlinkRouteMessage(RtNetlinkRouteMessage msg) {
-            if (!isNetlinkEventParsingEnabled()) return;
+            if (!mNetlinkEventParsingEnabled) return;
             if (msg.getInterfaceIndex() != mIfindex) return;
             // Ignore the unsupported route protocol and non-global unicast routes.
             if (!isSupportedRouteProtocol(msg)
diff --git a/src/android/net/ip/IpReachabilityMonitor.java b/src/android/net/ip/IpReachabilityMonitor.java
index 82eb074..d16840d 100644
--- a/src/android/net/ip/IpReachabilityMonitor.java
+++ b/src/android/net/ip/IpReachabilityMonitor.java
@@ -20,9 +20,10 @@
 import static android.net.metrics.IpReachabilityEvent.NUD_FAILED_ORGANIC;
 import static android.net.metrics.IpReachabilityEvent.PROVISIONING_LOST;
 import static android.net.metrics.IpReachabilityEvent.PROVISIONING_LOST_ORGANIC;
-import static android.net.util.NetworkStackUtils.IP_REACHABILITY_MCAST_RESOLICIT_VERSION;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 
+import static com.android.networkstack.util.NetworkStackUtils.IP_REACHABILITY_MCAST_RESOLICIT_VERSION;
+
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.INetd;
@@ -175,7 +176,8 @@
      * Encapsulates IpReachabilityMonitor dependencies on systems that hinder unit testing.
      * TODO: consider also wrapping MultinetworkPolicyTracker in this interface.
      */
-    interface Dependencies {
+    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+    public interface Dependencies {
         void acquireWakeLock(long durationMs);
         IpNeighborMonitor makeIpNeighborMonitor(Handler h, SharedLog log, NeighborEventConsumer cb);
         boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled);
@@ -230,6 +232,7 @@
     private int mInterSolicitIntervalMs;
     @NonNull
     private final Callback mCallback;
+    private final boolean mMulticastResolicitEnabled;
 
     public IpReachabilityMonitor(
             Context context, InterfaceParams ifParams, Handler h, SharedLog log, Callback callback,
@@ -239,9 +242,9 @@
     }
 
     @VisibleForTesting
-    IpReachabilityMonitor(Context context, InterfaceParams ifParams, Handler h, SharedLog log,
-            Callback callback, boolean usingMultinetworkPolicyTracker, Dependencies dependencies,
-            final IpConnectivityLog metricsLog, final INetd netd) {
+    public IpReachabilityMonitor(Context context, InterfaceParams ifParams, Handler h,
+            SharedLog log, Callback callback, boolean usingMultinetworkPolicyTracker,
+            Dependencies dependencies, final IpConnectivityLog metricsLog, final INetd netd) {
         if (ifParams == null) throw new IllegalArgumentException("null InterfaceParams");
 
         mContext = context;
@@ -251,6 +254,8 @@
         mUsingMultinetworkPolicyTracker = usingMultinetworkPolicyTracker;
         mCm = context.getSystemService(ConnectivityManager.class);
         mDependencies = dependencies;
+        mMulticastResolicitEnabled = dependencies.isFeatureEnabled(context,
+                IP_REACHABILITY_MCAST_RESOLICIT_VERSION, false /* defaultEnabled */);
         mMetricsLog = metricsLog;
         mNetd = netd;
         Preconditions.checkNotNull(mNetd);
@@ -259,7 +264,7 @@
         // In case the overylaid parameters specify an invalid configuration, set the parameters
         // to the hardcoded defaults first, then set them to the values used in the steady state.
         try {
-            int numResolicits = isMulticastResolicitEnabled()
+            int numResolicits = mMulticastResolicitEnabled
                     ? NUD_MCAST_RESOLICIT_NUM
                     : INVALID_NUD_MCAST_RESOLICIT_NUM;
             setNeighborParameters(MIN_NUD_SOLICIT_NUM, MIN_NUD_SOLICIT_INTERVAL_MS, numResolicits);
@@ -268,7 +273,7 @@
         }
         setNeighbourParametersForSteadyState();
 
-        mIpNeighborMonitor = mDependencies.makeIpNeighborMonitor(h, mLog,
+        mIpNeighborMonitor = dependencies.makeIpNeighborMonitor(h, mLog,
                 (NeighborEvent event) -> {
                     if (mInterfaceParams.index != event.ifindex) return;
                     if (!mNeighborWatchList.containsKey(event.ip)) return;
@@ -360,11 +365,6 @@
         return false;
     }
 
-    private boolean isMulticastResolicitEnabled() {
-        return mDependencies.isFeatureEnabled(mContext, IP_REACHABILITY_MCAST_RESOLICIT_VERSION,
-                false /* defaultEnabled */);
-    }
-
     public void updateLinkProperties(LinkProperties lp) {
         if (!mInterfaceParams.name.equals(lp.getInterfaceName())) {
             // TODO: figure out whether / how to cope with interface changes.
@@ -404,7 +404,7 @@
 
     private void handleNeighborReachable(@Nullable final NeighborEvent prev,
             @NonNull final NeighborEvent event) {
-        if (isMulticastResolicitEnabled()
+        if (mMulticastResolicitEnabled
                 && hasDefaultRouterNeighborMacAddressChanged(prev, event)) {
             // This implies device has confirmed the neighbor's reachability from
             // other states(e.g., NUD_PROBE or NUD_STALE), checking if the mac
@@ -527,7 +527,7 @@
     private long getProbeWakeLockDuration() {
         final long gracePeriodMs = 500;
         final int numSolicits =
-                mNumSolicits + (isMulticastResolicitEnabled() ? NUD_MCAST_RESOLICIT_NUM : 0);
+                mNumSolicits + (mMulticastResolicitEnabled ? NUD_MCAST_RESOLICIT_NUM : 0);
         return (long) (numSolicits * mInterSolicitIntervalMs) + gracePeriodMs;
     }
 
diff --git a/src/android/net/util/DataStallUtils.java b/src/android/net/util/DataStallUtils.java
index 4b25967..c005e7d 100644
--- a/src/android/net/util/DataStallUtils.java
+++ b/src/android/net/util/DataStallUtils.java
@@ -116,13 +116,6 @@
      */
     public static final String CONFIG_TCP_PACKETS_FAIL_PERCENTAGE = "tcp_packets_fail_percentage";
 
-    /** Corresponds to enum from bionic/libc/include/netinet/tcp.h. */
-    public static final int TCP_ESTABLISHED = 1;
-    public static final int TCP_SYN_SENT = 2;
-    public static final int TCP_SYN_RECV = 3;
-    public static final int TCP_MONITOR_STATE_FILTER =
-            (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
-
     /**
      * Threshold for the minimal tcp packets count to evaluate data stall via tcp info.
      */
diff --git a/src/com/android/server/TestNetworkStackService.java b/src/com/android/networkstack/TestNetworkStackService.java
similarity index 93%
rename from src/com/android/server/TestNetworkStackService.java
rename to src/com/android/networkstack/TestNetworkStackService.java
index 23981e5..f34300d 100644
--- a/src/com/android/server/TestNetworkStackService.java
+++ b/src/com/android/networkstack/TestNetworkStackService.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server;
+package com.android.networkstack;
 
 import static com.android.server.util.PermissionUtil.isDebuggableBuild;
 
@@ -23,6 +23,8 @@
 
 import androidx.annotation.Nullable;
 
+import com.android.server.NetworkStackService;
+
 /**
  * A {@link NetworkStackService} that can only be bound to on debuggable builds.
  */
diff --git a/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreDatabase.java b/src/com/android/networkstack/ipmemorystore/IpMemoryStoreDatabase.java
similarity index 98%
rename from src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreDatabase.java
rename to src/com/android/networkstack/ipmemorystore/IpMemoryStoreDatabase.java
index f9b6365..9e7df82 100644
--- a/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreDatabase.java
+++ b/src/com/android/networkstack/ipmemorystore/IpMemoryStoreDatabase.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
 import static com.android.net.module.util.Inet4AddressUtils.inet4AddressToIntHTH;
 import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
@@ -60,7 +60,9 @@
     /**
      * Contract class for the Network Attributes table.
      */
-    public static class NetworkAttributesContract {
+    public static final class NetworkAttributesContract {
+        private NetworkAttributesContract() {}
+
         public static final String TABLENAME = "NetworkAttributes";
 
         public static final String COLNAME_L2KEY = "l2Key";
@@ -112,7 +114,9 @@
     /**
      * Contract class for the Private Data table.
      */
-    public static class PrivateDataContract {
+    public static final class PrivateDataContract {
+        private PrivateDataContract() {}
+
         public static final String TABLENAME = "PrivateData";
 
         public static final String COLNAME_L2KEY = "l2Key";
diff --git a/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreService.java b/src/com/android/networkstack/ipmemorystore/IpMemoryStoreService.java
similarity index 98%
rename from src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreService.java
rename to src/com/android/networkstack/ipmemorystore/IpMemoryStoreService.java
index ae9c875..aa7d698 100644
--- a/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreService.java
+++ b/src/com/android/networkstack/ipmemorystore/IpMemoryStoreService.java
@@ -14,15 +14,15 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
 import static android.net.ipmemorystore.Status.ERROR_DATABASE_CANNOT_BE_OPENED;
 import static android.net.ipmemorystore.Status.ERROR_GENERIC;
 import static android.net.ipmemorystore.Status.ERROR_ILLEGAL_ARGUMENT;
 import static android.net.ipmemorystore.Status.SUCCESS;
 
-import static com.android.server.connectivity.ipmemorystore.IpMemoryStoreDatabase.EXPIRY_ERROR;
-import static com.android.server.connectivity.ipmemorystore.RegularMaintenanceJobService.InterruptMaintenance;
+import static com.android.networkstack.ipmemorystore.IpMemoryStoreDatabase.EXPIRY_ERROR;
+import static com.android.networkstack.ipmemorystore.RegularMaintenanceJobService.InterruptMaintenance;
 
 import android.content.Context;
 import android.database.SQLException;
diff --git a/src/com/android/server/connectivity/ipmemorystore/RegularMaintenanceJobService.java b/src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobService.java
similarity index 86%
rename from src/com/android/server/connectivity/ipmemorystore/RegularMaintenanceJobService.java
rename to src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobService.java
index c8559c8..b413689 100644
--- a/src/com/android/server/connectivity/ipmemorystore/RegularMaintenanceJobService.java
+++ b/src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobService.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
 import android.app.job.JobInfo;
 import android.app.job.JobParameters;
@@ -29,6 +29,9 @@
 import android.os.RemoteException;
 import android.util.Log;
 
+import androidx.annotation.NonNull;
+import androidx.annotation.VisibleForTesting;
+
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.TimeUnit;
 
@@ -36,7 +39,7 @@
  * Regular maintenance job service.
  * @hide
  */
-public final class RegularMaintenanceJobService extends JobService {
+public class RegularMaintenanceJobService extends JobService {
     // Must be unique within the system server uid.
     public static final int REGULAR_MAINTENANCE_ID = 3345678;
 
@@ -88,7 +91,7 @@
                             + " Error is " + result.resultCode);
                 }
                 sInterruptList.remove(im);
-                jobFinished(params, !result.isSuccess());
+                callJobFinished(params, !result.isSuccess());
             }
 
             @Override
@@ -109,6 +112,15 @@
         return true;
     }
 
+    // Unfortunately jobFinished is final in JobService and sends a message through a maze
+    // of messengers and callbacks, all of which are private and/or final. Although this method
+    // represents a small change to the production code, it looks like a reasonably safe way
+    // to write some of the tests for this service.
+    @VisibleForTesting
+    protected void callJobFinished(@NonNull final JobParameters params, final boolean reschedule) {
+        jobFinished(params, reschedule);
+    }
+
     @Override
     public boolean onStopJob(JobParameters params) {
         final int jobId = params.getJobId();
diff --git a/src/com/android/server/connectivity/ipmemorystore/RelevanceUtils.java b/src/com/android/networkstack/ipmemorystore/RelevanceUtils.java
similarity index 98%
rename from src/com/android/server/connectivity/ipmemorystore/RelevanceUtils.java
rename to src/com/android/networkstack/ipmemorystore/RelevanceUtils.java
index 38d5544..b967c35 100644
--- a/src/com/android/server/connectivity/ipmemorystore/RelevanceUtils.java
+++ b/src/com/android/networkstack/ipmemorystore/RelevanceUtils.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
 import com.android.internal.annotations.VisibleForTesting;
 
@@ -24,7 +24,7 @@
  *
  * @hide
  */
-public class RelevanceUtils {
+public final class RelevanceUtils {
     /**
      * The relevance is a decaying value that gets lower and lower until it
      * reaches 0 after some time passes. It follows an exponential decay law,
@@ -304,4 +304,7 @@
         final long newDuration = bumpExpiryDuration(oldExpiryDate - now);
         return now + newDuration;
     }
+
+    // This utility class is not publicly instantiable.
+    private RelevanceUtils() {}
 }
diff --git a/src/com/android/server/connectivity/ipmemorystore/StatusAndCount.java b/src/com/android/networkstack/ipmemorystore/StatusAndCount.java
similarity index 93%
rename from src/com/android/server/connectivity/ipmemorystore/StatusAndCount.java
rename to src/com/android/networkstack/ipmemorystore/StatusAndCount.java
index 2cbe843..a6abdba 100644
--- a/src/com/android/server/connectivity/ipmemorystore/StatusAndCount.java
+++ b/src/com/android/networkstack/ipmemorystore/StatusAndCount.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
 /**
  * Small data class to wrap a Status and an int.
diff --git a/src/com/android/server/connectivity/ipmemorystore/Utils.java b/src/com/android/networkstack/ipmemorystore/Utils.java
similarity index 84%
rename from src/com/android/server/connectivity/ipmemorystore/Utils.java
rename to src/com/android/networkstack/ipmemorystore/Utils.java
index d8a46ed..bc57429 100644
--- a/src/com/android/server/connectivity/ipmemorystore/Utils.java
+++ b/src/com/android/networkstack/ipmemorystore/Utils.java
@@ -14,20 +14,13 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
-
-import android.net.ipmemorystore.Blob;
+package com.android.networkstack.ipmemorystore;
 
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
 /** {@hide} */
-public class Utils {
-    /** Pretty print */
-    public static String blobToString(@Nullable final Blob blob) {
-        return "Blob : " + byteArrayToString(null == blob ? null : blob.data);
-    }
-
+public final class Utils {
     /** Pretty print */
     public static String byteArrayToString(@Nullable final byte[] data) {
         if (null == data) return "null";
@@ -50,4 +43,7 @@
             sb.append(String.format("%02X", ar[i]));
         }
     }
+
+    // This class is not publicly instantiable.
+    private Utils() {}
 }
diff --git a/src/com/android/networkstack/metrics/DataStallDetectionStats.java b/src/com/android/networkstack/metrics/DataStallDetectionStats.java
index 751d98d..e13d2d4 100644
--- a/src/com/android/networkstack/metrics/DataStallDetectionStats.java
+++ b/src/com/android/networkstack/metrics/DataStallDetectionStats.java
@@ -157,8 +157,9 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mNetworkType, mEvaluationType, mWifiInfo, mCellularInfo, mDns,
-                mTcpFailRate, mTcpSentSinceLastRecv);
+        return Objects.hash(mNetworkType, mEvaluationType, Arrays.hashCode(mWifiInfo),
+                Arrays.hashCode(mCellularInfo), Arrays.hashCode(mDns), mTcpFailRate,
+                mTcpSentSinceLastRecv);
     }
 
     /**
diff --git a/src/com/android/networkstack/netlink/TcpSocketTracker.java b/src/com/android/networkstack/netlink/TcpSocketTracker.java
index 99d2c13..a3a58e6 100644
--- a/src/com/android/networkstack/netlink/TcpSocketTracker.java
+++ b/src/com/android/networkstack/netlink/TcpSocketTracker.java
@@ -19,35 +19,29 @@
 import static android.net.util.DataStallUtils.CONFIG_TCP_PACKETS_FAIL_PERCENTAGE;
 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_MIN_PACKETS_THRESHOLD;
 import static android.net.util.DataStallUtils.DEFAULT_TCP_PACKETS_FAIL_PERCENTAGE;
-import static android.net.util.DataStallUtils.TCP_MONITOR_STATE_FILTER;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.AF_INET6;
-import static android.system.OsConstants.AF_NETLINK;
-import static android.system.OsConstants.IPPROTO_TCP;
-import static android.system.OsConstants.NETLINK_INET_DIAG;
-import static android.system.OsConstants.SOCK_CLOEXEC;
-import static android.system.OsConstants.SOCK_DGRAM;
 import static android.system.OsConstants.SOL_SOCKET;
 import static android.system.OsConstants.SO_SNDTIMEO;
 
-import static com.android.net.module.util.netlink.InetDiagMessage.inetDiagReqV2;
-import static com.android.net.module.util.netlink.NetlinkConstants.INET_DIAG_MEMINFO;
 import static com.android.net.module.util.netlink.NetlinkConstants.NLMSG_DONE;
 import static com.android.net.module.util.netlink.NetlinkConstants.SOCKDIAG_MSG_HEADER_SIZE;
 import static com.android.net.module.util.netlink.NetlinkConstants.SOCK_DIAG_BY_FAMILY;
-import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_DUMP;
-import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_REQUEST;
+import static com.android.net.module.util.netlink.NetlinkUtils.DEFAULT_RECV_BUFSIZE;
+import static com.android.net.module.util.netlink.NetlinkUtils.IO_TIMEOUT_MS;
 
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.net.INetd;
 import android.net.MarkMaskParcel;
 import android.net.Network;
-import android.net.util.NetworkStackUtils;
-import android.net.util.SocketUtils;
 import android.os.AsyncTask;
 import android.os.Build;
 import android.os.IBinder;
+import android.os.PowerManager;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.provider.DeviceConfig;
@@ -61,10 +55,13 @@
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.net.module.util.DeviceConfigUtils;
+import com.android.net.module.util.SocketUtils;
+import com.android.net.module.util.netlink.InetDiagMessage;
 import com.android.net.module.util.netlink.NetlinkConstants;
-import com.android.net.module.util.netlink.NetlinkSocket;
+import com.android.net.module.util.netlink.NetlinkUtils;
 import com.android.net.module.util.netlink.StructInetDiagMsg;
 import com.android.net.module.util.netlink.StructNlMsgHdr;
 import com.android.networkstack.apishim.NetworkShimImpl;
@@ -89,14 +86,10 @@
     private static final String TAG = TcpSocketTracker.class.getSimpleName();
     private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
     private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET6, AF_INET};
-    // Enough for parsing v1 tcp_info for more than 200 sockets per time.
-    private static final int DEFAULT_RECV_BUFSIZE = 60_000;
-    // Default I/O timeout time in ms of the socket request.
-    private static final long IO_TIMEOUT = 3_000L;
+
     /** Cookie offset of an InetMagMessage header. */
     private static final int IDIAG_COOKIE_OFFSET = 44;
-    private static final int UNKNOWN_MARK = 0xffffffff;
-    private static final int NULL_MASK = 0;
+    private static final int END_OF_PARSING = -1;
     /**
      *  Gather the socket info.
      *
@@ -127,6 +120,10 @@
     private final int mNetworkMask;
     private int mMinPacketsThreshold = DEFAULT_DATA_STALL_MIN_PACKETS_THRESHOLD;
     private int mTcpPacketsFailRateThreshold = DEFAULT_TCP_PACKETS_FAIL_PERCENTAGE;
+
+    private final Object mDozeModeLock = new Object();
+    @GuardedBy("mDozeModeLock")
+    private boolean mInDozeMode = false;
     @VisibleForTesting
     protected final DeviceConfig.OnPropertiesChangedListener mConfigListener =
             new DeviceConfig.OnPropertiesChangedListener() {
@@ -143,16 +140,29 @@
                 }
             };
 
+    final BroadcastReceiver mDeviceIdleReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (intent == null) return;
+
+            if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
+                final PowerManager powerManager = context.getSystemService(PowerManager.class);
+                final boolean deviceIdle = powerManager.isDeviceIdleMode();
+                setDozeMode(deviceIdle);
+            }
+        }
+    };
+
     public TcpSocketTracker(@NonNull final Dependencies dps, @NonNull final Network network) {
         mDependencies = dps;
         mNetwork = network;
         mNetd = mDependencies.getNetd();
 
         // If the parcel is null, nothing should be matched which is achieved by the combination of
-        // {@code NULL_MASK} and {@code UNKNOWN_MARK}.
+        // {@code NetlinkUtils#NULL_MASK} and {@code NetlinkUtils#UNKNOWN_MARK}.
         final MarkMaskParcel parcel = getNetworkMarkMask();
-        mNetworkMark = (parcel != null) ? parcel.mark : UNKNOWN_MARK;
-        mNetworkMask = (parcel != null) ? parcel.mask : NULL_MASK;
+        mNetworkMark = (parcel != null) ? parcel.mark : NetlinkUtils.UNKNOWN_MARK;
+        mNetworkMask = (parcel != null) ? parcel.mask : NetlinkUtils.NULL_MASK;
 
         // Request tcp info from NetworkStack directly needs extra SELinux permission added after Q
         // release.
@@ -160,17 +170,10 @@
         // Build SocketDiag messages.
         for (final int family : ADDRESS_FAMILIES) {
             mSockDiagMsg.put(
-                    family,
-                    inetDiagReqV2(IPPROTO_TCP,
-                            null /* local addr */,
-                            null /* remote addr */,
-                            family,
-                            (short) (NLM_F_REQUEST | NLM_F_DUMP) /* flag */,
-                            0 /* pad */,
-                            1 << INET_DIAG_MEMINFO /* idiagExt */,
-                            TCP_MONITOR_STATE_FILTER));
+                    family, InetDiagMessage.buildInetDiagReqForAliveTcpSockets(family));
         }
         mDependencies.addDeviceConfigChangedListener(mConfigListener);
+        mDependencies.addDeviceIdleReceiver(mDeviceIdleReceiver);
     }
 
     @Nullable
@@ -190,11 +193,19 @@
      * Request to send a SockDiag Netlink request. Receive and parse the returned message. This
      * function is not thread-safe and should only be called from only one thread.
      *
-     * @Return if this polling request executes successfully or not.
+     * @Return if this polling request is sent to kernel and executes successfully or not.
      */
     public boolean pollSocketsInfo() {
         if (!mDependencies.isTcpInfoParsingSupported()) return false;
+        // Traffic will be restricted in doze mode. TCP info may not reflect the correct network
+        // behavior.
+        // TODO: Traffic may be restricted by other reason. Get the restriction info from bpf in T+.
+        synchronized (mDozeModeLock) {
+            if (mInDozeMode) return false;
+        }
+
         FileDescriptor fd = null;
+
         try {
             final long time = SystemClock.elapsedRealtime();
             fd = mDependencies.connectToKernel();
@@ -202,61 +213,12 @@
             final TcpStat stat = new TcpStat();
             for (final int family : ADDRESS_FAMILIES) {
                 mDependencies.sendPollingRequest(fd, mSockDiagMsg.get(family));
-                // Messages are composed with the following format. Stop parsing when receiving
-                // message with nlmsg_type NLMSG_DONE.
-                // +------------------+---------------+--------------+--------+
-                // | Netlink Header   | Family Header | Attributes   | rtattr |
-                // | struct nlmsghdr  | struct rtmsg  | struct rtattr|  data  |
-                // +------------------+---------------+--------------+--------+
-                //               :           :               :
-                // +------------------+---------------+--------------+--------+
-                // | Netlink Header   | Family Header | Attributes   | rtattr |
-                // | struct nlmsghdr  | struct rtmsg  | struct rtattr|  data  |
-                // +------------------+---------------+--------------+--------+
-                final ByteBuffer bytes = mDependencies.recvMessage(fd);
-                try {
-                    while (enoughBytesRemainForValidNlMsg(bytes)) {
-                        final StructNlMsgHdr nlmsghdr = StructNlMsgHdr.parse(bytes);
-                        if (nlmsghdr == null) {
-                            Log.e(TAG, "Badly formatted data.");
-                            break;
-                        }
-                        final int nlmsgLen = nlmsghdr.nlmsg_len;
-                        log("pollSocketsInfo: nlmsghdr=" + nlmsghdr + ", limit=" + bytes.limit());
-                        // End of the message. Stop parsing.
-                        if (nlmsghdr.nlmsg_type == NLMSG_DONE) break;
 
-                        if (nlmsghdr.nlmsg_type != SOCK_DIAG_BY_FAMILY) {
-                            Log.e(TAG, "Expect to get family " + family
-                                    + " SOCK_DIAG_BY_FAMILY message but get "
-                                    + nlmsghdr.nlmsg_type);
-                            break;
-                        }
-
-                        if (isValidInetDiagMsgSize(nlmsgLen)) {
-                            // Get the socket cookie value. Composed by two Integers value.
-                            // Corresponds to inet_diag_sockid in
-                            // &lt;linux_src&gt;/include/uapi/linux/inet_diag.h
-                            bytes.position(bytes.position() + IDIAG_COOKIE_OFFSET);
-                            // It's stored in native with 2 int. Parse it as long for convenience.
-                            final long cookie = bytes.getLong();
-                            // Skip the rest part of StructInetDiagMsg.
-                            bytes.position(bytes.position()
-                                    + StructInetDiagMsg.STRUCT_SIZE - IDIAG_COOKIE_OFFSET
-                                    - Long.BYTES);
-                            final SocketInfo info = parseSockInfo(bytes, family, nlmsgLen, time);
-                            // Update TcpStats based on previous and current socket info.
-                            stat.accumulate(
-                                    calculateLatestPacketsStat(info, mSocketInfos.get(cookie)));
-                            mSocketInfos.put(cookie, info);
-                        }
-                    }
-                } catch (IllegalArgumentException | BufferUnderflowException e) {
-                    Log.wtf(TAG, "Unexpected socket info parsing, family " + family
-                            + " buffer:" + bytes + " "
-                            + Base64.getEncoder().encodeToString(bytes.array()), e);
+                while (parseMessage(mDependencies.recvMessage(fd), family, stat, time)) {
+                    log("Pending info exist. Attempt to read more");
                 }
             }
+
             // Calculate mLatestReceiveCount, mSentSinceLastRecv and mLatestPacketFailPercentage.
             mSentSinceLastRecv = (stat.receivedCount == 0)
                     ? (mSentSinceLastRecv + stat.sentCount) : 0;
@@ -270,12 +232,91 @@
         } catch (ErrnoException | SocketException | InterruptedIOException e) {
             Log.e(TAG, "Fail to get TCP info via netlink.", e);
         } finally {
-            NetworkStackUtils.closeSocketQuietly(fd);
+            SocketUtils.closeSocketQuietly(fd);
         }
 
         return false;
     }
 
+    // Return true if there are more pending messages to read
+    private boolean parseMessage(ByteBuffer bytes, int family, TcpStat stat, long time) {
+        if (!enoughBytesRemainForValidNlMsg(bytes)) {
+            // This is unlikely to happen in real cases. Check this first for testing.
+            Log.e(TAG, "Size is less than header size. Ignored.");
+            return false;
+        }
+
+        // Messages are composed with the following format. Stop parsing when receiving
+        // message with nlmsg_type NLMSG_DONE.
+        // +------------------+---------------+--------------+--------+
+        // | Netlink Header   | Family Header | Attributes   | rtattr |
+        // | struct nlmsghdr  | struct rtmsg  | struct rtattr|  data  |
+        // +------------------+---------------+--------------+--------+
+        //               :           :               :
+        // +------------------+---------------+--------------+--------+
+        // | Netlink Header   | Family Header | Attributes   | rtattr |
+        // | struct nlmsghdr  | struct rtmsg  | struct rtattr|  data  |
+        // +------------------+---------------+--------------+--------+
+        try {
+            do {
+                final int nlmsgLen = getLengthAndVerifyMsgHeader(bytes, family);
+                if (nlmsgLen == END_OF_PARSING) return false;
+
+                if (isValidInetDiagMsgSize(nlmsgLen)) {
+                    // Get the socket cookie value. Composed by two Integers value.
+                    // Corresponds to inet_diag_sockid in
+                    // &lt;linux_src&gt;/include/uapi/linux/inet_diag.h
+                    bytes.position(bytes.position() + IDIAG_COOKIE_OFFSET);
+
+                    // It's stored in native with 2 int. Parse it as long for
+                    // convenience.
+                    final long cookie = bytes.getLong();
+                    log("cookie=" + cookie);
+                    // Skip the rest part of StructInetDiagMsg.
+                    bytes.position(bytes.position()
+                            + StructInetDiagMsg.STRUCT_SIZE - IDIAG_COOKIE_OFFSET
+                            - Long.BYTES);
+                    final SocketInfo info = parseSockInfo(bytes, family, nlmsgLen,
+                            time);
+                    // Update TcpStats based on previous and current socket info.
+                    stat.accumulate(
+                            calculateLatestPacketsStat(info, mSocketInfos.get(cookie)));
+                    mSocketInfos.put(cookie, info);
+                }
+            } while (enoughBytesRemainForValidNlMsg(bytes));
+        } catch (IllegalArgumentException | BufferUnderflowException e) {
+            Log.wtf(TAG, "Unexpected socket info parsing, family " + family
+                    + " buffer:" + bytes + " "
+                    + Base64.getEncoder().encodeToString(bytes.array()), e);
+            return false;
+        }
+
+        return true;
+    }
+
+    private int getLengthAndVerifyMsgHeader(@NonNull ByteBuffer bytes, int family) {
+        final StructNlMsgHdr nlmsghdr = StructNlMsgHdr.parse(bytes);
+        if (nlmsghdr == null) {
+            Log.e(TAG, "Badly formatted data.");
+            return END_OF_PARSING;
+        }
+
+        log("pollSocketsInfo: nlmsghdr=" + nlmsghdr + ", limit=" + bytes.limit());
+        // End of the message. Stop parsing.
+        if (nlmsghdr.nlmsg_type == NLMSG_DONE) {
+            return END_OF_PARSING;
+        }
+
+        if (nlmsghdr.nlmsg_type != SOCK_DIAG_BY_FAMILY) {
+            Log.e(TAG, "Expect to get family " + family
+                    + " SOCK_DIAG_BY_FAMILY message but get "
+                    + nlmsghdr.nlmsg_type);
+            return END_OF_PARSING;
+        }
+
+        return nlmsghdr.nlmsg_len;
+    }
+
     private void cleanupSocketInfo(final long time) {
         final int size = mSocketInfos.size();
         final List<Long> toRemove = new ArrayList<Long>();
@@ -297,15 +338,15 @@
             final int nlmsgLen, final long time) {
         final int remainingDataSize = bytes.position() + nlmsgLen - SOCKDIAG_MSG_HEADER_SIZE;
         TcpInfo tcpInfo = null;
-        int mark = SocketInfo.INIT_MARK_VALUE;
+        int mark = NetlinkUtils.INIT_MARK_VALUE;
         // Get a tcp_info.
         while (bytes.position() < remainingDataSize) {
             final RoutingAttribute rtattr =
                     new RoutingAttribute(bytes.getShort(), bytes.getShort());
             final short dataLen = rtattr.getDataLength();
-            if (rtattr.rtaType == RoutingAttribute.INET_DIAG_INFO) {
+            if (rtattr.rtaType == NetlinkUtils.INET_DIAG_INFO) {
                 tcpInfo = TcpInfo.parse(bytes, dataLen);
-            } else if (rtattr.rtaType == RoutingAttribute.INET_DIAG_MARK) {
+            } else if (rtattr.rtaType == NetlinkUtils.INET_DIAG_MARK) {
                 mark = bytes.getInt();
             } else {
                 // Data provided by kernel will include both valid data and padding data. The data
@@ -326,6 +367,14 @@
      */
     public boolean isDataStallSuspected() {
         if (!mDependencies.isTcpInfoParsingSupported()) return false;
+
+        // Skip checking data stall since the traffic will be restricted and it will not be real
+        // network stall.
+        // TODO: Traffic may be restricted by other reason. Get the restriction info from bpf in T+.
+        synchronized (mDozeModeLock) {
+            if (mInDozeMode) return false;
+        }
+
         return (getLatestPacketFailPercentage() >= getTcpPacketsFailRateThreshold());
     }
 
@@ -435,7 +484,12 @@
 
     /** Stops monitoring and releases resources. */
     public void quit() {
+        // Do not need to unregister receiver and listener since registration is skipped
+        // in the constructor.
+        if (!mDependencies.isTcpInfoParsingSupported()) return;
+
         mDependencies.removeDeviceConfigChangedListener(mConfigListener);
+        mDependencies.removeBroadcastReceiver(mDeviceIdleReceiver);
     }
 
     /**
@@ -449,9 +503,6 @@
      */
     class RoutingAttribute {
         public static final int HEADER_LENGTH = 4;
-        // Corresponds to enum definition in bionic/libc/kernel/uapi/linux/inet_diag.h
-        public static final int INET_DIAG_INFO = 2;
-        public static final int INET_DIAG_MARK = 15;
 
         public final short rtaLen;  // The whole valid size of the struct.
         public final short rtaType;
@@ -470,8 +521,6 @@
      */
     @VisibleForTesting
     class SocketInfo {
-        // Initial mark value corresponds to the initValue in system/netd/include/Fwmark.h.
-        public static final int INIT_MARK_VALUE = 0;
         @Nullable
         public final TcpInfo tcpInfo;
         // One of {@code AF_INET6, AF_INET}.
@@ -532,6 +581,14 @@
         }
     }
 
+    private void setDozeMode(boolean isEnabled) {
+        synchronized (mDozeModeLock) {
+            if (mInDozeMode == isEnabled) return;
+            mInDozeMode = isEnabled;
+            log("Doze mode enabled=" + mInDozeMode);
+        }
+    }
+
     /**
      * Dependencies class for testing.
      */
@@ -550,11 +607,10 @@
          * Throw ErrnoException, SocketException if the exception is thrown.
          */
         public FileDescriptor connectToKernel() throws ErrnoException, SocketException {
-            final FileDescriptor fd =
-                    Os.socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
-            Os.connect(
-                    fd, SocketUtils.makeNetlinkSocketAddress(0 /* portId */, 0 /* groupMask */));
-
+            final FileDescriptor fd = NetlinkUtils.createNetLinkInetDiagSocket();
+            NetlinkUtils.connectSocketToNetlink(fd);
+            Os.setsockoptTimeval(fd, SOL_SOCKET, SO_SNDTIMEO,
+                    StructTimeval.fromMillis(IO_TIMEOUT_MS));
             return fd;
         }
 
@@ -567,8 +623,6 @@
          */
         public void sendPollingRequest(@NonNull final FileDescriptor fd, @NonNull final byte[] msg)
                 throws ErrnoException, InterruptedIOException {
-            Os.setsockoptTimeval(fd, SOL_SOCKET, SO_SNDTIMEO,
-                    StructTimeval.fromMillis(IO_TIMEOUT));
             Os.write(fd, msg, 0 /* byteOffset */, msg.length);
         }
 
@@ -599,7 +653,7 @@
          */
         public ByteBuffer recvMessage(@NonNull final FileDescriptor fd)
                 throws ErrnoException, InterruptedIOException {
-            return NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, IO_TIMEOUT);
+            return NetlinkUtils.recvMessage(fd, DEFAULT_RECV_BUFSIZE, IO_TIMEOUT_MS);
         }
 
         public Context getContext() {
@@ -626,5 +680,16 @@
                 @NonNull final DeviceConfig.OnPropertiesChangedListener listener) {
             DeviceConfig.removeOnPropertiesChangedListener(listener);
         }
+
+        /** Add receiver for detecting doze mode change to control TCP detection. */
+        public void addDeviceIdleReceiver(@NonNull final BroadcastReceiver receiver) {
+            mContext.registerReceiver(receiver,
+                    new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
+        }
+
+        /** Remove broadcast receiver. */
+        public void removeBroadcastReceiver(@NonNull final BroadcastReceiver receiver) {
+            mContext.unregisterReceiver(receiver);
+        }
     }
 }
diff --git a/src/android/net/util/NetworkStackUtils.java b/src/com/android/networkstack/util/NetworkStackUtils.java
similarity index 86%
rename from src/android/net/util/NetworkStackUtils.java
rename to src/com/android/networkstack/util/NetworkStackUtils.java
index 1730b9d..5b329dd 100755
--- a/src/android/net/util/NetworkStackUtils.java
+++ b/src/com/android/networkstack/util/NetworkStackUtils.java
@@ -14,13 +14,16 @@
  * limitations under the License.
  */
 
-package android.net.util;
+package com.android.networkstack.util;
 
 import android.content.Context;
+import android.net.LinkAddress;
 import android.net.MacAddress;
 import android.system.ErrnoException;
+import android.util.Log;
 
 import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
 
 import com.android.net.module.util.DeviceConfigUtils;
 
@@ -28,7 +31,9 @@
 import java.io.IOException;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
+import java.net.InetAddress;
 import java.net.SocketException;
+import java.net.UnknownHostException;
 
 /**
  * Collection of utilities for the network stack.
@@ -160,6 +165,11 @@
     public static final String DHCP_RAPID_COMMIT_ENABLED = "dhcp_rapid_commit_enabled";
 
     /**
+     * Disable dropping DHCP packets with IPv4 MF flag set.
+     */
+    public static final String DHCP_DISABLE_DROP_MF = "dhcp_disable_drop_mf";
+
+    /**
      * Minimum module version at which to enable the DHCP INIT-REBOOT state.
      */
     public static final String DHCP_INIT_REBOOT_VERSION = "dhcp_init_reboot_version";
@@ -188,14 +198,6 @@
             "dhcp_slow_retransmission_version";
 
     /**
-     * Minimum module version at which to enable dismissal CaptivePortalLogin app in validated
-     * network feature. CaptivePortalLogin app will also use validation facilities in
-     * {@link NetworkMonitor} to perform portal validation if feature is enabled.
-     */
-    public static final String DISMISS_PORTAL_IN_VALIDATED_NETWORK =
-            "dismiss_portal_in_validated_network";
-
-    /**
      * Experiment flag to enable considering DNS probes returning private IP addresses as failed
      * when attempting to detect captive portals.
      *
@@ -220,6 +222,13 @@
     public static final String IPCLIENT_GRATUITOUS_NA_VERSION = "ipclient_gratuitous_na_version";
 
     /**
+     * Experiment flag to send multicast NS from the global IPv6 GUA to the solicited-node
+     * multicast address based on the default router's IPv6 link-local address, which helps
+     * flush the first-hop routers' neighbor cache entry for the global IPv6 GUA.
+     */
+    public static final String IPCLIENT_MULTICAST_NS_VERSION = "ipclient_multicast_ns_version";
+
+    /**
      * Experiment flag to enable sending Gratuitous APR and Gratuitous Neighbor Advertisement for
      * all assigned IPv4 and IPv6 GUAs after completing L2 roaming.
      */
@@ -251,16 +260,6 @@
     }
 
     /**
-     * Close a socket, ignoring any exception while closing.
-     */
-    public static void closeSocketQuietly(FileDescriptor fd) {
-        try {
-            SocketUtils.closeSocket(fd);
-        } catch (IOException ignored) {
-        }
-    }
-
-    /**
      * Convert IPv6 multicast address to ethernet multicast address in network order.
      */
     public static MacAddress ipv6MulticastToEthernetMulticast(@NonNull final Inet6Address addr) {
@@ -276,9 +275,40 @@
     }
 
     /**
+     * Convert IPv6 unicast or anycast address to solicited node multicast address
+     * per RFC4291 section 2.7.1.
+     */
+    @Nullable
+    public static Inet6Address ipv6AddressToSolicitedNodeMulticast(
+            @NonNull final Inet6Address addr) {
+        final byte[] address = new byte[16];
+        address[0] = (byte) 0xFF;
+        address[1] = (byte) 0x02;
+        address[11] = (byte) 0x01;
+        address[12] = (byte) 0xFF;
+        address[13] = addr.getAddress()[13];
+        address[14] = addr.getAddress()[14];
+        address[15] = addr.getAddress()[15];
+        try {
+            return (Inet6Address) InetAddress.getByAddress(address);
+        } catch (UnknownHostException e) {
+            Log.e(TAG, "Invalid host IP address " + addr.getHostAddress(), e);
+            return null;
+        }
+    }
+
+    /**
+     * Check whether a link address is IPv6 global preferred unicast address.
+     */
+    public static boolean isIPv6GUA(@NonNull final LinkAddress address) {
+        return address.isIpv6() && address.isGlobalPreferred();
+    }
+
+    /**
      * Attaches a socket filter that accepts DHCP packets to the given socket.
      */
-    public static native void attachDhcpFilter(FileDescriptor fd) throws ErrnoException;
+    public static native void attachDhcpFilter(FileDescriptor fd, boolean dropMF)
+            throws ErrnoException;
 
     /**
      * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
diff --git a/src/com/android/server/NetworkStackService.java b/src/com/android/server/NetworkStackService.java
index 1e09f45..368a6d4 100644
--- a/src/com/android/server/NetworkStackService.java
+++ b/src/com/android/server/NetworkStackService.java
@@ -63,8 +63,8 @@
 import com.android.networkstack.NetworkStackNotifier;
 import com.android.networkstack.R;
 import com.android.networkstack.apishim.common.ShimUtils;
+import com.android.networkstack.ipmemorystore.IpMemoryStoreService;
 import com.android.server.connectivity.NetworkMonitor;
-import com.android.server.connectivity.ipmemorystore.IpMemoryStoreService;
 import com.android.server.util.PermissionUtil;
 
 import java.io.FileDescriptor;
@@ -421,8 +421,8 @@
             if (cb != null) cb.onStatusAvailable(0);
         }
 
-        @Override
-        protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
+        @Override @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
+        public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter fout,
                 @Nullable String[] args) {
             checkDumpPermission();
 
diff --git a/src/com/android/server/connectivity/NetworkMonitor.java b/src/com/android/server/connectivity/NetworkMonitor.java
index 84081b5..4be1d89 100755
--- a/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/src/com/android/server/connectivity/NetworkMonitor.java
@@ -55,26 +55,9 @@
 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_VALID_DNS_TIME_THRESHOLD_MS;
 import static android.net.util.DataStallUtils.DEFAULT_DNS_LOG_SIZE;
 import static android.net.util.DataStallUtils.DEFAULT_TCP_POLLING_INTERVAL_MS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_URL;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTPS_URL;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTP_URL;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_IGNORE;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_PROMPT;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTPS_URLS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTP_URLS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_USER_AGENT;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_USE_HTTPS;
-import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT;
-import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
-import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTPS_URLS;
-import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTP_URLS;
-import static android.net.util.NetworkStackUtils.DISMISS_PORTAL_IN_VALIDATED_NETWORK;
-import static android.net.util.NetworkStackUtils.DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 
+import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
 import static com.android.net.module.util.CollectionUtils.isEmpty;
 import static com.android.net.module.util.ConnectivityUtils.isIPv6ULA;
 import static com.android.net.module.util.DeviceConfigUtils.getResBooleanConfig;
@@ -87,6 +70,23 @@
 import static com.android.networkstack.apishim.ConstantsShim.TRANSPORT_TEST;
 import static com.android.networkstack.util.DnsUtils.PRIVATE_DNS_PROBE_HOST_SUFFIX;
 import static com.android.networkstack.util.DnsUtils.TYPE_ADDRCONFIG;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_URL;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTPS_URL;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTP_URL;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_IGNORE;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_PROMPT;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTPS_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTP_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_USER_AGENT;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_USE_HTTPS;
+import static com.android.networkstack.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT;
+import static com.android.networkstack.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
+import static com.android.networkstack.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTPS_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTP_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION;
 
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
@@ -116,7 +116,6 @@
 import android.net.networkstack.aidl.NetworkMonitorParameters;
 import android.net.shared.PrivateDnsConfig;
 import android.net.util.DataStallUtils.EvaluationType;
-import android.net.util.NetworkStackUtils;
 import android.net.util.Stopwatch;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
@@ -126,7 +125,6 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.SystemClock;
-import android.os.SystemProperties;
 import android.provider.DeviceConfig;
 import android.provider.Settings;
 import android.stats.connectivity.ProbeResult;
@@ -177,6 +175,7 @@
 import com.android.networkstack.metrics.NetworkValidationMetrics;
 import com.android.networkstack.netlink.TcpSocketTracker;
 import com.android.networkstack.util.DnsUtils;
+import com.android.networkstack.util.NetworkStackUtils;
 import com.android.server.NetworkStackService.NetworkStackServiceManager;
 
 import org.json.JSONException;
@@ -226,9 +225,7 @@
     private static final String TAG = NetworkMonitor.class.getSimpleName();
     private static final boolean DBG  = true;
     private static final boolean VDBG = false;
-    // TODO(b/185082309): For flaky test debug only, remove it after fixing.
-    private static final boolean DDBG_STALL = "cf_x86_auto-userdebug".equals(
-            SystemProperties.get("ro.build.flavor", ""));
+    private static final boolean DDBG_STALL = false;
     private static final boolean VDBG_STALL = Log.isLoggable(TAG, Log.DEBUG);
     private static final String DEFAULT_USER_AGENT    = "Mozilla/5.0 (X11; Linux x86_64) "
                                                       + "AppleWebKit/537.36 (KHTML, like Gecko) "
@@ -282,7 +279,12 @@
 
     static {
         // CTC
+        // This is a wrong config, but it may need to be here for a while since the
+        // carrier_list.textpb in OEM side may still wrong.
+        // TODO: Remove this wrong config when the carrier_list.textpb is corrected everywhere.
         sCarrierIdToMccMnc.put(1854, new MccMncOverrideInfo(460, 03));
+        // China telecom.
+        sCarrierIdToMccMnc.put(2237, new MccMncOverrideInfo(460, 03));
     }
 
     /**
@@ -445,6 +447,10 @@
     private final String mCaptivePortalHttpsUrlFromSetting;
     private final String mCaptivePortalHttpUrlFromSetting;
     @Nullable
+    private final URL mTestCaptivePortalHttpsUrl;
+    @Nullable
+    private final URL mTestCaptivePortalHttpUrl;
+    @Nullable
     private final CaptivePortalProbeSpec[] mCaptivePortalFallbackSpecs;
 
     // The probing URLs may be updated after constructor if system notifies configuration changed.
@@ -470,8 +476,7 @@
     @NonNull
     private LinkProperties mLinkProperties;
 
-    @VisibleForTesting
-    protected boolean mIsCaptivePortalCheckEnabled;
+    private final boolean mIsCaptivePortalCheckEnabled;
 
     private boolean mUseHttps;
     /**
@@ -571,7 +576,8 @@
     public NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network,
             SharedLog validationLog, @NonNull NetworkStackServiceManager serviceManager) {
         this(context, cb, network, new IpConnectivityLog(), validationLog, serviceManager,
-                Dependencies.DEFAULT, getTcpSocketTrackerOrNull(context, network));
+                Dependencies.DEFAULT, getTcpSocketTrackerOrNull(context, network,
+                        Dependencies.DEFAULT));
     }
 
     @VisibleForTesting
@@ -616,7 +622,10 @@
                 mDependencies.getSetting(context, CAPTIVE_PORTAL_HTTPS_URL, null);
         mCaptivePortalHttpUrlFromSetting =
                 mDependencies.getSetting(context, CAPTIVE_PORTAL_HTTP_URL, null);
-        mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
+        mTestCaptivePortalHttpsUrl =
+                getTestUrl(TEST_CAPTIVE_PORTAL_HTTPS_URL, validationLogs, deps);
+        mTestCaptivePortalHttpUrl = getTestUrl(TEST_CAPTIVE_PORTAL_HTTP_URL, validationLogs, deps);
+        mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled(context, deps);
         mPrivateIpNoInternetEnabled = getIsPrivateIpNoInternetEnabled();
         mMetricsEnabled = deps.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
                 NetworkStackUtils.VALIDATION_METRICS_VERSION, true /* defaultEnabled */);
@@ -630,8 +639,8 @@
         mDataStallMinEvaluateTime = getDataStallMinEvaluateTime();
         mDataStallValidDnsTimeThreshold = getDataStallValidDnsTimeThreshold();
         mDataStallEvaluationType = getDataStallEvaluationType();
-        mDnsStallDetector = initDnsStallDetectorIfRequired(mDataStallEvaluationType,
-                mConsecutiveDnsTimeoutThreshold);
+        mDnsStallDetector = initDnsStallDetectorIfRequired(mIsCaptivePortalCheckEnabled,
+                mDataStallEvaluationType, mConsecutiveDnsTimeoutThreshold);
         mTcpTracker = tst;
         // Read the configurations of evaluating network bandwidth.
         mEvaluatingBandwidthUrl = getResStringConfig(mContext,
@@ -781,10 +790,16 @@
     }
 
     private boolean isValidationRequired() {
-        return NetworkMonitorUtils.isValidationRequired(
+        final boolean dunValidationRequired = isAtLeastU()
+                || mContext.getResources().getBoolean(R.bool.config_validate_dun_networks);
+        return NetworkMonitorUtils.isValidationRequired(dunValidationRequired,
                 mNetworkAgentConfig.isVpnValidationRequired(), mNetworkCapabilities);
     }
 
+    private boolean isDataStallDetectionRequired() {
+        return mIsCaptivePortalCheckEnabled && isValidationRequired();
+    }
+
     private boolean isPrivateDnsValidationRequired() {
         return NetworkMonitorUtils.isPrivateDnsValidationRequired(mNetworkCapabilities);
     }
@@ -1003,7 +1018,7 @@
                             mUserDoesNotWant = true;
                             mEvaluationState.reportEvaluationResult(
                                     NETWORK_VALIDATION_RESULT_INVALID, null);
-                            // TODO: Should teardown network.
+
                             mUidResponsibleForReeval = 0;
                             transitionTo(mEvaluatingState);
                             break;
@@ -1137,7 +1152,7 @@
         }
 
         private void initSocketTrackingIfRequired() {
-            if (!isValidationRequired()) return;
+            if (!isDataStallDetectionRequired()) return;
 
             final TcpSocketTracker tst = getTcpSocketTracker();
             if (tst != null) {
@@ -1200,7 +1215,7 @@
 
     @VisibleForTesting
     void sendTcpPollingEvent() {
-        if (isValidationRequired()) {
+        if (isDataStallDetectionRequired()) {
             sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval());
         }
     }
@@ -1318,10 +1333,7 @@
         private boolean useRedirectUrlForPortal() {
             // It must match the conditions in CaptivePortalLogin in which the redirect URL is not
             // used to validate that the portal is gone.
-            final boolean aboveQ =
-                    ShimUtils.isReleaseOrDevelopmentApiAbove(Build.VERSION_CODES.Q);
-            return aboveQ && mDependencies.isFeatureEnabled(mContext, NAMESPACE_CONNECTIVITY,
-                    DISMISS_PORTAL_IN_VALIDATED_NETWORK, aboveQ /* defaultEnabled */);
+            return ShimUtils.isReleaseOrDevelopmentApiAbove(Build.VERSION_CODES.Q);
         }
 
         @Override
@@ -1947,10 +1959,11 @@
         return true;
     }
 
-    private boolean getIsCaptivePortalCheckEnabled() {
+    private static boolean getIsCaptivePortalCheckEnabled(@NonNull Context context,
+            @NonNull Dependencies dependencies) {
         String symbol = CAPTIVE_PORTAL_MODE;
         int defaultValue = CAPTIVE_PORTAL_MODE_PROMPT;
-        int mode = mDependencies.getSetting(mContext, symbol, defaultValue);
+        int mode = dependencies.getSetting(context, symbol, defaultValue);
         return mode != CAPTIVE_PORTAL_MODE_IGNORE;
     }
 
@@ -2068,8 +2081,9 @@
     }
 
     @Nullable
-    private URL getTestUrl(@NonNull String key) {
-        final String strExpiration = mDependencies.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY,
+    private static URL getTestUrl(@NonNull String key, @NonNull SharedLog log,
+            @NonNull Dependencies deps) {
+        final String strExpiration = deps.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY,
                 TEST_URL_EXPIRATION_TIME, null);
         if (strExpiration == null) return null;
 
@@ -2077,23 +2091,23 @@
         try {
             expTime = Long.parseUnsignedLong(strExpiration);
         } catch (NumberFormatException e) {
-            loge("Invalid test URL expiration time format", e);
+            log.e("Invalid test URL expiration time format", e);
             return null;
         }
 
         final long now = System.currentTimeMillis();
         if (expTime < now || (expTime - now) > TEST_URL_EXPIRATION_MS) {
-            logw("Skipping test URL with expiration " + expTime + ", now " + now);
+            log.w("Skipping test URL with expiration " + expTime + ", now " + now);
             return null;
         }
 
-        final String strUrl = mDependencies.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY,
+        final String strUrl = deps.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY,
                 key, null /* defaultValue */);
         if (!isValidTestUrl(strUrl)) {
-            logw("Skipping invalid test URL " + strUrl);
+            log.w("Skipping invalid test URL " + strUrl);
             return null;
         }
-        return makeURL(strUrl);
+        return makeURL(strUrl, log);
     }
 
     private String getCaptivePortalServerHttpsUrl(@NonNull Context context) {
@@ -2254,8 +2268,7 @@
     }
 
     private URL[] makeCaptivePortalHttpsUrls(@NonNull Context context) {
-        final URL testUrl = getTestUrl(TEST_CAPTIVE_PORTAL_HTTPS_URL);
-        if (testUrl != null) return new URL[] { testUrl };
+        if (mTestCaptivePortalHttpsUrl != null) return new URL[] { mTestCaptivePortalHttpsUrl };
 
         final String firstUrl = getCaptivePortalServerHttpsUrl(context);
         try {
@@ -2275,8 +2288,7 @@
     }
 
     private URL[] makeCaptivePortalHttpUrls(@NonNull Context context) {
-        final URL testUrl = getTestUrl(TEST_CAPTIVE_PORTAL_HTTP_URL);
-        if (testUrl != null) return new URL[] { testUrl };
+        if (mTestCaptivePortalHttpUrl != null) return new URL[] { mTestCaptivePortalHttpUrl };
 
         final String firstUrl = getCaptivePortalServerHttpUrl(context);
         try {
@@ -3174,12 +3186,18 @@
         }
     }
 
-    private URL makeURL(String url) {
+    @Nullable
+    private URL makeURL(@Nullable String url) {
+        return makeURL(url, mValidationLogs);
+    }
+
+    @Nullable
+    private static URL makeURL(@Nullable String url, @NonNull SharedLog log) {
         if (url != null) {
             try {
                 return new URL(url);
             } catch (MalformedURLException e) {
-                validationLog("Bad URL: " + url);
+                log.w("Bad URL: " + url);
             }
         }
         return null;
@@ -3431,7 +3449,7 @@
 
     @VisibleForTesting
     protected boolean isDataStall() {
-        if (!isValidationRequired()) {
+        if (!isDataStallDetectionRequired()) {
             return false;
         }
 
@@ -3685,8 +3703,10 @@
     }
 
     @Nullable
-    private static TcpSocketTracker getTcpSocketTrackerOrNull(Context context, Network network) {
-        return ((Dependencies.DEFAULT.getDeviceConfigPropertyInt(
+    private static TcpSocketTracker getTcpSocketTrackerOrNull(Context context, Network network,
+                Dependencies deps) {
+        return (getIsCaptivePortalCheckEnabled(context, deps)
+                && (deps.getDeviceConfigPropertyInt(
                 NAMESPACE_CONNECTIVITY,
                 CONFIG_DATA_STALL_EVALUATION_TYPE,
                 DEFAULT_DATA_STALL_EVALUATION_TYPES)
@@ -3696,8 +3716,9 @@
     }
 
     @Nullable
-    private DnsStallDetector initDnsStallDetectorIfRequired(int type, int threshold) {
-        return ((type & DATA_STALL_EVALUATION_TYPE_DNS) != 0)
+    private DnsStallDetector initDnsStallDetectorIfRequired(boolean isCaptivePortalCheckEnabled,
+                int type, int threshold) {
+        return (isCaptivePortalCheckEnabled && (type & DATA_STALL_EVALUATION_TYPE_DNS) != 0)
                 ? new DnsStallDetector(threshold) : null;
     }
 
diff --git a/tests/integration/Android.bp b/tests/integration/Android.bp
index 2bf0529..6b98d4a 100644
--- a/tests/integration/Android.bp
+++ b/tests/integration/Android.bp
@@ -34,7 +34,10 @@
 
 java_defaults {
     name: "NetworkStackIntegrationTestsDefaults",
-    defaults: ["framework-connectivity-test-defaults"],
+    defaults: [
+        "framework-connectivity-test-defaults",
+        "NetworkStackReleaseTargetSdk",
+    ],
     srcs: [
         "common/**/*.java",
         "common/**/*.kt",
@@ -70,14 +73,17 @@
 // Network stack integration tests.
 android_test {
     name: "NetworkStackIntegrationTests",
-    defaults: ["NetworkStackIntegrationTestsJniDefaults"],
+    defaults: [
+        "NetworkStackReleaseTargetSdk",
+        "NetworkStackIntegrationTestsJniDefaults",
+    ],
     static_libs: ["NetworkStackIntegrationTestsLib"],
     certificate: "networkstack",
     platform_apis: true,
     test_suites: ["device-tests"],
-    min_sdk_version: "29",
-    target_sdk_version: "30",
     jarjar_rules: ":NetworkStackJarJarRules",
+    host_required: ["net-tests-utils-host-common"],
+    test_config_template: "AndroidTestTemplate_Integration.xml",
 }
 
 // Network stack next integration tests.
@@ -93,12 +99,14 @@
         "signature/**/*.kt",
     ],
     static_libs: [
-        "NetworkStackApiCurrentLib",
+        "NetworkStackApiStableLib",
     ],
     certificate: "networkstack",
     platform_apis: true,
     test_suites: ["device-tests"],
     jarjar_rules: ":NetworkStackJarJarRules",
+    host_required: ["net-tests-utils-host-common"],
+    test_config_template: "AndroidTestTemplate_Integration.xml",
 }
 
 // Network stack integration root tests.
@@ -113,12 +121,15 @@
         "root/**/*.kt",
     ],
     static_libs: [
-        "NetworkStackApiCurrentLib",
+        "NetworkStackApiStableLib",
     ],
     platform_apis: true,
     test_suites: ["general-tests", "mts-networking"],
+    compile_multilib: "both",
     manifest: "AndroidManifest_root.xml",
     jarjar_rules: ":NetworkStackJarJarRules",
+    host_required: ["net-tests-utils-host-common"],
+    test_config_template: "AndroidTestTemplate_Integration.xml",
 }
 
 // Special version of the network stack tests that includes all tests necessary for code coverage
@@ -127,11 +138,12 @@
     name: "NetworkStackCoverageTests",
     certificate: "networkstack",
     platform_apis: true,
-    min_sdk_version: "29",
-    target_sdk_version: "30",
     test_suites: ["device-tests", "mts-networking"],
     test_config: "AndroidTest_Coverage.xml",
-    defaults: ["NetworkStackIntegrationTestsJniDefaults"],
+    defaults: [
+        "NetworkStackReleaseTargetSdk",
+        "NetworkStackIntegrationTestsJniDefaults",
+    ],
     static_libs: [
         "modules-utils-native-coverage-listener",
         "NetworkStackTestsLib",
diff --git a/tests/integration/AndroidTestTemplate_Integration.xml b/tests/integration/AndroidTestTemplate_Integration.xml
new file mode 100644
index 0000000..6107ccc
--- /dev/null
+++ b/tests/integration/AndroidTestTemplate_Integration.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Test config for {MODULE}">
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="{MODULE}.apk" />
+    </target_preparer>
+
+    <!-- Needed to push to the app's data directory. Without root, there appears to be no directory
+         that the shell can write to and that the networkstack can read from. -->
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"/>
+
+    <target_preparer class="com.android.testutils.DisableConfigSyncTargetPreparer" />
+
+    <option name="config-descriptor:metadata" key="mainline-param" value="CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex" />
+    <option name="config-descriptor:metadata" key="mainline-param" value="CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk" />
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="{PACKAGE}" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <!-- By default, include and exclude filters go into /data/local/tmp/ajur/, which these
+             tests cannot access because they run in the network_stack selinux context. Move
+             them to the tests' data directory instead.
+
+             This avoids confusing module errors in presubmit when a test fails, the test infra
+             attempts to retry it, but the retry run results in the test process crashing with a
+             permission denial trying to read the exclude file. -->
+        <option name="test-filter-dir" value="/data/data/{PACKAGE}/cache" />
+        <option name="hidden-api-checks" value="false"/>
+    </test>
+</configuration>
diff --git a/tests/integration/AndroidTest_Coverage.xml b/tests/integration/AndroidTest_Coverage.xml
index 3e7361b..1c63a93 100644
--- a/tests/integration/AndroidTest_Coverage.xml
+++ b/tests/integration/AndroidTest_Coverage.xml
@@ -22,6 +22,14 @@
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="com.android.server.networkstack.coverage" />
         <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <!-- By default, include and exclude filters go into /data/local/tmp/ajur/, which these
+             tests cannot access because they run in the network_stack selinux context. Move
+             them to the tests' data directory instead.
+
+             This avoids confusing module errors in presubmit when a test fails, the test infra
+             attempts to retry it, but the retry run results in the test process crashing with a
+             permission denial trying to read the exclude file. -->
+        <option name="test-filter-dir" value="/data/data/{PACKAGE}/cache" />
         <option name="hidden-api-checks" value="false"/>
         <option name="device-listeners" value="com.android.modules.utils.testing.NativeCoverageHackInstrumentationListener" />
     </test>
diff --git a/tests/integration/common/android/net/ip/IpClientIntegrationTestCommon.java b/tests/integration/common/android/net/ip/IpClientIntegrationTestCommon.java
index ff99bc8..3cb651e 100644
--- a/tests/integration/common/android/net/ip/IpClientIntegrationTestCommon.java
+++ b/tests/integration/common/android/net/ip/IpClientIntegrationTestCommon.java
@@ -59,6 +59,7 @@
 import static com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_ANY;
 import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_ALL_NODES_MULTICAST;
 import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_ALL_ROUTERS_MULTICAST;
+import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_ANY;
 import static com.android.net.module.util.NetworkStackConstants.IPV6_HEADER_LEN;
 import static com.android.net.module.util.NetworkStackConstants.IPV6_PROTOCOL_OFFSET;
 import static com.android.net.module.util.NetworkStackConstants.NEIGHBOR_ADVERTISEMENT_FLAG_OVERRIDE;
@@ -88,6 +89,7 @@
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.argThat;
 import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.eq;
@@ -122,11 +124,11 @@
 import android.net.NetworkAgentConfig;
 import android.net.NetworkCapabilities;
 import android.net.NetworkRequest;
+import android.net.NetworkSpecifier;
 import android.net.NetworkStackIpMemoryStore;
 import android.net.RouteInfo;
 import android.net.TestNetworkInterface;
 import android.net.TestNetworkManager;
-import android.net.TestNetworkSpecifier;
 import android.net.Uri;
 import android.net.dhcp.DhcpClient;
 import android.net.dhcp.DhcpDeclinePacket;
@@ -144,7 +146,6 @@
 import android.net.shared.Layer2Information;
 import android.net.shared.ProvisioningConfiguration;
 import android.net.shared.ProvisioningConfiguration.ScanResultInfo;
-import android.net.util.NetworkStackUtils;
 import android.os.Build;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -180,15 +181,17 @@
 import com.android.networkstack.apishim.ConstantsShim;
 import com.android.networkstack.apishim.common.ShimUtils;
 import com.android.networkstack.arp.ArpPacket;
+import com.android.networkstack.ipmemorystore.IpMemoryStoreService;
 import com.android.networkstack.metrics.IpProvisioningMetrics;
 import com.android.networkstack.metrics.IpReachabilityMonitorMetrics;
 import com.android.networkstack.metrics.NetworkQuirkMetrics;
 import com.android.networkstack.packets.NeighborAdvertisement;
 import com.android.networkstack.packets.NeighborSolicitation;
+import com.android.networkstack.util.NetworkStackUtils;
 import com.android.server.NetworkObserver;
 import com.android.server.NetworkObserverRegistry;
 import com.android.server.NetworkStackService.NetworkStackServiceManager;
-import com.android.server.connectivity.ipmemorystore.IpMemoryStoreService;
+import com.android.testutils.CompatUtil;
 import com.android.testutils.DevSdkIgnoreRule;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
@@ -264,6 +267,7 @@
     private static final int IFA_F_STABLE_PRIVACY = 0x800;
 
     protected static final long TEST_TIMEOUT_MS = 2_000L;
+    private static final long TEST_WAIT_ENOBUFS_TIMEOUT_MS = 30_000L;
 
     @Rule
     public final DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
@@ -610,8 +614,15 @@
                 mIsNetlinkEventParseEnabled /* default value */);
 
         setUpTapInterface();
-        mCb = mock(IIpClientCallbacks.class);
+        // It turns out that Router Solicitation will also be sent out even after the tap interface
+        // is brought up, however, we want to wait for RS which is sent due to IPv6 stack is enabled
+        // in the test code. The early RS might bring kind of race, for example, the IPv6 stack has
+        // not been enabled when test code sees the RS, then kernel will not process RA even if we
+        // replies immediately after receiving RS. Always waiting for the first RS show up after
+        // interface is brought up helps prevent the race.
+        waitForRouterSolicitation();
 
+        mCb = mock(IIpClientCallbacks.class);
         if (useNetworkStackSignature()) {
             setUpMocks();
             setUpIpClient();
@@ -1555,7 +1566,8 @@
     private void createTestNetworkAgentAndRegister(final LinkProperties lp) throws Exception {
         final Context context = InstrumentationRegistry.getInstrumentation().getContext();
         final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
-        final TestNetworkSpecifier testNetworkSpecifier = new TestNetworkSpecifier(mIfaceName);
+        final NetworkSpecifier testNetworkSpecifier =
+                CompatUtil.makeTestNetworkSpecifier(mIfaceName);
         final TestableNetworkCallback cb = new TestableNetworkCallback();
 
         // Requesting a network make sure the NetworkAgent is alive during the whole life cycle of
@@ -1804,9 +1816,10 @@
                 mPacketReader.popPacket(PACKET_TIMEOUT_MS, this::isRouterSolicitation));
     }
 
-    private void sendRouterAdvertisement(boolean waitForRs, short lifetime) throws Exception {
+    private void sendRouterAdvertisement(boolean waitForRs, short lifetime, int valid,
+            int preferred) throws Exception {
         final String dnsServer = "2001:4860:4860::64";
-        final ByteBuffer pio = buildPioOption(3600, 1800, "2001:db8:1::/64");
+        final ByteBuffer pio = buildPioOption(valid, preferred, "2001:db8:1::/64");
         final ByteBuffer rdnss = buildRdnssOption(3600, dnsServer);
         sendRouterAdvertisement(waitForRs, lifetime, pio, rdnss);
     }
@@ -1821,11 +1834,13 @@
     }
 
     private void sendBasicRouterAdvertisement(boolean waitForRs) throws Exception {
-        sendRouterAdvertisement(waitForRs, (short) 1800);
+        sendRouterAdvertisement(waitForRs, (short) 1800 /* lifetime */, 3600 /* valid */,
+                1800 /* preferred */);
     }
 
-    private void sendRouterAdvertisementWithZeroLifetime() throws Exception {
-        sendRouterAdvertisement(false /* waitForRs */, (short) 0);
+    private void sendRouterAdvertisementWithZeroRouterLifetime() throws Exception {
+        sendRouterAdvertisement(false /* waitForRs */, (short) 0 /* lifetime */, 3600 /* valid */,
+                1800 /* preferred */);
     }
 
     // TODO: move this and the following method to a common location and use them in ApfTest.
@@ -2837,7 +2852,7 @@
         assertTrue(lp.getDnsServers().contains(InetAddress.getByName(dnsServer)));
         assertTrue(lp.getDnsServers().contains(SERVER_ADDR));
 
-        reset(mCb);
+        clearInvocations(mCb);
     }
 
     private void doDualStackProvisioning(boolean shouldDisableAcceptRa) throws Exception {
@@ -2866,7 +2881,7 @@
 
         // Send RA with 0-lifetime and wait until all IPv6-related default route and DNS servers
         // have been removed, then verify if there is IPv4-only info left in the LinkProperties.
-        sendRouterAdvertisementWithZeroLifetime();
+        sendRouterAdvertisementWithZeroRouterLifetime();
         verify(mCb, timeout(TEST_TIMEOUT_MS).atLeastOnce()).onLinkPropertiesChange(
                 argThat(x -> {
                     final boolean isOnlyIPv4Provisioned = (x.getLinkAddresses().size() == 1
@@ -2905,7 +2920,7 @@
         // Send RA with 0-lifetime and wait until all global IPv6 addresses, IPv6-related default
         // route and DNS servers have been removed, then verify if there is IPv4-only, IPv6 link
         // local address and route to fe80::/64 info left in the LinkProperties.
-        sendRouterAdvertisementWithZeroLifetime();
+        sendRouterAdvertisementWithZeroRouterLifetime();
         verify(mCb, timeout(TEST_TIMEOUT_MS).atLeastOnce()).onLinkPropertiesChange(
                 argThat(x -> {
                     // Only IPv4 provisioned and IPv6 link-local address
@@ -3174,10 +3189,15 @@
         }
         final int after = getNumOpenFds();
 
-        // Check that the number of open fds is the same as before.
-        // If this exact match becomes flaky, we could add some tolerance here (e.g., allow 2-3
-        // extra fds), since it's likely that any leak would at least leak one FD per loop.
-        assertEquals("Fd leak after " + iterations + " iterations: ", before, after);
+        // Check that the number of open fds is the same as before, within some tolerance (e.g.,
+        // garbage collection or other cleanups might have caused an fd to be closed). This
+        // shouldn't make leak detection much less reliable, since it's likely that any leak would
+        // at least leak one FD per loop.
+        final int tolerance = 4;
+        assertTrue(
+                "FD leak detected after " + iterations + " iterations: expected "
+                        + before + " +/- " + tolerance + " fds, found " + after,
+                Math.abs(after - before) <= tolerance);
     }
 
     // TODO: delete when DhcpOption is @JavaOnlyImmutable.
@@ -3492,6 +3512,25 @@
         assertTrue(target.isGlobalPreferred());
     }
 
+    private void assertMulticastNsFromIpv6Gua(final NeighborSolicitation ns) throws Exception {
+        final Inet6Address solicitedNodeMulticast =
+                NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(ROUTER_LINK_LOCAL);
+        final MacAddress etherMulticast =
+                NetworkStackUtils.ipv6MulticastToEthernetMulticast(solicitedNodeMulticast);
+
+        assertEquals(etherMulticast, ns.ethHdr.dstMac);
+        assertEquals(ETH_P_IPV6, ns.ethHdr.etherType);
+        assertEquals(IPPROTO_ICMPV6, ns.ipv6Hdr.nextHeader);
+        assertEquals(0xff, ns.ipv6Hdr.hopLimit);
+
+        final LinkAddress srcIp = new LinkAddress(ns.ipv6Hdr.srcIp.getHostAddress() + "/64");
+        assertTrue(srcIp.isGlobalPreferred());
+        assertEquals(solicitedNodeMulticast, ns.ipv6Hdr.dstIp);
+        assertEquals(ICMPV6_NEIGHBOR_SOLICITATION, ns.icmpv6Hdr.type);
+        assertEquals(0, ns.icmpv6Hdr.code);
+        assertEquals(ROUTER_LINK_LOCAL, ns.nsHdr.target);
+    }
+
     @Test
     public void testGratuitousNaForNewGlobalUnicastAddresses() throws Exception {
         final ProvisioningConfiguration config = new ProvisioningConfiguration.Builder()
@@ -3674,6 +3713,23 @@
         return nsList;
     }
 
+    private NeighborSolicitation expectDadNeighborSolicitationForLinkLocal(boolean shouldDisableDad)
+            throws Exception {
+        final NeighborSolicitation ns = getNextNeighborSolicitation();
+        if (!shouldDisableDad) {
+            final Inet6Address solicitedNodeMulticast =
+                    NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(ns.nsHdr.target);
+            assertNotNull("No multicast NS received on interface within timeout", ns);
+            assertEquals(IPV6_ADDR_ANY, ns.ipv6Hdr.srcIp);     // srcIp: ::/
+            assertTrue(ns.ipv6Hdr.dstIp.isMulticastAddress()); // dstIp: solicited-node mcast
+            assertTrue(ns.ipv6Hdr.dstIp.equals(solicitedNodeMulticast));
+            assertTrue(ns.nsHdr.target.isLinkLocalAddress());  // targetIp: IPv6 LL address
+        } else {
+            assertNull(ns);
+        }
+        return ns;
+    }
+
     // Override this function with disabled experiment flag by default, in order not to
     // affect those tests which are just related to basic IpReachabilityMonitor infra.
     private void prepareIpReachabilityMonitorTest() throws Exception {
@@ -3920,6 +3976,59 @@
         );
     }
 
+    private void runIpv6LinkLocalOnlyDadTransmitsCheckTest(boolean shouldDisableDad)
+            throws Exception {
+        ProvisioningConfiguration.Builder config = new ProvisioningConfiguration.Builder()
+                .withoutIPv4()
+                .withIpv6LinkLocalOnly()
+                .withRandomMacAddress();
+        if (shouldDisableDad) config.withUniqueEui64AddressesOnly();
+
+        // dad_transmits has been set to 0 in disableIpv6ProvisioningDelays, re-enable dad_transmits
+        // for testing, but production code could disable dad again later, we should never see any
+        // multicast NS for duplicate address detection then.
+        mNetd.setProcSysNet(INetd.IPV6, INetd.CONF, mIfaceName, "dad_transmits", "1");
+        startIpClientProvisioning(config.build());
+        verify(mNetd, timeout(TEST_TIMEOUT_MS)).interfaceSetEnableIPv6(mIfaceName, true);
+        // Check dad_transmits should be set to 0 if UniqueEui64AddressesOnly mode is enabled.
+        int dadTransmits = Integer.parseUnsignedInt(
+                mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, mIfaceName, "dad_transmits"));
+        if (shouldDisableDad) {
+            assertEquals(0, dadTransmits);
+        } else {
+            assertEquals(1, dadTransmits);
+        }
+
+        final NeighborSolicitation ns =
+                expectDadNeighborSolicitationForLinkLocal(shouldDisableDad);
+        if (shouldDisableDad) {
+            assertNull(ns);
+        } else {
+            assertNotNull(ns);
+        }
+
+        // Shutdown IpClient and check if the dad_transmits always equals to default value 1 (if
+        // dad_transmit was set to 0 before, it should get recovered to default value 1 after
+        // shutting down IpClient)
+        mIpc.shutdown();
+        awaitIpClientShutdown();
+        dadTransmits = Integer.parseUnsignedInt(
+                mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, mIfaceName, "dad_transmits"));
+        assertEquals(1, dadTransmits);
+    }
+
+    @Test
+    @SignatureRequiredTest(reason = "requires mocked netd")
+    public void testIPv6LinkLocalOnly_enableDad() throws Exception {
+        runIpv6LinkLocalOnlyDadTransmitsCheckTest(false /* shouldDisableDad */);
+    }
+
+    @Test
+    @SignatureRequiredTest(reason = "requires mocked netd")
+    public void testIPv6LinkLocalOnly_disableDad() throws Exception {
+        runIpv6LinkLocalOnlyDadTransmitsCheckTest(true /* shouldDisableDad */);
+    }
+
     // Since createTapInterface(boolean, String) method was introduced since T, this method
     // cannot be found on Q/R/S platform, ignore this test on T- platform.
     @Test
@@ -3982,7 +4091,7 @@
 
         // Unblock the IpClient handler and ENOBUFS should happen then.
         latch.countDown();
-        HandlerUtils.waitForIdle(handler, TEST_TIMEOUT_MS);
+        HandlerUtils.waitForIdle(handler, TEST_WAIT_ENOBUFS_TIMEOUT_MS);
 
         reset(mCb);
 
@@ -3990,7 +4099,7 @@
         // Due to ignoring the ENOBUFS and wait until handler gets idle, IpClient should be still
         // able to see the RA with 0 router lifetime and the IPv6 default route will be removed.
         // LinkProperties should not include any route to the new prefix 2001:db8:dead:beef::/64.
-        sendRouterAdvertisementWithZeroLifetime();
+        sendRouterAdvertisementWithZeroRouterLifetime();
         final ArgumentCaptor<LinkProperties> captor = ArgumentCaptor.forClass(LinkProperties.class);
         verify(mCb, timeout(TEST_TIMEOUT_MS)).onProvisioningFailure(captor.capture());
         final LinkProperties lp = captor.getValue();
@@ -3998,4 +4107,84 @@
         assertFalse(hasRouteTo(lp, prefix));
         assertFalse(lp.hasIpv6DefaultRoute());
     }
+
+    @Test
+    public void testMulticastNsFromIPv6Gua() throws Exception {
+        final ProvisioningConfiguration config = new ProvisioningConfiguration.Builder()
+                .withoutIpReachabilityMonitor()
+                .withoutIPv4()
+                .build();
+
+        setFeatureEnabled(NetworkStackUtils.IPCLIENT_MULTICAST_NS_VERSION,
+                true /* isUnsolicitedNsEnabled */);
+        assertTrue(isFeatureEnabled(NetworkStackUtils.IPCLIENT_MULTICAST_NS_VERSION, false));
+        startIpClientProvisioning(config);
+
+        doIpv6OnlyProvisioning();
+
+        final List<NeighborSolicitation> nsList = new ArrayList<>();
+        NeighborSolicitation packet;
+        while ((packet = getNextNeighborSolicitation()) != null) {
+            // Filter out the NSes used for duplicate address detetction, whose target address
+            // is the global IPv6 address inside these NSes.
+            if (packet.nsHdr.target.isLinkLocalAddress()) {
+                assertMulticastNsFromIpv6Gua(packet);
+                nsList.add(packet);
+            }
+        }
+        assertEquals(2, nsList.size()); // from privacy address and stable privacy address
+    }
+
+    @Test
+    public void testDeprecatedGlobalUnicastAddress() throws Exception {
+        ProvisioningConfiguration config = new ProvisioningConfiguration.Builder()
+                .withoutIPv4()
+                .build();
+        startIpClientProvisioning(config);
+        doIpv6OnlyProvisioning();
+
+        // Send RA with PIO(0 preferred but valid lifetime) to deprecate the global IPv6 addresses.
+        // Check all of global IPv6 addresses will become deprecated, but still valid.
+        // NetworkStackUtils#isIPv6GUA() will return false for deprecated addresses, however, when
+        // checking if the DNS is still reachable, deprecated addresses are not acceptable, that
+        // results in the on-link DNS server gets lost from LinkProperties, and provisioning failure
+        // happened.
+        // TODO: update the logic of checking reachable on-link DNS server to accept the deprecated
+        // addresses, then onProvisioningFailure callback should never happen.
+        sendRouterAdvertisement(false /* waitForRs*/, (short) 1800 /* router lifetime */,
+                3600 /* valid */, 0 /* preferred */);
+        final ArgumentCaptor<LinkProperties> captor = ArgumentCaptor.forClass(LinkProperties.class);
+        verify(mCb, timeout(TEST_TIMEOUT_MS)).onProvisioningFailure(captor.capture());
+        final LinkProperties lp = captor.getValue();
+        assertNotNull(lp);
+        assertFalse(lp.hasGlobalIpv6Address());
+        assertEquals(3, lp.getLinkAddresses().size()); // IPv6 privacy, stable privacy, link-local
+        for (LinkAddress la : lp.getLinkAddresses()) {
+            assertFalse(NetworkStackUtils.isIPv6GUA(la));
+        }
+    }
+
+    @Test @SignatureRequiredTest(reason = "requires mNetd to delete IPv6 GUAs")
+    public void testOnIpv6AddressRemoved() throws Exception {
+        ProvisioningConfiguration config = new ProvisioningConfiguration.Builder()
+                .withoutIPv4()
+                .build();
+        startIpClientProvisioning(config);
+
+        LinkProperties lp = doIpv6OnlyProvisioning();
+        assertNotNull(lp);
+        assertEquals(3, lp.getLinkAddresses().size()); // IPv6 privacy, stable privacy, link-local
+        for (LinkAddress la : lp.getLinkAddresses()) {
+            final Inet6Address address = (Inet6Address) la.getAddress();
+            if (address.isLinkLocalAddress()) continue;
+            // Remove IPv6 GUAs from interface.
+            mNetd.interfaceDelAddress(mIfaceName, address.getHostAddress(), la.getPrefixLength());
+        }
+
+        final ArgumentCaptor<LinkProperties> captor = ArgumentCaptor.forClass(LinkProperties.class);
+        verify(mCb, timeout(TEST_TIMEOUT_MS)).onProvisioningFailure(captor.capture());
+        lp = captor.getValue();
+        assertFalse(lp.hasGlobalIpv6Address());
+        assertEquals(1, lp.getLinkAddresses().size()); // only link-local
+    }
 }
diff --git a/tests/integration/common/android/net/networkstack/TestNetworkStackServiceClient.kt b/tests/integration/common/android/net/networkstack/TestNetworkStackServiceClient.kt
index 9f5e5e7..481bfdc 100644
--- a/tests/integration/common/android/net/networkstack/TestNetworkStackServiceClient.kt
+++ b/tests/integration/common/android/net/networkstack/TestNetworkStackServiceClient.kt
@@ -23,6 +23,7 @@
 import android.content.pm.PackageManager.MATCH_SYSTEM_ONLY
 import android.net.INetworkStackConnector
 import android.os.IBinder
+import android.util.Log
 import androidx.test.platform.app.InstrumentationRegistry
 import kotlin.test.fail
 
@@ -31,9 +32,11 @@
  */
 class TestNetworkStackServiceClient private constructor() : NetworkStackClientBase() {
     companion object {
+        private val TAG = "TestNetworkStackServiceClient"
+        private val testNetworkStackServiceAction = "android.net.INetworkStackConnector.Test"
         private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
         private val networkStackVersion by lazy {
-            val component = getNetworkStackComponent(INetworkStackConnector::class.java.name)
+            val component = getNetworkStackComponent(testNetworkStackServiceAction)
             val info = context.packageManager.getPackageInfo(component.packageName, 0 /* flags */)
             info.longVersionCode
         }
@@ -48,6 +51,7 @@
 
         @JvmStatic
         fun isSupported(): Boolean {
+            Log.d(TAG, "Running network stack module version is " + networkStackVersion)
             // TestNetworkStackService was introduced in NetworkStack version 301100000.
             // It is also available at HEAD in development branches, where the version code is
             // 300000000.
@@ -61,16 +65,22 @@
         }
     }
 
+    // Inner class defined in subclass cannot access the protected methods of parent class directly,
+    // so have a method outside of the inner class: serviceConnection and call this method instead.
+    private fun onNetworkStackConnected(service: IBinder) {
+        onNetworkStackConnected(INetworkStackConnector.Stub.asInterface(service))
+    }
+
     private val serviceConnection = object : ServiceConnection {
         override fun onServiceConnected(name: ComponentName, service: IBinder) {
-            onNetworkStackConnected(INetworkStackConnector.Stub.asInterface(service))
+            onNetworkStackConnected(service)
         }
 
         override fun onServiceDisconnected(name: ComponentName) = Unit
     }
 
     private fun init() {
-        val bindIntent = Intent(INetworkStackConnector::class.java.name + ".Test")
+        val bindIntent = Intent(testNetworkStackServiceAction)
         bindIntent.component = getNetworkStackComponent(bindIntent.action)
         context.bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE)
     }
diff --git a/tests/integration/signature/android/net/util/NetworkStackUtilsIntegrationTest.kt b/tests/integration/signature/android/net/util/NetworkStackUtilsIntegrationTest.kt
index 2dd984d..0a80d70 100644
--- a/tests/integration/signature/android/net/util/NetworkStackUtilsIntegrationTest.kt
+++ b/tests/integration/signature/android/net/util/NetworkStackUtilsIntegrationTest.kt
@@ -25,7 +25,9 @@
 import android.net.TestNetworkManager
 import android.net.dhcp.DhcpPacket
 import android.os.HandlerThread
+import android.system.ErrnoException
 import android.system.Os
+import android.system.OsConstants
 import android.system.OsConstants.AF_INET
 import android.system.OsConstants.AF_PACKET
 import android.system.OsConstants.ARPHRD_ETHER
@@ -33,17 +35,24 @@
 import android.system.OsConstants.IPPROTO_UDP
 import android.system.OsConstants.SOCK_DGRAM
 import android.system.OsConstants.SOCK_NONBLOCK
-import androidx.test.platform.app.InstrumentationRegistry
 import android.system.OsConstants.SOCK_RAW
 import android.system.OsConstants.SOL_SOCKET
 import android.system.OsConstants.SO_RCVTIMEO
 import android.system.StructTimeval
+import androidx.test.platform.app.InstrumentationRegistry
+import com.android.internal.util.HexDump
 import com.android.net.module.util.InterfaceParams
+import com.android.net.module.util.IpUtils
 import com.android.net.module.util.Ipv6Utils
 import com.android.net.module.util.NetworkStackConstants.ETHER_ADDR_LEN
 import com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_ANY
+import com.android.net.module.util.NetworkStackConstants.IPV4_CHECKSUM_OFFSET
+import com.android.net.module.util.NetworkStackConstants.IPV4_FLAG_DF
+import com.android.net.module.util.NetworkStackConstants.IPV4_FLAG_MF
+import com.android.net.module.util.NetworkStackConstants.IPV4_FLAGS_OFFSET
 import com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_ALL_NODES_MULTICAST
 import com.android.net.module.util.structs.PrefixInformationOption
+import com.android.networkstack.util.NetworkStackUtils
 import com.android.testutils.ArpRequestFilter
 import com.android.testutils.ETHER_HEADER_LENGTH
 import com.android.testutils.IPV4_HEADER_LENGTH
@@ -56,10 +65,12 @@
 import org.junit.Test
 import java.io.FileDescriptor
 import java.net.Inet4Address
-import kotlin.reflect.KClass
 import java.net.Inet6Address
 import java.nio.ByteBuffer
+import java.util.Arrays
+import kotlin.reflect.KClass
 import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
 import kotlin.test.assertTrue
 import kotlin.test.fail
 
@@ -74,6 +85,10 @@
     private val TEST_TARGET_MAC = MacAddress.fromString("01:23:45:67:89:0A")
     private val TEST_INET6ADDR_1 = parseNumericAddress("2001:db8::1") as Inet6Address
     private val TEST_INET6ADDR_2 = parseNumericAddress("2001:db8::2") as Inet6Address
+    private val TEST_INET6ADDR_3 = parseNumericAddress("fd01:db8::3") as Inet6Address
+
+    // RFC4291 section 2.7.1
+    private val SOLICITED_NODE_MULTICAST_PREFIX = "FF02:0:0:0:0:1:FF00::/104"
 
     private val readerHandler = HandlerThread(
             NetworkStackUtilsIntegrationTest::class.java.simpleName)
@@ -184,6 +199,103 @@
         assertArrayEquals("Received packet != expected $descr",
                 expected, buffer.copyOfRange(0, readPacket))
     }
+
+    private fun assertSolicitedNodeMulticastAddress(
+        expected: Inet6Address?,
+        unicast: Inet6Address
+    ) {
+        assertNotNull(expected)
+        val prefix = IpPrefix(SOLICITED_NODE_MULTICAST_PREFIX)
+        assertTrue(prefix.contains(expected))
+        assertTrue(expected.isMulticastAddress())
+        // check the last 3 bytes of address
+        assertArrayEquals(Arrays.copyOfRange(expected.getAddress(), 13, 15),
+                Arrays.copyOfRange(unicast.getAddress(), 13, 15))
+    }
+
+    @Test
+    fun testConvertIpv6AddressToSolicitedNodeMulticast() {
+        val addr1 = NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(TEST_INET6ADDR_1)
+        assertSolicitedNodeMulticastAddress(addr1, TEST_INET6ADDR_1)
+
+        val addr2 = NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(TEST_INET6ADDR_2)
+        assertSolicitedNodeMulticastAddress(addr2, TEST_INET6ADDR_2)
+
+        val addr3 = NetworkStackUtils.ipv6AddressToSolicitedNodeMulticast(TEST_INET6ADDR_3)
+        assertSolicitedNodeMulticastAddress(addr3, TEST_INET6ADDR_3)
+    }
+
+    private fun assertSocketReadErrno(msg: String, fd: FileDescriptor, errno: Int) {
+        val received = ByteBuffer.allocate(TEST_MTU)
+        try {
+            val len = Os.read(fd, received)
+            fail(msg + ": " + toHexString(received, len))
+        } catch (expected: ErrnoException) {
+            assertEquals(errno.toLong(), expected.errno.toLong())
+        }
+    }
+
+    private fun assertNextPacketOnSocket(fd: FileDescriptor, expectedPacket: ByteBuffer) {
+        val received = ByteBuffer.allocate(TEST_MTU)
+        val len = Os.read(fd, received)
+        assertEquals(toHexString(expectedPacket, expectedPacket.limit()),
+            toHexString(received, len))
+    }
+
+    private fun setMfBit(packet: ByteBuffer, set: Boolean) {
+        val offset = ETHER_HEADER_LENGTH + IPV4_FLAGS_OFFSET
+        var flagOff: Int = packet.getShort(offset).toInt()
+        if (set) {
+            flagOff = (flagOff or IPV4_FLAG_MF) and IPV4_FLAG_DF.inv()
+        } else {
+            flagOff = (flagOff or IPV4_FLAG_DF) and IPV4_FLAG_MF.inv()
+        }
+        packet.putShort(offset, flagOff.toShort())
+        // Recalculate the checksum, which requires first clearing the checksum field.
+        val checksumOffset = ETHER_HEADER_LENGTH + IPV4_CHECKSUM_OFFSET
+        packet.putShort(checksumOffset, 0)
+        packet.putShort(checksumOffset, IpUtils.ipChecksum(packet, ETHER_HEADER_LENGTH))
+    }
+
+    private fun doTestDhcpResponseWithMfBit(dropMf: Boolean) {
+        val ifindex = InterfaceParams.getByName(iface.interfaceName).index
+        val packetSock = Os.socket(AF_PACKET, SOCK_RAW or SOCK_NONBLOCK, /*protocol=*/0)
+        try {
+            NetworkStackUtils.attachDhcpFilter(packetSock, dropMf)
+            val addr = SocketUtils.makePacketSocketAddress(OsConstants.ETH_P_IP, ifindex)
+            Os.bind(packetSock, addr)
+            val packet = DhcpPacket.buildNakPacket(DhcpPacket.ENCAP_L2, 42,
+                TEST_TARGET_IPV4_ADDR, /*relayIp=*/ IPV4_ADDR_ANY, TEST_TARGET_MAC.toByteArray(),
+                /*broadcast=*/ false, "NAK")
+            setMfBit(packet, true)
+            reader.sendResponse(packet)
+
+            // Packet with MF bit set is received iff dropMf is false.
+            if (dropMf) {
+                assertSocketReadErrno("Packet with MF bit should have been dropped",
+                    packetSock, OsConstants.EAGAIN)
+            } else {
+                assertNextPacketOnSocket(packetSock, packet)
+            }
+
+            // Identical packet, except with MF bit cleared, should always be received.
+            setMfBit(packet, false)
+            reader.sendResponse(packet)
+            assertNextPacketOnSocket(packetSock, packet)
+        } finally {
+            Os.close(packetSock)
+        }
+    }
+
+    @Test
+    fun testDhcpResponseWithMfBitDropped() {
+        doTestDhcpResponseWithMfBit(/*dropMf=*/ true)
+    }
+
+    @Test
+    fun testDhcpResponseWithMfBitReceived() {
+        doTestDhcpResponseWithMfBit(/*dropMf=*/ false)
+    }
 }
 
 private fun ByteBuffer.readAsArray(): ByteArray {
@@ -192,5 +304,9 @@
     return out
 }
 
+private fun toHexString(b: ByteBuffer, len: Int): String {
+    return HexDump.toHexString(Arrays.copyOf(b.array(), len))
+}
+
 private fun <T : Any> Context.assertHasService(manager: KClass<T>) = getSystemService(manager.java)
         ?: fail("Could not find service $manager")
diff --git a/tests/unit/src/android/net/apf/ApfTest.java b/tests/unit/src/android/net/apf/ApfTest.java
index 6532f95..0846127 100644
--- a/tests/unit/src/android/net/apf/ApfTest.java
+++ b/tests/unit/src/android/net/apf/ApfTest.java
@@ -965,7 +965,7 @@
         public static final byte[] MOCK_MAC_ADDR = {1,2,3,4,5,6};
 
         private FileDescriptor mWriteSocket;
-        private final long mFixedTimeMs = SystemClock.elapsedRealtime();
+        private long mCurrentTimeMs = SystemClock.elapsedRealtime();
 
         public TestApfFilter(Context context, ApfConfiguration config,
                 IpClientCallbacksWrapper ipClientCallback, IpConnectivityLog log) throws Exception {
@@ -978,13 +978,18 @@
             Os.write(mWriteSocket, packet, 0, packet.length);
         }
 
-        @Override
-        protected long currentTimeSeconds() {
-            return mFixedTimeMs / DateUtils.SECOND_IN_MILLIS;
+        // Simulate current time changes
+        public void increaseCurrentTimeSeconds(int delta) {
+            mCurrentTimeMs += delta * DateUtils.SECOND_IN_MILLIS;
         }
 
         @Override
-        void maybeStartFilter() {
+        protected long currentTimeSeconds() {
+            return mCurrentTimeMs / DateUtils.SECOND_IN_MILLIS;
+        }
+
+        @Override
+        public synchronized void maybeStartFilter() {
             mHardwareAddress = MOCK_MAC_ADDR;
             installNewProgramLocked();
 
@@ -1951,8 +1956,16 @@
     // Verify that the last program pushed to the IpClient.Callback properly filters the
     // given packet for the given lifetime.
     private void verifyRaLifetime(byte[] program, ByteBuffer packet, int lifetime) {
+        verifyRaLifetime(program, packet, lifetime, 0);
+    }
+
+    // Verify that the last program pushed to the IpClient.Callback properly filters the
+    // given packet for the given lifetime and programInstallTime. programInstallTime is
+    // the time difference between when RA is last seen and the program is installed.
+    private void verifyRaLifetime(byte[] program, ByteBuffer packet, int lifetime,
+            int programInstallTime) {
         final int FRACTION_OF_LIFETIME = 6;
-        final int ageLimit = lifetime / FRACTION_OF_LIFETIME;
+        final int ageLimit = lifetime / FRACTION_OF_LIFETIME - programInstallTime;
 
         // Verify new program should drop RA for 1/6th its lifetime and pass afterwards.
         assertDrop(program, packet.array());
@@ -2207,6 +2220,48 @@
         assertPass(program, raPacket.array());
     }
 
+    // The ByteBuffer is always created by ByteBuffer#wrap in the helper functions
+    @SuppressWarnings("ByteBufferBackingArray")
+    @Test
+    public void testRaWithProgramInstalledSomeTimeAfterLastSeen() throws Exception {
+        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
+        final ApfConfiguration config = getDefaultConfig();
+        config.multicastFilter = DROP_MULTICAST;
+        config.ieee802_3Filter = DROP_802_3_FRAMES;
+        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback, mLog);
+        byte[] program = ipClientCallback.getApfProgram();
+
+        final int routerLifetime = 1000;
+        final int timePassedSeconds = 12;
+
+        // Verify that when the program is generated and installed some time after RA is last seen
+        // it should be installed with the correct remaining lifetime.
+        ByteBuffer basePacket = makeBaseRaPacket();
+        verifyRaLifetime(apfFilter, ipClientCallback, basePacket, routerLifetime);
+        apfFilter.increaseCurrentTimeSeconds(timePassedSeconds);
+        synchronized (apfFilter) {
+            apfFilter.installNewProgramLocked();
+        }
+        program = ipClientCallback.getApfProgram();
+        verifyRaLifetime(program, basePacket, routerLifetime, timePassedSeconds);
+
+        // Packet should be passed if the program is installed after 1/6 * lifetime from last seen
+        apfFilter.increaseCurrentTimeSeconds((int) (routerLifetime / 6) - timePassedSeconds - 1);
+        synchronized (apfFilter) {
+            apfFilter.installNewProgramLocked();
+        }
+        program = ipClientCallback.getApfProgram();
+        assertDrop(program, basePacket.array());
+        apfFilter.increaseCurrentTimeSeconds(1);
+        synchronized (apfFilter) {
+            apfFilter.installNewProgramLocked();
+        }
+        program = ipClientCallback.getApfProgram();
+        assertPass(program, basePacket.array());
+
+        apfFilter.shutdown();
+    }
+
     /**
      * Stage a file for testing, i.e. make it native accessible. Given a resource ID,
      * copy that resource into the app's data directory and return the path to it.
diff --git a/tests/unit/src/android/net/dhcp/DhcpServerTest.java b/tests/unit/src/android/net/dhcp/DhcpServerTest.java
index 345c341..6d4bc13 100644
--- a/tests/unit/src/android/net/dhcp/DhcpServerTest.java
+++ b/tests/unit/src/android/net/dhcp/DhcpServerTest.java
@@ -23,9 +23,9 @@
 import static android.net.dhcp.DhcpPacket.INADDR_BROADCAST;
 import static android.net.dhcp.DhcpServer.CMD_RECEIVE_PACKET;
 import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
-import static android.net.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
 
 import static com.android.net.module.util.Inet4AddressUtils.inet4AddressToIntHTH;
+import static com.android.networkstack.util.NetworkStackUtils.DHCP_RAPID_COMMIT_VERSION;
 
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertFalse;
diff --git a/tests/unit/src/android/net/ip/IpClientTest.java b/tests/unit/src/android/net/ip/IpClientTest.java
index b88317a..8efa9ab 100644
--- a/tests/unit/src/android/net/ip/IpClientTest.java
+++ b/tests/unit/src/android/net/ip/IpClientTest.java
@@ -16,9 +16,10 @@
 
 package android.net.ip;
 
-import static android.net.util.NetworkStackUtils.IPCLIENT_PARSE_NETLINK_EVENTS_VERSION;
 import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
 
+import static com.android.networkstack.util.NetworkStackUtils.IPCLIENT_PARSE_NETLINK_EVENTS_VERSION;
+
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -69,10 +70,10 @@
 
 import com.android.net.module.util.InterfaceParams;
 import com.android.networkstack.R;
+import com.android.networkstack.ipmemorystore.IpMemoryStoreService;
 import com.android.server.NetworkObserver;
 import com.android.server.NetworkObserverRegistry;
 import com.android.server.NetworkStackService;
-import com.android.server.connectivity.ipmemorystore.IpMemoryStoreService;
 import com.android.testutils.DevSdkIgnoreRule;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
diff --git a/tests/unit/src/android/net/ip/IpReachabilityMonitorTest.kt b/tests/unit/src/android/net/ip/IpReachabilityMonitorTest.kt
index a8c5c97..3800752 100644
--- a/tests/unit/src/android/net/ip/IpReachabilityMonitorTest.kt
+++ b/tests/unit/src/android/net/ip/IpReachabilityMonitorTest.kt
@@ -24,7 +24,7 @@
 import android.net.LinkProperties
 import android.net.RouteInfo
 import android.net.metrics.IpConnectivityLog
-import android.net.util.NetworkStackUtils.IP_REACHABILITY_MCAST_RESOLICIT_VERSION
+import com.android.networkstack.util.NetworkStackUtils.IP_REACHABILITY_MCAST_RESOLICIT_VERSION
 import android.os.Handler
 import android.os.HandlerThread
 import android.os.MessageQueue
@@ -54,7 +54,6 @@
 import com.android.net.module.util.InterfaceParams
 import com.android.net.module.util.SharedLog
 import com.android.net.module.util.ip.IpNeighborMonitor
-import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEventConsumer
 import com.android.net.module.util.netlink.StructNdMsg.NUD_FAILED
 import com.android.net.module.util.netlink.StructNdMsg.NUD_REACHABLE
 import com.android.net.module.util.netlink.StructNdMsg.NUD_STALE
@@ -262,6 +261,8 @@
         }.`when`(dependencies).makeIpNeighborMonitor(any(), any(), any())
         doReturn(mIpReachabilityMonitorMetrics)
                 .`when`(dependencies).getIpReachabilityMonitorMetrics()
+        doReturn(true).`when`(dependencies).isFeatureEnabled(anyObject(),
+                eq(IP_REACHABILITY_MCAST_RESOLICIT_VERSION), anyBoolean())
 
         val monitorFuture = CompletableFuture<IpReachabilityMonitor>()
         // IpReachabilityMonitor needs to be started from the handler thread
@@ -349,9 +350,6 @@
         newLp: LinkProperties,
         neighbor: InetAddress
     ) {
-        doReturn(true).`when`(dependencies).isFeatureEnabled(anyObject(),
-                eq(IP_REACHABILITY_MCAST_RESOLICIT_VERSION), anyBoolean())
-
         reachabilityMonitor.updateLinkProperties(newLp)
 
         neighborMonitor.enqueuePacket(makeNewNeighMessage(neighbor, NUD_REACHABLE,
diff --git a/tests/unit/src/android/net/shared/ProvisioningConfigurationTest.java b/tests/unit/src/android/net/shared/ProvisioningConfigurationTest.java
index 2734fd2..00c544b 100644
--- a/tests/unit/src/android/net/shared/ProvisioningConfigurationTest.java
+++ b/tests/unit/src/android/net/shared/ProvisioningConfigurationTest.java
@@ -115,6 +115,7 @@
                 new String("android-dhcp-11").getBytes());
         config.mIPv4ProvisioningMode = PROV_IPV4_DHCP;
         config.mIPv6ProvisioningMode = PROV_IPV6_SLAAC;
+        config.mUniqueEui64AddressesOnly = false;
         return config;
     }
 
@@ -122,6 +123,7 @@
         final ProvisioningConfigurationParcelable p = new ProvisioningConfigurationParcelable();
         p.enableIPv4 = true;
         p.enableIPv6 = true;
+        p.uniqueEui64AddressesOnly = false;
         p.usingMultinetworkPolicyTracker = true;
         p.usingIpReachabilityMonitor = true;
         p.requestedPreDhcpActionMs = 42;
@@ -151,7 +153,7 @@
     public void setUp() {
         mConfig = makeTestProvisioningConfiguration();
         // Any added field must be included in equals() to be tested properly
-        assertFieldCountEquals(16, ProvisioningConfiguration.class);
+        assertFieldCountEquals(17, ProvisioningConfiguration.class);
     }
 
     @Test
@@ -282,7 +284,8 @@
         assertNotEqualsAfterChange(c -> c.mIPv4ProvisioningMode = PROV_IPV4_STATIC);
         assertNotEqualsAfterChange(c -> c.mIPv6ProvisioningMode = PROV_IPV6_DISABLED);
         assertNotEqualsAfterChange(c -> c.mIPv6ProvisioningMode = PROV_IPV6_LINKLOCAL);
-        assertFieldCountEquals(16, ProvisioningConfiguration.class);
+        assertNotEqualsAfterChange(c -> c.mUniqueEui64AddressesOnly = true);
+        assertFieldCountEquals(17, ProvisioningConfiguration.class);
     }
 
     private void assertNotEqualsAfterChange(Consumer<ProvisioningConfiguration> mutator) {
@@ -315,7 +318,7 @@
             + DhcpOption.class.getName()
             + "{type: 60,"
             + " value: [97, 110, 100, 114, 111, 105, 100, 45, 100, 104, 99, 112, 45, 49, 49]}],"
-            + " ipv4ProvisioningMode: 2, ipv6ProvisioningMode: 1}";
+            + " ipv4ProvisioningMode: 2, ipv6ProvisioningMode: 1, uniqueEui64AddressesOnly: false}";
 
     @Test
     public void testParcelableToString() {
diff --git a/tests/unit/src/android/net/testutils/DnsAnswerProviderTest.kt b/tests/unit/src/android/net/testutils/DnsAnswerProviderTest.kt
new file mode 100644
index 0000000..5e625e5
--- /dev/null
+++ b/tests/unit/src/android/net/testutils/DnsAnswerProviderTest.kt
@@ -0,0 +1,102 @@
+/*
+ * 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 android.net.testutils
+
+import android.net.DnsResolver.CLASS_IN
+import android.net.DnsResolver.TYPE_A
+import android.net.DnsResolver.TYPE_AAAA
+import androidx.test.filters.SmallTest
+import com.android.net.module.util.DnsPacket
+import com.android.testutils.DnsAnswerProvider
+import libcore.net.InetAddressUtils
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import kotlin.test.assertEquals
+
+@RunWith(JUnit4::class)
+@SmallTest
+class DnsAnswerProviderTest {
+    val ansProvider = DnsAnswerProvider()
+
+    private fun listOfAddresses(vararg addresses: String) =
+        addresses.map { address -> InetAddressUtils.parseNumericAddress(address) }
+
+    @Test
+    fun testIpv4Answers() {
+        val record1 = getTestDnsRecord("www.google.com", "1.2.3.4")
+        val record2 = getTestDnsRecord("www.google.com", "5.6.7.8")
+
+        // Verifies that empty response is returned before mocking.
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_A))
+
+        // Verifies that single response can be returned correctly.
+        ansProvider.setAnswer("www.google.com", listOfAddresses("1.2.3.4"))
+        assertEquals(listOf(record1), ansProvider.getAnswer("www.google.com", TYPE_A))
+
+        // Verifies that multiple responses can be returned correctly.
+        ansProvider.setAnswer("www.google.com", listOfAddresses("1.2.3.4", "5.6.7.8"))
+        assertEquals(listOf(record1, record2), ansProvider.getAnswer("www.google.com", TYPE_A))
+
+        // Verifies that null response is returned if queried with wrong type or wrong name.
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+        assertEquals(emptyList(), ansProvider.getAnswer("www.android.com", TYPE_A))
+
+        // Verifies that the answers for different entry has no effect to the testing one.
+        ansProvider.setAnswer("www.example.com", listOfAddresses("8.8.8.8"))
+        assertEquals(listOf(record1, record2), ansProvider.getAnswer("www.google.com", TYPE_A))
+
+        // Verifies that the responses can be cleared.
+        ansProvider.clearAnswer("www.google.com")
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_A))
+    }
+
+    @Test
+    fun testIpv4v6Answers() {
+        val record1 = getTestDnsRecord("www.google.com", "2001:db8::1")
+        val record2 = getTestDnsRecord("www.google.com", "2001:db8::2")
+        val record3 = getTestDnsRecord("www.google.com", "2001:db8::4")
+        val v4Record1 = getTestDnsRecord("www.google.com", "1.2.3.4")
+
+        // Verifies that null response is returned before mocking
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+
+        ansProvider.setAnswer("www.google.com", listOfAddresses("2001:db8::1", "2001:db8::2"))
+        assertEquals(listOf(record1, record2), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+
+        // Verifies that the answers for different entry has no effect to the testing one.
+        ansProvider.setAnswer("www.example.com", listOfAddresses("2001:db8::3"))
+        assertEquals(listOf(record1, record2), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+
+        // Verifies that null response is returned if queried with wrong type or wrong name.
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_A))
+        assertEquals(emptyList(), ansProvider.getAnswer("www.android.com", TYPE_AAAA))
+
+        // Verifies that the responses can be replaced. And different types can be mixed.
+        ansProvider.setAnswer("www.google.com", listOfAddresses("2001:db8::4", "1.2.3.4"))
+        assertEquals(listOf(record3), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+        assertEquals(listOf(v4Record1), ansProvider.getAnswer("www.google.com", TYPE_A))
+
+        // Verifies that the responses can be cleared.
+        ansProvider.clearAnswer("www.google.com")
+        assertEquals(emptyList(), ansProvider.getAnswer("www.google.com", TYPE_AAAA))
+    }
+
+    private fun getTestDnsRecord(dName: String, address: String) =
+            DnsPacket.DnsRecord.makeAOrAAAARecord(DnsPacket.ANSECTION, dName, CLASS_IN, 5 /* ttl */,
+                    InetAddressUtils.parseNumericAddress(address))
+}
\ No newline at end of file
diff --git a/tests/unit/src/android/net/testutils/HandlerUtilsTest.kt b/tests/unit/src/android/net/testutils/HandlerUtilsTest.kt
deleted file mode 100644
index c885874..0000000
--- a/tests/unit/src/android/net/testutils/HandlerUtilsTest.kt
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2019 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.testutils
-
-import android.os.HandlerThread
-import com.android.testutils.waitForIdle
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.JUnit4
-import kotlin.test.assertEquals
-
-const val ATTEMPTS = 50 // Causes the test to take about 150ms on aosp_crosshatch-eng.
-const val TIMEOUT_MS = 200
-
-@RunWith(JUnit4::class)
-class HandlerUtilsTest {
-    @Test
-    fun testWaitForIdle() {
-        val handlerThread = HandlerThread("testHandler").apply { start() }
-
-        // Tests that waitForIdle can be called many times without ill impact if the service is
-        // already idle.
-        repeat(ATTEMPTS) {
-            handlerThread.waitForIdle(TIMEOUT_MS)
-        }
-
-        // Tests that calling waitForIdle waits for messages to be processed. Use both an
-        // inline runnable that's instantiated at each loop run and a runnable that's instantiated
-        // once for all.
-        val tempRunnable = object : Runnable {
-            // Use StringBuilder preferentially to StringBuffer because StringBuilder is NOT
-            // thread-safe. It's part of the point that both runnables run on the same thread
-            // so if anything is wrong in that space it's better to opportunistically use a class
-            // where things might go wrong, even if there is no guarantee of failure.
-            var memory = StringBuilder()
-            override fun run() {
-                memory.append("b")
-            }
-        }
-        repeat(ATTEMPTS) { i ->
-            handlerThread.threadHandler.post({ tempRunnable.memory.append("a"); })
-            handlerThread.threadHandler.post(tempRunnable)
-            handlerThread.waitForIdle(TIMEOUT_MS)
-            assertEquals(tempRunnable.memory.toString(), "ab".repeat(i + 1))
-        }
-    }
-}
diff --git a/tests/unit/src/android/net/testutils/TestableNetworkCallbackTest.kt b/tests/unit/src/android/net/testutils/TestableNetworkCallbackTest.kt
deleted file mode 100644
index 5ca20d8..0000000
--- a/tests/unit/src/android/net/testutils/TestableNetworkCallbackTest.kt
+++ /dev/null
@@ -1,375 +0,0 @@
-package android.net.testutils
-
-import android.annotation.SuppressLint
-import android.net.LinkAddress
-import android.net.LinkProperties
-import android.net.Network
-import android.net.NetworkCapabilities
-import com.android.testutils.ConcurrentInterpreter
-import com.android.testutils.InterpretMatcher
-import com.android.testutils.RecorderCallback.CallbackEntry
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.AVAILABLE
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.BLOCKED_STATUS
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.LINK_PROPERTIES_CHANGED
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.LOSING
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.NETWORK_CAPS_UPDATED
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.LOST
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.RESUMED
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.SUSPENDED
-import com.android.testutils.RecorderCallback.CallbackEntry.Companion.UNAVAILABLE
-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.TestableNetworkCallback
-import com.android.testutils.intArg
-import com.android.testutils.strArg
-import com.android.testutils.timeArg
-import org.junit.Before
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.JUnit4
-import kotlin.reflect.KClass
-import kotlin.test.assertEquals
-import kotlin.test.assertFails
-import kotlin.test.assertNull
-import kotlin.test.assertTrue
-import kotlin.test.fail
-
-const val SHORT_TIMEOUT_MS = 20L
-const val DEFAULT_LINGER_DELAY_MS = 30000
-const val NOT_METERED = NetworkCapabilities.NET_CAPABILITY_NOT_METERED
-const val WIFI = NetworkCapabilities.TRANSPORT_WIFI
-const val CELLULAR = NetworkCapabilities.TRANSPORT_CELLULAR
-const val TEST_INTERFACE_NAME = "testInterfaceName"
-
-@RunWith(JUnit4::class)
-@SuppressLint("NewApi") // Uses hidden APIs, which the linter would identify as missing APIs.
-class TestableNetworkCallbackTest {
-    private lateinit var mCallback: TestableNetworkCallback
-
-    private fun makeHasNetwork(netId: Int) = object : TestableNetworkCallback.HasNetwork {
-        override val network: Network = Network(netId)
-    }
-
-    @Before
-    fun setUp() {
-        mCallback = TestableNetworkCallback()
-    }
-
-    @Test
-    fun testLastAvailableNetwork() {
-        // Make sure there is no last available network at first, then the last available network
-        // is returned after onAvailable is called.
-        val net2097 = Network(2097)
-        assertNull(mCallback.lastAvailableNetwork)
-        mCallback.onAvailable(net2097)
-        assertEquals(mCallback.lastAvailableNetwork, net2097)
-
-        // Make sure calling onCapsChanged/onLinkPropertiesChanged don't affect the last available
-        // network.
-        mCallback.onCapabilitiesChanged(net2097, NetworkCapabilities())
-        mCallback.onLinkPropertiesChanged(net2097, LinkProperties())
-        assertEquals(mCallback.lastAvailableNetwork, net2097)
-
-        // Make sure onLost clears the last available network.
-        mCallback.onLost(net2097)
-        assertNull(mCallback.lastAvailableNetwork)
-
-        // Do the same but with a different network after onLost : make sure the last available
-        // network is the new one, not the original one.
-        val net2098 = Network(2098)
-        mCallback.onAvailable(net2098)
-        mCallback.onCapabilitiesChanged(net2098, NetworkCapabilities())
-        mCallback.onLinkPropertiesChanged(net2098, LinkProperties())
-        assertEquals(mCallback.lastAvailableNetwork, net2098)
-
-        // Make sure onAvailable changes the last available network even if onLost was not called.
-        val net2099 = Network(2099)
-        mCallback.onAvailable(net2099)
-        assertEquals(mCallback.lastAvailableNetwork, net2099)
-
-        // For legacy reasons, lastAvailableNetwork is null as soon as any is lost, not necessarily
-        // the last available one. Check that behavior.
-        mCallback.onLost(net2098)
-        assertNull(mCallback.lastAvailableNetwork)
-
-        // Make sure that losing the really last available one still results in null.
-        mCallback.onLost(net2099)
-        assertNull(mCallback.lastAvailableNetwork)
-
-        // Make sure multiple onAvailable in a row then onLost still results in null.
-        mCallback.onAvailable(net2097)
-        mCallback.onAvailable(net2098)
-        mCallback.onAvailable(net2099)
-        mCallback.onLost(net2097)
-        assertNull(mCallback.lastAvailableNetwork)
-    }
-
-    @Test
-    fun testAssertNoCallback() {
-        mCallback.assertNoCallback(SHORT_TIMEOUT_MS)
-        mCallback.onAvailable(Network(100))
-        assertFails { mCallback.assertNoCallback(SHORT_TIMEOUT_MS) }
-    }
-
-    @Test
-    fun testAssertNoCallbackThat() {
-        val net = Network(101)
-        mCallback.assertNoCallbackThat { it is Available }
-        mCallback.onAvailable(net)
-        // Expect no blocked status change. Receive other callback does not fail the test.
-        mCallback.assertNoCallbackThat { it is BlockedStatus }
-        mCallback.onBlockedStatusChanged(net, true)
-        assertFails { mCallback.assertNoCallbackThat { it is BlockedStatus } }
-        mCallback.onBlockedStatusChanged(net, false)
-        mCallback.onCapabilitiesChanged(net, NetworkCapabilities())
-        assertFails { mCallback.assertNoCallbackThat { it is CapabilitiesChanged } }
-    }
-
-    @Test
-    fun testCapabilitiesWithAndWithout() {
-        val net = Network(101)
-        val matcher = makeHasNetwork(101)
-        val meteredNc = NetworkCapabilities()
-        val unmeteredNc = NetworkCapabilities().addCapability(NOT_METERED)
-        // Check that expecting caps (with or without) fails when no callback has been received.
-        assertFails { mCallback.expectCapabilitiesWith(NOT_METERED, matcher, SHORT_TIMEOUT_MS) }
-        assertFails { mCallback.expectCapabilitiesWithout(NOT_METERED, matcher, SHORT_TIMEOUT_MS) }
-
-        // Add NOT_METERED and check that With succeeds and Without fails.
-        mCallback.onCapabilitiesChanged(net, unmeteredNc)
-        mCallback.expectCapabilitiesWith(NOT_METERED, matcher)
-        mCallback.onCapabilitiesChanged(net, unmeteredNc)
-        assertFails { mCallback.expectCapabilitiesWithout(NOT_METERED, matcher, SHORT_TIMEOUT_MS) }
-
-        // Don't add NOT_METERED and check that With fails and Without succeeds.
-        mCallback.onCapabilitiesChanged(net, meteredNc)
-        assertFails { mCallback.expectCapabilitiesWith(NOT_METERED, matcher, SHORT_TIMEOUT_MS) }
-        mCallback.onCapabilitiesChanged(net, meteredNc)
-        mCallback.expectCapabilitiesWithout(NOT_METERED, matcher)
-    }
-
-    @Test
-    fun testExpectCallbackThat() {
-        val net = Network(193)
-        val netCaps = NetworkCapabilities().addTransportType(CELLULAR)
-        // Check that expecting callbackThat anything fails when no callback has been received.
-        assertFails { mCallback.expectCallbackThat(SHORT_TIMEOUT_MS) { true } }
-
-        // Basic test for true and false
-        mCallback.onAvailable(net)
-        mCallback.expectCallbackThat { true }
-        mCallback.onAvailable(net)
-        assertFails { mCallback.expectCallbackThat(SHORT_TIMEOUT_MS) { false } }
-
-        // Try a positive and a negative case
-        mCallback.onBlockedStatusChanged(net, true)
-        mCallback.expectCallbackThat { cb -> cb is BlockedStatus && cb.blocked }
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        assertFails { mCallback.expectCallbackThat(SHORT_TIMEOUT_MS) { cb ->
-            cb is CapabilitiesChanged && cb.caps.hasTransport(WIFI)
-        } }
-    }
-
-    @Test
-    fun testCapabilitiesThat() {
-        val net = Network(101)
-        val netCaps = NetworkCapabilities().addCapability(NOT_METERED).addTransportType(WIFI)
-        // Check that expecting capabilitiesThat anything fails when no callback has been received.
-        assertFails { mCallback.expectCapabilitiesThat(net, SHORT_TIMEOUT_MS) { true } }
-
-        // Basic test for true and false
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        mCallback.expectCapabilitiesThat(net) { true }
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        assertFails { mCallback.expectCapabilitiesThat(net, SHORT_TIMEOUT_MS) { false } }
-
-        // Try a positive and a negative case
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        mCallback.expectCapabilitiesThat(net) { caps ->
-            caps.hasCapability(NOT_METERED) &&
-                    caps.hasTransport(WIFI) &&
-                    !caps.hasTransport(CELLULAR)
-        }
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        assertFails { mCallback.expectCapabilitiesThat(net, SHORT_TIMEOUT_MS) { caps ->
-            caps.hasTransport(CELLULAR)
-        } }
-
-        // Try a matching callback on the wrong network
-        mCallback.onCapabilitiesChanged(net, netCaps)
-        assertFails { mCallback.expectCapabilitiesThat(Network(100), SHORT_TIMEOUT_MS) { true } }
-    }
-
-    @Test
-    fun testLinkPropertiesThat() {
-        val net = Network(112)
-        val linkAddress = LinkAddress("fe80::ace:d00d/64")
-        val mtu = 1984
-        val linkProps = LinkProperties().apply {
-            this.mtu = mtu
-            interfaceName = TEST_INTERFACE_NAME
-            addLinkAddress(linkAddress)
-        }
-
-        // Check that expecting linkPropsThat anything fails when no callback has been received.
-        assertFails { mCallback.expectLinkPropertiesThat(net, SHORT_TIMEOUT_MS) { true } }
-
-        // Basic test for true and false
-        mCallback.onLinkPropertiesChanged(net, linkProps)
-        mCallback.expectLinkPropertiesThat(net) { true }
-        mCallback.onLinkPropertiesChanged(net, linkProps)
-        assertFails { mCallback.expectLinkPropertiesThat(net, SHORT_TIMEOUT_MS) { false } }
-
-        // Try a positive and negative case
-        mCallback.onLinkPropertiesChanged(net, linkProps)
-        mCallback.expectLinkPropertiesThat(net) { lp ->
-            lp.interfaceName == TEST_INTERFACE_NAME &&
-                    lp.linkAddresses.contains(linkAddress) &&
-                    lp.mtu == mtu
-        }
-        mCallback.onLinkPropertiesChanged(net, linkProps)
-        assertFails { mCallback.expectLinkPropertiesThat(net, SHORT_TIMEOUT_MS) { lp ->
-            lp.interfaceName != TEST_INTERFACE_NAME
-        } }
-
-        // Try a matching callback on the wrong network
-        mCallback.onLinkPropertiesChanged(net, linkProps)
-        assertFails { mCallback.expectLinkPropertiesThat(Network(114), SHORT_TIMEOUT_MS) { lp ->
-            lp.interfaceName == TEST_INTERFACE_NAME
-        } }
-    }
-
-    @Test
-    fun testExpectCallback() {
-        val net = Network(103)
-        // Test expectCallback fails when nothing was sent.
-        assertFails { mCallback.expectCallback<BlockedStatus>(net, SHORT_TIMEOUT_MS) }
-
-        // Test onAvailable is seen and can be expected
-        mCallback.onAvailable(net)
-        mCallback.expectCallback<Available>(net, SHORT_TIMEOUT_MS)
-
-        // Test onAvailable won't return calls with a different network
-        mCallback.onAvailable(Network(106))
-        assertFails { mCallback.expectCallback<Available>(net, SHORT_TIMEOUT_MS) }
-
-        // Test onAvailable won't return calls with a different callback
-        mCallback.onAvailable(net)
-        assertFails { mCallback.expectCallback<BlockedStatus>(net, SHORT_TIMEOUT_MS) }
-    }
-
-    @Test
-    fun testPollForNextCallback() {
-        assertFails { mCallback.pollForNextCallback(SHORT_TIMEOUT_MS) }
-        TNCInterpreter.interpretTestSpec(initial = mCallback, lineShift = 1,
-                threadTransform = { cb -> cb.createLinkedCopy() }, spec = """
-            sleep; onAvailable(133)    | poll(2) = Available(133) time 1..4
-                                       | poll(1) fails
-            onCapabilitiesChanged(108) | poll(1) = CapabilitiesChanged(108) time 0..3
-            onBlockedStatus(199)       | poll(1) = BlockedStatus(199) time 0..3
-        """)
-    }
-
-    @Test
-    fun testEventuallyExpect() {
-        // TODO: Current test does not verify the inline one. Also verify the behavior after
-        // aligning two eventuallyExpect()
-        val net1 = Network(100)
-        val net2 = Network(101)
-        mCallback.onAvailable(net1)
-        mCallback.onCapabilitiesChanged(net1, NetworkCapabilities())
-        mCallback.onLinkPropertiesChanged(net1, LinkProperties())
-        mCallback.eventuallyExpect(LINK_PROPERTIES_CHANGED) {
-            net1.equals(it.network)
-        }
-        // No further new callback. Expect no callback.
-        assertFails { mCallback.eventuallyExpect(LINK_PROPERTIES_CHANGED) }
-
-        // Verify no predicate set.
-        mCallback.onAvailable(net2)
-        mCallback.onLinkPropertiesChanged(net2, LinkProperties())
-        mCallback.onBlockedStatusChanged(net1, false)
-        mCallback.eventuallyExpect(BLOCKED_STATUS) { net1.equals(it.network) }
-        // Verify no callback received if the callback does not happen.
-        assertFails { mCallback.eventuallyExpect(LOSING) }
-    }
-
-    @Test
-    fun testEventuallyExpectOnMultiThreads() {
-        TNCInterpreter.interpretTestSpec(initial = mCallback, lineShift = 1,
-                threadTransform = { cb -> cb.createLinkedCopy() }, spec = """
-                onAvailable(100)                   | eventually(CapabilitiesChanged(100), 1) fails
-                sleep ; onCapabilitiesChanged(100) | eventually(CapabilitiesChanged(100), 2)
-                onAvailable(101) ; onBlockedStatus(101) | eventually(BlockedStatus(100), 2) fails
-                onSuspended(100) ; sleep ; onLost(100)  | eventually(Lost(100), 2)
-        """)
-    }
-}
-
-private object TNCInterpreter : ConcurrentInterpreter<TestableNetworkCallback>(interpretTable)
-
-val EntryList = CallbackEntry::class.sealedSubclasses.map { it.simpleName }.joinToString("|")
-private fun callbackEntryFromString(name: String): KClass<out CallbackEntry> {
-    return CallbackEntry::class.sealedSubclasses.first { it.simpleName == name }
-}
-
-@SuppressLint("NewApi") // Uses hidden APIs, which the linter would identify as missing APIs.
-private val interpretTable = listOf<InterpretMatcher<TestableNetworkCallback>>(
-    // Interpret "Available(xx)" as "call to onAvailable with netId xx", and likewise for
-    // all callback types. This is implemented above by enumerating the subclasses of
-    // CallbackEntry and reading their simpleName.
-    Regex("""(.*)\s+=\s+($EntryList)\((\d+)\)""") to { i, cb, t ->
-        val record = i.interpret(t.strArg(1), cb)
-        assertTrue(callbackEntryFromString(t.strArg(2)).isInstance(record))
-        // Strictly speaking testing for is CallbackEntry is useless as it's been tested above
-        // but the compiler can't figure things out from the isInstance call. It does understand
-        // from the assertTrue(is CallbackEntry) that this is true, which allows to access
-        // the 'network' member below.
-        assertTrue(record is CallbackEntry)
-        assertEquals(record.network.netId, t.intArg(3))
-    },
-    // Interpret "onAvailable(xx)" as calling "onAvailable" with a netId of xx, and likewise for
-    // all callback types. NetworkCapabilities and LinkProperties just get an empty object
-    // as their argument. Losing gets the default linger timer. Blocked gets false.
-    Regex("""on($EntryList)\((\d+)\)""") to { i, cb, t ->
-        val net = Network(t.intArg(2))
-        when (t.strArg(1)) {
-            "Available" -> cb.onAvailable(net)
-            // PreCheck not used in tests. Add it here if it becomes useful.
-            "CapabilitiesChanged" -> cb.onCapabilitiesChanged(net, NetworkCapabilities())
-            "LinkPropertiesChanged" -> cb.onLinkPropertiesChanged(net, LinkProperties())
-            "Suspended" -> cb.onNetworkSuspended(net)
-            "Resumed" -> cb.onNetworkResumed(net)
-            "Losing" -> cb.onLosing(net, DEFAULT_LINGER_DELAY_MS)
-            "Lost" -> cb.onLost(net)
-            "Unavailable" -> cb.onUnavailable()
-            "BlockedStatus" -> cb.onBlockedStatusChanged(net, false)
-            else -> fail("Unknown callback type")
-        }
-    },
-    Regex("""poll\((\d+)\)""") to { i, cb, t ->
-        cb.pollForNextCallback(t.timeArg(1))
-    },
-    // Interpret "eventually(Available(xx), timeout)" as calling eventuallyExpect that expects
-    // CallbackEntry.AVAILABLE with netId of xx within timeout*INTERPRET_TIME_UNIT timeout, and
-    // likewise for all callback types.
-    Regex("""eventually\(($EntryList)\((\d+)\),\s+(\d+)\)""") to { i, cb, t ->
-        val net = Network(t.intArg(2))
-        val timeout = t.timeArg(3)
-        when (t.strArg(1)) {
-            "Available" -> cb.eventuallyExpect(AVAILABLE, timeout) { net == it.network }
-            "Suspended" -> cb.eventuallyExpect(SUSPENDED, timeout) { net == it.network }
-            "Resumed" -> cb.eventuallyExpect(RESUMED, timeout) { net == it.network }
-            "Losing" -> cb.eventuallyExpect(LOSING, timeout) { net == it.network }
-            "Lost" -> cb.eventuallyExpect(LOST, timeout) { net == it.network }
-            "Unavailable" -> cb.eventuallyExpect(UNAVAILABLE, timeout) { net == it.network }
-            "BlockedStatus" -> cb.eventuallyExpect(BLOCKED_STATUS, timeout) { net == it.network }
-            "CapabilitiesChanged" ->
-                cb.eventuallyExpect(NETWORK_CAPS_UPDATED, timeout) { net == it.network }
-            "LinkPropertiesChanged" ->
-                cb.eventuallyExpect(LINK_PROPERTIES_CHANGED, timeout) { net == it.network }
-            else -> fail("Unknown callback type")
-        }
-    }
-)
diff --git a/tests/unit/src/com/android/server/NetworkStackServiceTest.kt b/tests/unit/src/com/android/networkstack/NetworkStackServiceTest.kt
similarity index 98%
rename from tests/unit/src/com/android/server/NetworkStackServiceTest.kt
rename to tests/unit/src/com/android/networkstack/NetworkStackServiceTest.kt
index 40abe9e..4c4864b 100644
--- a/tests/unit/src/com/android/server/NetworkStackServiceTest.kt
+++ b/tests/unit/src/com/android/networkstack/NetworkStackServiceTest.kt
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server
+package com.android.networkstack
 
 import android.content.Context
 import android.net.IIpMemoryStoreCallbacks
@@ -40,7 +40,7 @@
 import com.android.server.NetworkStackService.NetworkStackConnector
 import com.android.server.NetworkStackService.PermissionChecker
 import com.android.server.connectivity.NetworkMonitor
-import com.android.server.connectivity.ipmemorystore.IpMemoryStoreService
+import com.android.networkstack.ipmemorystore.IpMemoryStoreService
 import com.android.testutils.DevSdkIgnoreRule
 import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter
 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
diff --git a/tests/unit/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreServiceTest.java b/tests/unit/src/com/android/networkstack/ipmemorystore/IpMemoryStoreServiceTest.java
similarity index 95%
rename from tests/unit/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreServiceTest.java
rename to tests/unit/src/com/android/networkstack/ipmemorystore/IpMemoryStoreServiceTest.java
index 73edcc7..37bd808 100644
--- a/tests/unit/src/com/android/server/connectivity/ipmemorystore/IpMemoryStoreServiceTest.java
+++ b/tests/unit/src/com/android/networkstack/ipmemorystore/IpMemoryStoreServiceTest.java
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
-import static com.android.server.connectivity.ipmemorystore.RegularMaintenanceJobService.InterruptMaintenance;
+import static com.android.networkstack.ipmemorystore.RegularMaintenanceJobService.InterruptMaintenance;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -45,6 +45,7 @@
 import android.os.ConditionVariable;
 import android.os.IBinder;
 import android.os.RemoteException;
+import android.util.Pair;
 
 import androidx.annotation.NonNull;
 import androidx.test.InstrumentationRegistry;
@@ -435,7 +436,7 @@
                 assertEquals(errorCode, Status.SUCCESS);
             }
 
-            // After inserted fake data, db size should be larger than threshold.
+            // After inserting fake data, the size of the DB should be larger than the threshold.
             assertTrue(mService.isDbSizeOverThreshold());
         } catch (final UnknownHostException e) {
             fail("Insert fake data fail");
@@ -794,11 +795,11 @@
     @Test
     public void testFullMaintenance() throws Exception {
         copyTestData(mDbFile);
-        // After inserted test data, db size should be larger than threshold.
+        // After inserting test data, the size of the DB should be larger than the threshold.
         assertTrue(mService.isDbSizeOverThreshold());
 
         final InterruptMaintenance im = new InterruptMaintenance(0/* Fake JobId */);
-        // Do full maintenance and then db size should go down and meet the threshold.
+        // Do full maintenance and then the db should go down in size and be under the threshold.
         doLatched("Maintenance unexpectedly completed successfully", latch ->
                 mService.fullMaintenance(onStatus((status) -> {
                     assertTrue("Execute full maintenance failed: "
@@ -806,35 +807,36 @@
                     latch.countDown();
                 }), im), LONG_TIMEOUT_MS);
 
-        // Assume that maintenance is successful, db size shall meet the threshold.
+        // If maintenance is successful, the db size shall meet the threshold.
         assertFalse(mService.isDbSizeOverThreshold());
     }
 
     @Test
     public void testInterruptMaintenance() throws Exception {
         copyTestData(mDbFile);
-        // After inserted test data, db size should be larger than threshold.
+        // After inserting test data, the size of the DB should be larger than the threshold.
         assertTrue(mService.isDbSizeOverThreshold());
 
-        final InterruptMaintenance im = new InterruptMaintenance(0/* Fake JobId */);
+        final InterruptMaintenance im = new InterruptMaintenance(48 /* Fake JobId */);
+        assertEquals(48, im.getJobId());
 
         // Test interruption immediately.
         im.setInterrupted(true);
-        // Do full maintenance and the expectation is not completed by interruption.
+        // Start full maintenance. It should be interrupted.
         doLatched("Maintenance unexpectedly completed successfully", latch ->
                 mService.fullMaintenance(onStatus((status) -> {
                     assertFalse(status.isSuccess());
                     latch.countDown();
                 }), im), LONG_TIMEOUT_MS);
 
-        // Assume that no data are removed, db size shall be over the threshold.
+        // No data has been removed, so the db size should still be over the threshold.
         assertTrue(mService.isDbSizeOverThreshold());
 
         // Reset the flag and test interruption during maintenance.
         im.setInterrupted(false);
 
         final ConditionVariable latch = new ConditionVariable();
-        // Do full maintenance and the expectation is not completed by interruption.
+        // Start full maintenance. It should be interrupted soon.
         mService.fullMaintenance(onStatus((status) -> {
             assertFalse(status.isSuccess());
             latch.open();
@@ -849,7 +851,7 @@
             fail("Maintenance unexpectedly completed successfully");
         }
 
-        // Assume that only do dropAllExpiredRecords method in previous maintenance, db size shall
+        // As maintenance should only have started dropAllExpiredRecords, the db size should
         // still be over the threshold.
         assertTrue(mService.isDbSizeOverThreshold());
     }
@@ -917,4 +919,22 @@
                             assertTrue(System.currentTimeMillis() >= startTime + sleepTimeMs);
                         })), DEFAULT_TIMEOUT_MS);
     }
+
+    private final List<Pair<String, byte[]>> mByteArrayTests = List.of(
+            new Pair<>("null", null),
+            new Pair<>("[]", new byte[] {}),
+            new Pair<>("[0102030405060708090A0B0C]",
+                    new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }),
+            new Pair<>("[0F1080FF]", new byte[] { 15, 16, -128, -1 }),
+            new Pair<>("[0102030405060708090A0B0C0D0E0F10...15161718191A1B1C]",
+                    new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+                            17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 })
+    );
+
+    @Test
+    public void testByteArrayToString() {
+        for (final Pair<String, byte[]> testCase : mByteArrayTests) {
+            assertEquals(testCase.first, Utils.byteArrayToString(testCase.second));
+        }
+    }
 }
diff --git a/tests/unit/src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobServiceTest.kt b/tests/unit/src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobServiceTest.kt
new file mode 100644
index 0000000..4309d71
--- /dev/null
+++ b/tests/unit/src/com/android/networkstack/ipmemorystore/RegularMaintenanceJobServiceTest.kt
@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2020 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.networkstack.ipmemorystore
+
+import android.app.job.JobInfo
+import android.app.job.JobParameters
+import android.app.job.JobScheduler
+import android.content.Context
+import android.net.ipmemorystore.IOnStatusListener
+import android.net.ipmemorystore.Status
+import android.os.Looper
+import android.testing.AndroidTestingRunner
+import android.util.Log
+import androidx.test.filters.SmallTest
+import com.android.networkstack.ipmemorystore.RegularMaintenanceJobService.InterruptMaintenance
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.Mockito.doReturn
+import org.mockito.Mockito.mock
+import org.mockito.Mockito.verify
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.TimeUnit
+import kotlin.reflect.full.staticFunctions
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+private const val TIMEOUT_MS = 2_000L
+
+@RunWith(AndroidTestingRunner::class)
+@SmallTest
+class RegularMaintenanceJobServiceTest {
+    private val mockContext = mock(Context::class.java)
+    private val mockJobScheduler = mock(JobScheduler::class.java)
+    private val mockIPMS = mock(IpMemoryStoreService::class.java)
+    private val jobService = InstrumentedRegularMaintenanceJobService()
+
+    private class InstrumentedRegularMaintenanceJobService : RegularMaintenanceJobService() {
+        // Store calls to jobFinished, which takes 2 arguments : params of the job to finish,
+        // and whether to reschedule
+        val events = ArrayBlockingQueue<Pair<JobParameters, Boolean>>(1 /* capacity */)
+        override fun getMainLooper() = mock(Looper::class.java)
+        override fun callJobFinished(params: JobParameters, reschedule: Boolean) {
+            events.offer(params to reschedule)
+        }
+    }
+
+    @Before
+    fun setUp() {
+        doReturn(mockJobScheduler)
+                .`when`(mockContext).getSystemService(Context.JOB_SCHEDULER_SERVICE)
+        // At this time JobService.onBind ignores its argument but must be called for it to work
+        // because JobService uses this method call to initialize some internal structures.
+        jobService.onBind(null)
+    }
+
+    private fun startMaintenance(): Triple<JobParameters, IOnStatusListener, InterruptMaintenance> {
+        val jobId = 12
+
+        RegularMaintenanceJobService.schedule(mockContext, mockIPMS)
+        val jobInfoCaptor = ArgumentCaptor.forClass(JobInfo::class.java)
+        verify(mockJobScheduler).schedule(jobInfoCaptor.capture())
+        val jobInfo = jobInfoCaptor.value
+        assertTrue(jobInfo.isRequireCharging)
+        assertTrue(jobInfo.isRequireBatteryNotLow)
+        assertTrue(jobInfo.isRequireDeviceIdle)
+        assertTrue(jobInfo.isPeriodic)
+        // AOSP sets the maintenance to once every 24h. It should be infrequent enough to not
+        // take up a lot of battery but also not so infrequent that it never gets done
+        assertTrue(jobInfo.intervalMillis in TimeUnit.HOURS.toMillis(12)..TimeUnit.DAYS.toMillis(5))
+
+        val params = mock(JobParameters::class.java)
+        doReturn(jobId).`when`(params).jobId
+        assertTrue(jobService.onStartJob(params))
+
+        val listenerCaptor = ArgumentCaptor.forClass(IOnStatusListener::class.java)
+        val imCaptor = ArgumentCaptor.forClass(InterruptMaintenance::class.java)
+        verify(mockIPMS).fullMaintenance(listenerCaptor.capture(), imCaptor.capture())
+        assertEquals(imCaptor.value.jobId, jobId)
+        assertFalse(imCaptor.value.isInterrupted)
+        return Triple(params, listenerCaptor.value, imCaptor.value)
+    }
+
+    private fun cleanupMaintenance(params: JobParameters) {
+        RegularMaintenanceJobService.unschedule(mockContext)
+        verify(mockJobScheduler).cancel(anyInt())
+        // This test may be compiled against the public SDK which prevents it from using
+        // Log#setWtfHandler. In this case there is no way to test that Log.wtf has been
+        // called if the onStartJob is called again on the same instance of the service.
+        // Only do this if the method is available.
+        if (Log::class.staticFunctions.any { it.name == "setWtfHandler" }) {
+            val call = CompletableFuture<String>()
+            val oldHandler = Log.setWtfHandler { _, what, _ -> call.complete(what.message) }
+            assertFalse(jobService.onStartJob(params))
+            assertNotNull(call.get())
+            Log.setWtfHandler(oldHandler)
+        }
+    }
+
+    @Test
+    fun testOnStopJob() {
+        val (params, _, im) = startMaintenance()
+        assertTrue(jobService.onStopJob(params))
+        assertTrue(im.isInterrupted)
+        cleanupMaintenance(params)
+    }
+
+    // Helper method to test completing maintenance with different statuses just in case, but
+    // in practice the only difference between success and other cases is that failures emit a
+    // log message.
+    private fun testListenToMaintenance(status: Int) {
+        val (params, listener, _) = startMaintenance()
+        assertTrue(listener.getInterfaceVersion() > 0)
+        assertNotNull(listener.getInterfaceHash())
+        assertNull(listener.asBinder())
+        listener.onComplete(Status(status).toParcelable())
+        val (completeParams, reschedule) = jobService.events.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)
+        assertEquals(completeParams.jobId, params.jobId)
+        if (Status.SUCCESS == status) {
+            assertFalse(reschedule)
+        } else {
+            assertTrue(reschedule)
+        }
+        cleanupMaintenance(params)
+    }
+
+    @Test fun testListenToMaintenanceSuccess() = testListenToMaintenance(Status.SUCCESS)
+    @Test fun testListenToMaintenanceFailure() = testListenToMaintenance(Status.ERROR_GENERIC)
+    // There is very little point in testing for each error status, as they all behave the same
+}
diff --git a/tests/unit/src/com/android/server/connectivity/ipmemorystore/RelevanceUtilsTests.java b/tests/unit/src/com/android/networkstack/ipmemorystore/RelevanceUtilsTests.java
similarity index 87%
rename from tests/unit/src/com/android/server/connectivity/ipmemorystore/RelevanceUtilsTests.java
rename to tests/unit/src/com/android/networkstack/ipmemorystore/RelevanceUtilsTests.java
index 3d3aabc..53d9749 100644
--- a/tests/unit/src/com/android/server/connectivity/ipmemorystore/RelevanceUtilsTests.java
+++ b/tests/unit/src/com/android/networkstack/ipmemorystore/RelevanceUtilsTests.java
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.server.connectivity.ipmemorystore;
+package com.android.networkstack.ipmemorystore;
 
-import static com.android.server.connectivity.ipmemorystore.RelevanceUtils.CAPPED_RELEVANCE;
+import static com.android.networkstack.ipmemorystore.RelevanceUtils.CAPPED_RELEVANCE;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
@@ -80,7 +80,7 @@
             final long newExpiry = RelevanceUtils.bumpExpiryDuration(expiry);
             if (newExpiry == expiry) {
                 // The relevance should be capped. Make sure it is, then exit without failure.
-                assertEquals(newExpiry, RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS);
+                assertEquals(RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS, newExpiry);
                 return;
             }
             // Make sure the new expiry is further in the future than last time.
@@ -101,10 +101,10 @@
         // Relevance at expiry and after expiry should be the cap.
         final int relevanceBeforeMaxLifetime = RelevanceUtils.computeRelevanceForTargetDate(expiry,
                 expiry - (RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS + 1_000_000));
-        assertEquals(relevanceBeforeMaxLifetime, CAPPED_RELEVANCE);
+        assertEquals(CAPPED_RELEVANCE, relevanceBeforeMaxLifetime);
         final int relevanceForMaxLifetime = RelevanceUtils.computeRelevanceForTargetDate(expiry,
                 expiry - RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS);
-        assertEquals(relevanceForMaxLifetime, CAPPED_RELEVANCE);
+        assertEquals(CAPPED_RELEVANCE, relevanceForMaxLifetime);
 
         // If the max relevance is reached at the cap lifetime, one millisecond less than this
         // should be very close. Strictly speaking this is a bit brittle, but it should be
@@ -122,10 +122,18 @@
         assertTrue(relevanceOneMillisecBeforeExpiry >= 0);
 
         final int relevanceAtExpiry = RelevanceUtils.computeRelevanceForTargetDate(expiry, expiry);
-        assertEquals(relevanceAtExpiry, 0);
+        assertEquals(0, relevanceAtExpiry);
         final int relevanceAfterExpiry = RelevanceUtils.computeRelevanceForTargetDate(expiry,
                 expiry + 1_000_000);
-        assertEquals(relevanceAfterExpiry, 0);
+        assertEquals(0, relevanceAfterExpiry);
+
+        // Basic test of computeRelevanceForNow
+        assertEquals(0, RelevanceUtils.computeRelevanceForNow(expiry));
+        assertEquals(CAPPED_RELEVANCE, RelevanceUtils.computeRelevanceForNow(expiry
+                + RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS + 5));
+        final int midRelevance = RelevanceUtils.computeRelevanceForNow(expiry
+                + RelevanceUtils.CAPPED_RELEVANCE_LIFETIME_MS / 2);
+        assertTrue(0 < midRelevance && midRelevance < CAPPED_RELEVANCE);
     }
 
     // testIncreaseRelevance makes sure bumping the expiry continuously always yields a
diff --git a/tests/unit/src/com/android/networkstack/netlink/TcpSocketTrackerTest.java b/tests/unit/src/com/android/networkstack/netlink/TcpSocketTrackerTest.java
index 457f0c3..85d3842 100644
--- a/tests/unit/src/com/android/networkstack/netlink/TcpSocketTrackerTest.java
+++ b/tests/unit/src/com/android/networkstack/netlink/TcpSocketTrackerTest.java
@@ -21,9 +21,6 @@
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 import static android.system.OsConstants.AF_INET;
 
-import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
-
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.net.module.util.netlink.NetlinkConstants.SOCKDIAG_MSG_HEADER_SIZE;
 
 import static junit.framework.Assert.assertEquals;
@@ -35,20 +32,28 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+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.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
 import android.net.INetd;
 import android.net.MarkMaskParcel;
 import android.net.Network;
 import android.os.Build;
+import android.os.PowerManager;
 import android.util.Log;
 import android.util.Log.TerribleFailureHandler;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.modules.utils.build.SdkLevel;
 import com.android.net.module.util.netlink.StructNlMsgHdr;
 import com.android.networkstack.apishim.ConstantsShim;
 import com.android.testutils.DevSdkIgnoreRule;
@@ -62,6 +67,7 @@
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -76,116 +82,23 @@
     private static final int TEST_BUFFER_SIZE = 1024;
     private static final String DIAG_MSG_HEX =
             // struct nlmsghdr.
-            "58000000" +      // length = 88
+            "10000000" +     // length = 16
             "1400" +         // type = SOCK_DIAG_BY_FAMILY
             "0301" +         // flags = NLM_F_REQUEST | NLM_F_DUMP
             "00000000" +     // seqno
-            "00000000" +     // pid (0 == kernel)
-            // struct inet_diag_req_v2
-            "02" +           // family = AF_INET
-            "06" +           // state
-            "00" +           // timer
-            "00" +           // retrans
-            // inet_diag_sockid
-            "DEA5" +         // idiag_sport = 42462
-            "71B9" +         // idiag_dport = 47473
-            "0a006402000000000000000000000000" + // idiag_src = 10.0.100.2
-            "08080808000000000000000000000000" + // idiag_dst = 8.8.8.8
-            "00000000" +    // idiag_if
-            "34ED000076270000" + // idiag_cookie = 43387759684916
-            "00000000" +    // idiag_expires
-            "00000000" +    // idiag_rqueue
-            "00000000" +    // idiag_wqueue
-            "00000000" +    // idiag_uid
-            "00000000";    // idiag_inode
+            "00000000";      // pid (0 == kernel)
     private static final byte[] SOCK_DIAG_MSG_BYTES =
             HexEncoding.decode(DIAG_MSG_HEX.toCharArray(), false);
     // Hexadecimal representation of a SOCK_DIAG response with tcp info.
-    private static final String SOCK_DIAG_TCP_INET_HEX =
-            // struct nlmsghdr.
-            "14010000" +        // length = 276
-            "1400" +            // type = SOCK_DIAG_BY_FAMILY
-            "0301" +            // flags = NLM_F_REQUEST | NLM_F_DUMP
-            "00000000" +        // seqno
-            "00000000" +        // pid (0 == kernel)
-            // struct inet_diag_req_v2
-            "02" +              // family = AF_INET
-            "06" +              // state
-            "00" +              // timer
-            "00" +              // retrans
-            // inet_diag_sockid
-            "DEA5" +            // idiag_sport = 42462
-            "71B9" +            // idiag_dport = 47473
-            "0a006402000000000000000000000000" + // idiag_src = 10.0.100.2
-            "08080808000000000000000000000000" + // idiag_dst = 8.8.8.8
-            "00000000" +            // idiag_if
-            "34ED000076270000" +    // idiag_cookie = 43387759684916
-            "00000000" +            // idiag_expires
-            "00000000" +            // idiag_rqueue
-            "00000000" +            // idiag_wqueue
-            "00000000" +            // idiag_uid
-            "00000000" +            // idiag_inode
-            // rtattr
-            "0500" +            // len = 5
-            "0800" +            // type = 8
-            "00000000" +        // data
-            "0800" +            // len = 8
-            "0F00" +            // type = 15(INET_DIAG_MARK)
-            "850A0C00" +        // data, socket mark=789125
-            "AC00" +            // len = 172
-            "0200" +            // type = 2(INET_DIAG_INFO)
-            // tcp_info
-            "01" +              // state = TCP_ESTABLISHED
-            "00" +              // ca_state = TCP_CA_OPEN
-            "05" +              // retransmits = 5
-            "00" +              // probes = 0
-            "00" +              // backoff = 0
-            "07" +              // option = TCPI_OPT_WSCALE|TCPI_OPT_SACK|TCPI_OPT_TIMESTAMPS
-            "88" +              // wscale = 8
-            "00" +              // delivery_rate_app_limited = 0
-            "4A911B00" +        // rto = 1806666
-            "00000000" +        // ato = 0
-            "2E050000" +        // sndMss = 1326
-            "18020000" +        // rcvMss = 536
-            "00000000" +        // unsacked = 0
-            "00000000" +        // acked = 0
-            "00000000" +        // lost = 0
-            "00000000" +        // retrans = 0
-            "00000000" +        // fackets = 0
-            "BB000000" +        // lastDataSent = 187
-            "00000000" +        // lastAckSent = 0
-            "BB000000" +        // lastDataRecv = 187
-            "BB000000" +        // lastDataAckRecv = 187
-            "DC050000" +        // pmtu = 1500
-            "30560100" +        // rcvSsthresh = 87600
-            "3E2C0900" +        // rttt = 601150
-            "1F960400" +        // rttvar = 300575
-            "78050000" +        // sndSsthresh = 1400
-            "0A000000" +        // sndCwnd = 10
-            "A8050000" +        // advmss = 1448
-            "03000000" +        // reordering = 3
-            "00000000" +        // rcvrtt = 0
-            "30560100" +        // rcvspace = 87600
-            "00000000" +        // totalRetrans = 0
-            "53AC000000000000" +    // pacingRate = 44115
-            "FFFFFFFFFFFFFFFF" +    // maxPacingRate = 18446744073709551615
-            "0100000000000000" +    // bytesAcked = 1
-            "0000000000000000" +    // bytesReceived = 0
-            "0A000000" +        // SegsOut = 10
-            "00000000" +        // SegsIn = 0
-            "00000000" +        // NotSentBytes = 0
-            "3E2C0900" +        // minRtt = 601150
-            "00000000" +        // DataSegsIn = 0
-            "00000000" +        // DataSegsOut = 0
-            "0000000000000000"; // deliverRate = 0
-    private static final byte[] SOCK_DIAG_TCP_INET_BYTES =
-            HexEncoding.decode(SOCK_DIAG_TCP_INET_HEX.toCharArray(), false);
+    private static final String SOCK_DIAG_TCP_ZERO_LOST_HEX =
+            composeSockDiagTcpHex(0 /* lost */, 10 /* sent */);
+    private static final byte[] SOCK_DIAG_TCP_INET_ZERO_LOST_BYTES =
+            HexEncoding.decode(SOCK_DIAG_TCP_ZERO_LOST_HEX.toCharArray(), false);
     private static final TcpInfo TEST_TCPINFO =
             new TcpInfo(5 /* retransmits */, 0 /* lost */, 10 /* segsOut */, 0 /* segsIn */);
-
-    private static final String TEST_RESPONSE_HEX = SOCK_DIAG_TCP_INET_HEX
+    private static final String NLMSG_DONE_HEX =
             // struct nlmsghdr
-            + "14000000"     // length = 20
+            "14000000"     // length = 20
             + "0300"         // type = NLMSG_DONE
             + "0301"         // flags = NLM_F_REQUEST | NLM_F_DUMP
             + "00000000"     // seqno
@@ -195,6 +108,7 @@
             + "06"           // state
             + "00"           // timer
             + "00";          // retrans
+    private static final String TEST_RESPONSE_HEX = SOCK_DIAG_TCP_ZERO_LOST_HEX + NLMSG_DONE_HEX;
     private static final byte[] TEST_RESPONSE_BYTES =
             HexEncoding.decode(TEST_RESPONSE_HEX.toCharArray(), false);
     private static final int TEST_NETID1 = 0xA85;
@@ -207,6 +121,8 @@
     private final Network mNetwork = new Network(TEST_NETID1);
     private final Network mOtherNetwork = new Network(TEST_NETID2);
     private TerribleFailureHandler mOldWtfHandler;
+    @Mock private Context mContext;
+    @Mock private PowerManager mPowerManager;
 
     @Rule
     public final DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
@@ -228,6 +144,7 @@
 
         when(mNetd.getFwmarkForNetwork(eq(TEST_NETID1)))
                 .thenReturn(makeMarkMaskParcel(NETID_MASK, TEST_NETID1_FWMARK));
+        doReturn(mPowerManager).when(mContext).getSystemService(PowerManager.class);
     }
 
     @After
@@ -242,15 +159,20 @@
         return parcel;
     }
 
+    private ByteBuffer getByteBufferFromHexString(String hexStr) {
+        final byte[] bytes = HexEncoding.decode(hexStr.toCharArray(), false);
+        return getByteBuffer(bytes);
+    }
+
     private ByteBuffer getByteBuffer(final byte[] bytes) {
         final ByteBuffer buffer = ByteBuffer.wrap(bytes);
-        buffer.order(ByteOrder.LITTLE_ENDIAN);
+        buffer.order(ByteOrder.nativeOrder());
         return buffer;
     }
 
     @Test
     public void testParseSockInfo() {
-        final ByteBuffer buffer = getByteBuffer(SOCK_DIAG_TCP_INET_BYTES);
+        final ByteBuffer buffer = getByteBuffer(SOCK_DIAG_TCP_INET_ZERO_LOST_BYTES);
         final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mNetwork);
         buffer.position(SOCKDIAG_MSG_HEADER_SIZE);
         final TcpSocketTracker.SocketInfo parsed =
@@ -279,7 +201,7 @@
     @Test @IgnoreUpTo(Build.VERSION_CODES.Q) // TCP info parsing is not supported on Q
     public void testPollSocketsInfo() throws Exception {
         // This test requires shims that provide API 30 access
-        assumeTrue(ConstantsShim.VERSION >= 30);
+        assumeTrue(ConstantsShim.VERSION >= Build.VERSION_CODES.R);
         when(mDependencies.isTcpInfoParsingSupported()).thenReturn(false);
         final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mNetwork);
         assertFalse(tst.pollSocketsInfo());
@@ -287,7 +209,7 @@
         when(mDependencies.isTcpInfoParsingSupported()).thenReturn(true);
         // No enough bytes remain for a valid NlMsg.
         final ByteBuffer invalidBuffer = ByteBuffer.allocate(1);
-        invalidBuffer.order(ByteOrder.LITTLE_ENDIAN);
+        invalidBuffer.order(ByteOrder.nativeOrder());
         when(mDependencies.recvMessage(any())).thenReturn(invalidBuffer);
         assertTrue(tst.pollSocketsInfo());
         assertEquals(-1, tst.getLatestPacketFailPercentage());
@@ -300,8 +222,7 @@
         assertEquals(-1, tst.getLatestPacketFailPercentage());
         assertEquals(0, tst.getSentSinceLastRecv());
 
-        final ByteBuffer tcpBuffer = getByteBuffer(TEST_RESPONSE_BYTES);
-        when(mDependencies.recvMessage(any())).thenReturn(tcpBuffer);
+        setupNormalTestTcpInfo();
         assertTrue(tst.pollSocketsInfo());
 
         assertEquals(10, tst.getSentSinceLastRecv());
@@ -331,17 +252,275 @@
 
         verify(mDependencies, atLeastOnce()).isTcpInfoParsingSupported();
         verifyNoMoreInteractions(mDependencies);
+
+        // Verify that no un-registration for the device configuration listener and broadcast
+        // receiver if TcpInfo parsing is not supported.
+        tst.quit();
+        verify(mDependencies, never()).removeDeviceConfigChangedListener(any());
+        verify(mDependencies, never()).removeBroadcastReceiver(any());
+    }
+
+    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    public void testTcpInfoParsingWithMultipleMsgs() throws Exception {
+        final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mNetwork);
+
+        // Case 1: A message about 5 sockets, then a message about 2 sockets,
+        // then a message about 2 sockets together with DONE
+        //
+        // Mocking 6 return results for different IP families(3 for IPv6; 3 for Ipv4). Use the same
+        // message for different IP families to reduce the complexity.
+        doReturn(getByteBufferFromHexString(repeat(composeSockDiagTcpHex(0, 10), 5)),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(0, 10), 2)),
+                getByteBufferFromHexString(
+                        repeat(composeSockDiagTcpHex(0, 10), 2) + NLMSG_DONE_HEX),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(0, 10), 5)),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(0, 10), 2)),
+                getByteBufferFromHexString(
+                        repeat(composeSockDiagTcpHex(0, 10), 2) + NLMSG_DONE_HEX))
+                .when(mDependencies).recvMessage(any());
+
+        assertTrue(tst.pollSocketsInfo());
+        // Verify that code reads all the messages. (3 times for IPv4, 3 times for IPv6)
+        verify(mDependencies, times(6)).recvMessage(any());
+        // Calculated from (retransmits + lost) / segsout.
+        assertEquals(50, tst.getLatestPacketFailPercentage());
+        // Lower than the 80% threshold
+        assertFalse(tst.isDataStallSuspected());
+
+        // Case 2: A message about 1 socket, then a message about 5 sockets,
+        // then a message about 1 socket with DONE.
+        // "Sent" increases by 5. No change for lost and retrans.
+        //
+        // Mocking 6 return results for different IP families(3 for IPv6; 3 for Ipv4). Use the same
+        // message for different IP families to reduce the complexity.
+        doReturn(getByteBufferFromHexString(composeSockDiagTcpHex(5, 15)),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(5, 15), 5)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15) + NLMSG_DONE_HEX),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15)),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(5, 15), 5)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15) + NLMSG_DONE_HEX))
+                .when(mDependencies).recvMessage(any());
+
+        assertTrue(tst.pollSocketsInfo());
+        // Not reset mDependencies because it will reset other mocks.
+        // Another 3 times for IPv6 and 3 times for IPv4
+        verify(mDependencies, times(12)).recvMessage(any());
+        // (5 lost + 0 retrans)/5 sent
+        assertEquals(100, tst.getLatestPacketFailPercentage());
+        assertTrue(tst.isDataStallSuspected());
+
+        // Case 3: A message about 5 sockets, then a message about 1 socket,
+        // then a message about 1 socket with DONE.
+        // No change for sent, lost and retrans.
+        //
+        // Mocking 4 return results for different IP families(2 for IPv6; 2 for Ipv4). Use the same
+        // message for different IP families to reduce the complexity.
+        doReturn(getByteBufferFromHexString(repeat(composeSockDiagTcpHex(5, 15), 5)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15) + NLMSG_DONE_HEX),
+                getByteBufferFromHexString(repeat(composeSockDiagTcpHex(5, 15), 5)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15)),
+                getByteBufferFromHexString(composeSockDiagTcpHex(5, 15) + NLMSG_DONE_HEX))
+                .when(mDependencies).recvMessage(any());
+
+        assertTrue(tst.pollSocketsInfo());
+        // Another 3 times for IPv6 and 3 times for IPv4
+        verify(mDependencies, times(18)).recvMessage(any());
+        // (0 lost + 0 retrans)/0 sent
+        assertEquals(0, tst.getLatestPacketFailPercentage());
+        // Lower than the 80% threshold
+        assertFalse(tst.isDataStallSuspected());
+
+        // Case 4: A message about 8 sockets with DONE.
+        // "lost" increases by 3 and "sent" increases by 5
+        //
+        // Mocking 2 return results for different IP families(1 for IPv6; 1 for Ipv4). Use the same
+        // message for different IP families to reduce the complexity.
+        doReturn(getByteBufferFromHexString(
+                        repeat(composeSockDiagTcpHex(9, 20), 8) + NLMSG_DONE_HEX),
+                getByteBufferFromHexString(
+                        repeat(composeSockDiagTcpHex(9, 20), 8) + NLMSG_DONE_HEX))
+                .when(mDependencies).recvMessage(any());
+
+        assertTrue(tst.pollSocketsInfo());
+        // Another 1 time for IPv6 and 1 time for IPv4
+        verify(mDependencies, times(20)).recvMessage(any());
+        // (4 lost + 0 retrans)/5 sent
+        assertEquals(80, tst.getLatestPacketFailPercentage());
+        //Reach 80% threshold
+        assertTrue(tst.isDataStallSuspected());
+
+        // Case 5: A message about DONE with 2 sockets.
+        // No socket information will be parsed though "lost" increases by 6 and "sent"
+        // increases by 6.
+        //
+        // Mocking 2 return results for different IP families(1 for IPv6; 1 for Ipv4). Use the same
+        // message for different IP families to reduce the complexity.
+        doReturn(getByteBufferFromHexString(
+                        NLMSG_DONE_HEX + repeat(composeSockDiagTcpHex(15, 26), 2)),
+                getByteBufferFromHexString(
+                        NLMSG_DONE_HEX + repeat(composeSockDiagTcpHex(15, 26), 2)))
+                .when(mDependencies).recvMessage(any());
+        assertTrue(tst.pollSocketsInfo());
+        // Another 1 time for IPv6 and 1 time for IPv4
+        verify(mDependencies, times(22)).recvMessage(any());
+        // (0 lost + 0 retrans)/0 sent.
+        // Parsing will be stopped in DONE message. No socket information will be parsed.
+        assertEquals(0, tst.getLatestPacketFailPercentage());
+        // Lower than the 80% threshold
+        assertFalse(tst.isDataStallSuspected());
+    }
+
+    private String repeat(String orig, int times) {
+        if (SdkLevel.isAtLeastT()) {
+            // Only supported from Java 11
+            return orig.repeat(times);
+        } else {
+            String repeated = "";
+            for (int i = 0; i < times; i++) {
+                repeated += orig;
+            }
+            return repeated;
+        }
+    }
+
+    private static String getHexStringFromInt(int v) {
+        final ByteBuffer bb = ByteBuffer.allocate(4);
+        // Android is always little-endian. Refer to https://developer.android.com/ndk/guides/abis.
+        bb.order(ByteOrder.nativeOrder());
+        bb.putInt(v);
+        String s = "";
+        for (byte b : bb.array()) {
+            s += String.format("%02X", b);
+        }
+        return s;
+    }
+
+    private static String composeSockDiagTcpHex(int lost, int sent) {
+        return // struct nlmsghdr.
+                "14010000" +        // length = 276
+                "1400" +            // type = SOCK_DIAG_BY_FAMILY
+                "0301" +            // flags = NLM_F_REQUEST | NLM_F_DUMP
+                "00000000" +        // seqno
+                "00000000" +        // pid (0 == kernel)
+                // struct inet_diag_req_v2
+                "02" +              // family = AF_INET
+                "06" +              // state
+                "00" +              // timer
+                "00" +              // retrans
+                // inet_diag_sockid
+                "DEA5" +            // idiag_sport = 42462
+                "71B9" +            // idiag_dport = 47473
+                "0a006402000000000000000000000000" + // idiag_src = 10.0.100.2
+                "08080808000000000000000000000000" + // idiag_dst = 8.8.8.8
+                "00000000" +            // idiag_if
+                "34ED000076270000" +    // idiag_cookie = 43387759684916
+                "00000000" +            // idiag_expires
+                "00000000" +            // idiag_rqueue
+                "00000000" +            // idiag_wqueue
+                "00000000" +            // idiag_uid
+                "00000000" +            // idiag_inode
+                // rtattr
+                "0500" +            // len = 5
+                "0800" +            // type = 8
+                "00000000" +        // data
+                "0800" +            // len = 8
+                "0F00" +            // type = 15(INET_DIAG_MARK)
+                "850A0C00" +        // data, socket mark=789125
+                "AC00" +            // len = 172
+                "0200" +            // type = 2(INET_DIAG_INFO)
+                // tcp_info
+                "01" +              // state = TCP_ESTABLISHED
+                "00" +              // ca_state = TCP_CA_OPEN
+                "05" +              // retransmits = 5
+                "00" +              // probes = 0
+                "00" +              // backoff = 0
+                "07" +              // option = TCPI_OPT_WSCALE|TCPI_OPT_SACK|TCPI_OPT_TIMESTAMPS
+                "88" +              // wscale = 8
+                "00" +              // delivery_rate_app_limited = 0
+                "4A911B00" +        // rto = 1806666
+                "00000000" +        // ato = 0
+                "2E050000" +        // sndMss = 1326
+                "18020000" +        // rcvMss = 536
+                "00000000" +        // unsacked = 0
+                "00000000" +        // acked = 0
+                getHexStringFromInt(lost) + // lost
+                "00000000" +        // retrans = 0
+                "00000000" +        // fackets = 0
+                "BB000000" +        // lastDataSent = 187
+                "00000000" +        // lastAckSent = 0
+                "BB000000" +        // lastDataRecv = 187
+                "BB000000" +        // lastDataAckRecv = 187
+                "DC050000" +        // pmtu = 1500
+                "30560100" +        // rcvSsthresh = 87600
+                "3E2C0900" +        // rttt = 601150
+                "1F960400" +        // rttvar = 300575
+                "78050000" +        // sndSsthresh = 1400
+                "0A000000" +        // sndCwnd = 10
+                "A8050000" +        // advmss = 1448
+                "03000000" +        // reordering = 3
+                "00000000" +        // rcvrtt = 0
+                "30560100" +        // rcvspace = 87600
+                "00000000" +        // totalRetrans = 0
+                "53AC000000000000" +    // pacingRate = 44115
+                "FFFFFFFFFFFFFFFF" +    // maxPacingRate = 18446744073709551615
+                "0100000000000000" +    // bytesAcked = 1
+                "0000000000000000" +    // bytesReceived = 0
+                getHexStringFromInt(sent) + // SegsOut
+                "00000000" +        // SegsIn = 0
+                "00000000" +        // NotSentBytes = 0
+                "3E2C0900" +        // minRtt = 601150
+                "00000000" +        // DataSegsIn = 0
+                "00000000" +        // DataSegsOut = 0
+                "0000000000000000"; // deliverRate = 0
+    }
+
+    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    public void testTcpInfoParsingWithDozeMode() throws Exception {
+        // This test requires shims that provide API 30 access
+        assumeTrue(ConstantsShim.VERSION >= Build.VERSION_CODES.R);
+
+        final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mNetwork);
+        final ArgumentCaptor<BroadcastReceiver> receiverCaptor =
+                ArgumentCaptor.forClass(BroadcastReceiver.class);
+
+        verify(mDependencies).addDeviceIdleReceiver(receiverCaptor.capture());
+        setupNormalTestTcpInfo();
+        assertTrue(tst.pollSocketsInfo());
+
+        // Lower the threshold.
+        when(mDependencies.getDeviceConfigPropertyInt(any(), eq(CONFIG_TCP_PACKETS_FAIL_PERCENTAGE),
+                anyInt())).thenReturn(40);
+
+        // Trigger a config update
+        tst.mConfigListener.onPropertiesChanged(null /* properties */);
+        assertEquals(10, tst.getSentSinceLastRecv());
+        assertEquals(50, tst.getLatestPacketFailPercentage());
+        assertTrue(tst.isDataStallSuspected());
+
+        // Enable doze mode
+        doReturn(true).when(mPowerManager).isDeviceIdleMode();
+        final BroadcastReceiver receiver = receiverCaptor.getValue();
+        receiver.onReceive(mContext, new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
+        assertFalse(tst.pollSocketsInfo());
+        assertFalse(tst.isDataStallSuspected());
+    }
+
+    private void setupNormalTestTcpInfo() throws Exception {
+        final ByteBuffer tcpBufferV6 = getByteBuffer(TEST_RESPONSE_BYTES);
+        final ByteBuffer tcpBufferV4 = getByteBuffer(TEST_RESPONSE_BYTES);
+        doReturn(tcpBufferV6, tcpBufferV4).when(mDependencies).recvMessage(any());
     }
 
     @Test @IgnoreAfter(Build.VERSION_CODES.Q)
     public void testTcpInfoParsingNotSupportedOnQ() {
-        assertFalse(new TcpSocketTracker.Dependencies(getInstrumentation().getContext())
+        assertFalse(new TcpSocketTracker.Dependencies(mContext)
                 .isTcpInfoParsingSupported());
     }
 
     @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
     public void testTcpInfoParsingSupportedFromR() {
-        assertTrue(new TcpSocketTracker.Dependencies(getInstrumentation().getContext())
+        assertTrue(new TcpSocketTracker.Dependencies(mContext)
                 .isTcpInfoParsingSupported());
     }
 
@@ -375,17 +554,16 @@
     @Test @IgnoreUpTo(Build.VERSION_CODES.Q) // TCP info parsing is not supported on Q
     public void testPollSocketsInfo_BadFormat() throws Exception {
         // This test requires shims that provide API 30 access
-        assumeTrue(ConstantsShim.VERSION >= 30);
+        assumeTrue(ConstantsShim.VERSION >= Build.VERSION_CODES.R);
         final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mNetwork);
-        ByteBuffer tcpBuffer = getByteBuffer(TEST_RESPONSE_BYTES);
-
-        when(mDependencies.recvMessage(any())).thenReturn(tcpBuffer);
+        setupNormalTestTcpInfo();
         assertTrue(tst.pollSocketsInfo());
         assertEquals(10, tst.getSentSinceLastRecv());
         assertEquals(50, tst.getLatestPacketFailPercentage());
 
-        tcpBuffer = getByteBuffer(BAD_SOCK_DIAG_MSG_BYTES);
-        when(mDependencies.recvMessage(any())).thenReturn(tcpBuffer);
+        final ByteBuffer badTcpBufferV6 = getByteBuffer(BAD_SOCK_DIAG_MSG_BYTES);
+        final ByteBuffer badTcpBufferV4 = getByteBuffer(BAD_SOCK_DIAG_MSG_BYTES);
+        doReturn(badTcpBufferV6, badTcpBufferV4).when(mDependencies).recvMessage(any());
         assertTrue(tst.pollSocketsInfo());
         // Expect no additional packets, so still 10.
         assertEquals(10, tst.getSentSinceLastRecv());
@@ -398,8 +576,7 @@
         when(mNetd.getFwmarkForNetwork(eq(TEST_NETID2)))
                 .thenReturn(makeMarkMaskParcel(NETID_MASK, TEST_NETID2_FWMARK));
         final TcpSocketTracker tst = new TcpSocketTracker(mDependencies, mOtherNetwork);
-        final ByteBuffer tcpBuffer = getByteBuffer(TEST_RESPONSE_BYTES);
-        when(mDependencies.recvMessage(any())).thenReturn(tcpBuffer);
+        setupNormalTestTcpInfo();
         assertTrue(tst.pollSocketsInfo());
 
         assertEquals(0, tst.getSentSinceLastRecv());
diff --git a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
index bf8a6e5..a9e5950 100644
--- a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -47,12 +47,6 @@
 import static android.net.util.DataStallUtils.DATA_STALL_EVALUATION_TYPE_DNS;
 import static android.net.util.DataStallUtils.DATA_STALL_EVALUATION_TYPE_TCP;
 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_EVALUATION_TYPES;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS;
-import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_USE_HTTPS;
-import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT;
-import static android.net.util.NetworkStackUtils.DISMISS_PORTAL_IN_VALIDATED_NETWORK;
-import static android.net.util.NetworkStackUtils.DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION;
 import static android.os.Build.VERSION_CODES.S_V2;
 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
 
@@ -60,6 +54,14 @@
 import static com.android.net.module.util.NetworkStackConstants.TEST_CAPTIVE_PORTAL_HTTP_URL;
 import static com.android.net.module.util.NetworkStackConstants.TEST_URL_EXPIRATION_TIME;
 import static com.android.networkstack.util.DnsUtils.PRIVATE_DNS_PROBE_HOST_SUFFIX;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_IGNORE;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_PROMPT;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS;
+import static com.android.networkstack.util.NetworkStackUtils.CAPTIVE_PORTAL_USE_HTTPS;
+import static com.android.networkstack.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT;
+import static com.android.networkstack.util.NetworkStackUtils.DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION;
 import static com.android.server.connectivity.NetworkMonitor.INITIAL_REEVALUATE_DELAY_MS;
 import static com.android.server.connectivity.NetworkMonitor.extractCharset;
 
@@ -74,7 +76,6 @@
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
-import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.after;
@@ -92,7 +93,6 @@
 import static org.mockito.Mockito.timeout;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
 import static java.lang.System.currentTimeMillis;
 import static java.util.Collections.singletonList;
@@ -301,6 +301,7 @@
 
     private static final int HANDLER_TIMEOUT_MS = 1000;
     private static final int TEST_MIN_STALL_EVALUATE_INTERVAL_MS = 500;
+    private static final int TEST_MIN_VALID_STALL_DNS_TIME_THRESHOLD_MS = 5000;
     private static final int STALL_EXPECTED_LAST_PROBE_TIME_MS =
             TEST_MIN_STALL_EVALUATE_INTERVAL_MS + HANDLER_TIMEOUT_MS;
     private static final NetworkAgentConfigShim TEST_AGENT_CONFIG =
@@ -475,46 +476,46 @@
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        when(mDependencies.getPrivateDnsBypassNetwork(any())).thenReturn(mCleartextDnsNetwork);
-        when(mDependencies.getDnsResolver()).thenReturn(mDnsResolver);
-        when(mDependencies.getRandom()).thenReturn(mRandom);
-        when(mDependencies.getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_MODE), anyInt()))
-                .thenReturn(Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
-        when(mDependencies.getDeviceConfigPropertyInt(any(), eq(CAPTIVE_PORTAL_USE_HTTPS),
-                anyInt())).thenReturn(1);
-        when(mDependencies.getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any()))
-                .thenReturn(TEST_HTTP_URL);
-        when(mDependencies.getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTPS_URL), any()))
-                .thenReturn(TEST_HTTPS_URL);
+        doReturn(mCleartextDnsNetwork).when(mDependencies).getPrivateDnsBypassNetwork(any());
+        doReturn(mDnsResolver).when(mDependencies).getDnsResolver();
+        doReturn(mRandom).when(mDependencies).getRandom();
+        doReturn(Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT).when(mDependencies)
+                .getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_MODE), anyInt());
+        doReturn(1).when(mDependencies)
+                .getDeviceConfigPropertyInt(any(), eq(CAPTIVE_PORTAL_USE_HTTPS), anyInt());
+        doReturn(TEST_HTTP_URL).when(mDependencies)
+                .getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any());
+        doReturn(TEST_HTTPS_URL).when(mDependencies)
+                .getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTPS_URL), any());
 
         doReturn(mCleartextDnsNetwork).when(mNetwork).getPrivateDnsBypassingCopy();
 
-        when(mContext.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(mCm);
-        when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephony);
-        when(mContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(mWifi);
-        when(mContext.getResources()).thenReturn(mResources);
+        doReturn(mCm).when(mContext).getSystemService(Context.CONNECTIVITY_SERVICE);
+        doReturn(mTelephony).when(mContext).getSystemService(Context.TELEPHONY_SERVICE);
+        doReturn(mWifi).when(mContext).getSystemService(Context.WIFI_SERVICE);
+        doReturn(mResources).when(mContext).getResources();
 
-        when(mServiceManager.getNotifier()).thenReturn(mNotifier);
+        doReturn(mNotifier).when(mServiceManager).getNotifier();
 
-        when(mTelephony.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_LTE);
-        when(mTelephony.getNetworkOperator()).thenReturn(TEST_MCCMNC);
-        when(mTelephony.getSimOperator()).thenReturn(TEST_MCCMNC);
+        doReturn(TelephonyManager.NETWORK_TYPE_LTE).when(mTelephony).getDataNetworkType();
+        doReturn(TEST_MCCMNC).when(mTelephony).getNetworkOperator();
+        doReturn(TEST_MCCMNC).when(mTelephony).getSimOperator();
 
-        when(mResources.getString(anyInt())).thenReturn("");
-        when(mResources.getStringArray(anyInt())).thenReturn(new String[0]);
+        doReturn("").when(mResources).getString(anyInt());
+        doReturn(new String[0]).when(mResources).getStringArray(anyInt());
         doReturn(mConfiguration).when(mResources).getConfiguration();
-        when(mMccContext.getResources()).thenReturn(mMccResource);
+        doReturn(mMccResource).when(mMccContext).getResources();
 
         setFallbackUrl(TEST_FALLBACK_URL);
         setOtherFallbackUrls(TEST_OTHER_FALLBACK_URL);
         setFallbackSpecs(null); // Test with no fallback spec by default
-        when(mRandom.nextInt()).thenReturn(0);
+        doReturn(0).when(mRandom).nextInt();
 
-        when(mTstDependencies.getNetd()).thenReturn(mNetd);
+        doReturn(mNetd).when(mTstDependencies).getNetd();
         // DNS probe timeout should not be defined more than half of HANDLER_TIMEOUT_MS. Otherwise,
         // it will fail the test because of timeout expired for querying AAAA and A sequentially.
-        when(mResources.getInteger(eq(R.integer.config_captive_portal_dns_probe_timeout)))
-                .thenReturn(200);
+        doReturn(200).when(mResources)
+                .getInteger(eq(R.integer.config_captive_portal_dns_probe_timeout));
 
         doAnswer((invocation) -> {
             URL url = invocation.getArgument(0);
@@ -547,8 +548,8 @@
                     return null;
             }
         }).when(mCleartextDnsNetwork).openConnection(any());
-        when(mHttpConnection.getRequestProperties()).thenReturn(new ArrayMap<>());
-        when(mHttpsConnection.getRequestProperties()).thenReturn(new ArrayMap<>());
+        doReturn(new ArrayMap<>()).when(mHttpConnection).getRequestProperties();
+        doReturn(new ArrayMap<>()).when(mHttpsConnection).getRequestProperties();
 
         mFakeDns = new FakeDns();
         mFakeDns.startMocking();
@@ -560,15 +561,14 @@
         mFakeDns.setAnswer(PRIVATE_DNS_PROBE_HOST_SUFFIX, new String[]{"192.0.2.2"}, TYPE_A);
         mFakeDns.setAnswer(PRIVATE_DNS_PROBE_HOST_SUFFIX, new String[]{"2001:db8::1"}, TYPE_AAAA);
 
-        when(mContext.registerReceiver(any(BroadcastReceiver.class), any())).then((invocation) -> {
+        doAnswer((invocation) -> {
             mRegisteredReceivers.add(invocation.getArgument(0));
             return new Intent();
-        });
-        when(mContext.registerReceiver(any(BroadcastReceiver.class), any(), anyInt())).then(
-                (invocation) -> {
-                    mRegisteredReceivers.add(invocation.getArgument(0));
-                    return new Intent();
-                });
+        }).when(mContext).registerReceiver(any(BroadcastReceiver.class), any());
+        doAnswer((invocation) -> {
+            mRegisteredReceivers.add(invocation.getArgument(0));
+            return new Intent();
+        }).when(mContext).registerReceiver(any(BroadcastReceiver.class), any(), anyInt());
 
         doAnswer((invocation) -> {
             mRegisteredReceivers.remove(invocation.getArgument(0));
@@ -579,11 +579,10 @@
 
         setMinDataStallEvaluateInterval(TEST_MIN_STALL_EVALUATE_INTERVAL_MS);
         setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS);
-        setValidDataStallDnsTimeThreshold(500);
+        setValidDataStallDnsTimeThreshold(TEST_MIN_VALID_STALL_DNS_TIME_THRESHOLD_MS);
         setConsecutiveDnsTimeoutThreshold(5);
         mCreatedNetworkMonitors = new HashSet<>();
         mRegisteredReceivers = new HashSet<>();
-        setDismissPortalInValidatedNetwork(false);
     }
 
     @After
@@ -621,8 +620,18 @@
         }
     }
 
-    private TcpSocketTracker getTcpSocketTrackerOrNull(NetworkMonitor.Dependencies dp) {
-        return ((dp.getDeviceConfigPropertyInt(
+    private boolean getIsCaptivePortalCheckEnabled(Context context,
+                NetworkMonitor.Dependencies dp) {
+        String symbol = CAPTIVE_PORTAL_MODE;
+        int defaultValue = CAPTIVE_PORTAL_MODE_PROMPT;
+        int mode = dp.getSetting(context, symbol, defaultValue);
+        return mode != CAPTIVE_PORTAL_MODE_IGNORE;
+    }
+
+    private TcpSocketTracker getTcpSocketTrackerOrNull(Context context,
+                NetworkMonitor.Dependencies dp) {
+        return (getIsCaptivePortalCheckEnabled(context, dp)
+                && (dp.getDeviceConfigPropertyInt(
                 NAMESPACE_CONNECTIVITY,
                 CONFIG_DATA_STALL_EVALUATION_TYPE,
                 DEFAULT_DATA_STALL_EVALUATION_TYPES)
@@ -635,7 +644,7 @@
 
         WrappedNetworkMonitor() {
             super(mContext, mCallbacks, mNetwork, mLogger, mValidationLogger, mServiceManager,
-                    mDependencies, getTcpSocketTrackerOrNull(mDependencies));
+                    mDependencies, getTcpSocketTrackerOrNull(mContext, mDependencies));
         }
 
         @Override
@@ -677,7 +686,7 @@
         setNetworkCapabilities(nm, nc);
         HandlerUtils.waitForIdle(nm.getHandler(), HANDLER_TIMEOUT_MS);
         mCreatedNetworkMonitors.add(nm);
-        when(mTstDependencies.isTcpInfoParsingSupported()).thenReturn(false);
+        doReturn(false).when(mTstDependencies).isTcpInfoParsingSupported();
 
         return nm;
     }
@@ -890,8 +899,8 @@
         doReturn(TEST_HTTP_URL).when(mResources).getString(R.string.config_captive_portal_http_url);
         doReturn(TEST_HTTP_OTHER_URL2).when(mResources).getString(
                 R.string.default_captive_portal_http_url);
-        when(mDependencies.getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any()))
-                .thenReturn(TEST_HTTP_OTHER_URL1);
+        doReturn(TEST_HTTP_OTHER_URL1).when(mDependencies)
+                .getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any());
         final WrappedNetworkMonitor wnm = makeCellNotMeteredNetworkMonitor();
         assertEquals(TEST_HTTP_URL, wnm.getCaptivePortalServerHttpUrl(mContext));
         // If config_captive_portal_http_url is unset and the global setting is set, the global
@@ -901,8 +910,8 @@
         // If both config_captive_portal_http_url and global setting are unset,
         // default_captive_portal_http_url is used. But the global setting will only be read in the
         // constructor.
-        when(mDependencies.getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any()))
-                .thenReturn(null);
+        doReturn(null).when(mDependencies)
+                .getSetting(any(), eq(Settings.Global.CAPTIVE_PORTAL_HTTP_URL), any());
         assertEquals(TEST_HTTP_OTHER_URL1, wnm.getCaptivePortalServerHttpUrl(mContext));
         // default_captive_portal_http_url is used when the configuration is applied in new NM.
         final WrappedNetworkMonitor wnm2 = makeCellNotMeteredNetworkMonitor();
@@ -940,6 +949,16 @@
         assertEquals(wnm.getContext(), wnm.getCustomizedContextOrDefault());
     }
 
+    private void checkCustomizedContextByCarrierId(WrappedNetworkMonitor wnm, int carrierId) {
+        doReturn(carrierId).when(mTelephony).getSimCarrierId();
+        assertNotNull(wnm.getMccMncOverrideInfo());
+        // Check if the mcc & mnc has changed as expected.
+        assertEquals(460,
+                wnm.getCustomizedContextOrDefault().getResources().getConfiguration().mcc);
+        assertEquals(03,
+                wnm.getCustomizedContextOrDefault().getResources().getConfiguration().mnc);
+    }
+
     @Test
     public void testGetMccMncOverrideInfo() {
         final WrappedNetworkMonitor wnm = makeCellNotMeteredNetworkMonitor();
@@ -948,13 +967,10 @@
         doReturn(1839).when(mTelephony).getSimCarrierId();
         assertNull(wnm.getMccMncOverrideInfo());
         // 1854 is CTC's carrier id.
-        doReturn(1854).when(mTelephony).getSimCarrierId();
-        assertNotNull(wnm.getMccMncOverrideInfo());
-        // Check if the mcc & mnc has changed as expected.
-        assertEquals(460,
-                wnm.getCustomizedContextOrDefault().getResources().getConfiguration().mcc);
-        assertEquals(03,
-                wnm.getCustomizedContextOrDefault().getResources().getConfiguration().mnc);
+        // This line should be removed when the production code is corrected.
+        checkCustomizedContextByCarrierId(wnm, 1854);
+        // 2237 is CT's carrier id.
+        checkCustomizedContextByCarrierId(wnm, 2237);
         // Every mcc and mnc should be set in sCarrierIdToMccMnc.
         // Check if there is any unset value in mcc or mnc.
         for (int i = 0; i < wnm.sCarrierIdToMccMnc.size(); i++) {
@@ -1050,8 +1066,8 @@
         // Clear setting provider value. Verify it to get configuration from resource instead.
         setFallbackUrl(null);
         // Verify that getting resource with exception.
-        when(mResources.getStringArray(R.array.config_captive_portal_fallback_urls))
-                .thenThrow(Resources.NotFoundException.class);
+        doThrow(Resources.NotFoundException.class).when(mResources)
+                .getStringArray(R.array.config_captive_portal_fallback_urls);
         urls = wnm.makeCaptivePortalFallbackUrls(mContext);
         assertEquals(urls.length, 0);
 
@@ -1138,17 +1154,16 @@
                 DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT));
 
         // Set device config. Expect to get device config.
-        when(mDependencies.getDeviceConfigPropertyInt(any(),
-                eq(NetworkMonitor.CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT), anyInt()))
-                        .thenReturn(1234);
+        doReturn(1234).when(mDependencies).getDeviceConfigPropertyInt(any(),
+                eq(NetworkMonitor.CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT), anyInt());
         assertEquals(1234, wnm.getIntSetting(mContext,
                 R.integer.config_captive_portal_dns_probe_timeout,
                 NetworkMonitor.CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT,
                 DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT));
 
         // Set config resource. Expect to get config resource.
-        when(mResources.getInteger(eq(R.integer.config_captive_portal_dns_probe_timeout)))
-                .thenReturn(5678);
+        doReturn(5678).when(mResources)
+                        .getInteger(eq(R.integer.config_captive_portal_dns_probe_timeout));
         assertEquals(5678, wnm.getIntSetting(mContext,
                 R.integer.config_captive_portal_dns_probe_timeout,
                 NetworkMonitor.CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT,
@@ -1202,16 +1217,16 @@
 
     @Test
     public void testIsCaptivePortal_PrivateIpNotPortal_Enabled_IPv4() throws Exception {
-        when(mDependencies.isFeatureEnabled(any(), eq(DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION)))
-                .thenReturn(true);
+        doReturn(true).when(mDependencies)
+                .isFeatureEnabled(any(), eq(DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION));
         setupPrivateIpResponse("192.168.1.1");
         runFailedNetworkTest();
     }
 
     @Test
     public void testIsCaptivePortal_PrivateIpNotPortal_Enabled_IPv6() throws Exception {
-        when(mDependencies.isFeatureEnabled(any(), eq(DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION)))
-                .thenReturn(true);
+        doReturn(true).when(mDependencies)
+                .isFeatureEnabled(any(), eq(DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION));
         setupPrivateIpResponse("fec0:1234::1");
         runFailedNetworkTest();
     }
@@ -1268,7 +1283,7 @@
         setPortal302(mOtherFallbackConnection);
 
         // TEST_OTHER_FALLBACK_URL is third
-        when(mRandom.nextInt()).thenReturn(2);
+        doReturn(2).when(mRandom).nextInt();
 
         // First check always uses the first fallback URL: inconclusive
         final NetworkMonitor monitor = runFailedNetworkTest();
@@ -1613,7 +1628,7 @@
         setStatus(mHttpConnection, 500);
 
         // Use the 2nd fallback spec
-        when(mRandom.nextInt()).thenReturn(1);
+        doReturn(1).when(mRandom).nextInt();
     }
 
     @Test
@@ -1757,6 +1772,17 @@
     }
 
     @Test
+    public void testIsDataStall_EvaluationDisabledOnIgnorePortal() {
+        setCaptivePortalMode(Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE);
+        setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS);
+        final WrappedNetworkMonitor nm = makeCellMeteredNetworkMonitor();
+        nm.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
+
+        assertNull(nm.getDnsStallDetector());
+        assertFalse(nm.isDataStall());
+    }
+
+    @Test
     public void testIsDataStall_EvaluationDnsOnNotMeteredNetwork() throws Exception {
         WrappedNetworkMonitor wrappedMonitor = makeCellNotMeteredNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
@@ -1819,9 +1845,9 @@
     public void testIsDataStall_SkipEvaluateOnValidationNotRequiredNetwork() {
         // Make DNS and TCP stall condition satisfied.
         setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS | DATA_STALL_EVALUATION_TYPE_TCP);
-        when(mTstDependencies.isTcpInfoParsingSupported()).thenReturn(true);
-        when(mTst.getLatestReceivedCount()).thenReturn(0);
-        when(mTst.isDataStallSuspected()).thenReturn(true);
+        doReturn(true).when(mTstDependencies).isTcpInfoParsingSupported();
+        doReturn(0).when(mTst).getLatestReceivedCount();
+        doReturn(true).when(mTst).isDataStallSuspected();
         final WrappedNetworkMonitor nm = makeMonitor(CELL_NO_INTERNET_CAPABILITIES);
         nm.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         makeDnsTimeoutEvent(nm, DEFAULT_DNS_TIMEOUT_THRESHOLD);
@@ -1854,21 +1880,21 @@
 
     @Test
     public void testIsDataStall_EvaluationTcp() throws Exception {
-        when(mTstDependencies.isTcpInfoParsingSupported()).thenReturn(true);
+        doReturn(true).when(mTstDependencies).isTcpInfoParsingSupported();
         // Evaluate TCP only. Expect ignoring DNS signal.
         setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_TCP);
         WrappedNetworkMonitor wrappedMonitor = makeMonitor(CELL_METERED_CAPABILITIES);
         assertFalse(wrappedMonitor.isDataStall());
         // Packet received.
-        when(mTst.getLatestReceivedCount()).thenReturn(5);
+        doReturn(5).when(mTst).getLatestReceivedCount();
         // Trigger a tcp event immediately.
         setTcpPollingInterval(0);
         wrappedMonitor.sendTcpPollingEvent();
         HandlerUtils.waitForIdle(wrappedMonitor.getHandler(), HANDLER_TIMEOUT_MS);
         assertFalse(wrappedMonitor.isDataStall());
 
-        when(mTst.getLatestReceivedCount()).thenReturn(0);
-        when(mTst.isDataStallSuspected()).thenReturn(true);
+        doReturn(0).when(mTst).getLatestReceivedCount();
+        doReturn(true).when(mTst).isDataStallSuspected();
         // Trigger a tcp event immediately.
         setTcpPollingInterval(0);
         wrappedMonitor.sendTcpPollingEvent();
@@ -1888,7 +1914,7 @@
         verify(mCallbacks).notifyDataStallSuspected(
                 matchDnsAndTcpDataStallParcelable(DEFAULT_DNS_TIMEOUT_THRESHOLD));
 
-        when(mTst.getLatestReceivedCount()).thenReturn(5);
+        doReturn(5).when(mTst).getLatestReceivedCount();
         // Trigger a tcp event immediately.
         setTcpPollingInterval(0);
         nm.sendTcpPollingEvent();
@@ -1966,7 +1992,7 @@
                 NETWORK_VALIDATION_RESULT_VALID | NETWORK_VALIDATION_RESULT_SKIPPED);
     }
 
-    private NetworkCapabilities getVcnUnderlyingCarrierWifiCaps() {
+    private static NetworkCapabilities makeVcnUnderlyingCarrierWifiCaps() {
         // Must be called from within the test because NOT_VCN_MANAGED is an invalid capability
         // value up to Android R. Thus, this must be guarded by an SDK check in tests that use this.
         return new NetworkCapabilities.Builder()
@@ -1985,7 +2011,7 @@
         setStatus(mHttpConnection, 204);
 
         final NetworkMonitor nm = runNetworkTest(TEST_AGENT_CONFIG,
-                TEST_LINK_PROPERTIES, getVcnUnderlyingCarrierWifiCaps(),
+                TEST_LINK_PROPERTIES, makeVcnUnderlyingCarrierWifiCaps(),
                 NETWORK_VALIDATION_RESULT_VALID,
                 NETWORK_VALIDATION_PROBE_DNS | NETWORK_VALIDATION_PROBE_HTTPS,
                 null /* redirectUrl */);
@@ -2001,16 +2027,67 @@
         setStatus(mFallbackConnection, 404);
 
         final NetworkMonitor nm = runNetworkTest(TEST_AGENT_CONFIG,
-                TEST_LINK_PROPERTIES, getVcnUnderlyingCarrierWifiCaps(),
+                TEST_LINK_PROPERTIES, makeVcnUnderlyingCarrierWifiCaps(),
                 VALIDATION_RESULT_INVALID, 0 /* probesSucceeded */, null /* redirectUrl */);
         assertEquals(VALIDATION_RESULT_INVALID,
                 nm.getEvaluationState().getEvaluationResult());
     }
 
-    public void setupAndLaunchCaptivePortalApp(final NetworkMonitor nm) throws Exception {
+    private static NetworkCapabilities makeDunNetworkCaps() {
+        return new NetworkCapabilities.Builder()
+                .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
+                .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
+                .addCapability(NetworkCapabilities.NET_CAPABILITY_DUN)
+                .build();
+    }
+
+    @Test @IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
+    public void testDunNetwork() throws Exception {
+        setStatus(mHttpsConnection, 204);
+        setStatus(mHttpConnection, 204);
+
+        runNetworkTest(TEST_AGENT_CONFIG,
+                TEST_LINK_PROPERTIES, makeDunNetworkCaps(),
+                NETWORK_VALIDATION_RESULT_VALID,
+                NETWORK_VALIDATION_PROBE_DNS | NETWORK_VALIDATION_PROBE_HTTPS,
+                null /* redirectUrl */);
+    }
+
+    @Test @IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
+    public void testDunNetwork_BadNetwork() throws Exception {
+        setStatus(mHttpsConnection, 500);
+        setStatus(mHttpConnection, 500);
+
+        runNetworkTest(TEST_AGENT_CONFIG,
+                TEST_LINK_PROPERTIES, makeDunNetworkCaps(),
+                VALIDATION_RESULT_INVALID, 0 /* probesSucceeded */, null /* redirectUrl */);
+    }
+
+    @Test @IgnoreAfter(Build.VERSION_CODES.TIRAMISU)
+    public void testDunNetwork_UpToT_Disabled() throws Exception {
+        doValidationSkippedTest(makeDunNetworkCaps(),
+                NETWORK_VALIDATION_RESULT_VALID | NETWORK_VALIDATION_RESULT_SKIPPED);
+    }
+
+    @Test @IgnoreAfter(Build.VERSION_CODES.TIRAMISU)
+    public void testDunNetwork_UpToT_Enabled() throws Exception {
+        doReturn(true).when(mResources).getBoolean(R.bool.config_validate_dun_networks);
+
+        setStatus(mHttpsConnection, 204);
+        setStatus(mHttpConnection, 204);
+
+        runNetworkTest(TEST_AGENT_CONFIG,
+                TEST_LINK_PROPERTIES, makeDunNetworkCaps(),
+                NETWORK_VALIDATION_RESULT_VALID,
+                NETWORK_VALIDATION_PROBE_DNS | NETWORK_VALIDATION_PROBE_HTTPS,
+                null /* redirectUrl */);
+    }
+
+    public void setupAndLaunchCaptivePortalApp(final NetworkMonitor nm, String expectedUrl)
+            throws Exception {
         setSslException(mHttpsConnection);
         setPortal302(mHttpConnection);
-        when(mHttpConnection.getHeaderField(eq("location"))).thenReturn(TEST_LOGIN_URL);
+        doReturn(TEST_LOGIN_URL).when(mHttpConnection).getHeaderField(eq("location"));
         notifyNetworkConnected(nm, CELL_METERED_CAPABILITIES);
 
         verify(mCallbacks, timeout(HANDLER_TIMEOUT_MS).times(1))
@@ -2035,15 +2112,27 @@
         assertEquals(TEST_NETID, networkCaptor.getValue().netId);
         // Portal URL should be detection URL.
         final String redirectUrl = bundle.getString(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL);
-        assertEquals(TEST_HTTP_URL, redirectUrl);
+        assertEquals(expectedUrl, redirectUrl);
 
         resetCallbacks();
     }
 
+
     @Test
-    public void testCaptivePortalLogin() throws Exception {
+    public void testCaptivePortalLogin_beforeR() throws Exception {
+        assumeFalse(ShimUtils.isAtLeastR());
+        testCaptivePortalLogin(TEST_HTTP_URL);
+    }
+
+    @Test
+    public void testCaptivePortalLogin_AfterR() throws Exception {
+        assumeTrue(ShimUtils.isAtLeastR());
+        testCaptivePortalLogin(TEST_LOGIN_URL);
+    }
+
+    private void testCaptivePortalLogin(String expectedUrl) throws Exception {
         final NetworkMonitor nm = makeMonitor(CELL_METERED_CAPABILITIES);
-        setupAndLaunchCaptivePortalApp(nm);
+        setupAndLaunchCaptivePortalApp(nm, expectedUrl);
 
         // Have the app report that the captive portal is dismissed, and check that we revalidate.
         setStatus(mHttpsConnection, 204);
@@ -2058,9 +2147,20 @@
     }
 
     @Test
-    public void testCaptivePortalUseAsIs() throws Exception {
+    public void testCaptivePortalUseAsIs_beforeR() throws Exception {
+        assumeFalse(ShimUtils.isAtLeastR());
+        testCaptivePortalUseAsIs(TEST_HTTP_URL);
+    }
+
+    @Test
+    public void testCaptivePortalUseAsIs_AfterR() throws Exception {
+        assumeTrue(ShimUtils.isAtLeastR());
+        testCaptivePortalUseAsIs(TEST_LOGIN_URL);
+    }
+
+    private void testCaptivePortalUseAsIs(String expectedUrl) throws Exception {
         final NetworkMonitor nm = makeMonitor(CELL_METERED_CAPABILITIES);
-        setupAndLaunchCaptivePortalApp(nm);
+        setupAndLaunchCaptivePortalApp(nm, expectedUrl);
 
         // The user decides this network is wanted as is, either by encountering an SSL error or
         // encountering an unknown scheme and then deciding to continue through the browser, or by
@@ -2291,12 +2391,12 @@
     }
 
     private void setupTcpDataStall() {
-        when(mTstDependencies.isTcpInfoParsingSupported()).thenReturn(true);
-        when(mTst.getLatestReceivedCount()).thenReturn(0);
-        when(mTst.getLatestPacketFailPercentage()).thenReturn(TEST_TCP_FAIL_RATE);
-        when(mTst.getSentSinceLastRecv()).thenReturn(TEST_TCP_PACKET_COUNT);
-        when(mTst.isDataStallSuspected()).thenReturn(true);
-        when(mTst.pollSocketsInfo()).thenReturn(true);
+        doReturn(true).when(mTstDependencies).isTcpInfoParsingSupported();
+        doReturn(0).when(mTst).getLatestReceivedCount();
+        doReturn(TEST_TCP_FAIL_RATE).when(mTst).getLatestPacketFailPercentage();
+        doReturn(TEST_TCP_PACKET_COUNT).when(mTst).getSentSinceLastRecv();
+        doReturn(true).when(mTst).isDataStallSuspected();
+        doReturn(true).when(mTst).pollSocketsInfo();
     }
 
     private void verifySendDataStallDetectionStats(WrappedNetworkMonitor nm, int evalType,
@@ -2417,10 +2517,10 @@
     }
 
     private void setupTestWifiInfo() {
-        when(mWifi.getConnectionInfo()).thenReturn(mWifiInfo);
-        when(mWifiInfo.getRssi()).thenReturn(TEST_SIGNAL_STRENGTH);
+        doReturn(mWifiInfo).when(mWifi).getConnectionInfo();
+        doReturn(TEST_SIGNAL_STRENGTH).when(mWifiInfo).getRssi();
         // Set to 2.4G band. Map to DataStallEventProto.AP_BAND_2GHZ proto definition.
-        when(mWifiInfo.getFrequency()).thenReturn(2450);
+        doReturn(2450).when(mWifiInfo).getFrequency();
     }
 
     private void testDataStallMetricsWithCellular(int evalType) {
@@ -2628,10 +2728,9 @@
 
     private void testDismissPortalInValidatedNetworkEnabled(String expectedUrl, String locationUrl)
             throws Exception {
-        setDismissPortalInValidatedNetwork(true);
         setSslException(mHttpsConnection);
         setPortal302(mHttpConnection);
-        when(mHttpConnection.getHeaderField(eq("location"))).thenReturn(locationUrl);
+        doReturn(locationUrl).when(mHttpConnection).getHeaderField(eq("location"));
         final NetworkMonitor nm = makeMonitor(CELL_METERED_CAPABILITIES);
         notifyNetworkConnected(nm, CELL_METERED_CAPABILITIES);
 
@@ -2832,8 +2931,6 @@
     public void testIsCaptivePortal_FromExternalSource() throws Exception {
         assumeTrue(CaptivePortalDataShimImpl.isSupported());
         assumeTrue(ShimUtils.isAtLeastS());
-        when(mDependencies.isFeatureEnabled(any(), eq(NAMESPACE_CONNECTIVITY),
-                eq(DISMISS_PORTAL_IN_VALIDATED_NETWORK), anyBoolean())).thenReturn(true);
         final NetworkMonitor monitor = makeMonitor(WIFI_NOT_METERED_CAPABILITIES);
 
         NetworkInformationShim networkShim = NetworkInformationShimImpl.newInstance();
@@ -2940,10 +3037,10 @@
 
     private void setupResourceForMultipleProbes() {
         // Configure the resource to send multiple probe.
-        when(mResources.getStringArray(R.array.config_captive_portal_https_urls))
-                .thenReturn(TEST_HTTPS_URLS);
-        when(mResources.getStringArray(R.array.config_captive_portal_http_urls))
-                .thenReturn(TEST_HTTP_URLS);
+        doReturn(TEST_HTTPS_URLS).when(mResources)
+                .getStringArray(R.array.config_captive_portal_https_urls);
+        doReturn(TEST_HTTP_URLS).when(mResources)
+                .getStringArray(R.array.config_captive_portal_http_urls);
     }
 
     private void makeDnsTimeoutEvent(WrappedNetworkMonitor wrappedMonitor, int count) {
@@ -2965,23 +3062,23 @@
     }
 
     private void setDataStallEvaluationType(int type) {
-        when(mDependencies.getDeviceConfigPropertyInt(any(),
-            eq(CONFIG_DATA_STALL_EVALUATION_TYPE), anyInt())).thenReturn(type);
+        doReturn(type).when(mDependencies).getDeviceConfigPropertyInt(any(),
+                eq(CONFIG_DATA_STALL_EVALUATION_TYPE), anyInt());
     }
 
     private void setMinDataStallEvaluateInterval(int time) {
-        when(mDependencies.getDeviceConfigPropertyInt(any(),
-            eq(CONFIG_DATA_STALL_MIN_EVALUATE_INTERVAL), anyInt())).thenReturn(time);
+        doReturn(time).when(mDependencies).getDeviceConfigPropertyInt(any(),
+                eq(CONFIG_DATA_STALL_MIN_EVALUATE_INTERVAL), anyInt());
     }
 
     private void setValidDataStallDnsTimeThreshold(int time) {
-        when(mDependencies.getDeviceConfigPropertyInt(any(),
-            eq(CONFIG_DATA_STALL_VALID_DNS_TIME_THRESHOLD), anyInt())).thenReturn(time);
+        doReturn(time).when(mDependencies).getDeviceConfigPropertyInt(any(),
+                eq(CONFIG_DATA_STALL_VALID_DNS_TIME_THRESHOLD), anyInt());
     }
 
     private void setConsecutiveDnsTimeoutThreshold(int num) {
-        when(mDependencies.getDeviceConfigPropertyInt(any(),
-            eq(CONFIG_DATA_STALL_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD), anyInt())).thenReturn(num);
+        doReturn(num).when(mDependencies).getDeviceConfigPropertyInt(any(),
+                eq(CONFIG_DATA_STALL_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD), anyInt());
     }
 
     private void setTcpPollingInterval(int time) {
@@ -2990,28 +3087,23 @@
     }
 
     private void setFallbackUrl(String url) {
-        when(mDependencies.getSetting(any(),
-                eq(Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL), any())).thenReturn(url);
+        doReturn(url).when(mDependencies).getSetting(any(),
+                eq(Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL), any());
     }
 
     private void setOtherFallbackUrls(String urls) {
-        when(mDependencies.getDeviceConfigProperty(any(),
-                eq(CAPTIVE_PORTAL_OTHER_FALLBACK_URLS), any())).thenReturn(urls);
+        doReturn(urls).when(mDependencies).getDeviceConfigProperty(any(),
+                eq(CAPTIVE_PORTAL_OTHER_FALLBACK_URLS), any());
     }
 
     private void setFallbackSpecs(String specs) {
-        when(mDependencies.getDeviceConfigProperty(any(),
-                eq(CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS), any())).thenReturn(specs);
+        doReturn(specs).when(mDependencies).getDeviceConfigProperty(any(),
+                eq(CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS), any());
     }
 
     private void setCaptivePortalMode(int mode) {
-        when(mDependencies.getSetting(any(),
-                eq(Settings.Global.CAPTIVE_PORTAL_MODE), anyInt())).thenReturn(mode);
-    }
-
-    private void setDismissPortalInValidatedNetwork(boolean enabled) {
-        when(mDependencies.isFeatureEnabled(any(), any(),
-                eq(DISMISS_PORTAL_IN_VALIDATED_NETWORK), anyBoolean())).thenReturn(enabled);
+        doReturn(mode).when(mDependencies).getSetting(any(),
+                eq(Settings.Global.CAPTIVE_PORTAL_MODE), anyInt());
     }
 
     private void setDeviceConfig(String key, String value) {
@@ -3170,8 +3262,8 @@
     }
 
     private void generateTestTcpStats(DataStallDetectionStats.Builder stats) {
-        when(mTst.getLatestPacketFailPercentage()).thenReturn(TEST_TCP_FAIL_RATE);
-        when(mTst.getSentSinceLastRecv()).thenReturn(TEST_TCP_PACKET_COUNT);
+        doReturn(TEST_TCP_FAIL_RATE).when(mTst).getLatestPacketFailPercentage();
+        doReturn(TEST_TCP_PACKET_COUNT).when(mTst).getSentSinceLastRecv();
         stats.setTcpFailRate(TEST_TCP_FAIL_RATE).setTcpSentSinceLastRecv(TEST_TCP_PACKET_COUNT);
     }
 
@@ -3211,4 +3303,3 @@
         assertEquals(isPortal ? 2 : 1, mRegisteredReceivers.size());
     }
 }
-