Revert "Added SIM events handling and fix crashes"

Revert submission 20813798-smsvc_bootup

Reason for revert: b/263772382

Reverted changes: /q/submissionid:20813798-smsvc_bootup

Change-Id: I3fb32444d6f50dc8ace1276f2998551118832c7f
(cherry picked from commit 9c185193949cd67e87d172f5ba1f3919e8bb7fc3)
Merged-In: I3fb32444d6f50dc8ace1276f2998551118832c7f
diff --git a/src/java/com/android/internal/telephony/PhoneFactory.java b/src/java/com/android/internal/telephony/PhoneFactory.java
index 43aa154..cb8f984 100644
--- a/src/java/com/android/internal/telephony/PhoneFactory.java
+++ b/src/java/com/android/internal/telephony/PhoneFactory.java
@@ -214,14 +214,9 @@
                     TelephonyComponentFactory.getInstance().inject(SubscriptionController.class
                             .getName()).initSubscriptionController(context);
                 }
-
-                SubscriptionController sc = null;
-                if (!isSubscriptionManagerServiceEnabled()) {
-                    sc = SubscriptionController.getInstance();
-                }
-
                 TelephonyComponentFactory.getInstance().inject(MultiSimSettingController.class.
-                        getName()).initMultiSimSettingController(context, sc);
+                        getName()).initMultiSimSettingController(context,
+                        SubscriptionController.getInstance());
 
                 if (context.getPackageManager().hasSystemFeature(
                         PackageManager.FEATURE_TELEPHONY_EUICC)) {
diff --git a/src/java/com/android/internal/telephony/ServiceStateTracker.java b/src/java/com/android/internal/telephony/ServiceStateTracker.java
index 2a76a84..9c7178a 100644
--- a/src/java/com/android/internal/telephony/ServiceStateTracker.java
+++ b/src/java/com/android/internal/telephony/ServiceStateTracker.java
@@ -2751,8 +2751,8 @@
 
             if (mPhone.isSubscriptionManagerServiceEnabled()) {
                 mSubscriptionManagerService.setCarrierName(mPhone.getSubId(),
-                        TextUtils.emptyIfNull(getCarrierName(data.shouldShowPlmn(), data.getPlmn(),
-                                data.shouldShowSpn(), data.getSpn())));
+                        getCarrierName(data.shouldShowPlmn(), data.getPlmn(),
+                                data.shouldShowSpn(), data.getSpn()));
             } else {
                 if (!mSubscriptionController.setPlmnSpn(mPhone.getPhoneId(),
                         data.shouldShowPlmn(), data.getPlmn(), data.shouldShowSpn(),
diff --git a/src/java/com/android/internal/telephony/SubscriptionController.java b/src/java/com/android/internal/telephony/SubscriptionController.java
index af759ea..4974182 100644
--- a/src/java/com/android/internal/telephony/SubscriptionController.java
+++ b/src/java/com/android/internal/telephony/SubscriptionController.java
@@ -331,11 +331,8 @@
 
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
     public static SubscriptionController getInstance() {
-        if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
-            throw new RuntimeException("getInstance should not be called.");
-        }
         if (sInstance == null) {
-            Log.wtf(LOG_TAG, "getInstance null");
+           Log.wtf(LOG_TAG, "getInstance null");
         }
 
         return sInstance;
diff --git a/src/java/com/android/internal/telephony/data/PhoneSwitcher.java b/src/java/com/android/internal/telephony/data/PhoneSwitcher.java
index fe63ada..1eb07aa 100644
--- a/src/java/com/android/internal/telephony/data/PhoneSwitcher.java
+++ b/src/java/com/android/internal/telephony/data/PhoneSwitcher.java
@@ -531,14 +531,8 @@
         mMaxDataAttachModemCount = maxActivePhones;
         mLocalLog = new LocalLog(MAX_LOCAL_LOG_LINES);
 
-        if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
-            mSubscriptionManagerService = SubscriptionManagerService.getInstance();
-            mSubscriptionController = null;
-        } else {
-            mSubscriptionController = SubscriptionController.getInstance();
-            mSubscriptionManagerService = null;
-        }
-
+        mSubscriptionController = SubscriptionController.getInstance();
+        mSubscriptionManagerService = SubscriptionManagerService.getInstance();
         mRadioConfig = RadioConfig.getInstance();
         mValidator = CellularNetworkValidator.getInstance();
 
diff --git a/src/java/com/android/internal/telephony/subscription/SubscriptionDatabaseManager.java b/src/java/com/android/internal/telephony/subscription/SubscriptionDatabaseManager.java
index 199d2d4..501d4f0 100644
--- a/src/java/com/android/internal/telephony/subscription/SubscriptionDatabaseManager.java
+++ b/src/java/com/android/internal/telephony/subscription/SubscriptionDatabaseManager.java
@@ -39,7 +39,6 @@
 import android.telephony.SubscriptionManager.SubscriptionType;
 import android.telephony.SubscriptionManager.UsageSetting;
 import android.telephony.TelephonyManager;
-import android.telephony.UiccAccessRule;
 import android.telephony.ims.ImsMmTelManager;
 import android.text.TextUtils;
 import android.util.Base64;
@@ -563,7 +562,6 @@
     public SubscriptionDatabaseManager(@NonNull Context context, @NonNull Looper looper,
             @NonNull SubscriptionDatabaseManagerCallback callback) {
         super(looper);
-        log("Created SubscriptionDatabaseManager.");
         mContext = context;
         mCallback = callback;
         mUiccController = UiccController.getInstance();
@@ -686,8 +684,6 @@
 
         for (String columnName : Telephony.SimInfo.getAllColumns()) {
             if (DEPRECATED_DATABASE_COLUMNS.contains(columnName)) continue;
-            // subId is generated by the database. Cannot be updated.
-            if (columnName.equals(SimInfo.COLUMN_UNIQUE_KEY_SUBSCRIPTION_ID)) continue;
             Object newValue = getSubscriptionInfoFieldByColumnName(newSubInfo, columnName);
             if (newValue != null) {
                 Object oldValue = null;
@@ -716,16 +712,13 @@
         Objects.requireNonNull(contentValues);
         Uri uri = mContext.getContentResolver().insert(SimInfo.CONTENT_URI, contentValues);
         if (uri != null && uri.getLastPathSegment() != null) {
-            int subId = Integer.parseInt(uri.getLastPathSegment());
-            if (SubscriptionManager.isValidSubscriptionId(subId)) {
-                logl("insertNewRecordIntoDatabaseSync: Successfully added subscription. subId="
-                        + uri.getLastPathSegment());
-                return subId;
-            }
+            logl("insertNewRecordIntoDatabaseSync: Successfully added subscription. subId="
+                    + uri.getLastPathSegment());
+            return Integer.parseInt(uri.getLastPathSegment());
+        } else {
+            logel("insertNewRecordIntoDatabaseSync: Failed to insert subscription into database. "
+                    + "contentValues=" + contentValues);
         }
-
-        logel("insertNewRecordIntoDatabaseSync: Failed to insert subscription into database. "
-                + "contentValues=" + contentValues);
         return INVALID_ROW_INDEX;
     }
 
@@ -882,8 +875,6 @@
                     // Check if the new value is different from the old value in the cache.
                     if (!Objects.equals(getSubscriptionInfoFieldByColumnName(subInfo, columnName),
                             newValue)) {
-                        logv("writeDatabaseAndCacheHelper: subId=" + subId + ",columnName="
-                                + columnName + ", newValue=" + newValue);
                         // If the value is different, then we need to update the cache. Since all
                         // fields in SubscriptionInfo are final, we need to create a new
                         // SubscriptionInfo.
@@ -1220,24 +1211,6 @@
     }
 
     /**
-     * Set the carrier certificates for this subscription that are saved in carrier configs.
-     * This does not include access rules from the Uicc, whether embedded or non-embedded.
-     *
-     * @param subId Subscription id.
-     * @param carrierConfigAccessRules The carrier certificates for this subscription.
-     *
-     * @throws IllegalArgumentException if the subscription does not exist.
-     */
-    public void setCarrierConfigAccessRules(int subId,
-            @NonNull UiccAccessRule[] carrierConfigAccessRules) {
-        Objects.requireNonNull(carrierConfigAccessRules);
-        byte[] carrierConfigAccessRulesBytes = UiccAccessRule.encodeRules(carrierConfigAccessRules);
-        writeDatabaseAndCacheHelper(subId, SimInfo.COLUMN_ACCESS_RULES_FROM_CARRIER_CONFIGS,
-                carrierConfigAccessRulesBytes,
-                SubscriptionInfoInternal.Builder::setCarrierConfigAccessRules);
-    }
-
-    /**
      * Set whether an embedded subscription is on a removable card. Such subscriptions are
      * marked inaccessible as soon as the current card is removed. Otherwise, they will remain
      * accessible unless explicitly deleted. Only meaningful for embedded subscription.
@@ -1788,23 +1761,11 @@
         // publicCardId is the publicly exposed int card ID
         int publicCardId = mUiccController.convertToPublicCardId(cardString);
 
-        byte[] rules = cursor.getBlob(cursor.getColumnIndexOrThrow(SimInfo.COLUMN_ACCESS_RULES));
-        if (rules != null) {
-            builder.setNativeAccessRules(rules);
-        }
-
-        rules = cursor.getBlob(cursor.getColumnIndexOrThrow(
-                SimInfo.COLUMN_ACCESS_RULES_FROM_CARRIER_CONFIGS));
-        if (rules != null) {
-            builder.setCarrierConfigAccessRules(rules);
-        }
-
-        byte[] config = cursor.getBlob(cursor.getColumnIndexOrThrow(SimInfo.COLUMN_RCS_CONFIG));
-        if (config != null) {
-            builder.setRcsConfig(config);
-        }
-
         builder.setCardId(publicCardId)
+                .setNativeAccessRules(cursor.getBlob(cursor.getColumnIndexOrThrow(
+                        SimInfo.COLUMN_ACCESS_RULES)))
+                .setCarrierConfigAccessRules(cursor.getBlob(cursor.getColumnIndexOrThrow(
+                        SimInfo.COLUMN_ACCESS_RULES_FROM_CARRIER_CONFIGS)))
                 .setRemovableEmbedded(cursor.getInt(cursor.getColumnIndexOrThrow(
                         SimInfo.COLUMN_IS_REMOVABLE)))
                 .setEnhanced4GModeEnabled(cursor.getInt(cursor.getColumnIndexOrThrow(
@@ -1844,6 +1805,8 @@
                         SimInfo.COLUMN_IMS_RCS_UCE_ENABLED)))
                 .setCrossSimCallingEnabled(cursor.getInt(cursor.getColumnIndexOrThrow(
                         SimInfo.COLUMN_CROSS_SIM_CALLING_ENABLED)))
+                .setRcsConfig(cursor.getBlob(cursor.getColumnIndexOrThrow(
+                        SimInfo.COLUMN_RCS_CONFIG)))
                 .setAllowedNetworkTypesForReasons(TextUtils.emptyIfNull(
                         cursor.getString(cursor.getColumnIndexOrThrow(
                                 SimInfo.COLUMN_ALLOWED_NETWORK_TYPES_FOR_REASONS))))
diff --git a/src/java/com/android/internal/telephony/subscription/SubscriptionManagerService.java b/src/java/com/android/internal/telephony/subscription/SubscriptionManagerService.java
index 27007f1..9e31428 100644
--- a/src/java/com/android/internal/telephony/subscription/SubscriptionManagerService.java
+++ b/src/java/com/android/internal/telephony/subscription/SubscriptionManagerService.java
@@ -37,7 +37,6 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.ParcelUuid;
-import android.os.PersistableBundle;
 import android.os.RemoteException;
 import android.os.TelephonyServiceManager;
 import android.os.UserHandle;
@@ -76,7 +75,6 @@
 import com.android.internal.telephony.CarrierResolver;
 import com.android.internal.telephony.ISetOpportunisticDataCallback;
 import com.android.internal.telephony.ISub;
-import com.android.internal.telephony.IccCard;
 import com.android.internal.telephony.MultiSimSettingController;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneFactory;
@@ -86,9 +84,7 @@
 import com.android.internal.telephony.euicc.EuiccController;
 import com.android.internal.telephony.subscription.SubscriptionDatabaseManager.SubscriptionDatabaseManagerCallback;
 import com.android.internal.telephony.uicc.IccUtils;
-import com.android.internal.telephony.uicc.UiccCard;
 import com.android.internal.telephony.uicc.UiccController;
-import com.android.internal.telephony.uicc.UiccPort;
 import com.android.internal.telephony.uicc.UiccSlot;
 import com.android.internal.telephony.util.ArrayUtils;
 import com.android.telephony.Rlog;
@@ -141,7 +137,6 @@
             SimInfo.COLUMN_IMS_RCS_UCE_ENABLED,
             SimInfo.COLUMN_CROSS_SIM_CALLING_ENABLED,
             SimInfo.COLUMN_RCS_CONFIG,
-            SimInfo.COLUMN_ALLOWED_NETWORK_TYPES_FOR_REASONS,
             SimInfo.COLUMN_D2D_STATUS_SHARING,
             SimInfo.COLUMN_VOIMS_OPT_IN_STATUS,
             SimInfo.COLUMN_D2D_STATUS_SHARING_SELECTED_CONTACTS,
@@ -235,10 +230,6 @@
     @NonNull
     private final WatchedInt mDefaultSmsSubId;
 
-    /** Sim state per logical SIM slot index. */
-    @NonNull
-    private final int[] mSimState;
-
     /**
      * Watched map that automatically invalidate cache in {@link SubscriptionManager}.
      */
@@ -272,7 +263,7 @@
      * Watched integer.
      */
     public static class WatchedInt {
-        protected int mValue;
+        private int mValue;
 
         /**
          * Constructor.
@@ -386,9 +377,7 @@
                 SubscriptionManager.INVALID_SUBSCRIPTION_ID)) {
             @Override
             public boolean set(int newValue) {
-                int oldValue = mValue;
                 if (super.set(newValue)) {
-                    logl("Default voice sub changed from " + oldValue + " to " + newValue);
                     Settings.Global.putInt(mContext.getContentResolver(),
                             Settings.Global.MULTI_SIM_VOICE_CALL_SUBSCRIPTION, newValue);
                     return true;
@@ -402,9 +391,7 @@
                 SubscriptionManager.INVALID_SUBSCRIPTION_ID)) {
             @Override
             public boolean set(int newValue) {
-                int oldValue = mValue;
                 if (super.set(newValue)) {
-                    logl("Default data sub changed from " + oldValue + " to " + newValue);
                     Settings.Global.putInt(mContext.getContentResolver(),
                             Settings.Global.MULTI_SIM_DATA_CALL_SUBSCRIPTION, newValue);
                     return true;
@@ -418,9 +405,7 @@
                 SubscriptionManager.INVALID_SUBSCRIPTION_ID)) {
             @Override
             public boolean set(int newValue) {
-                int oldValue = mValue;
                 if (super.set(newValue)) {
-                    logl("Default voice sms changed from " + oldValue + " to " + newValue);
                     Settings.Global.putInt(mContext.getContentResolver(),
                             Settings.Global.MULTI_SIM_SMS_SUBSCRIPTION, newValue);
                     return true;
@@ -431,9 +416,6 @@
 
         mDefaultSubId = new WatchedInt(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
 
-        mSimState = new int[mTelephonyManager.getSupportedModemCount()];
-        Arrays.fill(mSimState, TelephonyManager.SIM_STATE_UNKNOWN);
-
         // Create a separate thread for subscription database manager. The database will be updated
         // from a different thread.
         HandlerThread handlerThread = new HandlerThread(LOG_TAG);
@@ -1009,291 +991,12 @@
     }
 
     /**
-     * Check if the SIM application is enabled on the card or not.
-     *
-     * @param phoneId The phone id.
-     *
-     * @return {@code true} if the application is enabled.
-     */
-    public boolean areUiccAppsEnabledOnCard(int phoneId) {
-        // When uicc apps are disabled(supported in IRadio 1.5), we will still get IccId from
-        // cardStatus (since IRadio 1.2). And upon cardStatus change we'll receive another
-        // handleSimNotReady so this will be evaluated again.
-        UiccSlot slot = mUiccController.getUiccSlotForPhone(phoneId);
-        if (slot == null) return false;
-        UiccPort port = mUiccController.getUiccPort(phoneId);
-        String iccId = (port == null) ? null : port.getIccId();
-        if (iccId == null) {
-            return false;
-        }
-
-        SubscriptionInfoInternal subInfo = mSubscriptionDatabaseManager
-                .getSubscriptionInfoInternalByIccId(IccUtils.stripTrailingFs(iccId));
-        return subInfo != null && subInfo.areUiccApplicationsEnabled();
-    }
-
-    /**
-     * Get ICCID by phone id.
-     *
-     * @param phoneId The phone id (i.e. Logical SIM slot index.)
-     *
-     * @return The ICCID. Empty string if not available.
-     */
-    @NonNull
-    private String getIccId(int phoneId) {
-        UiccPort port = mUiccController.getUiccPort(phoneId);
-        return (port == null) ? "" : TextUtils.emptyIfNull(
-                IccUtils.stripTrailingFs(port.getIccId()));
-    }
-
-    /**
      * Update the subscriptions on the logical SIM slot index (i.e. phone id).
      *
-     * @param phoneId The phone id (i.e. Logical SIM slot index)
+     * @param slotIndex The logical SIM slot index.
      */
-    private void updateSubscriptions(int phoneId) {
-        int simState = mSimState[phoneId];
-        log("updateSubscriptions: phoneId=" + phoneId + ", simState="
-                + TelephonyManager.simStateToString(simState));
-        if (simState == TelephonyManager.SIM_STATE_ABSENT) {
-            if (mSlotIndexToSubId.containsKey(phoneId)) {
-                // Re-enable the SIM when it's removed, so it will be in enabled state when it gets
-                // re-inserted again. (pre-U behavior)
-                mSubscriptionDatabaseManager.setUiccApplicationsEnabled(
-                        mSlotIndexToSubId.get(phoneId), true);
-                // When sim is absent, set the port index to invalid port index. (pre-U behavior)
-                mSubscriptionDatabaseManager.setPortIndex(mSlotIndexToSubId.get(phoneId),
-                        TelephonyManager.INVALID_PORT_INDEX);
-            }
-        } else if (simState == TelephonyManager.SIM_STATE_NOT_READY) {
-            // Check if this is the final state. Only update the subscription if NOT_READY is a
-            // final state.
-            IccCard iccCard = PhoneFactory.getPhone(phoneId).getIccCard();
-            if (!iccCard.isEmptyProfile() && areUiccAppsEnabledOnCard(phoneId)) {
-                log("updateSubscriptions: SIM_STATE_NOT_READY is not a final state. Will update "
-                        + "subscription later.");
-                return;
-            }
-        }
+    private void updateSubscriptions(int slotIndex) {
 
-        String iccId = getIccId(phoneId);
-        // Loop through all the subscriptions. If we found any ICCID matched, apply the right
-        // logical index to that.
-        int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-        for (SubscriptionInfoInternal subInfo
-                : mSubscriptionDatabaseManager.getAllSubscriptions()) {
-            int simSlotIndex = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
-            if (!TextUtils.isEmpty(iccId) && subInfo.getIccId().equals(iccId)) {
-                subId = subInfo.getSubscriptionId();
-                simSlotIndex = phoneId;
-                mSlotIndexToSubId.put(simSlotIndex, subId);
-                logl("updateSubscriptions: Found sub " + subInfo.getSubscriptionId()
-                        + ", phoneId=" + phoneId);
-            }
-            mSubscriptionDatabaseManager.setSimSlotIndex(subInfo.getSubscriptionId(), simSlotIndex);
-        }
-
-        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
-            logl("updateSubscriptions: Did not find any subscription. phoneId=" + phoneId);
-            mSlotIndexToSubId.remove(phoneId);
-        }
-
-        if (!TextUtils.isEmpty(iccId)) {
-            // Check if the subscription already existed.
-            SubscriptionInfoInternal subInfo = mSubscriptionDatabaseManager
-                    .getSubscriptionInfoInternalByIccId(iccId);
-            if (subInfo == null) {
-                // This is a new SIM card. Insert a new record.
-                subId = mSubscriptionDatabaseManager.insertSubscriptionInfo(
-                        new SubscriptionInfoInternal.Builder()
-                                .setIccId(iccId)
-                                .setSimSlotIndex(phoneId)
-                                .build());
-                logl("updateSubscriptions: Inserted a new subscription. subId=" + subId
-                        + ", phoneId=" + phoneId);
-            } else {
-                subId = subInfo.getSubscriptionId();
-            }
-
-            // Update the SIM slot index. This will make the subscription active.
-            mSubscriptionDatabaseManager.setSimSlotIndex(subId, phoneId);
-
-            // Update the card id.
-            UiccCard card = mUiccController.getUiccCardForPhone(phoneId);
-            if (card != null) {
-                String cardId = card.getCardId();
-                if (cardId != null) {
-                    mSubscriptionDatabaseManager.setCardString(subId, cardId);
-                }
-            }
-
-            // Update the port index.
-            UiccSlot slot = mUiccController.getUiccSlotForPhone(phoneId);
-            if (slot != null && !slot.isEuicc()) {
-                int portIndex = slot.getPortIndexFromIccId(iccId);
-                mSubscriptionDatabaseManager.setPortIndex(subId, portIndex);
-            }
-        }
-
-        updateDefaultSubIds();
-    }
-
-    /**
-     * Calculate the usage setting based on the carrier request.
-     *
-     * @param currentUsageSetting the current setting in the subscription DB.
-     * @param preferredUsageSetting provided by the carrier config.
-     *
-     * @return the calculated usage setting.
-     */
-    @VisibleForTesting
-    @UsageSetting public int calculateUsageSetting(@UsageSetting int currentUsageSetting,
-            @UsageSetting int preferredUsageSetting) {
-        int[] supportedUsageSettings;
-
-        //  Load the resources to provide the device capability
-        try {
-            supportedUsageSettings = mContext.getResources().getIntArray(
-                    com.android.internal.R.array.config_supported_cellular_usage_settings);
-            // If usage settings are not supported, return the default setting, which is UNKNOWN.
-            if (supportedUsageSettings == null
-                    || supportedUsageSettings.length < 1) return currentUsageSetting;
-        } catch (Resources.NotFoundException nfe) {
-            loge("calculateUsageSetting: Failed to load usage setting resources!");
-            return currentUsageSetting;
-        }
-
-        // If the current setting is invalid, including the first time the value is set,
-        // update it to default (this will trigger a change in the DB).
-        if (currentUsageSetting < SubscriptionManager.USAGE_SETTING_DEFAULT
-                || currentUsageSetting > SubscriptionManager.USAGE_SETTING_DATA_CENTRIC) {
-            log("calculateUsageSetting: Updating usage setting for current subscription");
-            currentUsageSetting = SubscriptionManager.USAGE_SETTING_DEFAULT;
-        }
-
-        // Range check the inputs, and on failure, make no changes
-        if (preferredUsageSetting < SubscriptionManager.USAGE_SETTING_DEFAULT
-                || preferredUsageSetting > SubscriptionManager.USAGE_SETTING_DATA_CENTRIC) {
-            loge("calculateUsageSetting: Invalid usage setting!" + preferredUsageSetting);
-            return currentUsageSetting;
-        }
-
-        // Default is always allowed
-        if (preferredUsageSetting == SubscriptionManager.USAGE_SETTING_DEFAULT) {
-            return preferredUsageSetting;
-        }
-
-        // Forced setting must be explicitly supported
-        for (int supportedUsageSetting : supportedUsageSettings) {
-            if (preferredUsageSetting == supportedUsageSetting) return preferredUsageSetting;
-        }
-
-        // If the preferred setting is not possible, just keep the current setting.
-        return currentUsageSetting;
-    }
-
-    /**
-     * Called by CarrierConfigLoader to update the subscription before sending a broadcast.
-     */
-    public void updateSubscriptionByCarrierConfig(int phoneId, @NonNull String configPackageName,
-            @NonNull PersistableBundle config, @NonNull Runnable callback) {
-        mHandler.post(() -> {
-            updateSubscriptionByCarrierConfigInternal(phoneId, configPackageName, config);
-            callback.run();
-        });
-    }
-
-    private void updateSubscriptionByCarrierConfigInternal(int phoneId,
-            @NonNull String configPackageName, @NonNull PersistableBundle config) {
-        log("updateSubscriptionByCarrierConfig: phoneId=" + phoneId + ", configPackageName="
-                + configPackageName);
-        if (!SubscriptionManager.isValidPhoneId(phoneId)
-                || TextUtils.isEmpty(configPackageName) || config == null) {
-            loge("updateSubscriptionByCarrierConfig: Failed to update the subscription. phoneId="
-                    + phoneId + " configPackageName=" + configPackageName + " config="
-                        + ((config == null) ? "null" : config.hashCode()));
-            return;
-        }
-
-        if (!mSlotIndexToSubId.containsKey(phoneId)) {
-            log("updateSubscriptionByCarrierConfig: No subscription is active for phone being "
-                    + "updated.");
-            return;
-        }
-
-        int subId = mSlotIndexToSubId.get(phoneId);
-
-        SubscriptionInfoInternal subInfo = mSubscriptionDatabaseManager
-                .getSubscriptionInfoInternal(subId);
-        if (subInfo == null) {
-            loge("updateSubscriptionByCarrierConfig: Couldn't retrieve subscription info for "
-                    + "current subscription. subId=" + subId);
-            return;
-        }
-
-        ParcelUuid groupUuid;
-
-        // carrier certificates are not subscription-specific, so we want to load them even if
-        // this current package is not a CarrierServicePackage
-        String[] certs = config.getStringArray(
-                CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY);
-        UiccAccessRule[] carrierConfigAccessRules = UiccAccessRule.decodeRulesFromCarrierConfig(
-                certs);
-        if (carrierConfigAccessRules != null) {
-            mSubscriptionDatabaseManager.setCarrierConfigAccessRules(
-                    subId, carrierConfigAccessRules);
-        }
-
-        boolean isOpportunistic = config.getBoolean(
-                CarrierConfigManager.KEY_IS_OPPORTUNISTIC_SUBSCRIPTION_BOOL,
-                subInfo.isOpportunistic());
-        mSubscriptionDatabaseManager.setOpportunistic(subId, isOpportunistic);
-
-        String groupUuidString = config.getString(
-                CarrierConfigManager.KEY_SUBSCRIPTION_GROUP_UUID_STRING, "");
-        String oldGroupUuidString = subInfo.getGroupUuid();
-        if (!TextUtils.isEmpty(groupUuidString)) {
-            try {
-                // Update via a UUID Structure to ensure consistent formatting
-                groupUuid = ParcelUuid.fromString(groupUuidString);
-                if (groupUuidString.equals(CarrierConfigManager.REMOVE_GROUP_UUID_STRING)) {
-                    // Remove the group UUID.
-                    mSubscriptionDatabaseManager.setGroupUuid(subId, "");
-                } else if (canPackageManageGroup(groupUuid, configPackageName)) {
-                    mSubscriptionDatabaseManager.setGroupUuid(subId, groupUuidString);
-                    mSubscriptionDatabaseManager.setGroupOwner(subId, configPackageName);
-                    log("updateSubscriptionByCarrierConfig: Group added for sub " + subId);
-                } else {
-                    loge("updateSubscriptionByCarrierConfig: configPackageName "
-                            + configPackageName + " doesn't own groupUuid " + groupUuid);
-                }
-
-                if (!groupUuidString.equals(oldGroupUuidString)) {
-                    MultiSimSettingController.getInstance()
-                            .notifySubscriptionGroupChanged(groupUuid);
-                }
-            } catch (IllegalArgumentException e) {
-                loge("updateSubscriptionByCarrierConfig: Invalid Group UUID="
-                        + groupUuidString);
-            }
-        }
-
-        final int preferredUsageSetting = config.getInt(
-                CarrierConfigManager.KEY_CELLULAR_USAGE_SETTING_INT,
-                SubscriptionManager.USAGE_SETTING_UNKNOWN);
-
-        int newUsageSetting = calculateUsageSetting(
-                subInfo.getUsageSetting(), preferredUsageSetting);
-
-        if (newUsageSetting != subInfo.getUsageSetting()) {
-            mSubscriptionDatabaseManager.setUsageSetting(subId, newUsageSetting);
-            log("updateSubscriptionByCarrierConfig: UsageSetting changed,"
-                    + " oldSetting=" + SubscriptionManager.usageSettingToString(
-                            subInfo.getUsageSetting())
-                    + " preferredSetting=" + SubscriptionManager.usageSettingToString(
-                            preferredUsageSetting)
-                    + " newSetting=" + SubscriptionManager.usageSettingToString(newUsageSetting));
-        }
     }
 
     /**
@@ -1341,20 +1044,26 @@
                     + "carrier privilege");
         }
 
-        return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
-                // callers have READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE can get a full
-                // list. Carrier apps can only get the subscriptions they have privileged.
-                .filter(subInfo -> TelephonyPermissions.checkCallingOrSelfReadPhoneStateNoThrow(
-                        mContext, subInfo.getSubscriptionId(), callingPackage, callingFeatureId,
-                        "getAllSubInfoList"))
-                // Remove the identifier if the caller does not have sufficient permission.
-                // carrier apps will get full subscription info on the subscriptions associated
-                // to them.
-                .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
-                        callingPackage, callingFeatureId, "getAllSubInfoList"))
-                .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
-                        .thenComparing(SubscriptionInfo::getSubscriptionId))
-                .collect(Collectors.toList());
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
+                    // callers have READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE can get a full
+                    // list. Carrier apps can only get the subscriptions they have privileged.
+                    .filter(subInfo -> TelephonyPermissions.checkCallingOrSelfReadPhoneStateNoThrow(
+                            mContext, subInfo.getSubscriptionId(), callingPackage, callingFeatureId,
+                            "getAllSubInfoList"))
+                    // Remove the identifier if the caller does not have sufficient permission.
+                    // carrier apps will get full subscription info on the subscriptions associated
+                    // to them.
+                    .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
+                            callingPackage, callingFeatureId, "getAllSubInfoList"))
+                    .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
+                            .thenComparing(SubscriptionInfo::getSubscriptionId))
+                    .collect(Collectors.toList());
+
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
     }
 
     /**
@@ -1517,16 +1226,22 @@
                     + "carrier privilege");
         }
 
-        return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
-                .filter(SubscriptionInfoInternal::isActive)
-                // Remove the identifier if the caller does not have sufficient permission.
-                // carrier apps will get full subscription info on the subscriptions associated
-                // to them.
-                .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
-                        callingPackage, callingFeatureId, "getAllSubInfoList"))
-                .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
-                        .thenComparing(SubscriptionInfo::getSubscriptionId))
-                .collect(Collectors.toList());
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
+                    .filter(SubscriptionInfoInternal::isActive)
+                    // Remove the identifier if the caller does not have sufficient permission.
+                    // carrier apps will get full subscription info on the subscriptions associated
+                    // to them.
+                    .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
+                            callingPackage, callingFeatureId, "getAllSubInfoList"))
+                    .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
+                            .thenComparing(SubscriptionInfo::getSubscriptionId))
+                    .collect(Collectors.toList());
+
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
     }
 
     /**
@@ -1570,7 +1285,7 @@
      */
     @Override
     public int getActiveSubInfoCountMax() {
-        return mTelephonyManager.getActiveModemCount();
+        return mTelephonyManager.getSimCount();
     }
 
     /**
@@ -2142,21 +1857,26 @@
                     + "carrier privilege");
         }
 
-        return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
-                // callers have READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE can get a full
-                // list. Carrier apps can only get the subscriptions they have privileged.
-                .filter(subInfo -> subInfo.isOpportunistic()
-                        && TelephonyPermissions.checkCallingOrSelfReadPhoneStateNoThrow(
-                        mContext, subInfo.getSubscriptionId(), callingPackage,
-                        callingFeatureId, "getOpportunisticSubscriptions"))
-                // Remove the identifier if the caller does not have sufficient permission.
-                // carrier apps will get full subscription info on the subscriptions associated
-                // to them.
-                .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
-                        callingPackage, callingFeatureId, "getOpportunisticSubscriptions"))
-                .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
-                        .thenComparing(SubscriptionInfo::getSubscriptionId))
-                .collect(Collectors.toList());
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
+                    // callers have READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE can get a full
+                    // list. Carrier apps can only get the subscriptions they have privileged.
+                    .filter(subInfo -> subInfo.isOpportunistic()
+                            && TelephonyPermissions.checkCallingOrSelfReadPhoneStateNoThrow(
+                                    mContext, subInfo.getSubscriptionId(), callingPackage,
+                            callingFeatureId, "getOpportunisticSubscriptions"))
+                    // Remove the identifier if the caller does not have sufficient permission.
+                    // carrier apps will get full subscription info on the subscriptions associated
+                    // to them.
+                    .map(subInfo -> conditionallyRemoveIdentifiers(subInfo.toSubscriptionInfo(),
+                            callingPackage, callingFeatureId, "getOpportunisticSubscriptions"))
+                    .sorted(Comparator.comparing(SubscriptionInfo::getSimSlotIndex)
+                            .thenComparing(SubscriptionInfo::getSubscriptionId))
+                    .collect(Collectors.toList());
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
     }
 
     /**
@@ -2412,32 +2132,6 @@
     }
 
     /**
-     * Update default voice, sms, and data sub id.
-     */
-    private void updateDefaultSubIds() {
-        if (getActiveSubInfoCountMax() == 0) {
-            mDefaultVoiceSubId.set(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
-            mDefaultSmsSubId.set(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
-            mDefaultDataSubId.set(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
-        }
-        if (getActiveSubInfoCountMax() == 1) {
-            int[] activeSubIds = getActiveSubIdList(false);
-            if (activeSubIds.length == 1) {
-                mDefaultVoiceSubId.set(activeSubIds[0]);
-                mDefaultSmsSubId.set(activeSubIds[0]);
-                mDefaultDataSubId.set(activeSubIds[0]);
-            } else {
-                loge("updateDefaultSubIds: Single SIM device, but active subs are more than one."
-                        + " activeSubIds=" + Arrays.toString(activeSubIds));
-            }
-        } else {
-            // TODO: Support dual sim
-        }
-
-        updateDefaultSubId();
-    }
-
-    /**
      * Update default sub id.
      */
     private void updateDefaultSubId() {
@@ -2657,12 +2351,9 @@
 
         final long token = Binder.clearCallingIdentity();
         try {
-            return mSlotIndexToSubId.values().stream()
-                    .filter(subId -> {
-                        SubscriptionInfoInternal subInfo = mSubscriptionDatabaseManager
-                                .getSubscriptionInfoInternal(subId);
-                        return subInfo != null && (!visibleOnly || subInfo.isVisible()); })
-                    .mapToInt(x -> x)
+            return mSubscriptionDatabaseManager.getAllSubscriptions().stream()
+                    .filter(subInfo -> subInfo.isActive() && (!visibleOnly || subInfo.isVisible()))
+                    .mapToInt(SubscriptionInfoInternal::getSubscriptionId)
                     .toArray();
         } finally {
             Binder.restoreCallingIdentity(token);
@@ -2867,6 +2558,9 @@
     })
     public boolean isActiveSubId(int subId, @NonNull String callingPackage,
             @Nullable String callingFeatureId) {
+        // Verify that the callingPackage belongs to the calling UID
+        mAppOpsManager.checkPackage(Binder.getCallingUid(), callingPackage);
+
         if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(mContext, subId, callingPackage,
                 callingFeatureId, "isActiveSubId")) {
             throw new SecurityException("Need READ_PHONE_STATE, READ_PRIVILEGED_PHONE_STATE, or "
@@ -3495,6 +3189,68 @@
     }
 
     /**
+     * Called when SIM state changed to absent.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimAbsent(int slotIndex) {
+        if (mSlotIndexToSubId.containsKey(slotIndex)) {
+            // Re-enable the SIM when it's removed, so it will be in enabled state when it gets
+            // re-inserted again. (pre-U behavior)
+            mSubscriptionDatabaseManager.setUiccApplicationsEnabled(
+                    mSlotIndexToSubId.get(slotIndex), true);
+            // When sim is absent, set the port index to invalid port index. (pre-U behavior)
+            mSubscriptionDatabaseManager.setPortIndex(mSlotIndexToSubId.get(slotIndex),
+                    TelephonyManager.INVALID_PORT_INDEX);
+        }
+        updateSubscriptions(slotIndex);
+    }
+
+    /**
+     * Called when SIM state changed to locked.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimLocked(int slotIndex) {
+
+    }
+
+    /**
+     * Called when SIM state changed to ready.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimReady(int slotIndex) {
+
+    }
+
+    /**
+     * Called when SIM state changed to not ready.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimNotReady(int slotIndex) {
+
+    }
+
+    /**
+     * Called when SIM encounters error.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimError(int slotIndex) {
+
+    }
+
+    /**
+     * Called when SIM state changed to loaded.
+     *
+     * @param slotIndex The logical SIM slot index.
+     */
+    private void onSimLoaded(int slotIndex) {
+    }
+
+    /**
      * Called when eSIM becomes inactive.
      *
      * @param slotIndex The logical SIM slot index.
@@ -3525,24 +3281,34 @@
             @Nullable @CallbackExecutor Executor executor,
             @Nullable Runnable updateCompleteCallback) {
         mHandler.post(() -> {
-            mSimState[slotIndex] = simState;
             switch (simState) {
                 case TelephonyManager.SIM_STATE_ABSENT:
+                    onSimAbsent(slotIndex);
+                    break;
                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                 case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                 case TelephonyManager.SIM_STATE_PERM_DISABLED:
+                    onSimLocked(slotIndex);
+                    break;
                 case TelephonyManager.SIM_STATE_READY:
-                case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
-                case TelephonyManager.SIM_STATE_LOADED:
+                    onSimReady(slotIndex);
+                    break;
                 case TelephonyManager.SIM_STATE_NOT_READY:
-                    updateSubscriptions(slotIndex);
+                    onSimNotReady(slotIndex);
+                    break;
+                case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
+                    onSimError(slotIndex);
                     break;
                 case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
-                default:
                     // No specific things needed to be done. Just return and broadcast the SIM
                     // states.
                     break;
+                case TelephonyManager.SIM_STATE_LOADED:
+                    onSimLoaded(slotIndex);
+                    break;
+                default:
+                    break;
             }
             if (executor != null && updateCompleteCallback != null) {
                 executor.execute(updateCompleteCallback);
diff --git a/src/java/com/android/internal/telephony/uicc/UiccController.java b/src/java/com/android/internal/telephony/uicc/UiccController.java
index f88aa7d..1ad7ee3 100644
--- a/src/java/com/android/internal/telephony/uicc/UiccController.java
+++ b/src/java/com/android/internal/telephony/uicc/UiccController.java
@@ -40,6 +40,7 @@
 import android.sysprop.TelephonyProperties;
 import android.telephony.AnomalyReporter;
 import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
 import android.telephony.TelephonyManager.SimState;
@@ -950,6 +951,31 @@
     }
 
     /**
+     * Check if the SIM application is enabled on the card or not.
+     *
+     * @param phoneId The phone id.
+     * @return {@code true} if the application is enabled.
+     */
+    private boolean areUiccAppsEnabledOnCard(int phoneId) {
+        // When uicc apps are disabled(supported in IRadio 1.5), we will still get IccId from
+        // cardStatus (since IRadio 1.2). Amd upon cardStatus change we'll receive another
+        // handleSimNotReady so this will be evaluated again.
+        UiccSlot slot = getUiccSlotForPhone(phoneId);
+        if (slot == null) return false;
+        UiccPort port = getUiccPort(phoneId);
+        String iccId = (port == null) ? null : port.getIccId();
+        if (iccId == null) {
+            return false;
+        }
+        SubscriptionInfo info = SubscriptionManagerService.getInstance()
+                .getAllSubInfoList(mContext.getOpPackageName(), mContext.getAttributionTag())
+                .stream().filter(subInfo -> subInfo.getIccId().equals(
+                        IccUtils.stripTrailingFs(iccId)))
+                .findFirst().orElse(null);
+        return info != null && info.areUiccApplicationsEnabled();
+    }
+
+    /**
      * Update the SIM state.
      *
      * @param phoneId Phone id.
@@ -985,8 +1011,7 @@
 
                         if (simState == TelephonyManager.SIM_STATE_NOT_READY
                                 && (uiccProfile != null && !uiccProfile.isEmptyProfile())
-                                && SubscriptionManagerService.getInstance()
-                                .areUiccAppsEnabledOnCard(phoneId)) {
+                                && areUiccAppsEnabledOnCard(phoneId)) {
                             // STATE_NOT_READY is not a final state for when both
                             // 1) It's not an empty profile, and
                             // 2) Its uicc applications are set to enabled.
diff --git a/src/java/com/android/internal/telephony/uicc/UiccProfile.java b/src/java/com/android/internal/telephony/uicc/UiccProfile.java
index 11f6738..d9ff3f1 100644
--- a/src/java/com/android/internal/telephony/uicc/UiccProfile.java
+++ b/src/java/com/android/internal/telephony/uicc/UiccProfile.java
@@ -527,15 +527,8 @@
 
     private void updateCarrierNameForSubscription(int subId, int nameSource) {
         /* update display name with carrier override */
-        SubscriptionInfo subInfo;
-
-        if (PhoneFactory.isSubscriptionManagerServiceEnabled()) {
-            subInfo = SubscriptionManagerService.getInstance().getActiveSubscriptionInfo(subId,
-                    mContext.getOpPackageName(), mContext.getAttributionTag());
-        } else {
-            subInfo = SubscriptionController.getInstance().getActiveSubscriptionInfo(
-                    subId, mContext.getOpPackageName(), mContext.getAttributionTag());
-        }
+        SubscriptionInfo subInfo = SubscriptionController.getInstance().getActiveSubscriptionInfo(
+                subId, mContext.getOpPackageName(), mContext.getAttributionTag());
 
         if (subInfo == null) {
             return;
diff --git a/tests/telephonytests/src/com/android/internal/telephony/subscription/SubscriptionManagerServiceTest.java b/tests/telephonytests/src/com/android/internal/telephony/subscription/SubscriptionManagerServiceTest.java
index ebd4ad2..51dea36 100644
--- a/tests/telephonytests/src/com/android/internal/telephony/subscription/SubscriptionManagerServiceTest.java
+++ b/tests/telephonytests/src/com/android/internal/telephony/subscription/SubscriptionManagerServiceTest.java
@@ -1557,13 +1557,24 @@
     }
 
     @Test
-    public void testGetNonAccessibleFields() throws Exception {
+    public void testGetNonAccessibleFields() {
         insertSubscription(FAKE_SUBSCRIPTION_INFO1);
-
-        Field field = SubscriptionManagerService.class.getDeclaredField(
-                "DIRECT_ACCESS_SUBSCRIPTION_COLUMNS");
-        field.setAccessible(true);
-        Set<String> accessibleColumns = (Set<String>) field.get(null);
+        Set<String> accessibleColumns = Set.of(
+                SimInfo.COLUMN_ENHANCED_4G_MODE_ENABLED,
+                SimInfo.COLUMN_VT_IMS_ENABLED,
+                SimInfo.COLUMN_WFC_IMS_ENABLED,
+                SimInfo.COLUMN_WFC_IMS_MODE,
+                SimInfo.COLUMN_WFC_IMS_ROAMING_MODE,
+                SimInfo.COLUMN_WFC_IMS_ROAMING_ENABLED,
+                SimInfo.COLUMN_ENABLED_MOBILE_DATA_POLICIES,
+                SimInfo.COLUMN_IMS_RCS_UCE_ENABLED,
+                SimInfo.COLUMN_CROSS_SIM_CALLING_ENABLED,
+                SimInfo.COLUMN_RCS_CONFIG,
+                SimInfo.COLUMN_D2D_STATUS_SHARING,
+                SimInfo.COLUMN_VOIMS_OPT_IN_STATUS,
+                SimInfo.COLUMN_D2D_STATUS_SHARING_SELECTED_CONTACTS,
+                SimInfo.COLUMN_NR_ADVANCED_CALLING_ENABLED
+        );
 
         mContextFixture.addCallingOrSelfPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE);