Merge "DO NOT MERGE - Merge pi-platform-release (PPRL.190505.001) into stage-aosp-master" into stage-aosp-master
diff --git a/config/hiddenapi-greylist-max-p.txt b/config/hiddenapi-greylist-max-p.txt
index 7840b18..f201063 100644
--- a/config/hiddenapi-greylist-max-p.txt
+++ b/config/hiddenapi-greylist-max-p.txt
@@ -71,5 +71,5 @@
 Lcom/android/internal/telephony/ITelephonyRegistry;->notifyCallForwardingChanged(Z)V
 Lcom/android/internal/telephony/ITelephonyRegistry;->notifyCellLocation(Landroid/os/Bundle;)V
 Lcom/android/internal/telephony/ITelephonyRegistry;->notifyDataActivity(I)V
-Lcom/android/internal/telephony/ITelephonyRegistry;->notifyOtaspChanged(I)V
+Lcom/android/internal/telephony/ITelephonyRegistry;->notifyOtaspChanged(II)V
 Lcom/android/internal/view/BaseIWindow;-><init>()V
diff --git a/core/java/android/annotation/OWNERS b/core/java/android/annotation/OWNERS
index 85adfa7..e07028b 100644
--- a/core/java/android/annotation/OWNERS
+++ b/core/java/android/annotation/OWNERS
@@ -1,2 +1,2 @@
 tnorbye@google.com
-per-file UnsupportedAppUsage.java = mathewi@google.com
+per-file UnsupportedAppUsage.java = mathewi@google.com, dbrazdil@google.com, atrost@google.com, andreionea@google.com
diff --git a/core/java/android/annotation/UnsupportedAppUsage.java b/core/java/android/annotation/UnsupportedAppUsage.java
index ac3daaf..a454df5 100644
--- a/core/java/android/annotation/UnsupportedAppUsage.java
+++ b/core/java/android/annotation/UnsupportedAppUsage.java
@@ -125,6 +125,32 @@
     String implicitMember() default "";
 
     /**
+     * Public API alternatives to this API.
+     *
+     * <p>If non-empty, the string must be a description of the public API alternative(s) to this
+     * API. The explanation must contain at least one Javadoc link tag to public API methods or
+     * fields. e.g.:
+     * {@literal @UnsupportedAppUsage(publicAlternatives="Use {@link foo.bar.Baz#bat()} instead.")}
+     *
+     * <p>Any elements that can be deduced can be omitted, e.g.:
+     * <ul>
+     *      <li>
+     *          the class, if it's the same as for the annotated element.
+     *      </li>
+     *      <li>
+     *          the package name, if it's the same as for the annotated element.
+     *      </li>
+     *      <li>
+     *          the method parameters, if there is only one method with that name in the given
+     *          package and class.
+     *      </li>
+     * </ul>
+     * @return A Javadoc-formatted string.
+     */
+    @SuppressWarnings("JavadocReference")
+    String publicAlternatives() default "";
+
+    /**
      * Container for {@link UnsupportedAppUsage} that allows it to be applied repeatedly to types.
      */
     @Retention(CLASS)
diff --git a/core/jni/android_os_HwBinder.cpp b/core/jni/android_os_HwBinder.cpp
index 129b8af..cbae2da 100644
--- a/core/jni/android_os_HwBinder.cpp
+++ b/core/jni/android_os_HwBinder.cpp
@@ -284,28 +284,17 @@
     }
 
     sp<hardware::IBinder> binder = JHwBinder::GetNativeBinder(env, thiz);
-
-    /* TODO(b/33440494) this is not right */
     sp<hidl::base::V1_0::IBase> base = new hidl::base::V1_0::BpHwBase(binder);
 
-    auto manager = hardware::defaultServiceManager();
-
-    if (manager == nullptr) {
-        LOG(ERROR) << "Could not get hwservicemanager.";
-        signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */);
-        return;
-    }
-
-    Return<bool> ret = manager->add(str.c_str(), base);
-
-    bool ok = ret.isOk() && ret;
+    bool ok = hardware::details::registerAsServiceInternal(base, str.c_str()) == OK;
 
     if (ok) {
         LOG(INFO) << "HwBinder: Starting thread pool for " << str.c_str();
         ::android::hardware::ProcessState::self()->startThreadPool();
     }
 
-    signalExceptionForError(env, (ok ? OK : UNKNOWN_ERROR), true /* canThrowRemoteException */);
+    // avoiding richer error exceptions to stick with legacy behavior
+    signalExceptionForError(env, (ok ? OK : UNKNOWN_ERROR), true /*canThrowRemoteException*/);
 }
 
 static jobject JHwBinder_native_getService(
diff --git a/packages/NetworkStack/Android.bp b/packages/NetworkStack/Android.bp
index 62de2ba..9c8efe6 100644
--- a/packages/NetworkStack/Android.bp
+++ b/packages/NetworkStack/Android.bp
@@ -116,6 +116,7 @@
     defaults: ["NetworkStackAppCommon"],
     certificate: "networkstack",
     manifest: "AndroidManifest.xml",
+    use_embedded_native_libs: true,
 }
 
 genrule {
diff --git a/packages/NetworkStack/AndroidManifest.xml b/packages/NetworkStack/AndroidManifest.xml
index 3fc1e98..3b39cee 100644
--- a/packages/NetworkStack/AndroidManifest.xml
+++ b/packages/NetworkStack/AndroidManifest.xml
@@ -37,7 +37,7 @@
     <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
     <!-- Signature permission defined in NetworkStackStub -->
     <uses-permission android:name="android.permission.MAINLINE_NETWORK_STACK" />
-    <application>
+    <application android:extractNativeLibs="false">
         <service android:name="com.android.server.NetworkStackService">
             <intent-filter>
                 <action android:name="android.net.INetworkStackConnector"/>
diff --git a/packages/NetworkStack/src/android/net/apf/ApfFilter.java b/packages/NetworkStack/src/android/net/apf/ApfFilter.java
index 2e1e96e..f054319 100644
--- a/packages/NetworkStack/src/android/net/apf/ApfFilter.java
+++ b/packages/NetworkStack/src/android/net/apf/ApfFilter.java
@@ -156,8 +156,7 @@
         DROPPED_ARP_REPLY_SPA_NO_HOST,
         DROPPED_IPV4_KEEPALIVE_ACK,
         DROPPED_IPV6_KEEPALIVE_ACK,
-        DROPPED_IPV4_NATT_KEEPALIVE,
-        DROPPED_IPV6_NATT_KEEPALIVE;
+        DROPPED_IPV4_NATT_KEEPALIVE;
 
         // Returns the negative byte offset from the end of the APF data segment for
         // a given counter.
@@ -873,17 +872,17 @@
     }
 
     // A class to hold NAT-T keepalive ack information.
-    private abstract static class NattKeepaliveAck extends KeepalivePacket {
+    private class NattKeepaliveResponse extends KeepalivePacket {
         static final int UDP_LENGTH_OFFSET = 4;
         static final int UDP_HEADER_LEN = 8;
 
-        protected static class NattKeepaliveAckData {
+        protected class NattKeepaliveResponseData {
             public final byte[] srcAddress;
             public final int srcPort;
             public final byte[] dstAddress;
             public final int dstPort;
 
-            NattKeepaliveAckData(final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
+            NattKeepaliveResponseData(final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
                 srcAddress = sentKeepalivePacket.dstAddress;
                 srcPort = sentKeepalivePacket.dstPort;
                 dstAddress = sentKeepalivePacket.srcAddress;
@@ -891,19 +890,19 @@
             }
         }
 
-        protected final NattKeepaliveAckData mPacket;
+        protected final NattKeepaliveResponseData mPacket;
         protected final byte[] mSrcDstAddr;
         protected final byte[] mPortFingerprint;
         // NAT-T keepalive packet
         protected final byte[] mPayload = {(byte) 0xff};
 
-        NattKeepaliveAck(final NattKeepaliveAckData packet,  final byte[] srcDstAddr) {
-            mPacket = packet;
-            mSrcDstAddr = srcDstAddr;
+        NattKeepaliveResponse(final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
+            mPacket = new NattKeepaliveResponseData(sentKeepalivePacket);
+            mSrcDstAddr = concatArrays(mPacket.srcAddress, mPacket.dstAddress);
             mPortFingerprint = generatePortFingerprint(mPacket.srcPort, mPacket.dstPort);
         }
 
-        static byte[] generatePortFingerprint(int srcPort, int dstPort) {
+        byte[] generatePortFingerprint(int srcPort, int dstPort) {
             final ByteBuffer fp = ByteBuffer.allocate(4);
             fp.order(ByteOrder.BIG_ENDIAN);
             fp.putShort((short) srcPort);
@@ -911,27 +910,6 @@
             return fp.array();
         }
 
-        public String toString() {
-            try {
-                return String.format("%s -> %s",
-                        NetworkStackUtils.addressAndPortToString(
-                                InetAddress.getByAddress(mPacket.srcAddress), mPacket.srcPort),
-                        NetworkStackUtils.addressAndPortToString(
-                                InetAddress.getByAddress(mPacket.dstAddress), mPacket.dstPort));
-            } catch (UnknownHostException e) {
-                return "Unknown host";
-            }
-        }
-    }
-
-    private class NattKeepaliveAckV4 extends NattKeepaliveAck {
-        NattKeepaliveAckV4(final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
-            this(new NattKeepaliveAckData(sentKeepalivePacket));
-        }
-        NattKeepaliveAckV4(final NattKeepaliveAckData packet) {
-            super(packet, concatArrays(packet.srcAddress, packet.dstAddress) /* srcDstAddr */);
-        }
-
         @Override
         void generateFilterLocked(ApfGenerator gen) throws IllegalInstructionException {
             final String nextFilterLabel = "natt_keepalive_filter" + getUniqueNumberLocked();
@@ -949,10 +927,9 @@
             gen.addAddR1();
             gen.addJumpIfR0NotEquals(1, nextFilterLabel);
 
-            // R0 = R0 + R1 -> R0 contains IP header
-            gen.addLoadFromMemory(Register.R1, gen.IPV4_HEADER_SIZE_MEMORY_SLOT);
-            gen.addLoadImmediate(Register.R0, ETH_HEADER_LEN);
-            gen.addAddR1();
+            // Check that the ports match
+            gen.addLoadFromMemory(Register.R0, gen.IPV4_HEADER_SIZE_MEMORY_SLOT);
+            gen.addAdd(ETH_HEADER_LEN);
             gen.addJumpIfBytesNotEqual(Register.R0, mPortFingerprint, nextFilterLabel);
 
             // Payload offset = R0 + UDP header length
@@ -963,20 +940,17 @@
             gen.addJump(mCountAndDropLabel);
             gen.defineLabel(nextFilterLabel);
         }
-    }
 
-    private class NattKeepaliveAckV6 extends NattKeepaliveAck {
-        NattKeepaliveAckV6(final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
-            this(new NattKeepaliveAckData(sentKeepalivePacket));
-        }
-
-        NattKeepaliveAckV6(final NattKeepaliveAckData packet) {
-            super(packet, concatArrays(packet.srcAddress, packet.dstAddress) /* srcDstAddr */);
-        }
-
-        @Override
-        void generateFilterLocked(ApfGenerator gen) throws IllegalInstructionException {
-            throw new UnsupportedOperationException("IPv6 NAT-T Keepalive is not supported yet");
+        public String toString() {
+            try {
+                return String.format("%s -> %s",
+                        NetworkStackUtils.addressAndPortToString(
+                                InetAddress.getByAddress(mPacket.srcAddress), mPacket.srcPort),
+                        NetworkStackUtils.addressAndPortToString(
+                                InetAddress.getByAddress(mPacket.dstAddress), mPacket.dstPort));
+            } catch (UnknownHostException e) {
+                return "Unknown host";
+            }
         }
     }
 
@@ -1296,6 +1270,7 @@
             gen.addJump(mCountAndDropLabel);
         } else {
             generateV4KeepaliveFilters(gen);
+            generateV4NattKeepaliveFilters(gen);
         }
 
         // Otherwise, pass
@@ -1303,36 +1278,36 @@
         gen.addJump(mCountAndPassLabel);
     }
 
-    private void generateFilters(ApfGenerator gen, Class<?> filterType, int proto, int offset,
-            String label) throws IllegalInstructionException {
-        final boolean haveKeepaliveAcks = NetworkStackUtils.any(mKeepalivePackets,
+    private void generateKeepaliveFilters(ApfGenerator gen, Class<?> filterType, int proto,
+            int offset, String label) throws IllegalInstructionException {
+        final boolean haveKeepaliveResponses = NetworkStackUtils.any(mKeepalivePackets,
                 ack -> filterType.isInstance(ack));
 
         // If no keepalive packets of this type
-        if (!haveKeepaliveAcks) return;
+        if (!haveKeepaliveResponses) return;
 
         // If not the right proto, skip keepalive filters
         gen.addLoad8(Register.R0, offset);
         gen.addJumpIfR0NotEquals(proto, label);
 
-        // Drop Keepalive packets
+        // Drop Keepalive responses
         for (int i = 0; i < mKeepalivePackets.size(); ++i) {
-            final KeepalivePacket ack = mKeepalivePackets.valueAt(i);
-            if (filterType.isInstance(ack)) ack.generateFilterLocked(gen);
+            final KeepalivePacket response = mKeepalivePackets.valueAt(i);
+            if (filterType.isInstance(response)) response.generateFilterLocked(gen);
         }
 
         gen.defineLabel(label);
     }
 
     private void generateV4KeepaliveFilters(ApfGenerator gen) throws IllegalInstructionException {
-        generateFilters(gen, TcpKeepaliveAckV4.class, IPPROTO_TCP, IPV4_PROTOCOL_OFFSET,
+        generateKeepaliveFilters(gen, TcpKeepaliveAckV4.class, IPPROTO_TCP, IPV4_PROTOCOL_OFFSET,
                 "skip_v4_keepalive_filter");
     }
 
     private void generateV4NattKeepaliveFilters(ApfGenerator gen)
             throws IllegalInstructionException {
-        generateFilters(gen, NattKeepaliveAckV4.class, IPPROTO_UDP, IPV4_PROTOCOL_OFFSET,
-                "skip_v4_nattkeepalive_filter");
+        generateKeepaliveFilters(gen, NattKeepaliveResponse.class,
+                IPPROTO_UDP, IPV4_PROTOCOL_OFFSET, "skip_v4_nattkeepalive_filter");
     }
 
     /**
@@ -1417,7 +1392,7 @@
     }
 
     private void generateV6KeepaliveFilters(ApfGenerator gen) throws IllegalInstructionException {
-        generateFilters(gen, TcpKeepaliveAckV6.class, IPPROTO_TCP, IPV6_NEXT_HEADER_OFFSET,
+        generateKeepaliveFilters(gen, TcpKeepaliveAckV6.class, IPPROTO_TCP, IPV6_NEXT_HEADER_OFFSET,
                 "skip_v6_keepalive_filter");
     }
 
@@ -1819,8 +1794,8 @@
     }
 
     /**
-     * Add NATT keepalive packet filter.
-     * This will add a filter to drop NATT keepalive packet which is passed as an argument.
+     * Add NAT-T keepalive packet filter.
+     * This will add a filter to drop NAT-T keepalive packet which is passed as an argument.
      *
      * @param slot The index used to access the filter.
      * @param sentKeepalivePacket The attributes of the sent keepalive packet.
@@ -1829,12 +1804,12 @@
             final NattKeepalivePacketDataParcelable sentKeepalivePacket) {
         log("Adding NAT-T keepalive packet(" + slot + ")");
         if (null != mKeepalivePackets.get(slot)) {
-            throw new IllegalArgumentException("Natt Keepalive slot " + slot + " is occupied");
+            throw new IllegalArgumentException("NAT-T Keepalive slot " + slot + " is occupied");
         }
-        final int ipVersion = sentKeepalivePacket.srcAddress.length == 4 ? 4 : 6;
-        mKeepalivePackets.put(slot, (ipVersion == 4)
-                ? new NattKeepaliveAckV4(sentKeepalivePacket)
-                : new NattKeepaliveAckV6(sentKeepalivePacket));
+        if (sentKeepalivePacket.srcAddress.length != 4) {
+            throw new IllegalArgumentException("NAT-T keepalive is only supported on IPv4");
+        }
+        mKeepalivePackets.put(slot, new NattKeepaliveResponse(sentKeepalivePacket));
         installNewProgramLocked();
     }
 
@@ -1908,7 +1883,7 @@
             if (keepalivePacket instanceof TcpKeepaliveAck) {
                 pw.print("Slot ");
                 pw.print(mKeepalivePackets.keyAt(i));
-                pw.print(" : ");
+                pw.print(": ");
                 pw.println(keepalivePacket);
             }
         }
@@ -1918,10 +1893,10 @@
         pw.increaseIndent();
         for (int i = 0; i < mKeepalivePackets.size(); ++i) {
             final KeepalivePacket keepalivePacket = mKeepalivePackets.valueAt(i);
-            if (keepalivePacket instanceof NattKeepaliveAck) {
+            if (keepalivePacket instanceof NattKeepaliveResponse) {
                 pw.print("Slot ");
                 pw.print(mKeepalivePackets.keyAt(i));
-                pw.print(" : ");
+                pw.print(": ");
                 pw.println(keepalivePacket);
             }
         }
diff --git a/packages/NetworkStack/src/com/android/networkstack/util/DnsUtils.java b/packages/NetworkStack/src/com/android/networkstack/util/DnsUtils.java
index 85f94e1..4767d55 100644
--- a/packages/NetworkStack/src/com/android/networkstack/util/DnsUtils.java
+++ b/packages/NetworkStack/src/com/android/networkstack/util/DnsUtils.java
@@ -55,12 +55,23 @@
             throws UnknownHostException {
         final List<InetAddress> result = new ArrayList<InetAddress>();
 
-        result.addAll(Arrays.asList(
-                getAllByName(dnsResolver, network, host, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP,
-                timeout)));
-        result.addAll(Arrays.asList(
-                getAllByName(dnsResolver, network, host, TYPE_A, FLAG_NO_CACHE_LOOKUP,
-                timeout)));
+        try {
+            result.addAll(Arrays.asList(
+                    getAllByName(dnsResolver, network, host, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP,
+                    timeout)));
+        } catch (UnknownHostException e) {
+            // Might happen if the host is v4-only, still need to query TYPE_A
+        }
+        try {
+            result.addAll(Arrays.asList(
+                    getAllByName(dnsResolver, network, host, TYPE_A, FLAG_NO_CACHE_LOOKUP,
+                    timeout)));
+        } catch (UnknownHostException e) {
+            // Might happen if the host is v6-only, still need to return AAAA answers
+        }
+        if (result.size() == 0) {
+            throw new UnknownHostException(host);
+        }
         return result.toArray(new InetAddress[0]);
     }
 
diff --git a/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java b/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
index 41c3fab..8f2b968 100644
--- a/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
+++ b/packages/NetworkStack/tests/src/android/net/apf/ApfTest.java
@@ -1734,7 +1734,8 @@
         final int dstPort = 4500;
         final int slot1 = 1;
         // NAT-T keepalive
-        final byte[] payload = {(byte) 0xff};
+        final byte[] kaPayload = {(byte) 0xff};
+        final byte[] nonKaPayload = {(byte) 0xfe};
 
         // src: 10.0.0.5, port: 1024
         // dst: 10.0.0.6, port: 4500
@@ -1753,15 +1754,21 @@
         // Verify IPv4 keepalive packet is dropped
         // src: 10.0.0.6, port: 4500
         // dst: 10.0.0.5, port: 1024
-        final byte[] nattKaPkt = ipv4UdpPacket(IPV4_KEEPALIVE_DST_ADDR,
+        byte[] pkt = ipv4UdpPacket(IPV4_KEEPALIVE_DST_ADDR,
                     IPV4_KEEPALIVE_SRC_ADDR, dstPort, srcPort, 1 /* dataLength */);
-        System.arraycopy(payload, 0, nattKaPkt, IPV4_UDP_PAYLOAD_OFFSET, payload.length);
-        assertDrop(program, nattKaPkt);
-        // Verify IPv4 non-keepalive packet from the same source address is passed
+        System.arraycopy(kaPayload, 0, pkt, IPV4_UDP_PAYLOAD_OFFSET, kaPayload.length);
+        assertDrop(program, pkt);
+
+        // Verify a packet with payload length 1 byte but it is not 0xff will pass the filter.
+        System.arraycopy(nonKaPayload, 0, pkt, IPV4_UDP_PAYLOAD_OFFSET, nonKaPayload.length);
+        assertPass(program, pkt);
+
+        // Verify IPv4 non-keepalive response packet from the same source address is passed
         assertPass(program,
                 ipv4UdpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                         dstPort, srcPort, 10 /* dataLength */));
-        // Verify IPv4 non-keepalive packet from other source address is passed
+
+        // Verify IPv4 non-keepalive response packet from other source address is passed
         assertPass(program,
                 ipv4UdpPacket(IPV4_ANOTHER_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                         dstPort, srcPort, 10 /* dataLength */));
diff --git a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
index abfb9c8..832b712 100644
--- a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -298,8 +298,10 @@
         setFallbackSpecs(null); // Test with no fallback spec by default
         when(mRandom.nextInt()).thenReturn(0);
 
+        // 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(500);
+                .thenReturn(200);
 
         doAnswer((invocation) -> {
             URL url = invocation.getArgument(0);
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 562199a..b3b5e45 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -3495,7 +3495,8 @@
      */
     @Override
     public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
-        mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
+        mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+                "ConnectivityService");
 
         final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
         appIntent.putExtras(appExtras);
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index a172fde..99365de 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -199,7 +199,7 @@
 
     private int[] mDataConnectionNetworkType;
 
-    private int mOtaspMode = TelephonyManager.OTASP_UNKNOWN;
+    private int[] mOtaspMode;
 
     private ArrayList<List<CellInfo>> mCellInfo = null;
 
@@ -207,13 +207,12 @@
 
     private Map<Integer, List<EmergencyNumber>> mEmergencyNumberList;
 
-    private CallQuality mCallQuality = new CallQuality();
+    private CallQuality[] mCallQuality;
 
-    private CallAttributes mCallAttributes = new CallAttributes(new PreciseCallState(),
-            TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
+    private CallAttributes[] mCallAttributes;
 
     // network type of the call associated with the mCallAttributes and mCallQuality
-    private int mCallNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+    private int[] mCallNetworkType;
 
     private int[] mSrvccState;
 
@@ -221,19 +220,19 @@
 
     private int mDefaultPhoneId = SubscriptionManager.INVALID_PHONE_INDEX;
 
-    private int mRingingCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+    private int[] mRingingCallState;
 
-    private int mForegroundCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+    private int[] mForegroundCallState;
 
-    private int mBackgroundCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+    private int[] mBackgroundCallState;
 
-    private PreciseCallState mPreciseCallState = new PreciseCallState();
+    private PreciseCallState[] mPreciseCallState;
 
-    private int mCallDisconnectCause = DisconnectCause.NOT_VALID;
+    private int[] mCallDisconnectCause;
 
     private List<ImsReasonInfo> mImsReasonInfo = null;
 
-    private int mCallPreciseDisconnectCause = PreciseDisconnectCause.NOT_VALID;
+    private int[] mCallPreciseDisconnectCause;
 
     private boolean mCarrierNetworkChangeState = false;
 
@@ -250,8 +249,7 @@
 
     private final LocalLog mListenLog = new LocalLog(100);
 
-    private PreciseDataConnectionState mPreciseDataConnectionState =
-                new PreciseDataConnectionState();
+    private PreciseDataConnectionState[] mPreciseDataConnectionState;
 
     // Nothing here yet, but putting it here in case we want to add more in the future.
     static final int ENFORCE_COARSE_LOCATION_PERMISSION_MASK = 0;
@@ -342,7 +340,7 @@
                 Integer newDefaultSubIdObj = new Integer(intent.getIntExtra(
                         PhoneConstants.SUBSCRIPTION_KEY,
                         SubscriptionManager.getDefaultSubscriptionId()));
-                int newDefaultPhoneId = intent.getIntExtra(PhoneConstants.SLOT_KEY,
+                int newDefaultPhoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY,
                     SubscriptionManager.getPhoneId(mDefaultSubId));
                 if (DBG) {
                     log("onReceive:current mDefaultSubId=" + mDefaultSubId
@@ -389,10 +387,21 @@
         mMessageWaiting = new boolean[numPhones];
         mCallForwarding = new boolean[numPhones];
         mCellLocation = new Bundle[numPhones];
-        mCellInfo = new ArrayList<List<CellInfo>>();
         mSrvccState = new int[numPhones];
-        mImsReasonInfo = new ArrayList<ImsReasonInfo>();
-        mPhysicalChannelConfigs = new ArrayList<List<PhysicalChannelConfig>>();
+        mOtaspMode = new int[numPhones];
+        mPreciseCallState = new PreciseCallState[numPhones];
+        mForegroundCallState = new int[numPhones];
+        mBackgroundCallState = new int[numPhones];
+        mRingingCallState = new int[numPhones];
+        mCallDisconnectCause = new int[numPhones];
+        mCallPreciseDisconnectCause = new int[numPhones];
+        mCallQuality = new CallQuality[numPhones];
+        mCallNetworkType = new int[numPhones];
+        mCallAttributes = new CallAttributes[numPhones];
+        mPreciseDataConnectionState = new PreciseDataConnectionState[numPhones];
+        mCellInfo = new ArrayList<>();
+        mImsReasonInfo = new ArrayList<>();
+        mPhysicalChannelConfigs = new ArrayList<>();
         mEmergencyNumberList = new HashMap<>();
         for (int i = 0; i < numPhones; i++) {
             mCallState[i] =  TelephonyManager.CALL_STATE_IDLE;
@@ -410,7 +419,19 @@
             mCellInfo.add(i, null);
             mImsReasonInfo.add(i, null);
             mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
-            mPhysicalChannelConfigs.add(i, new ArrayList<PhysicalChannelConfig>());
+            mPhysicalChannelConfigs.add(i, new ArrayList<>());
+            mOtaspMode[i] = TelephonyManager.OTASP_UNKNOWN;
+            mCallDisconnectCause[i] = DisconnectCause.NOT_VALID;
+            mCallPreciseDisconnectCause[i] = PreciseDisconnectCause.NOT_VALID;
+            mCallQuality[i] = new CallQuality();
+            mCallAttributes[i] = new CallAttributes(new PreciseCallState(),
+                    TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
+            mCallNetworkType[i] = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+            mPreciseCallState[i] = new PreciseCallState();
+            mRingingCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+            mForegroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+            mBackgroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
+            mPreciseDataConnectionState[i] = new PreciseDataConnectionState();
         }
 
         // Note that location can be null for non-phone builds like
@@ -731,7 +752,7 @@
                     }
                     if ((events & PhoneStateListener.LISTEN_OTASP_CHANGED) != 0) {
                         try {
-                            r.callback.onOtaspChanged(mOtaspMode);
+                            r.callback.onOtaspChanged(mOtaspMode[phoneId]);
                         } catch (RemoteException ex) {
                             remove(r.binder);
                         }
@@ -749,15 +770,15 @@
                     }
                     if ((events & PhoneStateListener.LISTEN_PRECISE_CALL_STATE) != 0) {
                         try {
-                            r.callback.onPreciseCallStateChanged(mPreciseCallState);
+                            r.callback.onPreciseCallStateChanged(mPreciseCallState[phoneId]);
                         } catch (RemoteException ex) {
                             remove(r.binder);
                         }
                     }
                     if ((events & PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES) != 0) {
                         try {
-                            r.callback.onCallDisconnectCauseChanged(mCallDisconnectCause,
-                                    mCallPreciseDisconnectCause);
+                            r.callback.onCallDisconnectCauseChanged(mCallDisconnectCause[phoneId],
+                                    mCallPreciseDisconnectCause[phoneId]);
                         } catch (RemoteException ex) {
                             remove(r.binder);
                         }
@@ -772,7 +793,7 @@
                     if ((events & PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE) != 0) {
                         try {
                             r.callback.onPreciseDataConnectionStateChanged(
-                                    mPreciseDataConnectionState);
+                                    mPreciseDataConnectionState[phoneId]);
                         } catch (RemoteException ex) {
                             remove(r.binder);
                         }
@@ -854,7 +875,7 @@
                     }
                     if ((events & PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED) != 0) {
                         try {
-                            r.callback.onCallAttributesChanged(mCallAttributes);
+                            r.callback.onCallAttributesChanged(mCallAttributes[phoneId]);
                         } catch (RemoteException ex) {
                             remove(r.binder);
                         }
@@ -1380,12 +1401,14 @@
                                      LinkProperties linkProperties,
                                      NetworkCapabilities networkCapabilities, int networkType,
                                      boolean roaming) {
-        notifyDataConnectionForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, state,
+        notifyDataConnectionForSubscriber(SubscriptionManager.DEFAULT_PHONE_INDEX,
+                SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,  state,
                 isDataAllowed, apn, apnType, linkProperties,
                 networkCapabilities, networkType, roaming);
     }
 
-    public void notifyDataConnectionForSubscriber(int subId, int state, boolean isDataAllowed,
+    public void notifyDataConnectionForSubscriber(int phoneId, int subId, int state,
+                                                  boolean isDataAllowed,
                                                   String apn, String apnType,
             LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
             int networkType, boolean roaming) {
@@ -1398,7 +1421,6 @@
                 + "' apn='" + apn + "' apnType=" + apnType + " networkType=" + networkType
                 + " mRecords.size()=" + mRecords.size());
         }
-        int phoneId = SubscriptionManager.getPhoneId(subId);
         synchronized (mRecords) {
             if (validatePhoneId(phoneId)) {
                 // We only call the callback when the change is for default APN type.
@@ -1413,8 +1435,8 @@
                     mLocalLog.log(str);
                     for (Record r : mRecords) {
                         if (r.matchPhoneStateListenerEvent(
-                                PhoneStateListener.LISTEN_DATA_CONNECTION_STATE) &&
-                                idMatch(r.subId, subId, phoneId)) {
+                                PhoneStateListener.LISTEN_DATA_CONNECTION_STATE)
+                                && idMatch(r.subId, subId, phoneId)) {
                             try {
                                 if (DBG) {
                                     log("Notify data connection state changed on sub: " + subId);
@@ -1430,15 +1452,17 @@
                     mDataConnectionState[phoneId] = state;
                     mDataConnectionNetworkType[phoneId] = networkType;
                 }
-                mPreciseDataConnectionState = new PreciseDataConnectionState(state, networkType,
+                mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
+                        state, networkType,
                         ApnSetting.getApnTypesBitmaskFromString(apnType), apn,
                         linkProperties, DataFailCause.NONE);
                 for (Record r : mRecords) {
                     if (r.matchPhoneStateListenerEvent(
-                            PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
+                            PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
+                            && idMatch(r.subId, subId, phoneId)) {
                         try {
                             r.callback.onPreciseDataConnectionStateChanged(
-                                    mPreciseDataConnectionState);
+                                    mPreciseDataConnectionState[phoneId]);
                         } catch (RemoteException ex) {
                             mRemoveList.add(r.binder);
                         }
@@ -1454,11 +1478,12 @@
     }
 
     public void notifyDataConnectionFailed(String apnType) {
-         notifyDataConnectionFailedForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
+         notifyDataConnectionFailedForSubscriber(SubscriptionManager.DEFAULT_PHONE_INDEX,
+                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
                  apnType);
     }
 
-    public void notifyDataConnectionFailedForSubscriber(int subId, String apnType) {
+    public void notifyDataConnectionFailedForSubscriber(int phoneId, int subId, String apnType) {
         if (!checkNotifyPermission("notifyDataConnectionFailed()")) {
             return;
         }
@@ -1467,20 +1492,25 @@
                     + " apnType=" + apnType);
         }
         synchronized (mRecords) {
-            mPreciseDataConnectionState = new PreciseDataConnectionState(
-                    TelephonyManager.DATA_UNKNOWN,TelephonyManager.NETWORK_TYPE_UNKNOWN,
-                    ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
-                    DataFailCause.NONE);
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
-                    try {
-                        r.callback.onPreciseDataConnectionStateChanged(mPreciseDataConnectionState);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
+                        TelephonyManager.DATA_UNKNOWN,TelephonyManager.NETWORK_TYPE_UNKNOWN,
+                        ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
+                        DataFailCause.NONE);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onPreciseDataConnectionStateChanged(
+                                    mPreciseDataConnectionState[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
+
             handleRemoveListLocked();
         }
         broadcastDataConnectionFailed(apnType, subId);
@@ -1527,18 +1557,22 @@
         }
     }
 
-    public void notifyOtaspChanged(int otaspMode) {
+    public void notifyOtaspChanged(int subId, int otaspMode) {
         if (!checkNotifyPermission("notifyOtaspChanged()" )) {
             return;
         }
+        int phoneId = SubscriptionManager.getPhoneId(subId);
         synchronized (mRecords) {
-            mOtaspMode = otaspMode;
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_OTASP_CHANGED)) {
-                    try {
-                        r.callback.onOtaspChanged(otaspMode);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                mOtaspMode[phoneId] = otaspMode;
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_OTASP_CHANGED)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onOtaspChanged(otaspMode);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
@@ -1546,49 +1580,55 @@
         }
     }
 
-    public void notifyPreciseCallState(int ringingCallState, int foregroundCallState,
-            int backgroundCallState, int phoneId) {
+    public void notifyPreciseCallState(int phoneId, int subId, int ringingCallState,
+                                       int foregroundCallState, int backgroundCallState) {
         if (!checkNotifyPermission("notifyPreciseCallState()")) {
             return;
         }
         synchronized (mRecords) {
-            mRingingCallState = ringingCallState;
-            mForegroundCallState = foregroundCallState;
-            mBackgroundCallState = backgroundCallState;
-            mPreciseCallState = new PreciseCallState(ringingCallState, foregroundCallState,
-                    backgroundCallState,
-                    DisconnectCause.NOT_VALID,
-                    PreciseDisconnectCause.NOT_VALID);
-            boolean notifyCallAttributes = true;
-            if (mCallQuality == null) {
-                log("notifyPreciseCallState: mCallQuality is null, skipping call attributes");
-                notifyCallAttributes = false;
-            } else {
-                // If the precise call state is no longer active, reset the call network type and
-                // call quality.
-                if (mPreciseCallState.getForegroundCallState()
-                        != PreciseCallState.PRECISE_CALL_STATE_ACTIVE) {
-                    mCallNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
-                    mCallQuality = new CallQuality();
-                }
-                mCallAttributes = new CallAttributes(mPreciseCallState, mCallNetworkType,
-                        mCallQuality);
-            }
-
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_PRECISE_CALL_STATE)) {
-                    try {
-                        r.callback.onPreciseCallStateChanged(mPreciseCallState);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                mRingingCallState[phoneId] = ringingCallState;
+                mForegroundCallState[phoneId] = foregroundCallState;
+                mBackgroundCallState[phoneId] = backgroundCallState;
+                mPreciseCallState[phoneId] = new PreciseCallState(
+                        ringingCallState, foregroundCallState,
+                        backgroundCallState,
+                        DisconnectCause.NOT_VALID,
+                        PreciseDisconnectCause.NOT_VALID);
+                boolean notifyCallAttributes = true;
+                if (mCallQuality == null) {
+                    log("notifyPreciseCallState: mCallQuality is null, "
+                            + "skipping call attributes");
+                    notifyCallAttributes = false;
+                } else {
+                    // If the precise call state is no longer active, reset the call network type
+                    // and call quality.
+                    if (mPreciseCallState[phoneId].getForegroundCallState()
+                            != PreciseCallState.PRECISE_CALL_STATE_ACTIVE) {
+                        mCallNetworkType[phoneId] = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+                        mCallQuality[phoneId] = new CallQuality();
                     }
+                    mCallAttributes[phoneId] = new CallAttributes(mPreciseCallState[phoneId],
+                            mCallNetworkType[phoneId], mCallQuality[phoneId]);
                 }
-                if (notifyCallAttributes && r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)) {
-                    try {
-                        r.callback.onCallAttributesChanged(mCallAttributes);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_PRECISE_CALL_STATE)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onPreciseCallStateChanged(mPreciseCallState[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
+                    }
+                    if (notifyCallAttributes && r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onCallAttributesChanged(mCallAttributes[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
@@ -1598,21 +1638,24 @@
                 backgroundCallState);
     }
 
-    public void notifyDisconnectCause(int disconnectCause, int preciseDisconnectCause) {
+    public void notifyDisconnectCause(int phoneId, int subId, int disconnectCause,
+                                      int preciseDisconnectCause) {
         if (!checkNotifyPermission("notifyDisconnectCause()")) {
             return;
         }
         synchronized (mRecords) {
-            mCallDisconnectCause = disconnectCause;
-            mCallPreciseDisconnectCause = preciseDisconnectCause;
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(PhoneStateListener
-                        .LISTEN_CALL_DISCONNECT_CAUSES)) {
-                    try {
-                        r.callback.onCallDisconnectCauseChanged(mCallDisconnectCause,
-                                mCallPreciseDisconnectCause);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                mCallDisconnectCause[phoneId] = disconnectCause;
+                mCallPreciseDisconnectCause[phoneId] = preciseDisconnectCause;
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(PhoneStateListener
+                            .LISTEN_CALL_DISCONNECT_CAUSES) && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onCallDisconnectCauseChanged(mCallDisconnectCause[phoneId],
+                                    mCallPreciseDisconnectCause[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
@@ -1648,25 +1691,30 @@
         }
     }
 
-    public void notifyPreciseDataConnectionFailed(String apnType,
+    public void notifyPreciseDataConnectionFailed(int phoneId, int subId, String apnType,
             String apn, @DataFailCause.FailCause int failCause) {
         if (!checkNotifyPermission("notifyPreciseDataConnectionFailed()")) {
             return;
         }
         synchronized (mRecords) {
-            mPreciseDataConnectionState = new PreciseDataConnectionState(
-                    TelephonyManager.DATA_UNKNOWN, TelephonyManager.NETWORK_TYPE_UNKNOWN,
-                    ApnSetting.getApnTypesBitmaskFromString(apnType), apn, null, failCause);
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
-                    try {
-                        r.callback.onPreciseDataConnectionStateChanged(mPreciseDataConnectionState);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
+                        TelephonyManager.DATA_UNKNOWN, TelephonyManager.NETWORK_TYPE_UNKNOWN,
+                        ApnSetting.getApnTypesBitmaskFromString(apnType), apn, null, failCause);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onPreciseDataConnectionStateChanged(
+                                    mPreciseDataConnectionState[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
+
             handleRemoveListLocked();
         }
         broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
@@ -1704,24 +1752,25 @@
         }
     }
 
-    public void notifyOemHookRawEventForSubscriber(int subId, byte[] rawData) {
+    public void notifyOemHookRawEventForSubscriber(int phoneId, int subId, byte[] rawData) {
         if (!checkNotifyPermission("notifyOemHookRawEventForSubscriber")) {
             return;
         }
 
         synchronized (mRecords) {
-            for (Record r : mRecords) {
-                if (VDBG) {
-                    log("notifyOemHookRawEventForSubscriber:  r=" + r + " subId=" + subId);
-                }
-                if ((r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT)) &&
-                        ((r.subId == subId) ||
-                        (r.subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID))) {
-                    try {
-                        r.callback.onOemHookRawEvent(rawData);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+            if (validatePhoneId(phoneId)) {
+                for (Record r : mRecords) {
+                    if (VDBG) {
+                        log("notifyOemHookRawEventForSubscriber:  r=" + r + " subId=" + subId);
+                    }
+                    if ((r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT))
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onOemHookRawEvent(rawData);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
@@ -1792,27 +1841,32 @@
         }
     }
 
-    public void notifyRadioPowerStateChanged(@TelephonyManager.RadioPowerState int state) {
+    public void notifyRadioPowerStateChanged(int phoneId, int subId,
+                                             @TelephonyManager.RadioPowerState int state) {
         if (!checkNotifyPermission("notifyRadioPowerStateChanged()")) {
             return;
         }
 
         if (VDBG) {
-            log("notifyRadioPowerStateChanged: state= " + state);
+            log("notifyRadioPowerStateChanged: state= " + state + " subId=" + subId);
         }
 
         synchronized (mRecords) {
-            mRadioPowerState = state;
+            if (validatePhoneId(phoneId)) {
+                mRadioPowerState = state;
 
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED)) {
-                    try {
-                        r.callback.onRadioPowerStateChanged(state);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onRadioPowerStateChanged(state);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
+
             }
             handleRemoveListLocked();
         }
@@ -1820,60 +1874,66 @@
 
 
     @Override
-    public void notifyEmergencyNumberList() {
+    public void notifyEmergencyNumberList(int phoneId, int subId) {
         if (!checkNotifyPermission("notifyEmergencyNumberList()")) {
             return;
         }
 
         synchronized (mRecords) {
-            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
-                    Context.TELEPHONY_SERVICE);
-            mEmergencyNumberList = tm.getEmergencyNumberList();
+            if (validatePhoneId(phoneId)) {
+                TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
+                        Context.TELEPHONY_SERVICE);
+                mEmergencyNumberList = tm.getEmergencyNumberList();
 
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_EMERGENCY_NUMBER_LIST)) {
-                    try {
-                        r.callback.onEmergencyNumberListChanged(mEmergencyNumberList);
-                        if (VDBG) {
-                            log("notifyEmergencyNumberList: emergencyNumberList= "
-                                    + mEmergencyNumberList);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_EMERGENCY_NUMBER_LIST)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onEmergencyNumberListChanged(mEmergencyNumberList);
+                            if (VDBG) {
+                                log("notifyEmergencyNumberList: emergencyNumberList= "
+                                        + mEmergencyNumberList);
+                            }
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
                         }
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
                     }
                 }
             }
+
             handleRemoveListLocked();
         }
     }
 
     @Override
-    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId,
+    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId, int subId,
             int callNetworkType) {
         if (!checkNotifyPermission("notifyCallQualityChanged()")) {
             return;
         }
 
-        // merge CallQuality with PreciseCallState and network type
-        mCallQuality = callQuality;
-        mCallNetworkType = callNetworkType;
-        mCallAttributes = new CallAttributes(mPreciseCallState, callNetworkType, callQuality);
-
         synchronized (mRecords) {
-            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
-                    Context.TELEPHONY_SERVICE);
+            if (validatePhoneId(phoneId)) {
+                // merge CallQuality with PreciseCallState and network type
+                mCallQuality[phoneId] = callQuality;
+                mCallNetworkType[phoneId] = callNetworkType;
+                mCallAttributes[phoneId] = new CallAttributes(mPreciseCallState[phoneId],
+                        callNetworkType, callQuality);
 
-            for (Record r : mRecords) {
-                if (r.matchPhoneStateListenerEvent(
-                        PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)) {
-                    try {
-                        r.callback.onCallAttributesChanged(mCallAttributes);
-                    } catch (RemoteException ex) {
-                        mRemoveList.add(r.binder);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onCallAttributesChanged(mCallAttributes[phoneId]);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
                     }
                 }
             }
+
             handleRemoveListLocked();
         }
     }
@@ -1893,6 +1953,11 @@
                 pw.println("Phone Id=" + i);
                 pw.increaseIndent();
                 pw.println("mCallState=" + mCallState[i]);
+                pw.println("mRingingCallState=" + mRingingCallState[i]);
+                pw.println("mForegroundCallState=" + mForegroundCallState[i]);
+                pw.println("mBackgroundCallState=" + mBackgroundCallState[i]);
+                pw.println("mPreciseCallState=" + mPreciseCallState[i]);
+                pw.println("mCallDisconnectCause=" + mCallDisconnectCause[i]);
                 pw.println("mCallIncomingNumber=" + mCallIncomingNumber[i]);
                 pw.println("mServiceState=" + mServiceState[i]);
                 pw.println("mVoiceActivationState= " + mVoiceActivationState[i]);
@@ -1906,26 +1971,23 @@
                 pw.println("mCellLocation=" + mCellLocation[i]);
                 pw.println("mCellInfo=" + mCellInfo.get(i));
                 pw.println("mImsCallDisconnectCause=" + mImsReasonInfo.get(i));
+                pw.println("mSrvccState=" + mSrvccState[i]);
+                pw.println("mOtaspMode=" + mOtaspMode[i]);
+                pw.println("mCallPreciseDisconnectCause=" + mCallPreciseDisconnectCause[i]);
+                pw.println("mCallQuality=" + mCallQuality[i]);
+                pw.println("mCallAttributes=" + mCallAttributes[i]);
+                pw.println("mCallNetworkType=" + mCallNetworkType[i]);
+                pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState[i]);
                 pw.decreaseIndent();
             }
-            pw.println("mCallNetworkType=" + mCallNetworkType);
-            pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState);
-            pw.println("mPreciseCallState=" + mPreciseCallState);
-            pw.println("mCallDisconnectCause=" + mCallDisconnectCause);
-            pw.println("mCallPreciseDisconnectCause=" + mCallPreciseDisconnectCause);
             pw.println("mCarrierNetworkChangeState=" + mCarrierNetworkChangeState);
-            pw.println("mRingingCallState=" + mRingingCallState);
-            pw.println("mForegroundCallState=" + mForegroundCallState);
-            pw.println("mBackgroundCallState=" + mBackgroundCallState);
-            pw.println("mSrvccState=" + mSrvccState);
+
             pw.println("mPhoneCapability=" + mPhoneCapability);
             pw.println("mActiveDataSubId=" + mActiveDataSubId);
             pw.println("mRadioPowerState=" + mRadioPowerState);
             pw.println("mEmergencyNumberList=" + mEmergencyNumberList);
-            pw.println("mCallQuality=" + mCallQuality);
-            pw.println("mCallAttributes=" + mCallAttributes);
-            pw.println("mDefaultPhoneId" + mDefaultPhoneId);
-            pw.println("mDefaultSubId" + mDefaultSubId);
+            pw.println("mDefaultPhoneId=" + mDefaultPhoneId);
+            pw.println("mDefaultSubId=" + mDefaultSubId);
 
             pw.decreaseIndent();
 
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index ee9bb3a..0ebbbc6 100755
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -836,13 +836,6 @@
             "carrier_metered_roaming_apn_types_strings";
 
     /**
-     * Default APN types that are metered on IWLAN by the carrier
-     * @hide
-     */
-    public static final String KEY_CARRIER_METERED_IWLAN_APN_TYPES_STRINGS =
-            "carrier_metered_iwlan_apn_types_strings";
-
-    /**
      * CDMA carrier ERI (Enhanced Roaming Indicator) file name
      * @hide
      */
@@ -2847,15 +2840,6 @@
                 new String[]{"default", "mms", "dun", "supl"});
         sDefaults.putStringArray(KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS,
                 new String[]{"default", "mms", "dun", "supl"});
-        // By default all APNs should be unmetered if the device is on IWLAN. However, we add
-        // default APN as metered here as a workaround for P because in some cases, a data
-        // connection was brought up on cellular, but later on the device camped on IWLAN. That
-        // data connection was incorrectly treated as unmetered due to the current RAT IWLAN.
-        // Marking it as metered for now can workaround the issue.
-        // Todo: This will be fixed in Q when IWLAN full refactoring is completed.
-        sDefaults.putStringArray(KEY_CARRIER_METERED_IWLAN_APN_TYPES_STRINGS,
-                new String[]{"default"});
-
         sDefaults.putIntArray(KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY,
                 new int[]{
                     4, /* IS95A */
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index 373c5d2..6a9cba1 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -60,6 +60,8 @@
 
     /**
      * Stop listening for updates.
+     *
+     * The PhoneStateListener is not tied to any subscription and unregistered for any update.
      */
     public static final int LISTEN_NONE = 0;
 
@@ -433,7 +435,13 @@
     }
 
     /**
-     * Callback invoked when device service state changes.
+     * Callback invoked when device service state changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @see ServiceState#STATE_EMERGENCY_ONLY
      * @see ServiceState#STATE_IN_SERVICE
@@ -445,7 +453,13 @@
     }
 
     /**
-     * Callback invoked when network signal strength changes.
+     * Callback invoked when network signal strength changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @see ServiceState#STATE_EMERGENCY_ONLY
      * @see ServiceState#STATE_IN_SERVICE
@@ -459,21 +473,39 @@
     }
 
     /**
-     * Callback invoked when the message-waiting indicator changes.
+     * Callback invoked when the message-waiting indicator changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      */
     public void onMessageWaitingIndicatorChanged(boolean mwi) {
         // default implementation empty
     }
 
     /**
-     * Callback invoked when the call-forwarding indicator changes.
+     * Callback invoked when the call-forwarding indicator changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      */
     public void onCallForwardingIndicatorChanged(boolean cfi) {
         // default implementation empty
     }
 
     /**
-     * Callback invoked when device cell location changes.
+     * Callback invoked when device cell location changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      */
     public void onCellLocationChanged(CellLocation location) {
         // default implementation empty
@@ -482,7 +514,14 @@
     /**
      * Callback invoked when device call state changes.
      * <p>
-     * Reports the state of Telephony (mobile) calls on the device.
+     * Reports the state of Telephony (mobile) calls on the device for the registered subscription.
+     * <p>
+     * Note: the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      * <p>
      * Note: The state returned here may differ from that returned by
      * {@link TelephonyManager#getCallState()}. Receivers of this callback should be aware that
@@ -500,7 +539,13 @@
     }
 
     /**
-     * Callback invoked when connection state changes.
+     * Callback invoked when connection state changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @see TelephonyManager#DATA_DISCONNECTED
      * @see TelephonyManager#DATA_CONNECTING
@@ -518,7 +563,13 @@
     }
 
     /**
-     * Callback invoked when data activity state changes.
+     * Callback invoked when data activity state changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @see TelephonyManager#DATA_ACTIVITY_NONE
      * @see TelephonyManager#DATA_ACTIVITY_IN
@@ -531,12 +582,13 @@
     }
 
     /**
-     * Callback invoked when network signal strengths changes.
-     *
-     * @see ServiceState#STATE_EMERGENCY_ONLY
-     * @see ServiceState#STATE_IN_SERVICE
-     * @see ServiceState#STATE_OUT_OF_SERVICE
-     * @see ServiceState#STATE_POWER_OFF
+     * Callback invoked when network signal strengths changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      */
     public void onSignalStrengthsChanged(SignalStrength signalStrength) {
         // default implementation empty
@@ -544,8 +596,15 @@
 
 
     /**
-     * The Over The Air Service Provisioning (OTASP) has changed. Requires
-     * the READ_PHONE_STATE permission.
+     * The Over The Air Service Provisioning (OTASP) has changed on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
+     * Requires the READ_PHONE_STATE permission.
      * @param otaspMode is integer <code>OTASP_UNKNOWN=1<code>
      *   means the value is currently unknown and the system should wait until
      *   <code>OTASP_NEEDED=2<code> or <code>OTASP_NOT_NEEDED=3<code> is received before
@@ -559,15 +618,28 @@
     }
 
     /**
-     * Callback invoked when a observed cell info has changed,
-     * or new cells have been added or removed.
+     * Callback invoked when a observed cell info has changed or new cells have been added
+     * or removed on the registered subscription.
+     * Note, the registration subId s from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param cellInfo is the list of currently visible cells.
      */
     public void onCellInfoChanged(List<CellInfo> cellInfo) {
     }
 
     /**
-     * Callback invoked when precise device call state changes.
+     * Callback invoked when precise device call state changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      * @param callState {@link PreciseCallState}
      * @hide
      */
@@ -578,7 +650,14 @@
     }
 
     /**
-     * Callback invoked when call disconnect cause changes.
+     * Callback invoked when call disconnect cause changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param disconnectCause {@link DisconnectCause}.
      * @param preciseDisconnectCause {@link PreciseDisconnectCause}.
      *
@@ -591,7 +670,14 @@
     }
 
     /**
-     * Callback invoked when Ims call disconnect cause changes.
+     * Callback invoked when Ims call disconnect cause changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param imsReasonInfo {@link ImsReasonInfo} contains details on why IMS call failed.
      *
      * @hide
@@ -603,7 +689,15 @@
     }
 
     /**
-     * Callback invoked when data connection state changes with precise information.
+     * Callback invoked when data connection state changes with precise information
+     * on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param dataConnectionState {@link PreciseDataConnectionState}
      *
      * @hide
@@ -616,7 +710,13 @@
     }
 
     /**
-     * Callback invoked when data connection state changes with precise information.
+     * Callback invoked when data connection real time info changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @hide
      */
@@ -628,7 +728,15 @@
 
     /**
      * Callback invoked when there has been a change in the Single Radio Voice Call Continuity
-     * (SRVCC) state for the currently active call.
+     * (SRVCC) state for the currently active call on the registered subscription.
+     *
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @hide
      */
     @SystemApi
@@ -637,7 +745,15 @@
     }
 
     /**
-     * Callback invoked when the SIM voice activation state has changed
+     * Callback invoked when the SIM voice activation state has changed on the registered
+     * subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param state is the current SIM voice activation state
      * @hide
      */
@@ -646,7 +762,15 @@
     }
 
     /**
-     * Callback invoked when the SIM data activation state has changed
+     * Callback invoked when the SIM data activation state has changed on the registered
+     * subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param state is the current SIM data activation state
      * @hide
      */
@@ -654,7 +778,14 @@
     }
 
     /**
-     * Callback invoked when the user mobile data state has changed
+     * Callback invoked when the user mobile data state has changed on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
      * @param enabled indicates whether the current user mobile data state is enabled or disabled.
      */
     public void onUserMobileDataStateChanged(boolean enabled) {
@@ -662,7 +793,14 @@
     }
 
     /**
-     * Callback invoked when the current physical channel configuration has changed
+     * Callback invoked when the current physical channel configuration has changed on the
+     * registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @param configs List of the current {@link PhysicalChannelConfig}s
      * @hide
@@ -673,7 +811,14 @@
     }
 
     /**
-     * Callback invoked when the current emergency number list has changed
+     * Callback invoked when the current emergency number list has changed on the registered
+     * subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
      *
      * @param emergencyNumberList Map including the key as the active subscription ID
      *                           (Note: if there is no active subscription, the key is
@@ -688,8 +833,15 @@
     }
 
     /**
-     * Callback invoked when OEM hook raw event is received. Requires
-     * the READ_PRIVILEGED_PHONE_STATE permission.
+     * Callback invoked when OEM hook raw event is received on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
+     * Requires the READ_PRIVILEGED_PHONE_STATE permission.
      * @param rawData is the byte array of the OEM hook raw data.
      * @hide
      */
@@ -699,8 +851,10 @@
     }
 
     /**
-     * Callback invoked when phone capability changes. Requires
-     * the READ_PRIVILEGED_PHONE_STATE permission.
+     * Callback invoked when phone capability changes.
+     * Note, this callback triggers regardless of registered subscription.
+     *
+     * Requires the READ_PRIVILEGED_PHONE_STATE permission.
      * @param capability the new phone capability
      * @hide
      */
@@ -709,8 +863,10 @@
     }
 
     /**
-     * Callback invoked when active data subId changes. Requires
-     * the READ_PHONE_STATE permission.
+     * Callback invoked when active data subId changes.
+     * Note, this callback triggers regardless of registered subscription.
+     *
+     * Requires the READ_PHONE_STATE permission.
      * @param subId current subscription used to setup Cellular Internet data.
      *              For example, it could be the current active opportunistic subscription in use,
      *              or the subscription user selected as default data subscription in DSDS mode.
@@ -720,8 +876,15 @@
     }
 
     /**
-     * Callback invoked when the call attributes changes. Requires
-     * the READ_PRIVILEGED_PHONE_STATE permission.
+     * Callback invoked when the call attributes changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
+     * Requires the READ_PRIVILEGED_PHONE_STATE permission.
      * @param callAttributes the call attributes
      * @hide
      */
@@ -731,7 +894,15 @@
     }
 
     /**
-     * Callback invoked when modem radio power state changes. Requires
+     * Callback invoked when modem radio power state changes on the registered subscription.
+     * Note, the registration subId comes from {@link TelephonyManager} object which registers
+     * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
+     * If this TelephonyManager object was created with
+     * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
+     * subId. Otherwise, this callback applies to
+     * {@link SubscriptionManager#getDefaultSubscriptionId()}.
+     *
+     * Requires
      * the READ_PRIVILEGED_PHONE_STATE permission.
      * @param state the modem radio power state
      * @hide
@@ -747,6 +918,10 @@
      * has been requested by an app using
      * {@link android.telephony.TelephonyManager#notifyCarrierNetworkChange(boolean)}
      *
+     * Note, this callback is pinned to the registered subscription and will be invoked when
+     * the notifying carrier app has carrier privilege rule on the registered
+     * subscription. {@link android.telephony.TelephonyManager#hasCarrierPrivileges}
+     *
      * @param active Whether the carrier network change is or shortly
      *               will be active. This value is true to indicate
      *               showing alternative UI and false to stop.
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 43acfdd..0b1a8e0 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -396,6 +396,12 @@
     public static final int NAME_SOURCE_USER_INPUT = 2;
 
     /**
+     * The name_source is carrier (carrier app, carrier config, etc.)
+     * @hide
+     */
+    public static final int NAME_SOURCE_CARRIER = 3;
+
+    /**
      * TelephonyProvider column name for the color of a SIM.
      * <P>Type: INTEGER (int)</P>
      */
diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java
index 4a7585d..f0c819d 100644
--- a/telephony/java/android/telephony/data/ApnSetting.java
+++ b/telephony/java/android/telephony/data/ApnSetting.java
@@ -1273,6 +1273,23 @@
     }
 
     /**
+     * Get supported APN types
+     *
+     * @return list of APN types
+     * @hide
+     */
+    @ApnType
+    public List<Integer> getApnTypes() {
+        List<Integer> types = new ArrayList<>();
+        for (Integer type : APN_TYPE_INT_MAP.keySet()) {
+            if ((mApnTypeBitmask & type) == type) {
+                types.add(type);
+            }
+        }
+        return types;
+    }
+
+    /**
      * @param apnTypeBitmask bitmask of APN types.
      * @return comma delimited list of APN types.
      * @hide
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index 0610c5d..f2f3c2d 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -56,38 +56,41 @@
     void notifyDataConnection(int state, boolean isDataConnectivityPossible,
             String apn, String apnType, in LinkProperties linkProperties,
             in NetworkCapabilities networkCapabilities, int networkType, boolean roaming);
-    void notifyDataConnectionForSubscriber(int subId, int state, boolean isDataConnectivityPossible,
+    void notifyDataConnectionForSubscriber(int phoneId, int subId, int state,
+            boolean isDataConnectivityPossible,
             String apn, String apnType, in LinkProperties linkProperties,
             in NetworkCapabilities networkCapabilities, int networkType, boolean roaming);
     @UnsupportedAppUsage
     void notifyDataConnectionFailed(String apnType);
-    void notifyDataConnectionFailedForSubscriber(int subId, String apnType);
+    void notifyDataConnectionFailedForSubscriber(int phoneId, int subId, String apnType);
     void notifyCellLocation(in Bundle cellLocation);
     void notifyCellLocationForSubscriber(in int subId, in Bundle cellLocation);
-    void notifyOtaspChanged(in int otaspMode);
+    void notifyOtaspChanged(in int subId, in int otaspMode);
     @UnsupportedAppUsage
     void notifyCellInfo(in List<CellInfo> cellInfo);
     void notifyPhysicalChannelConfiguration(in List<PhysicalChannelConfig> configs);
     void notifyPhysicalChannelConfigurationForSubscriber(in int subId,
             in List<PhysicalChannelConfig> configs);
-    void notifyPreciseCallState(int ringingCallState, int foregroundCallState,
-            int backgroundCallState, int phoneId);
-    void notifyDisconnectCause(int disconnectCause, int preciseDisconnectCause);
-    void notifyPreciseDataConnectionFailed(String apnType, String apn,
+    void notifyPreciseCallState(int phoneId, int subId, int ringingCallState,
+            int foregroundCallState, int backgroundCallState);
+    void notifyDisconnectCause(int phoneId, int subId, int disconnectCause,
+            int preciseDisconnectCause);
+    void notifyPreciseDataConnectionFailed(int phoneId, int subId, String apnType, String apn,
             int failCause);
     void notifyCellInfoForSubscriber(in int subId, in List<CellInfo> cellInfo);
     void notifySrvccStateChanged(in int subId, in int lteState);
     void notifySimActivationStateChangedForPhoneId(in int phoneId, in int subId,
             int activationState, int activationType);
-    void notifyOemHookRawEventForSubscriber(in int subId, in byte[] rawData);
+    void notifyOemHookRawEventForSubscriber(in int phoneId, in int subId, in byte[] rawData);
     void notifySubscriptionInfoChanged();
     void notifyOpportunisticSubscriptionInfoChanged();
     void notifyCarrierNetworkChange(in boolean active);
     void notifyUserMobileDataStateChangedForPhoneId(in int phoneId, in int subId, in boolean state);
     void notifyPhoneCapabilityChanged(in PhoneCapability capability);
     void notifyActiveDataSubIdChanged(int activeDataSubId);
-    void notifyRadioPowerStateChanged(in int state);
-    void notifyEmergencyNumberList();
-    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId, int callNetworkType);
+    void notifyRadioPowerStateChanged(in int phoneId, in int subId, in int state);
+    void notifyEmergencyNumberList(in int phoneId, in int subId);
+    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId, int subId,
+            int callNetworkType);
     void notifyImsDisconnectCause(int subId, in ImsReasonInfo imsReasonInfo);
 }
diff --git a/tests/net/common/Android.bp b/tests/net/common/Android.bp
index 07525a6..db1ccb4 100644
--- a/tests/net/common/Android.bp
+++ b/tests/net/common/Android.bp
@@ -24,6 +24,7 @@
         "frameworks-net-testutils",
         "junit",
         "mockito-target-minus-junit4",
+        "platform-test-annotations",
     ],
     libs: [
         "android.test.base.stubs",
diff --git a/tests/net/common/java/android/net/NetworkTest.java b/tests/net/common/java/android/net/NetworkTest.java
index bef66b2..38bc744 100644
--- a/tests/net/common/java/android/net/NetworkTest.java
+++ b/tests/net/common/java/android/net/NetworkTest.java
@@ -25,6 +25,7 @@
 import android.net.LocalSocket;
 import android.net.LocalSocketAddress;
 import android.net.Network;
+import android.platform.test.annotations.AppModeFull;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
@@ -74,6 +75,7 @@
     }
 
     @Test
+    @AppModeFull(reason = "Socket cannot bind in instant app mode")
     public void testBindSocketOfConnectedDatagramSocketThrows() throws Exception {
         final DatagramSocket mDgramSocket = new DatagramSocket(0, (InetAddress) Inet6Address.ANY);
         mDgramSocket.connect((InetAddress) Inet6Address.LOOPBACK, 53);