1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.telephony.data;
18 
19 import android.annotation.CallbackExecutor;
20 import android.annotation.NonNull;
21 import android.annotation.StringDef;
22 import android.content.res.Resources;
23 import android.net.LinkProperties;
24 import android.net.NetworkCapabilities;
25 import android.os.Handler;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.os.PersistableBundle;
29 import android.provider.DeviceConfig;
30 import android.telephony.Annotation.ApnType;
31 import android.telephony.Annotation.NetCapability;
32 import android.telephony.Annotation.NetworkType;
33 import android.telephony.CarrierConfigManager;
34 import android.telephony.NetworkRegistrationInfo;
35 import android.telephony.ServiceState;
36 import android.telephony.SignalStrength;
37 import android.telephony.SubscriptionManager;
38 import android.telephony.TelephonyDisplayInfo;
39 import android.telephony.TelephonyManager;
40 import android.telephony.data.ApnSetting;
41 import android.text.TextUtils;
42 import android.util.ArraySet;
43 import android.util.IndentingPrintWriter;
44 
45 import com.android.internal.annotations.VisibleForTesting;
46 import com.android.internal.telephony.Phone;
47 import com.android.internal.telephony.data.DataNetworkController.HandoverRule;
48 import com.android.internal.telephony.data.DataRetryManager.DataHandoverRetryRule;
49 import com.android.internal.telephony.data.DataRetryManager.DataSetupRetryRule;
50 import com.android.internal.telephony.flags.FeatureFlags;
51 import com.android.telephony.Rlog;
52 
53 import java.io.FileDescriptor;
54 import java.io.PrintWriter;
55 import java.lang.annotation.Retention;
56 import java.lang.annotation.RetentionPolicy;
57 import java.util.ArrayList;
58 import java.util.Arrays;
59 import java.util.Collections;
60 import java.util.HashSet;
61 import java.util.List;
62 import java.util.Locale;
63 import java.util.Map;
64 import java.util.Set;
65 import java.util.concurrent.ConcurrentHashMap;
66 import java.util.concurrent.Executor;
67 import java.util.concurrent.TimeUnit;
68 import java.util.stream.Collectors;
69 
70 /**
71  * DataConfigManager is the source of all data related configuration from carrier config and
72  * resource overlay. DataConfigManager is created to reduce the excessive access to the
73  * {@link CarrierConfigManager}. All the data config will be loaded once and stored here.
74  */
75 public class DataConfigManager extends Handler {
76     /** The default timeout in ms for data network stuck in a transit state. */
77     private static final int DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS = 300000;
78 
79     /** Event for carrier config changed. */
80     private static final int EVENT_CARRIER_CONFIG_CHANGED = 1;
81 
82     /** Event for device config changed. */
83     private static final int EVENT_DEVICE_CONFIG_CHANGED = 2;
84 
85     /** Indicates the bandwidth estimation source is from the modem. */
86     private static final String BANDWIDTH_SOURCE_MODEM_STRING_VALUE = "modem";
87 
88     /** Indicates the bandwidth estimation source is from the static carrier config. */
89     private static final String BANDWIDTH_SOURCE_CARRIER_CONFIG_STRING_VALUE = "carrier_config";
90 
91     /** Indicates the bandwidth estimation source is from {@link LinkBandwidthEstimator}. */
92     private static final String BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR_STRING_VALUE =
93             "bandwidth_estimator";
94 
95     /** Default downlink and uplink bandwidth value in kbps. */
96     private static final int DEFAULT_BANDWIDTH = 14;
97 
98     /** Network type GPRS. Should not be used outside of DataConfigManager. */
99     private static final String DATA_CONFIG_NETWORK_TYPE_GPRS = "GPRS";
100 
101     /** Network type EDGE. Should not be used outside of DataConfigManager. */
102     private static final String DATA_CONFIG_NETWORK_TYPE_EDGE = "EDGE";
103 
104     /** Network type UMTS. Should not be used outside of DataConfigManager. */
105     private static final String DATA_CONFIG_NETWORK_TYPE_UMTS = "UMTS";
106 
107     /** Network type CDMA. Should not be used outside of DataConfigManager. */
108     private static final String DATA_CONFIG_NETWORK_TYPE_CDMA = "CDMA";
109 
110     /** Network type 1xRTT. Should not be used outside of DataConfigManager. */
111     private static final String DATA_CONFIG_NETWORK_TYPE_1xRTT = "1xRTT";
112 
113     /** Network type EvDo Rev 0. Should not be used outside of DataConfigManager. */
114     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_0 = "EvDo_0";
115 
116     /** Network type EvDo Rev A. Should not be used outside of DataConfigManager. */
117     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_A = "EvDo_A";
118 
119     /** Network type HSDPA. Should not be used outside of DataConfigManager. */
120     private static final String DATA_CONFIG_NETWORK_TYPE_HSDPA = "HSDPA";
121 
122     /** Network type HSUPA. Should not be used outside of DataConfigManager. */
123     private static final String DATA_CONFIG_NETWORK_TYPE_HSUPA = "HSUPA";
124 
125     /** Network type HSPA. Should not be used outside of DataConfigManager. */
126     private static final String DATA_CONFIG_NETWORK_TYPE_HSPA = "HSPA";
127 
128     /** Network type EvDo Rev B. Should not be used outside of DataConfigManager. */
129     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_B = "EvDo_B";
130 
131     /** Network type eHRPD. Should not be used outside of DataConfigManager. */
132     private static final String DATA_CONFIG_NETWORK_TYPE_EHRPD = "eHRPD";
133 
134     /** Network type iDEN. Should not be used outside of DataConfigManager. */
135     private static final String DATA_CONFIG_NETWORK_TYPE_IDEN = "iDEN";
136 
137     /** Network type LTE. Should not be used outside of DataConfigManager. */
138     private static final String DATA_CONFIG_NETWORK_TYPE_LTE = "LTE";
139 
140     /** Network type HSPA+. Should not be used outside of DataConfigManager. */
141     private static final String DATA_CONFIG_NETWORK_TYPE_HSPAP = "HSPA+";
142 
143     /** Network type GSM. Should not be used outside of DataConfigManager. */
144     private static final String DATA_CONFIG_NETWORK_TYPE_GSM = "GSM";
145 
146     /** Network type IWLAN. Should not be used outside of DataConfigManager. */
147     private static final String DATA_CONFIG_NETWORK_TYPE_IWLAN = "IWLAN";
148 
149     /** Network type TD_SCDMA. Should not be used outside of DataConfigManager. */
150     private static final String DATA_CONFIG_NETWORK_TYPE_TD_SCDMA = "TD_SCDMA";
151 
152     /** Network type LTE_CA. Should not be used outside of DataConfigManager. */
153     private static final String DATA_CONFIG_NETWORK_TYPE_LTE_CA = "LTE_CA";
154 
155     /** Network type NR_NSA. Should not be used outside of DataConfigManager. */
156     private static final String DATA_CONFIG_NETWORK_TYPE_NR_NSA = "NR_NSA";
157 
158     /** Network type NR_NSA_MMWAVE. Should not be used outside of DataConfigManager. */
159     private static final String DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE = "NR_NSA_MMWAVE";
160 
161     /** Network type NR_SA. Should not be used outside of DataConfigManager. */
162     private static final String DATA_CONFIG_NETWORK_TYPE_NR_SA = "NR_SA";
163 
164     /** Network type NR_SA_MMWAVE. Should not be used outside of DataConfigManager. */
165     private static final String DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE = "NR_SA_MMWAVE";
166 
167     /**
168      * The delay in milliseconds to re-evaluate existing data networks for bootstrap sim data usage
169      * limit.
170      */
171     private static final long REEVALUATE_BOOTSTRAP_SIM_DATA_USAGE_MILLIS =
172             TimeUnit.SECONDS.toMillis(60);
173 
174     @StringDef(prefix = {"DATA_CONFIG_NETWORK_TYPE_"}, value = {
175             DATA_CONFIG_NETWORK_TYPE_GPRS,
176             DATA_CONFIG_NETWORK_TYPE_EDGE,
177             DATA_CONFIG_NETWORK_TYPE_UMTS,
178             DATA_CONFIG_NETWORK_TYPE_CDMA,
179             DATA_CONFIG_NETWORK_TYPE_1xRTT,
180             DATA_CONFIG_NETWORK_TYPE_EVDO_0,
181             DATA_CONFIG_NETWORK_TYPE_EVDO_A,
182             DATA_CONFIG_NETWORK_TYPE_HSDPA,
183             DATA_CONFIG_NETWORK_TYPE_HSUPA,
184             DATA_CONFIG_NETWORK_TYPE_HSPA,
185             DATA_CONFIG_NETWORK_TYPE_EVDO_B,
186             DATA_CONFIG_NETWORK_TYPE_EHRPD,
187             DATA_CONFIG_NETWORK_TYPE_IDEN,
188             DATA_CONFIG_NETWORK_TYPE_LTE,
189             DATA_CONFIG_NETWORK_TYPE_HSPAP,
190             DATA_CONFIG_NETWORK_TYPE_GSM,
191             DATA_CONFIG_NETWORK_TYPE_IWLAN,
192             DATA_CONFIG_NETWORK_TYPE_TD_SCDMA,
193             DATA_CONFIG_NETWORK_TYPE_LTE_CA,
194             DATA_CONFIG_NETWORK_TYPE_NR_NSA,
195             DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE,
196             DATA_CONFIG_NETWORK_TYPE_NR_SA,
197             DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE,
198     })
199     @Retention(RetentionPolicy.SOURCE)
200     private @interface DataConfigNetworkType {}
201 
202     /** Data config update callbacks. */
203     @NonNull
204     private final Set<DataConfigManagerCallback> mDataConfigManagerCallbacks = new ArraySet<>();
205 
206     /** DeviceConfig key of anomaly report threshold for back to back ims release-request. */
207     private static final String KEY_ANOMALY_IMS_RELEASE_REQUEST = "anomaly_ims_release_request";
208     /** DeviceConfig key of anomaly report threshold for frequent setup data failure. */
209     private static final String KEY_ANOMALY_SETUP_DATA_CALL_FAILURE =
210             "anomaly_setup_data_call_failure";
211     /** DeviceConfig key of anomaly report threshold for frequent network-unwanted call. */
212     private static final String KEY_ANOMALY_NETWORK_UNWANTED = "anomaly_network_unwanted";
213     /** DeviceConfig key of anomaly report threshold for invalid QNS params. */
214     private static final String KEY_ANOMALY_QNS_PARAM = "anomaly_qns_param";
215     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in connecting state. */
216     private static final String KEY_ANOMALY_NETWORK_CONNECTING_TIMEOUT =
217             "anomaly_network_connecting_timeout";
218     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in disconnecting state.*/
219     private static final String KEY_ANOMALY_NETWORK_DISCONNECTING_TIMEOUT =
220             "anomaly_network_disconnecting_timeout";
221     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in handover state. */
222     private static final String KEY_ANOMALY_NETWORK_HANDOVER_TIMEOUT =
223             "anomaly_network_handover_timeout";
224     /** DeviceConfig key of anomaly report: True for enabling APN config invalidity detection */
225     private static final String KEY_ANOMALY_APN_CONFIG_ENABLED = "anomaly_apn_config_enabled";
226     /** Placeholder indicating missing Auto data switch score config, meaning out of service. */
227     private static final int OUT_OF_SERVICE_AUTO_DATA_SWITCH_SCORE = 0;
228     /** Anomaly report thresholds for frequent setup data call failure. */
229     private EventFrequency mSetupDataCallAnomalyReportThreshold;
230 
231     /** Anomaly report thresholds for back to back release-request of IMS. */
232     private EventFrequency mImsReleaseRequestAnomalyReportThreshold;
233 
234     /**
235      * Anomaly report thresholds for frequent network unwanted call
236      * at {@link TelephonyNetworkAgent#onNetworkUnwanted}
237      */
238     private EventFrequency mNetworkUnwantedAnomalyReportThreshold;
239 
240     /**
241      * {@code true} if enabled anomaly detection for param when QNS wants to change preferred
242      * network at {@link AccessNetworksManager}.
243      */
244     private boolean mIsInvalidQnsParamAnomalyReportEnabled;
245 
246     /**
247      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
248      * {@link DataNetwork.ConnectingState}.
249      */
250     private int mNetworkConnectingTimeout;
251 
252     /**
253      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
254      * {@link DataNetwork.DisconnectingState}.
255      */
256     private int mNetworkDisconnectingTimeout;
257 
258     /**
259      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
260      * {@link DataNetwork.HandoverState}.
261      */
262     private int mNetworkHandoverTimeout;
263 
264     /**
265      * True if enabled anomaly detection for APN config that's read from {@link DataProfileManager}
266      */
267     private boolean mIsApnConfigAnomalyReportEnabled;
268 
269     @NonNull
270     private final Phone mPhone;
271     @NonNull
272     private final String mLogTag;
273     @NonNull
274     private final FeatureFlags mFeatureFlags;
275     @NonNull
276     private final CarrierConfigManager mCarrierConfigManager;
277     @NonNull
278     private PersistableBundle mCarrierConfig = null;
279     @NonNull
280     private Resources mResources = null;
281 
282     /** The network capability priority map */
283     @NonNull
284     private final Map<Integer, Integer> mNetworkCapabilityPriorityMap = new ConcurrentHashMap<>();
285     /** The data setup retry rules */
286     @NonNull
287     private final List<DataSetupRetryRule> mDataSetupRetryRules = new ArrayList<>();
288     /** The data handover retry rules */
289     @NonNull
290     private final List<DataHandoverRetryRule> mDataHandoverRetryRules = new ArrayList<>();
291     /** The metered APN types for home network */
292     @NonNull
293     @ApnType
294     private final Set<Integer> mMeteredApnTypes = new HashSet<>();
295     /** The metered APN types for roaming network */
296     @NonNull
297     @ApnType
298     private final Set<Integer> mRoamingMeteredApnTypes = new HashSet<>();
299     /** The network types that only support single data networks */
300     @NonNull
301     @NetworkType
302     private final List<Integer> mSingleDataNetworkTypeList = new ArrayList<>();
303     @NonNull
304     @NetCapability
305     private final Set<Integer> mCapabilitiesExemptFromSingleDataList = new HashSet<>();
306     /** The network types that support temporarily not metered */
307     @NonNull
308     @DataConfigNetworkType
309     private final Set<String> mUnmeteredNetworkTypes = new HashSet<>();
310     /** The network types that support temporarily not metered when roaming */
311     @NonNull
312     @DataConfigNetworkType
313     private final Set<String> mRoamingUnmeteredNetworkTypes = new HashSet<>();
314     /** A map of network types to the downlink and uplink bandwidth values for that network type */
315     @NonNull
316     @DataConfigNetworkType
317     private final Map<String, DataNetwork.NetworkBandwidth> mBandwidthMap =
318             new ConcurrentHashMap<>();
319     /** A map of network types to the TCP buffer sizes for that network type */
320     @NonNull
321     @DataConfigNetworkType
322     private final Map<String, String> mTcpBufferSizeMap = new ConcurrentHashMap<>();
323     /** Rules for handover between IWLAN and cellular network. */
324     @NonNull
325     private final List<HandoverRule> mHandoverRuleList = new ArrayList<>();
326     /** {@code True} keep IMS network in case of moving to non VOPS area; {@code false} otherwise.*/
327     private boolean mShouldKeepNetworkUpInNonVops = false;
328     /** The set of network types that enable VOPS even in non VOPS area. */
329     @NonNull
330     @CarrierConfigManager.Ims.NetworkType
331     private final List<Integer> mEnabledVopsNetworkTypesInNonVops = new ArrayList<>();
332     /**
333      * A map of network types to the estimated downlink values by signal strength 0 - 4 for that
334      * network type
335      */
336     @NonNull
337     @DataConfigNetworkType
338     private final Map<String, int[]> mAutoDataSwitchNetworkTypeSignalMap =
339             new ConcurrentHashMap<>();
340 
341     /**
342      * Constructor
343      *
344      * @param phone The phone instance.
345      * @param looper The looper to be used by the handler. Currently the handler thread is the
346      * phone process's main thread.
347      */
DataConfigManager(@onNull Phone phone, @NonNull Looper looper, @NonNull FeatureFlags featureFlags)348     public DataConfigManager(@NonNull Phone phone, @NonNull Looper looper,
349             @NonNull FeatureFlags featureFlags) {
350         super(looper);
351         mPhone = phone;
352         mFeatureFlags = featureFlags;
353         mLogTag = "DCM-" + mPhone.getPhoneId();
354         log("DataConfigManager created.");
355 
356         mCarrierConfigManager = mPhone.getContext().getSystemService(CarrierConfigManager.class);
357         // Callback send msg to handler thread, so callback itself can be executed in binder thread.
358         mCarrierConfigManager.registerCarrierConfigChangeListener(Runnable::run,
359                 (slotIndex, subId, carrierId, specificCarrierId) -> {
360                     if (slotIndex == mPhone.getPhoneId()) {
361                         sendEmptyMessage(EVENT_CARRIER_CONFIG_CHANGED);
362                     }
363                 });
364 
365         // Register for device config update
366         DeviceConfig.addOnPropertiesChangedListener(
367                 DeviceConfig.NAMESPACE_TELEPHONY, Runnable::run,
368                 properties -> {
369                     if (TextUtils.equals(DeviceConfig.NAMESPACE_TELEPHONY,
370                             properties.getNamespace())) {
371                         sendEmptyMessage(EVENT_DEVICE_CONFIG_CHANGED);
372                     }
373                 });
374 
375         // Must be called to set mCarrierConfig and mResources to non-null values
376         updateCarrierConfig();
377         // Must be called to set anomaly report threshold to non-null values
378         updateDeviceConfig();
379     }
380 
381     /**
382      * The data config callback.
383      */
384     public static class DataConfigManagerCallback extends DataCallback {
385         /**
386          * Constructor
387          *
388          * @param executor The executor of the callback.
389          */
DataConfigManagerCallback(@onNull @allbackExecutor Executor executor)390         public DataConfigManagerCallback(@NonNull @CallbackExecutor Executor executor) {
391             super(executor);
392         }
393 
394         /** Callback on carrier config update.*/
onCarrierConfigChanged()395         public void onCarrierConfigChanged() {}
396 
397         /** Callback on device config update.*/
onDeviceConfigChanged()398         public void onDeviceConfigChanged() {}
399     }
400 
401     /**
402      * Register the callback for receiving information from {@link DataConfigManager}.
403      *
404      * @param callback The callback.
405      */
registerCallback(@onNull DataConfigManagerCallback callback)406     public void registerCallback(@NonNull DataConfigManagerCallback callback) {
407         mDataConfigManagerCallbacks.add(callback);
408     }
409 
410     /**
411      * Unregister the callback.
412      *
413      * @param callback The previously registered callback.
414      */
unregisterCallback(@onNull DataConfigManagerCallback callback)415     public void unregisterCallback(@NonNull DataConfigManagerCallback callback) {
416         mDataConfigManagerCallbacks.remove(callback);
417     }
418 
419     @Override
handleMessage(Message msg)420     public void handleMessage(Message msg) {
421         switch (msg.what) {
422             case EVENT_CARRIER_CONFIG_CHANGED:
423                 log("EVENT_CARRIER_CONFIG_CHANGED");
424                 updateCarrierConfig();
425                 mDataConfigManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
426                         callback::onCarrierConfigChanged));
427                 break;
428             case EVENT_DEVICE_CONFIG_CHANGED:
429                 log("EVENT_DEVICE_CONFIG_CHANGED");
430                 updateDeviceConfig();
431                 mDataConfigManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
432                         callback::onDeviceConfigChanged));
433                 break;
434             default:
435                 loge("Unexpected message " + msg.what);
436         }
437     }
438 
439     /** Update local properties from {@link DeviceConfig} */
updateDeviceConfig()440     private void updateDeviceConfig() {
441         DeviceConfig.Properties properties = //read all telephony properties
442                 DeviceConfig.getProperties(DeviceConfig.NAMESPACE_TELEPHONY);
443 
444         mImsReleaseRequestAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
445                 properties.getString(KEY_ANOMALY_IMS_RELEASE_REQUEST, null), 0, 2);
446         mNetworkUnwantedAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
447                 properties.getString(KEY_ANOMALY_NETWORK_UNWANTED, null), 0, 12);
448         mSetupDataCallAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
449                 properties.getString(KEY_ANOMALY_SETUP_DATA_CALL_FAILURE, null), 0, 12);
450         mIsInvalidQnsParamAnomalyReportEnabled = properties.getBoolean(
451                 KEY_ANOMALY_QNS_PARAM, false);
452         mNetworkConnectingTimeout = properties.getInt(
453                 KEY_ANOMALY_NETWORK_CONNECTING_TIMEOUT, DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
454         mNetworkDisconnectingTimeout = properties.getInt(
455                 KEY_ANOMALY_NETWORK_DISCONNECTING_TIMEOUT,
456                 DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
457         mNetworkHandoverTimeout = properties.getInt(
458                 KEY_ANOMALY_NETWORK_HANDOVER_TIMEOUT, DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
459         mIsApnConfigAnomalyReportEnabled = properties.getBoolean(
460                 KEY_ANOMALY_APN_CONFIG_ENABLED, false);
461     }
462 
463     /**
464      * @return {@code true} if the configuration is carrier specific. {@code false} if the
465      * configuration is the default (i.e. SIM not inserted).
466      */
isConfigCarrierSpecific()467     public boolean isConfigCarrierSpecific() {
468         return mCarrierConfig.getBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL);
469     }
470 
471     /**
472      * Update the configuration from carrier configs and resources.
473      */
updateCarrierConfig()474     private void updateCarrierConfig() {
475         if (mCarrierConfigManager != null) {
476             mCarrierConfig = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId());
477         }
478         if (mCarrierConfig == null) {
479             mCarrierConfig = CarrierConfigManager.getDefaultConfig();
480         }
481         mResources = SubscriptionManager.getResourcesForSubId(mPhone.getContext(),
482                 mPhone.getSubId());
483 
484         updateNetworkCapabilityPriority();
485         updateDataRetryRules();
486         updateMeteredApnTypes();
487         updateSingleDataNetworkTypeAndCapabilityExemption();
488         updateVopsConfig();
489         updateUnmeteredNetworkTypes();
490         updateBandwidths();
491         updateTcpBuffers();
492         updateHandoverRules();
493         updateAutoDataSwitchConfig();
494 
495         log("Carrier config updated. Config is " + (isConfigCarrierSpecific() ? "" : "not ")
496                 + "carrier specific.");
497     }
498 
499     /**
500      * Update the network capability priority from carrier config.
501      */
updateNetworkCapabilityPriority()502     private void updateNetworkCapabilityPriority() {
503         synchronized (this) {
504             mNetworkCapabilityPriorityMap.clear();
505             String[] capabilityPriorityStrings = mCarrierConfig.getStringArray(
506                     CarrierConfigManager.KEY_TELEPHONY_NETWORK_CAPABILITY_PRIORITIES_STRING_ARRAY);
507             if (capabilityPriorityStrings != null) {
508                 for (String capabilityPriorityString : capabilityPriorityStrings) {
509                     capabilityPriorityString =
510                             capabilityPriorityString.trim().toUpperCase(Locale.ROOT);
511                     String[] tokens = capabilityPriorityString.split(":");
512                     if (tokens.length != 2) {
513                         loge("Invalid config \"" + capabilityPriorityString + "\"");
514                         continue;
515                     }
516 
517                     int netCap = DataUtils.getNetworkCapabilityFromString(tokens[0]);
518                     if (netCap < 0) {
519                         loge("Invalid config \"" + capabilityPriorityString + "\"");
520                         continue;
521                     }
522 
523                     int priority = Integer.parseInt(tokens[1]);
524                     mNetworkCapabilityPriorityMap.put(netCap, priority);
525                 }
526             }
527         }
528     }
529 
530     /**
531      * Get the priority of a network capability.
532      *
533      * @param capability The network capability
534      * @return The priority range from 0 ~ 100. 100 is the highest priority.
535      */
getNetworkCapabilityPriority(@etCapability int capability)536     public int getNetworkCapabilityPriority(@NetCapability int capability) {
537         if (mNetworkCapabilityPriorityMap.containsKey(capability)) {
538             return mNetworkCapabilityPriorityMap.get(capability);
539         }
540         return 0;
541     }
542 
543     /**
544      * Update the data retry rules from the carrier config.
545      */
updateDataRetryRules()546     private void updateDataRetryRules() {
547         synchronized (this) {
548             mDataSetupRetryRules.clear();
549             String[] dataRetryRulesStrings = mCarrierConfig.getStringArray(
550                     CarrierConfigManager.KEY_TELEPHONY_DATA_SETUP_RETRY_RULES_STRING_ARRAY);
551             if (dataRetryRulesStrings != null) {
552                 for (String ruleString : dataRetryRulesStrings) {
553                     try {
554                         mDataSetupRetryRules.add(new DataSetupRetryRule(ruleString));
555                     } catch (IllegalArgumentException e) {
556                         loge("updateDataRetryRules: " + e.getMessage());
557                     }
558                 }
559             }
560 
561             mDataHandoverRetryRules.clear();
562             dataRetryRulesStrings = mCarrierConfig.getStringArray(
563                     CarrierConfigManager.KEY_TELEPHONY_DATA_HANDOVER_RETRY_RULES_STRING_ARRAY);
564             if (dataRetryRulesStrings != null) {
565                 for (String ruleString : dataRetryRulesStrings) {
566                     try {
567                         mDataHandoverRetryRules.add(new DataHandoverRetryRule(ruleString));
568                     } catch (IllegalArgumentException e) {
569                         loge("updateDataRetryRules: " + e.getMessage());
570                     }
571                 }
572             }
573         }
574     }
575 
576     /**
577      * @return The data setup retry rules from carrier config.
578      */
579     @NonNull
getDataSetupRetryRules()580     public List<DataSetupRetryRule> getDataSetupRetryRules() {
581         return Collections.unmodifiableList(mDataSetupRetryRules);
582     }
583 
584     /**
585      * @return The data handover retry rules from carrier config.
586      */
587     @NonNull
getDataHandoverRetryRules()588     public List<DataHandoverRetryRule> getDataHandoverRetryRules() {
589         return Collections.unmodifiableList(mDataHandoverRetryRules);
590     }
591 
592     /**
593      * @return Whether data roaming is enabled by default in carrier config.
594      */
isDataRoamingEnabledByDefault()595     public boolean isDataRoamingEnabledByDefault() {
596         return mCarrierConfig.getBoolean(
597                 CarrierConfigManager.KEY_CARRIER_DEFAULT_DATA_ROAMING_ENABLED_BOOL);
598     }
599 
600     /**
601      * Update the home and roaming metered APN types from the carrier config.
602      */
updateMeteredApnTypes()603     private void updateMeteredApnTypes() {
604         synchronized (this) {
605             mMeteredApnTypes.clear();
606             String[] meteredApnTypes = mCarrierConfig.getStringArray(
607                     CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS);
608             if (meteredApnTypes != null) {
609                 Arrays.stream(meteredApnTypes)
610                         .map(ApnSetting::getApnTypeInt)
611                         .forEach(mMeteredApnTypes::add);
612             }
613             mRoamingMeteredApnTypes.clear();
614             String[] roamingMeteredApns = mCarrierConfig.getStringArray(
615                     CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS);
616             if (roamingMeteredApns != null) {
617                 Arrays.stream(roamingMeteredApns)
618                         .map(ApnSetting::getApnTypeInt)
619                         .forEach(mRoamingMeteredApnTypes::add);
620             }
621         }
622     }
623 
624     /**
625      * Get the metered network capabilities.
626      *
627      * @param isRoaming {@code true} for roaming scenario.
628      *
629      * @return The metered network capabilities when connected to a home network.
630      */
631     @NonNull
632     @NetCapability
getMeteredNetworkCapabilities(boolean isRoaming)633     public Set<Integer> getMeteredNetworkCapabilities(boolean isRoaming) {
634         Set<Integer> meteredApnTypes = isRoaming ? mRoamingMeteredApnTypes : mMeteredApnTypes;
635         Set<Integer> meteredCapabilities = meteredApnTypes.stream()
636                 .map(DataUtils::apnTypeToNetworkCapability)
637                 .filter(cap -> cap >= 0)
638                 .collect(Collectors.toSet());
639 
640         // Consumer slices are the slices that are allowed to be accessed by regular application to
641         // get better performance. They should be metered. This can be turned into configurations in
642         // the future.
643         if (mFeatureFlags.meteredEmbbUrlcc()) {
644             meteredCapabilities.add(NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH);
645             meteredCapabilities.add(NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
646         }
647 
648         return Collections.unmodifiableSet(meteredCapabilities);
649     }
650 
651     /**
652      * @return {@code true} if tethering profile should not be used when the device is roaming.
653      */
isTetheringProfileDisabledForRoaming()654     public boolean isTetheringProfileDisabledForRoaming() {
655         return mCarrierConfig.getBoolean(
656                 CarrierConfigManager.KEY_DISABLE_DUN_APN_WHILE_ROAMING_WITH_PRESET_APN_BOOL);
657     }
658 
659     /**
660      * Check if the network capability metered.
661      *
662      * @param networkCapability The network capability.
663      * @param isRoaming {@code true} for roaming scenario.
664      * @return {@code true} if the network capability is metered.
665      */
isMeteredCapability(@etCapability int networkCapability, boolean isRoaming)666     public boolean isMeteredCapability(@NetCapability int networkCapability, boolean isRoaming) {
667         return getMeteredNetworkCapabilities(isRoaming).contains(networkCapability);
668     }
669 
670     /**
671      * Check if the network capabilities are metered. If one of the capabilities is metered, then
672      * the capabilities are metered.
673      *
674      * @param networkCapabilities The network capabilities.
675      * @param isRoaming {@code true} for roaming scenario.
676      * @return {@code true} if the capabilities are metered.
677      */
isAnyMeteredCapability(@onNull @etCapability int[] networkCapabilities, boolean isRoaming)678     public boolean isAnyMeteredCapability(@NonNull @NetCapability int[] networkCapabilities,
679             boolean isRoaming) {
680         return Arrays.stream(networkCapabilities).boxed()
681                 .anyMatch(cap -> isMeteredCapability(cap, isRoaming));
682     }
683 
684     /**
685      * @return Whether to use data activity for RRC detection
686      */
shouldUseDataActivityForRrcDetection()687     public boolean shouldUseDataActivityForRrcDetection() {
688         return mCarrierConfig.getBoolean(
689                 CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL);
690     }
691 
692     /**
693      * Update the network types for only single data networks from the carrier config.
694      */
updateSingleDataNetworkTypeAndCapabilityExemption()695     private void updateSingleDataNetworkTypeAndCapabilityExemption() {
696         synchronized (this) {
697             mSingleDataNetworkTypeList.clear();
698             mCapabilitiesExemptFromSingleDataList.clear();
699             int[] singleDataNetworkTypeList = mCarrierConfig.getIntArray(
700                     CarrierConfigManager.KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY);
701             if (singleDataNetworkTypeList != null) {
702                 Arrays.stream(singleDataNetworkTypeList).forEach(mSingleDataNetworkTypeList::add);
703             }
704 
705             int[] singleDataCapabilitiesExemptList = mCarrierConfig.getIntArray(
706                     CarrierConfigManager.KEY_CAPABILITIES_EXEMPT_FROM_SINGLE_DC_CHECK_INT_ARRAY);
707             if (singleDataCapabilitiesExemptList != null) {
708                 Arrays.stream(singleDataCapabilitiesExemptList)
709                         .forEach(mCapabilitiesExemptFromSingleDataList::add);
710             }
711         }
712     }
713 
714     /**
715      * Update the voice over PS related config from the carrier config.
716      */
updateVopsConfig()717     private synchronized void updateVopsConfig() {
718             mShouldKeepNetworkUpInNonVops = mCarrierConfig.getBoolean(CarrierConfigManager
719                     .Ims.KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL);
720             int[] allowedNetworkTypes = mCarrierConfig.getIntArray(
721                     CarrierConfigManager.Ims.KEY_IMS_PDN_ENABLED_IN_NO_VOPS_SUPPORT_INT_ARRAY);
722             if (allowedNetworkTypes != null) {
723                 Arrays.stream(allowedNetworkTypes).forEach(mEnabledVopsNetworkTypesInNonVops::add);
724             }
725     }
726 
727     /**
728      * @return The list of {@link NetworkType} that only supports single data networks
729      */
730     @NonNull
731     @NetworkType
getNetworkTypesOnlySupportSingleDataNetwork()732     public List<Integer> getNetworkTypesOnlySupportSingleDataNetwork() {
733         return Collections.unmodifiableList(mSingleDataNetworkTypeList);
734     }
735 
736     /**
737      * @return The list of {@link android.net.NetworkCapabilities.NetCapability} that every of which
738      * is exempt from the single PDN check.
739      */
740     @NonNull
741     @NetCapability
getCapabilitiesExemptFromSingleDataNetwork()742     public Set<Integer> getCapabilitiesExemptFromSingleDataNetwork() {
743         return Collections.unmodifiableSet(mCapabilitiesExemptFromSingleDataList);
744     }
745 
746     /**
747      * @param regState The modem reported data registration state.
748      * @return {@code true} if should keep IMS network in case of moving to non VOPS area.
749      */
shouldKeepNetworkUpInNonVops(@etworkRegistrationInfo.RegistrationState int regState)750     public boolean shouldKeepNetworkUpInNonVops(@NetworkRegistrationInfo.RegistrationState
751             int regState) {
752         return mShouldKeepNetworkUpInNonVops || allowBringUpNetworkInNonVops(regState);
753     }
754 
755     /**
756      * @param regState The modem reported data registration state.
757      * @return {@code true} if allow bring up IMS network in case of moving to non VOPS area.
758      */
allowBringUpNetworkInNonVops(@etworkRegistrationInfo.RegistrationState int regState)759     public boolean allowBringUpNetworkInNonVops(@NetworkRegistrationInfo.RegistrationState
760             int regState) {
761         if (!mFeatureFlags.allowMmtelInNonVops()) return false;
762         int networkType = -1;
763         if (regState == NetworkRegistrationInfo.REGISTRATION_STATE_HOME) {
764             networkType = CarrierConfigManager.Ims.NETWORK_TYPE_HOME;
765         } else if (regState == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING) {
766             networkType = CarrierConfigManager.Ims.NETWORK_TYPE_ROAMING;
767         }
768         return mEnabledVopsNetworkTypesInNonVops.contains(networkType);
769     }
770 
771     /** {@code True} requires ping test to pass on the target slot before switching to it.*/
isPingTestBeforeAutoDataSwitchRequired()772     public boolean isPingTestBeforeAutoDataSwitchRequired() {
773         return mResources.getBoolean(com.android.internal.R.bool
774                 .auto_data_switch_ping_test_before_switch);
775     }
776 
777     /**
778      * @return Whether {@link NetworkCapabilities#NET_CAPABILITY_TEMPORARILY_NOT_METERED}
779      * is supported by the carrier.
780      */
isTempNotMeteredSupportedByCarrier()781     public boolean isTempNotMeteredSupportedByCarrier() {
782         return mCarrierConfig.getBoolean(
783                 CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL);
784     }
785 
786     /**
787      * Update the network types that are temporarily not metered from the carrier config.
788      */
updateUnmeteredNetworkTypes()789     private void updateUnmeteredNetworkTypes() {
790         synchronized (this) {
791             mUnmeteredNetworkTypes.clear();
792             String[] unmeteredNetworkTypes = mCarrierConfig.getStringArray(
793                     CarrierConfigManager.KEY_UNMETERED_NETWORK_TYPES_STRING_ARRAY);
794             if (unmeteredNetworkTypes != null) {
795                 mUnmeteredNetworkTypes.addAll(Arrays.asList(unmeteredNetworkTypes));
796             }
797             mRoamingUnmeteredNetworkTypes.clear();
798             String[] roamingUnmeteredNetworkTypes = mCarrierConfig.getStringArray(
799                     CarrierConfigManager.KEY_ROAMING_UNMETERED_NETWORK_TYPES_STRING_ARRAY);
800             if (roamingUnmeteredNetworkTypes != null) {
801                 mRoamingUnmeteredNetworkTypes.addAll(Arrays.asList(roamingUnmeteredNetworkTypes));
802             }
803         }
804     }
805 
806     /**
807      * Get whether the network type is unmetered from the carrier configs.
808      *
809      * @param displayInfo The {@link TelephonyDisplayInfo} to check meteredness for.
810      * @param serviceState The {@link ServiceState}, used to determine roaming state.
811      * @return Whether the carrier considers the given display info unmetered.
812      */
isNetworkTypeUnmetered(@onNull TelephonyDisplayInfo displayInfo, @NonNull ServiceState serviceState)813     public boolean isNetworkTypeUnmetered(@NonNull TelephonyDisplayInfo displayInfo,
814             @NonNull ServiceState serviceState) {
815         String dataConfigNetworkType = getDataConfigNetworkType(displayInfo);
816         return serviceState.getDataRoaming()
817                 ? mRoamingUnmeteredNetworkTypes.contains(dataConfigNetworkType)
818                 : mUnmeteredNetworkTypes.contains(dataConfigNetworkType);
819     }
820 
821     /**
822      * Update the downlink and uplink bandwidth values from the carrier config.
823      */
updateBandwidths()824     private void updateBandwidths() {
825         synchronized (this) {
826             mBandwidthMap.clear();
827             String[] bandwidths = mCarrierConfig.getStringArray(
828                     CarrierConfigManager.KEY_BANDWIDTH_STRING_ARRAY);
829             boolean useLte = mCarrierConfig.getBoolean(CarrierConfigManager
830                     .KEY_BANDWIDTH_NR_NSA_USE_LTE_VALUE_FOR_UPLINK_BOOL);
831             if (bandwidths != null) {
832                 for (String bandwidth : bandwidths) {
833                     // split1[0] = network type as string
834                     // split1[1] = downlink,uplink
835                     String[] split1 = bandwidth.split(":");
836                     if (split1.length != 2) {
837                         loge("Invalid bandwidth: " + bandwidth);
838                         continue;
839                     }
840                     // split2[0] = downlink bandwidth in kbps
841                     // split2[1] = uplink bandwidth in kbps
842                     String[] split2 = split1[1].split(",");
843                     if (split2.length != 2) {
844                         loge("Invalid bandwidth values: " + Arrays.toString(split2));
845                         continue;
846                     }
847                     int downlink, uplink;
848                     try {
849                         downlink = Integer.parseInt(split2[0]);
850                         uplink = Integer.parseInt(split2[1]);
851                     } catch (NumberFormatException e) {
852                         loge("Exception parsing bandwidth values for network type " + split1[0]
853                                 + ": " + e);
854                         continue;
855                     }
856                     if (useLte && split1[0].startsWith("NR")) {
857                         // We can get it directly from mBandwidthMap because LTE is defined before
858                         // the NR values in CarrierConfigManager#KEY_BANDWIDTH_STRING_ARRAY.
859                         uplink = mBandwidthMap.get(DATA_CONFIG_NETWORK_TYPE_LTE)
860                                 .uplinkBandwidthKbps;
861                     }
862                     mBandwidthMap.put(split1[0],
863                             new DataNetwork.NetworkBandwidth(downlink, uplink));
864                 }
865             }
866         }
867     }
868 
869     /**
870      * Get the bandwidth estimate from the carrier config.
871      *
872      * @param displayInfo The {@link TelephonyDisplayInfo} to get the bandwidth for.
873      * @return The pre-configured bandwidth estimate from carrier config.
874      */
875     @NonNull
getBandwidthForNetworkType( @onNull TelephonyDisplayInfo displayInfo)876     public DataNetwork.NetworkBandwidth getBandwidthForNetworkType(
877             @NonNull TelephonyDisplayInfo displayInfo) {
878         DataNetwork.NetworkBandwidth bandwidth = mBandwidthMap.get(
879                 getDataConfigNetworkType(displayInfo));
880         if (bandwidth != null) {
881             return bandwidth;
882         }
883         return new DataNetwork.NetworkBandwidth(DEFAULT_BANDWIDTH, DEFAULT_BANDWIDTH);
884     }
885 
886     /**
887      * @return What kind of traffic is supported on an unrestricted satellite network.
888      */
889     @CarrierConfigManager.SATELLITE_DATA_SUPPORT_MODE
getSatelliteDataSupportMode()890     public int getSatelliteDataSupportMode() {
891         return mCarrierConfig.getInt(CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT);
892     }
893 
894     /**
895      * @return Whether data throttling should be reset when the TAC changes from the carrier config.
896      */
shouldResetDataThrottlingWhenTacChanges()897     public boolean shouldResetDataThrottlingWhenTacChanges() {
898         return mCarrierConfig.getBoolean(
899                 CarrierConfigManager.KEY_UNTHROTTLE_DATA_RETRY_WHEN_TAC_CHANGES_BOOL);
900     }
901 
902     /**
903      * @return The data service package override string from the carrier config.
904      */
getDataServicePackageName()905     public String getDataServicePackageName() {
906         return mCarrierConfig.getString(
907                 CarrierConfigManager.KEY_CARRIER_DATA_SERVICE_WWAN_PACKAGE_OVERRIDE_STRING);
908     }
909 
910     /**
911      * @return The default MTU value in bytes from the carrier config.
912      */
getDefaultMtu()913     public int getDefaultMtu() {
914         return mCarrierConfig.getInt(CarrierConfigManager.KEY_DEFAULT_MTU_INT);
915     }
916 
917     /**
918      * @return the data limit in bytes that can be used for esim bootstrap usage.
919      */
getEsimBootStrapMaxDataLimitBytes()920     public long getEsimBootStrapMaxDataLimitBytes() {
921         return mResources.getInteger(
922                 com.android.internal.R.integer.config_esim_bootstrap_data_limit_bytes);
923     }
924 
925     /**
926      * @return the interval in millisecond used to re-evaluate bootstrap sim data usage during esim
927      * bootstrap activation
928      */
getReevaluateBootstrapSimDataUsageMillis()929     public long getReevaluateBootstrapSimDataUsageMillis() {
930         long bootStrapSimDataUsageReevaluateInterval = mResources.getInteger(
931                 com.android.internal.R.integer.config_reevaluate_bootstrap_sim_data_usage_millis);
932 
933         if (bootStrapSimDataUsageReevaluateInterval <= 0) {
934             bootStrapSimDataUsageReevaluateInterval = REEVALUATE_BOOTSTRAP_SIM_DATA_USAGE_MILLIS;
935         }
936 
937         return bootStrapSimDataUsageReevaluateInterval;
938     }
939 
940     /**
941      * Update the TCP buffer sizes from the resource overlays.
942      */
updateTcpBuffers()943     private void updateTcpBuffers() {
944         synchronized (this) {
945             mTcpBufferSizeMap.clear();
946             String[] configs = mResources.getStringArray(
947                     com.android.internal.R.array.config_network_type_tcp_buffers);
948             if (configs != null) {
949                 for (String config : configs) {
950                     // split[0] = network type as string
951                     // split[1] = rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max
952                     String[] split = config.split(":");
953                     if (split.length != 2) {
954                         loge("Invalid TCP buffer sizes entry: " + config);
955                         continue;
956                     }
957                     if (split[1].split(",").length != 6) {
958                         loge("Invalid TCP buffer sizes for " + split[0] + ": " + split[1]);
959                         continue;
960                     }
961                     mTcpBufferSizeMap.put(split[0], split[1]);
962                 }
963             }
964         }
965     }
966 
967     /**
968      * Anomaly report thresholds for frequent setup data call failure.
969      * @return EventFrequency to trigger the anomaly report
970      */
971     @NonNull
getAnomalySetupDataCallThreshold()972     public EventFrequency getAnomalySetupDataCallThreshold() {
973         return mSetupDataCallAnomalyReportThreshold;
974     }
975 
976     /**
977      * Anomaly report thresholds for frequent network unwanted call
978      * at {@link TelephonyNetworkAgent#onNetworkUnwanted}
979      * @return EventFrequency to trigger the anomaly report
980      */
981     @NonNull
getAnomalyNetworkUnwantedThreshold()982     public EventFrequency getAnomalyNetworkUnwantedThreshold() {
983         return mNetworkUnwantedAnomalyReportThreshold;
984     }
985 
986     /**
987      * Anomaly report thresholds for back to back release-request of IMS.
988      * @return EventFrequency to trigger the anomaly report
989      */
990     @NonNull
getAnomalyImsReleaseRequestThreshold()991     public EventFrequency getAnomalyImsReleaseRequestThreshold() {
992         return mImsReleaseRequestAnomalyReportThreshold;
993     }
994 
995     /**
996      * @return {@code true} if enabled anomaly report for invalid param when QNS wants to change
997      * preferred network at {@link AccessNetworksManager}.
998      */
isInvalidQnsParamAnomalyReportEnabled()999     public boolean isInvalidQnsParamAnomalyReportEnabled() {
1000         return mIsInvalidQnsParamAnomalyReportEnabled;
1001     }
1002 
1003     /**
1004      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
1005      * {@link DataNetwork.ConnectingState}.
1006      */
getAnomalyNetworkConnectingTimeoutMs()1007     public int getAnomalyNetworkConnectingTimeoutMs() {
1008         return mNetworkConnectingTimeout;
1009     }
1010 
1011     /**
1012      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
1013      * {@link DataNetwork.DisconnectingState}.
1014      */
getAnomalyNetworkDisconnectingTimeoutMs()1015     public int getAnomalyNetworkDisconnectingTimeoutMs() {
1016         return mNetworkDisconnectingTimeout;
1017     }
1018 
1019     /**
1020      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
1021      * {@link DataNetwork.HandoverState}.
1022      */
getNetworkHandoverTimeoutMs()1023     public int getNetworkHandoverTimeoutMs() {
1024         return mNetworkHandoverTimeout;
1025     }
1026 
1027     /**
1028      * @return {@code true} if enabled anomaly report for invalid APN config
1029      * at {@link DataProfileManager}
1030      */
isApnConfigAnomalyReportEnabled()1031     public boolean isApnConfigAnomalyReportEnabled() {
1032         return mIsApnConfigAnomalyReportEnabled;
1033     }
1034 
1035     /**
1036      * Update the network type and signal strength score table for auto data switch decisions.
1037      */
updateAutoDataSwitchConfig()1038     private void updateAutoDataSwitchConfig() {
1039         synchronized (this) {
1040             mAutoDataSwitchNetworkTypeSignalMap.clear();
1041             final PersistableBundle table = mCarrierConfig.getPersistableBundle(
1042                     CarrierConfigManager.KEY_AUTO_DATA_SWITCH_RAT_SIGNAL_SCORE_BUNDLE);
1043             String[] networkTypeKeys = {
1044                     DATA_CONFIG_NETWORK_TYPE_GPRS,
1045                     DATA_CONFIG_NETWORK_TYPE_EDGE,
1046                     DATA_CONFIG_NETWORK_TYPE_UMTS,
1047                     DATA_CONFIG_NETWORK_TYPE_CDMA,
1048                     DATA_CONFIG_NETWORK_TYPE_1xRTT,
1049                     DATA_CONFIG_NETWORK_TYPE_EVDO_0,
1050                     DATA_CONFIG_NETWORK_TYPE_EVDO_A,
1051                     DATA_CONFIG_NETWORK_TYPE_HSDPA,
1052                     DATA_CONFIG_NETWORK_TYPE_HSUPA,
1053                     DATA_CONFIG_NETWORK_TYPE_HSPA,
1054                     DATA_CONFIG_NETWORK_TYPE_EVDO_B,
1055                     DATA_CONFIG_NETWORK_TYPE_EHRPD,
1056                     DATA_CONFIG_NETWORK_TYPE_IDEN,
1057                     DATA_CONFIG_NETWORK_TYPE_LTE,
1058                     DATA_CONFIG_NETWORK_TYPE_LTE_CA,
1059                     DATA_CONFIG_NETWORK_TYPE_HSPAP,
1060                     DATA_CONFIG_NETWORK_TYPE_GSM,
1061                     DATA_CONFIG_NETWORK_TYPE_TD_SCDMA,
1062                     DATA_CONFIG_NETWORK_TYPE_NR_NSA,
1063                     DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE,
1064                     DATA_CONFIG_NETWORK_TYPE_NR_SA,
1065                     DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE
1066             };
1067             if (table != null) {
1068                 for (String networkType : networkTypeKeys) {
1069                     int[] scores = table.getIntArray(networkType);
1070                     if (scores != null
1071                             && scores.length == SignalStrength.NUM_SIGNAL_STRENGTH_BINS) {
1072                         for (int i = 0; i < scores.length; i++) {
1073                             if (scores[i] < 0) {
1074                                 loge("Auto switch score must not < 0 for network type "
1075                                         + networkType);
1076                                 break;
1077                             }
1078                             if (i == scores.length - 1) {
1079                                 mAutoDataSwitchNetworkTypeSignalMap.put(networkType, scores);
1080                             }
1081                         }
1082                     } else {
1083                         loge("Auto switch score table should specify "
1084                                 + SignalStrength.NUM_SIGNAL_STRENGTH_BINS
1085                                 + " signal strength for network type " + networkType);
1086                     }
1087                 }
1088             }
1089         }
1090     }
1091 
1092     /**
1093      * @param displayInfo The displayed network info.
1094      * @param signalStrength The signal strength.
1095      * @return Score base on network type and signal strength to inform auto data switch decision.
1096      * The min score is {@link #OUT_OF_SERVICE_AUTO_DATA_SWITCH_SCORE} indicating missing config.
1097      */
getAutoDataSwitchScore(@onNull TelephonyDisplayInfo displayInfo, @NonNull SignalStrength signalStrength)1098     public int getAutoDataSwitchScore(@NonNull TelephonyDisplayInfo displayInfo,
1099             @NonNull SignalStrength signalStrength) {
1100         int[] scores = mAutoDataSwitchNetworkTypeSignalMap.get(
1101                 getDataConfigNetworkType(displayInfo));
1102         return scores != null ? scores[signalStrength.getLevel()]
1103                 : OUT_OF_SERVICE_AUTO_DATA_SWITCH_SCORE;
1104     }
1105 
1106     /**
1107      * @return The tolerated gap of score for auto data switch decision, larger than which the
1108      * device will switch to the SIM with higher score. If 0, the device always switch to the higher
1109      * score SIM. If < 0, the network type and signal strength based auto switch is disabled.
1110      */
getAutoDataSwitchScoreTolerance()1111     public int getAutoDataSwitchScoreTolerance() {
1112         return mResources.getInteger(com.android.internal.R.integer
1113                 .auto_data_switch_score_tolerance);
1114     }
1115 
1116     /**
1117      * TODO: remove after V.
1118      * @return To indicate whether allow using roaming nDDS if user enabled its roaming when the DDS
1119      * is not usable(OOS or disabled roaming)
1120      */
doesAutoDataSwitchAllowRoaming()1121     public boolean doesAutoDataSwitchAllowRoaming() {
1122         return mResources.getBoolean(com.android.internal.R.bool.auto_data_switch_allow_roaming);
1123     }
1124 
1125     /**
1126      * @return The maximum number of retries when a validation for switching failed.
1127      */
getAutoDataSwitchValidationMaxRetry()1128     public int getAutoDataSwitchValidationMaxRetry() {
1129         return mResources.getInteger(com.android.internal.R.integer
1130                 .auto_data_switch_validation_max_retry);
1131     }
1132 
1133     /**
1134      * @return Time threshold in ms to define a internet connection status to be stable
1135      * (e.g. out of service, in service, wifi is the default active network.etc), while -1 indicates
1136      * auto switch feature disabled.
1137      */
getAutoDataSwitchAvailabilityStabilityTimeThreshold()1138     public long getAutoDataSwitchAvailabilityStabilityTimeThreshold() {
1139         return mResources.getInteger(com.android.internal.R.integer
1140                 .auto_data_switch_availability_stability_time_threshold_millis);
1141     }
1142 
1143     /**
1144      * @return Time threshold in ms to define a internet connection performance status to be stable
1145      * (e.g. LTE + 4 signal strength, UMTS + 2 signal strength), while -1 indicates
1146      * auto switch feature based on RAT/SS is disabled.
1147      */
getAutoDataSwitchPerformanceStabilityTimeThreshold()1148     public long getAutoDataSwitchPerformanceStabilityTimeThreshold() {
1149         return mResources.getInteger(com.android.internal.R.integer
1150                 .auto_data_switch_performance_stability_time_threshold_millis);
1151     }
1152 
1153     /**
1154      * Get the TCP config string, used by {@link LinkProperties#setTcpBufferSizes(String)}.
1155      * The config string will have the following form, with values in bytes:
1156      * "read_min,read_default,read_max,write_min,write_default,write_max"
1157      *
1158      * @param displayInfo The {@link TelephonyDisplayInfo} to get the TCP config string for.
1159      * @return The TCP configuration string for the given display info or the default value from
1160      *         {@code config_tcp_buffers} if unavailable.
1161      */
1162     @NonNull
getTcpConfigString(@onNull TelephonyDisplayInfo displayInfo)1163     public String getTcpConfigString(@NonNull TelephonyDisplayInfo displayInfo) {
1164         String config = mTcpBufferSizeMap.get(getDataConfigNetworkType(displayInfo));
1165         if (TextUtils.isEmpty(config)) {
1166             config = getDefaultTcpConfigString();
1167         }
1168         return config;
1169     }
1170 
1171     /**
1172      * @return The fixed TCP buffer size configured based on the device's memory and performance.
1173      */
1174     @NonNull
getDefaultTcpConfigString()1175     public String getDefaultTcpConfigString() {
1176         return mResources.getString(com.android.internal.R.string.config_tcp_buffers);
1177     }
1178 
1179     /**
1180      * @return The delay in millisecond for IMS graceful tear down. If IMS/RCS de-registration
1181      * does not complete within the window, the data network will be torn down after timeout.
1182      */
getImsDeregistrationDelay()1183     public long getImsDeregistrationDelay() {
1184         return mResources.getInteger(
1185                 com.android.internal.R.integer.config_delay_for_ims_dereg_millis);
1186     }
1187 
1188     /**
1189      * @return {@code true} if PDN should persist when IWLAN data service restarted/crashed.
1190      * {@code false} will cause all data networks on IWLAN torn down if IWLAN data service crashes.
1191      */
shouldPersistIwlanDataNetworksWhenDataServiceRestarted()1192     public boolean shouldPersistIwlanDataNetworksWhenDataServiceRestarted() {
1193         return mResources.getBoolean(com.android.internal.R.bool
1194                 .config_wlan_data_service_conn_persistence_on_restart);
1195     }
1196 
1197     /**
1198      * @return {@code true} if adopt predefined IWLAN handover policy. If {@code false}, handover is
1199      * allowed by default.
1200      */
isIwlanHandoverPolicyEnabled()1201     public boolean isIwlanHandoverPolicyEnabled() {
1202         return mResources.getBoolean(com.android.internal.R.bool
1203                 .config_enable_iwlan_handover_policy);
1204     }
1205 
1206     /**
1207      * @return {@code true} if tearing down IMS data network should be delayed until the voice call
1208      * ends.
1209      */
isImsDelayTearDownUntilVoiceCallEndEnabled()1210     public boolean isImsDelayTearDownUntilVoiceCallEndEnabled() {
1211         return mCarrierConfig.getBoolean(
1212                 CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL);
1213     }
1214 
1215     /**
1216      * @return The bandwidth estimation source.
1217      */
1218     @DataNetwork.BandwidthEstimationSource
getBandwidthEstimateSource()1219     public int getBandwidthEstimateSource() {
1220         String source = mResources.getString(
1221                 com.android.internal.R.string.config_bandwidthEstimateSource);
1222         return switch (source) {
1223             case BANDWIDTH_SOURCE_MODEM_STRING_VALUE -> DataNetwork.BANDWIDTH_SOURCE_MODEM;
1224             case BANDWIDTH_SOURCE_CARRIER_CONFIG_STRING_VALUE ->
1225                     DataNetwork.BANDWIDTH_SOURCE_CARRIER_CONFIG;
1226             case BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR_STRING_VALUE ->
1227                     DataNetwork.BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR;
1228             default -> {
1229                 loge("Invalid bandwidth estimation source config: " + source);
1230                 yield DataNetwork.BANDWIDTH_SOURCE_UNKNOWN;
1231             }
1232         };
1233     }
1234 
1235     /**
1236      * Get the {@link DataConfigNetworkType} based on the given {@link TelephonyDisplayInfo}.
1237      *
1238      * @param displayInfo The {@link TelephonyDisplayInfo} used to determine the type.
1239      * @return The equivalent {@link DataConfigNetworkType}.
1240      */
1241     @NonNull
1242     @DataConfigNetworkType
getDataConfigNetworkType(@onNull TelephonyDisplayInfo displayInfo)1243     private static String getDataConfigNetworkType(@NonNull TelephonyDisplayInfo displayInfo) {
1244         int networkType = displayInfo.getNetworkType();
1245         switch (displayInfo.getOverrideNetworkType()) {
1246             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED:
1247                 if (networkType == TelephonyManager.NETWORK_TYPE_NR) {
1248                     return DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE;
1249                 } else {
1250                     return DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE;
1251                 }
1252             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA:
1253                 return DATA_CONFIG_NETWORK_TYPE_NR_NSA;
1254             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO:
1255             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA:
1256                 return DATA_CONFIG_NETWORK_TYPE_LTE_CA;
1257             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE:
1258             default:
1259                 return networkTypeToDataConfigNetworkType(networkType);
1260         }
1261     }
1262 
1263     /** Update handover rules from carrier config. */
updateHandoverRules()1264     private void updateHandoverRules() {
1265         synchronized (this) {
1266             mHandoverRuleList.clear();
1267             String[] handoverRulesStrings = mCarrierConfig.getStringArray(
1268                     CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY);
1269             if (handoverRulesStrings != null) {
1270                 for (String ruleString : handoverRulesStrings) {
1271                     try {
1272                         mHandoverRuleList.add(new HandoverRule(ruleString));
1273                     } catch (IllegalArgumentException e) {
1274                         loge("updateHandoverRules: " + e.getMessage());
1275                     }
1276                 }
1277             }
1278         }
1279     }
1280 
1281     /**
1282      * Describe an event occurs eventNumOccurrence within a time span timeWindow
1283      */
1284     public static class EventFrequency {
1285         /** The time window in ms within which event occurs. */
1286         public final long timeWindow;
1287 
1288         /** The number of time the event occurs. */
1289         public final int eventNumOccurrence;
1290 
1291         /**
1292          * Constructor
1293          *
1294          * @param timeWindow The time window in ms within which event occurs.
1295          * @param eventNumOccurrence The number of time the event occurs.
1296          */
EventFrequency(long timeWindow, int eventNumOccurrence)1297         public EventFrequency(long timeWindow, int eventNumOccurrence) {
1298             this.timeWindow = timeWindow;
1299             this.eventNumOccurrence = eventNumOccurrence;
1300         }
1301 
1302         @Override
toString()1303         public String toString() {
1304             return String.format("EventFrequency=[timeWindow=%d, eventNumOccurrence=%d]",
1305                     timeWindow, eventNumOccurrence);
1306         }
1307     }
1308 
1309     /**
1310      * Parse a pair of event throttle thresholds of the form "time window in ms,occurrences"
1311      * into {@link EventFrequency}
1312      * @param s String to be parsed in the form of "time window in ms,occurrences"
1313      * @param defaultTimeWindow The time window to return if parsing failed.
1314      * @param defaultOccurrences The occurrence to return if parsing failed.
1315      * @return timeWindow and occurrence wrapped in EventFrequency
1316      */
1317     @VisibleForTesting
parseSlidingWindowCounterThreshold(String s, long defaultTimeWindow, int defaultOccurrences)1318     public EventFrequency parseSlidingWindowCounterThreshold(String s,
1319             long defaultTimeWindow, int defaultOccurrences) {
1320         EventFrequency defaultValue = new EventFrequency(defaultTimeWindow, defaultOccurrences);
1321         if (TextUtils.isEmpty(s)) return defaultValue;
1322 
1323         final String[] pair = s.split(",");
1324         if (pair.length != 2) {
1325             loge("Invalid format: " + s
1326                     + "Format should be in \"time window in ms,occurrences\". "
1327                     + "Using default instead.");
1328             return defaultValue;
1329         }
1330         long windowSpan;
1331         int occurrence;
1332         try {
1333             windowSpan = Long.parseLong(pair[0].trim());
1334         } catch (NumberFormatException e) {
1335             loge("Exception parsing SlidingWindow window span " + pair[0] + ": " + e);
1336             return defaultValue;
1337         }
1338         try {
1339             occurrence = Integer.parseInt(pair[1].trim());
1340         } catch (NumberFormatException e) {
1341             loge("Exception parsing SlidingWindow occurrence as integer " + pair[1] + ": " + e);
1342             return defaultValue;
1343         }
1344         return new EventFrequency(windowSpan, occurrence);
1345     }
1346 
1347     /**
1348      * @return Get rules for handover between IWLAN and cellular networks.
1349      *
1350      * @see CarrierConfigManager#KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY
1351      */
1352     @NonNull
getHandoverRules()1353     public List<HandoverRule> getHandoverRules() {
1354         return Collections.unmodifiableList(mHandoverRuleList);
1355     }
1356 
1357     /**
1358      * @return Get the delay in milliseconds for re-evaluating unsatisfied network requests.
1359      */
getRetrySetupAfterDisconnectMillis()1360     public long getRetrySetupAfterDisconnectMillis() {
1361         return mCarrierConfig.getLong(CarrierConfigManager
1362                 .KEY_CARRIER_DATA_CALL_APN_RETRY_AFTER_DISCONNECT_LONG);
1363     }
1364 
1365     /**
1366      * Get the data config network type for the given network type
1367      *
1368      * @param networkType The network type
1369      * @return The equivalent data config network type
1370      */
1371     @NonNull
1372     @DataConfigNetworkType
networkTypeToDataConfigNetworkType( @etworkType int networkType)1373     private static String networkTypeToDataConfigNetworkType(
1374             @NetworkType int networkType) {
1375         return switch (networkType) {
1376             case TelephonyManager.NETWORK_TYPE_GPRS -> DATA_CONFIG_NETWORK_TYPE_GPRS;
1377             case TelephonyManager.NETWORK_TYPE_EDGE -> DATA_CONFIG_NETWORK_TYPE_EDGE;
1378             case TelephonyManager.NETWORK_TYPE_UMTS -> DATA_CONFIG_NETWORK_TYPE_UMTS;
1379             case TelephonyManager.NETWORK_TYPE_HSDPA -> DATA_CONFIG_NETWORK_TYPE_HSDPA;
1380             case TelephonyManager.NETWORK_TYPE_HSUPA -> DATA_CONFIG_NETWORK_TYPE_HSUPA;
1381             case TelephonyManager.NETWORK_TYPE_HSPA -> DATA_CONFIG_NETWORK_TYPE_HSPA;
1382             case TelephonyManager.NETWORK_TYPE_CDMA -> DATA_CONFIG_NETWORK_TYPE_CDMA;
1383             case TelephonyManager.NETWORK_TYPE_EVDO_0 -> DATA_CONFIG_NETWORK_TYPE_EVDO_0;
1384             case TelephonyManager.NETWORK_TYPE_EVDO_A -> DATA_CONFIG_NETWORK_TYPE_EVDO_A;
1385             case TelephonyManager.NETWORK_TYPE_EVDO_B -> DATA_CONFIG_NETWORK_TYPE_EVDO_B;
1386             case TelephonyManager.NETWORK_TYPE_1xRTT -> DATA_CONFIG_NETWORK_TYPE_1xRTT;
1387             case TelephonyManager.NETWORK_TYPE_LTE -> DATA_CONFIG_NETWORK_TYPE_LTE;
1388             case TelephonyManager.NETWORK_TYPE_EHRPD -> DATA_CONFIG_NETWORK_TYPE_EHRPD;
1389             case TelephonyManager.NETWORK_TYPE_IDEN -> DATA_CONFIG_NETWORK_TYPE_IDEN;
1390             case TelephonyManager.NETWORK_TYPE_HSPAP -> DATA_CONFIG_NETWORK_TYPE_HSPAP;
1391             case TelephonyManager.NETWORK_TYPE_GSM -> DATA_CONFIG_NETWORK_TYPE_GSM;
1392             case TelephonyManager.NETWORK_TYPE_TD_SCDMA -> DATA_CONFIG_NETWORK_TYPE_TD_SCDMA;
1393             case TelephonyManager.NETWORK_TYPE_IWLAN -> DATA_CONFIG_NETWORK_TYPE_IWLAN;
1394             case TelephonyManager.NETWORK_TYPE_LTE_CA -> DATA_CONFIG_NETWORK_TYPE_LTE_CA;
1395             case TelephonyManager.NETWORK_TYPE_NR -> DATA_CONFIG_NETWORK_TYPE_NR_SA;
1396             default -> "";
1397         };
1398     }
1399 
1400     /**
1401      * @return Get recovery action delay in milliseconds between recovery actions.
1402      *
1403      * @see CarrierConfigManager#KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY
1404      */
1405     @NonNull
1406     public long[] getDataStallRecoveryDelayMillis() {
1407         return mCarrierConfig.getLongArray(
1408             CarrierConfigManager.KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY);
1409     }
1410 
1411     /**
1412      * @return Get the data stall recovery should skip boolean array.
1413      *
1414      * @see CarrierConfigManager#KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY
1415      */
1416     @NonNull
1417     public boolean[] getDataStallRecoveryShouldSkipArray() {
1418         return mCarrierConfig.getBooleanArray(
1419             CarrierConfigManager.KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY);
1420     }
1421 
1422     /**
1423      * @return The default preferred APN. An empty string if not configured. This is used for the
1424      * first time boot up where preferred APN is not set.
1425      */
1426     @NonNull
1427     public String getDefaultPreferredApn() {
1428         return TextUtils.emptyIfNull(mCarrierConfig.getString(
1429                 CarrierConfigManager.KEY_DEFAULT_PREFERRED_APN_NAME_STRING));
1430     }
1431 
1432     /**
1433      * @return The PCO id used for determine if data networks are using NR advanced networks. 0
1434      * indicates this feature is disabled.
1435      */
1436     public int getNrAdvancedCapablePcoId() {
1437         return mCarrierConfig.getInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT);
1438     }
1439 
1440     /**
1441      * @return The allowed APN types for initial attach. The order in the list determines the
1442      * priority of it being considered as IA APN. Note this should be only used for some exception
1443      * cases that we need to use "user-added" APN for initial attach. The regular way to configure
1444      * IA APN is by adding "IA" type to the APN in APN config.
1445      */
1446     @NonNull
1447     @ApnType
1448     public List<Integer> getAllowedInitialAttachApnTypes() {
1449         String[] apnTypesArray = mCarrierConfig.getStringArray(
1450                 CarrierConfigManager.KEY_ALLOWED_INITIAL_ATTACH_APN_TYPES_STRING_ARRAY);
1451         if (apnTypesArray != null) {
1452             return Arrays.stream(apnTypesArray)
1453                     .map(ApnSetting::getApnTypesBitmaskFromString)
1454                     .collect(Collectors.toList());
1455         }
1456 
1457         return Collections.emptyList();
1458     }
1459 
1460     /**
1461      * @return {@code true} if enhanced IWLAN handover check is enabled. If enabled, telephony
1462      * frameworks will not perform handover if the target transport is out of service, or VoPS not
1463      * supported. The network will be torn down on the source transport, and will be
1464      * re-established on the target transport when condition is allowed for bringing up a new
1465      * network.
1466      */
1467     public boolean isEnhancedIwlanHandoverCheckEnabled() {
1468         return mResources.getBoolean(
1469                 com.android.internal.R.bool.config_enhanced_iwlan_handover_check);
1470     }
1471 
1472     /**
1473      * @return {@code true} if allow sending null data profile to ask modem to clear the initial
1474      * attach data profile.
1475      */
1476     public boolean allowClearInitialAttachDataProfile() {
1477         return mResources.getBoolean(
1478                 com.android.internal.R.bool.allow_clear_initial_attach_data_profile);
1479     }
1480 
1481     /**
1482      * @return Indicating whether the retry timer from setup data call response for data throttling
1483      * should be honored for emergency network request. By default this is off, meaning emergency
1484      * network requests will ignore the previous retry timer passed in from setup data call
1485      * response.
1486      */
1487     public boolean shouldHonorRetryTimerForEmergencyNetworkRequest() {
1488         return mResources.getBoolean(
1489                 com.android.internal.R.bool.config_honor_data_retry_timer_for_emergency_network);
1490     }
1491 
1492     /**
1493      * @return The capabilities that network will be forced to mark as cellular transport.
1494      */
1495     @NetCapability
1496     public Set<Integer> getForcedCellularTransportCapabilities() {
1497         String[] forcedCellularTransportCapabilities = mResources.getStringArray(
1498                 com.android.internal.R.array.config_force_cellular_transport_capabilities);
1499 
1500         return Arrays.stream(forcedCellularTransportCapabilities)
1501                 .map(DataUtils::getNetworkCapabilityFromString)
1502                 .collect(Collectors.toSet());
1503     }
1504 
1505     /**
1506      * {@code True} enables mms to be attempted on iwlan if possible, even if existing cellular
1507      *  networks already supports iwlan.
1508      */
1509     public boolean isForceIwlanMmsFeatureEnabled() {
1510         return mResources.getBoolean(com.android.internal.R.bool.force_iwlan_mms_feature_enabled);
1511     }
1512 
1513     /**
1514      * Log debug messages.
1515      * @param s debug messages
1516      */
1517     private void log(@NonNull String s) {
1518         Rlog.d(mLogTag, s);
1519     }
1520 
1521     /**
1522      * Log error messages.
1523      * @param s error messages
1524      */
1525     private void loge(@NonNull String s) {
1526         Rlog.e(mLogTag, s);
1527     }
1528 
1529     /**
1530      * Dump the state of DataConfigManager
1531      *
1532      * @param fd File descriptor
1533      * @param printWriter Print writer
1534      * @param args Arguments
1535      */
1536     public void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
1537         IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ");
1538         pw.println(DataConfigManager.class.getSimpleName() + "-" + mPhone.getPhoneId() + ":");
1539         pw.increaseIndent();
1540         pw.println("isConfigCarrierSpecific=" + isConfigCarrierSpecific());
1541         pw.println("Network capability priority:");
1542         pw.increaseIndent();
1543         mNetworkCapabilityPriorityMap.forEach((key, value) -> pw.print(
1544                 DataUtils.networkCapabilityToString(key) + ":" + value + " "));
1545         pw.decreaseIndent();
1546         pw.println();
1547         pw.println("Data setup retry rules:");
1548         pw.increaseIndent();
1549         mDataSetupRetryRules.forEach(pw::println);
1550         pw.decreaseIndent();
1551         pw.println("isIwlanHandoverPolicyEnabled=" + isIwlanHandoverPolicyEnabled());
1552         pw.println("Data handover retry rules:");
1553         pw.increaseIndent();
1554         mDataHandoverRetryRules.forEach(pw::println);
1555         pw.decreaseIndent();
1556         pw.println("shouldHonorRetryTimerForEmergencyNetworkRequest="
1557                 + shouldHonorRetryTimerForEmergencyNetworkRequest());
1558         pw.println("mSetupDataCallAnomalyReport=" + mSetupDataCallAnomalyReportThreshold);
1559         pw.println("mNetworkUnwantedAnomalyReport=" + mNetworkUnwantedAnomalyReportThreshold);
1560         pw.println("mImsReleaseRequestAnomalyReport=" + mImsReleaseRequestAnomalyReportThreshold);
1561         pw.println("mIsInvalidQnsParamAnomalyReportEnabled="
1562                 + mIsInvalidQnsParamAnomalyReportEnabled);
1563         pw.println("mNetworkConnectingTimeout=" + mNetworkConnectingTimeout);
1564         pw.println("mNetworkDisconnectingTimeout=" + mNetworkDisconnectingTimeout);
1565         pw.println("mNetworkHandoverTimeout=" + mNetworkHandoverTimeout);
1566         pw.println("mIsApnConfigAnomalyReportEnabled=" + mIsApnConfigAnomalyReportEnabled);
1567         pw.println("Auto data switch:");
1568         pw.increaseIndent();
1569         pw.println("getAutoDataSwitchScoreTolerance=" + getAutoDataSwitchScoreTolerance());
1570         mAutoDataSwitchNetworkTypeSignalMap.forEach((key, value) -> pw.println(key + ":"
1571                 + Arrays.toString(value)));
1572         pw.println("getAutoDataSwitchAvailabilityStabilityTimeThreshold="
1573                 + getAutoDataSwitchAvailabilityStabilityTimeThreshold());
1574         pw.println("getAutoDataSwitchPerformanceStabilityTimeThreshold="
1575                 + getAutoDataSwitchPerformanceStabilityTimeThreshold());
1576         pw.println("getAutoDataSwitchValidationMaxRetry=" + getAutoDataSwitchValidationMaxRetry());
1577         pw.decreaseIndent();
1578         pw.println("Metered APN types=" + mMeteredApnTypes.stream()
1579                 .map(ApnSetting::getApnTypeString).collect(Collectors.joining(",")));
1580         pw.println("Roaming metered APN types=" + mRoamingMeteredApnTypes.stream()
1581                 .map(ApnSetting::getApnTypeString).collect(Collectors.joining(",")));
1582         pw.println("Single data network types=" + mSingleDataNetworkTypeList.stream()
1583                 .map(TelephonyManager::getNetworkTypeName).collect(Collectors.joining(",")));
1584         pw.println("Capabilities exempt from single PDN=" + mCapabilitiesExemptFromSingleDataList
1585                 .stream().map(DataUtils::networkCapabilityToString)
1586                 .collect(Collectors.joining(",")));
1587         pw.println("mShouldKeepNetworkUpInNonVops=" + mShouldKeepNetworkUpInNonVops);
1588         pw.println("mEnabledVopsNetworkTypesInNonVops=" + mEnabledVopsNetworkTypesInNonVops);
1589         pw.println("isPingTestBeforeAutoDataSwitchRequired="
1590                 + isPingTestBeforeAutoDataSwitchRequired());
1591         pw.println("Unmetered network types=" + String.join(",", mUnmeteredNetworkTypes));
1592         pw.println("Roaming unmetered network types="
1593                 + String.join(",", mRoamingUnmeteredNetworkTypes));
1594         pw.println("Bandwidths:");
1595         pw.increaseIndent();
1596         mBandwidthMap.forEach((key, value) -> pw.println(key + ":" + value));
1597         pw.decreaseIndent();
1598         pw.println("shouldUseDataActivityForRrcDetection="
1599                 + shouldUseDataActivityForRrcDetection());
1600         pw.println("isTempNotMeteredSupportedByCarrier=" + isTempNotMeteredSupportedByCarrier());
1601         pw.println("shouldResetDataThrottlingWhenTacChanges="
1602                 + shouldResetDataThrottlingWhenTacChanges());
1603         pw.println("Data service package name=" + getDataServicePackageName());
1604         pw.println("Default MTU=" + getDefaultMtu());
1605         pw.println("TCP buffer sizes by RAT:");
1606         pw.increaseIndent();
1607         mTcpBufferSizeMap.forEach((key, value) -> pw.println(key + ":" + value));
1608         pw.decreaseIndent();
1609         pw.println("Default TCP buffer sizes=" + getDefaultTcpConfigString());
1610         pw.println("getImsDeregistrationDelay=" + getImsDeregistrationDelay());
1611         pw.println("shouldPersistIwlanDataNetworksWhenDataServiceRestarted="
1612                 + shouldPersistIwlanDataNetworksWhenDataServiceRestarted());
1613         pw.println("Bandwidth estimation source=" + mResources.getString(
1614                 com.android.internal.R.string.config_bandwidthEstimateSource));
1615         pw.println("isImsDelayTearDownUntilVoiceCallEndEnabled="
1616                 + isImsDelayTearDownUntilVoiceCallEndEnabled());
1617         pw.println("isEnhancedIwlanHandoverCheckEnabled=" + isEnhancedIwlanHandoverCheckEnabled());
1618         pw.println("isTetheringProfileDisabledForRoaming="
1619                 + isTetheringProfileDisabledForRoaming());
1620         pw.println("allowClearInitialAttachDataProfile=" + allowClearInitialAttachDataProfile());
1621         pw.println("forcedCellularTransportCapabilities=" + getForcedCellularTransportCapabilities()
1622                 .stream().map(DataUtils::networkCapabilityToString)
1623                 .collect(Collectors.joining(",")));
1624         pw.decreaseIndent();
1625     }
1626 }
1627