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