• 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.ElapsedRealtimeLong;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.app.usage.NetworkStats;
25 import android.app.usage.NetworkStatsManager;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.pm.PackageManager;
31 import android.net.NetworkAgent;
32 import android.net.NetworkCapabilities;
33 import android.net.NetworkPolicyManager;
34 import android.net.NetworkPolicyManager.SubscriptionCallback;
35 import android.net.NetworkRequest;
36 import android.net.NetworkTemplate;
37 import android.net.Uri;
38 import android.os.AsyncResult;
39 import android.os.Handler;
40 import android.os.Looper;
41 import android.os.Message;
42 import android.os.SystemClock;
43 import android.telecom.TelecomManager;
44 import android.telephony.AccessNetworkConstants;
45 import android.telephony.AccessNetworkConstants.AccessNetworkType;
46 import android.telephony.AccessNetworkConstants.RadioAccessNetworkType;
47 import android.telephony.AccessNetworkConstants.TransportType;
48 import android.telephony.Annotation.DataActivityType;
49 import android.telephony.Annotation.DataFailureCause;
50 import android.telephony.Annotation.NetCapability;
51 import android.telephony.Annotation.NetworkType;
52 import android.telephony.Annotation.ValidationStatus;
53 import android.telephony.AnomalyReporter;
54 import android.telephony.CarrierConfigManager;
55 import android.telephony.CellSignalStrength;
56 import android.telephony.DataFailCause;
57 import android.telephony.DataSpecificRegistrationInfo;
58 import android.telephony.NetworkRegistrationInfo;
59 import android.telephony.NetworkRegistrationInfo.RegistrationState;
60 import android.telephony.PcoData;
61 import android.telephony.ServiceState;
62 import android.telephony.SubscriptionManager;
63 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
64 import android.telephony.SubscriptionPlan;
65 import android.telephony.TelephonyManager;
66 import android.telephony.TelephonyManager.DataState;
67 import android.telephony.TelephonyManager.SimState;
68 import android.telephony.TelephonyRegistryManager;
69 import android.telephony.data.ApnSetting;
70 import android.telephony.data.DataCallResponse;
71 import android.telephony.data.DataCallResponse.HandoverFailureMode;
72 import android.telephony.data.DataCallResponse.LinkStatus;
73 import android.telephony.data.DataProfile;
74 import android.telephony.data.DataServiceCallback;
75 import android.telephony.data.QosBearerSession;
76 import android.telephony.ims.ImsException;
77 import android.telephony.ims.ImsManager;
78 import android.telephony.ims.ImsReasonInfo;
79 import android.telephony.ims.ImsRegistrationAttributes;
80 import android.telephony.ims.ImsStateCallback;
81 import android.telephony.ims.RegistrationManager;
82 import android.telephony.ims.feature.ImsFeature;
83 import android.text.TextUtils;
84 import android.util.ArrayMap;
85 import android.util.ArraySet;
86 import android.util.IndentingPrintWriter;
87 import android.util.LocalLog;
88 import android.util.SparseArray;
89 import android.util.SparseBooleanArray;
90 
91 import com.android.internal.annotations.VisibleForTesting;
92 import com.android.internal.telephony.Phone;
93 import com.android.internal.telephony.PhoneConstants;
94 import com.android.internal.telephony.SlidingWindowEventCounter;
95 import com.android.internal.telephony.TelephonyCapabilities;
96 import com.android.internal.telephony.TelephonyComponentFactory;
97 import com.android.internal.telephony.data.AccessNetworksManager.AccessNetworksManagerCallback;
98 import com.android.internal.telephony.data.DataConfigManager.DataConfigManagerCallback;
99 import com.android.internal.telephony.data.DataEvaluation.DataAllowedReason;
100 import com.android.internal.telephony.data.DataEvaluation.DataDisallowedReason;
101 import com.android.internal.telephony.data.DataEvaluation.DataEvaluationReason;
102 import com.android.internal.telephony.data.DataNetwork.DataNetworkCallback;
103 import com.android.internal.telephony.data.DataNetwork.TearDownReason;
104 import com.android.internal.telephony.data.DataProfileManager.DataProfileManagerCallback;
105 import com.android.internal.telephony.data.DataRetryManager.DataHandoverRetryEntry;
106 import com.android.internal.telephony.data.DataRetryManager.DataRetryEntry;
107 import com.android.internal.telephony.data.DataRetryManager.DataRetryManagerCallback;
108 import com.android.internal.telephony.data.DataRetryManager.DataSetupRetryEntry;
109 import com.android.internal.telephony.data.DataSettingsManager.DataSettingsManagerCallback;
110 import com.android.internal.telephony.data.DataStallRecoveryManager.DataStallRecoveryManagerCallback;
111 import com.android.internal.telephony.data.LinkBandwidthEstimator.LinkBandwidthEstimatorCallback;
112 import com.android.internal.telephony.flags.FeatureFlags;
113 import com.android.internal.telephony.ims.ImsResolver;
114 import com.android.internal.telephony.satellite.SatelliteController;
115 import com.android.internal.telephony.subscription.SubscriptionInfoInternal;
116 import com.android.internal.telephony.subscription.SubscriptionManagerService;
117 import com.android.internal.telephony.util.TelephonyUtils;
118 import com.android.internal.util.FunctionalUtils;
119 import com.android.telephony.Rlog;
120 
121 import java.io.FileDescriptor;
122 import java.io.PrintWriter;
123 import java.lang.annotation.Retention;
124 import java.lang.annotation.RetentionPolicy;
125 import java.util.ArrayList;
126 import java.util.Arrays;
127 import java.util.Collection;
128 import java.util.Collections;
129 import java.util.Comparator;
130 import java.util.HashSet;
131 import java.util.Iterator;
132 import java.util.LinkedList;
133 import java.util.List;
134 import java.util.Locale;
135 import java.util.Map;
136 import java.util.Objects;
137 import java.util.Set;
138 import java.util.UUID;
139 import java.util.concurrent.Executor;
140 import java.util.concurrent.TimeUnit;
141 import java.util.function.Consumer;
142 import java.util.function.Function;
143 import java.util.stream.Collectors;
144 
145 /**
146  * DataNetworkController in the central module of the telephony data stack. It is responsible to
147  * create and manage all the mobile data networks. It is per-SIM basis which means for DSDS devices,
148  * there will be two DataNetworkController instances. Unlike the Android 12 DcTracker, which is
149  * designed to be per-transport (i.e. cellular, IWLAN), DataNetworkController is designed to handle
150  * data networks on both cellular and IWLAN.
151  */
152 public class DataNetworkController extends Handler {
153     private static final boolean VDBG = false;
154 
155     /** Event for adding a network request. */
156     private static final int EVENT_ADD_NETWORK_REQUEST = 2;
157 
158     /** Event for removing a network request. */
159     private static final int EVENT_REMOVE_NETWORK_REQUEST = 3;
160 
161     /** Event for SRVCC state changed. */
162     private static final int EVENT_SRVCC_STATE_CHANGED = 4;
163 
164     /** Re-evaluate all unsatisfied network requests. */
165     private static final int EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS = 5;
166 
167     /** Event for packet switch restricted enabled by network. */
168     private static final int EVENT_PS_RESTRICT_ENABLED = 6;
169 
170     /** Event for packet switch restricted disabled by network. */
171     private static final int EVENT_PS_RESTRICT_DISABLED = 7;
172 
173     /** Event for data service binding changed. */
174     private static final int EVENT_DATA_SERVICE_BINDING_CHANGED = 8;
175 
176     /** Event for SIM state changed. */
177     private static final int EVENT_SIM_STATE_CHANGED = 9;
178 
179     /** Event for tearing down all data networks. */
180     private static final int EVENT_TEAR_DOWN_ALL_DATA_NETWORKS = 12;
181 
182     /** Event for registering data network controller callback. */
183     private static final int EVENT_REGISTER_DATA_NETWORK_CONTROLLER_CALLBACK = 13;
184 
185     /** Event for unregistering data network controller callback. */
186     private static final int EVENT_UNREGISTER_DATA_NETWORK_CONTROLLER_CALLBACK = 14;
187 
188     /** Event for subscription info changed. */
189     private static final int EVENT_SUBSCRIPTION_CHANGED = 15;
190 
191     /** Event for re-evaluating existing data networks. */
192     private static final int EVENT_REEVALUATE_EXISTING_DATA_NETWORKS = 16;
193 
194     /** Event for data RAT or registration state changed. */
195     private static final int EVENT_SERVICE_STATE_CHANGED = 17;
196 
197     /** Event for voice call ended. */
198     private static final int EVENT_VOICE_CALL_ENDED = 18;
199 
200     /** Event for registering all events. */
201     private static final int EVENT_REGISTER_ALL_EVENTS = 19;
202 
203     /** Event for emergency call started or ended. */
204     private static final int EVENT_EMERGENCY_CALL_CHANGED = 20;
205 
206     /** Event for evaluating preferred transport. */
207     private static final int EVENT_EVALUATE_PREFERRED_TRANSPORT = 21;
208 
209     /** Event for subscription plans changed. */
210     private static final int EVENT_SUBSCRIPTION_PLANS_CHANGED = 22;
211 
212     /** Event for unmetered or congested subscription override. */
213     private static final int EVENT_SUBSCRIPTION_OVERRIDE = 23;
214 
215     /** Event for slice config changed. */
216     private static final int EVENT_SLICE_CONFIG_CHANGED = 24;
217 
218     /** Event for tracking area code changed. */
219     private static final int EVENT_TAC_CHANGED = 25;
220 
221     /** The supported IMS features. This is for IMS graceful tear down support. */
222     private static final Collection<Integer> SUPPORTED_IMS_FEATURES =
223             List.of(ImsFeature.FEATURE_MMTEL, ImsFeature.FEATURE_RCS);
224 
225     /** The maximum number of previously connected data networks for debugging purposes. */
226     private static final int MAX_HISTORICAL_CONNECTED_DATA_NETWORKS = 10;
227 
228     /**
229      * The delay in milliseconds to re-evaluate preferred transport when handover failed and
230      * fallback to source.
231      */
232     private static final long REEVALUATE_PREFERRED_TRANSPORT_DELAY_MILLIS =
233             TimeUnit.SECONDS.toMillis(3);
234 
235     /** The delay in milliseconds to re-evaluate unsatisfied network requests after call end. */
236     private static final long REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_AFTER_CALL_END_DELAY_MILLIS =
237             TimeUnit.MILLISECONDS.toMillis(500);
238 
239     /** The delay in milliseconds to re-evaluate unsatisfied network requests after TAC changes. */
240     private static final long REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_TAC_CHANGED_DELAY_MILLIS =
241             TimeUnit.MILLISECONDS.toMillis(100);
242 
243     /**
244      * The delay in milliseconds to re-evaluate unsatisfied network requests after network request
245      * detached.
246      */
247     private static final long REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_AFTER_DETACHED_DELAY_MILLIS =
248             TimeUnit.SECONDS.toMillis(1);
249 
250     /**
251      * The guard timer in milliseconds to limit querying the data usage api stats frequently
252      */
253     private static final long GUARD_TIMER_INTERVAL_TO_QUERY_DATA_USAGE_API_STATS_MILLIS =
254             TimeUnit.SECONDS.toMillis(1);
255 
256     /**
257      * bootstrap sim total data usage bytes
258      */
259     private long mBootStrapSimTotalDataUsageBytes = 0L;
260 
261     /**
262      * bootstrap sim last data usage query time
263      */
264     @ElapsedRealtimeLong
265     private long mBootstrapSimLastDataUsageQueryTime = 0L;
266 
267     private final Phone mPhone;
268     private final String mLogTag;
269     private final LocalLog mLocalLog = new LocalLog(128);
270 
271     @NonNull
272     private final DataConfigManager mDataConfigManager;
273     @NonNull
274     private final DataSettingsManager mDataSettingsManager;
275     @NonNull
276     private final DataProfileManager mDataProfileManager;
277     @NonNull
278     private final DataStallRecoveryManager mDataStallRecoveryManager;
279     @NonNull
280     private final AccessNetworksManager mAccessNetworksManager;
281     @NonNull
282     private final DataRetryManager mDataRetryManager;
283     @NonNull
284     private final ImsManager mImsManager;
285     @NonNull
286     private final TelecomManager mTelecomManager;
287     @NonNull
288     private final NetworkPolicyManager mNetworkPolicyManager;
289     @NonNull
290     private final SparseArray<DataServiceManager> mDataServiceManagers = new SparseArray<>();
291 
292     /** The subscription index associated with this data network controller. */
293     private int mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
294 
295     /** The current service state of the device. */
296     // Note that keeping a copy here instead of directly using ServiceStateTracker.getServiceState()
297     // is intended for detecting the delta.
298     @NonNull
299     private ServiceState mServiceState;
300 
301     /** The list of SubscriptionPlans, updated when initialized and when plans are changed. */
302     @NonNull
303     private final List<SubscriptionPlan> mSubscriptionPlans = new ArrayList<>();
304 
305     /**
306      * The set of network types an unmetered override applies to, set by onSubscriptionOverride
307      * and cleared when the device is rebooted or the override expires.
308      */
309     @NonNull
310     @NetworkType
311     private final Set<Integer> mUnmeteredOverrideNetworkTypes = new ArraySet<>();
312 
313     /**
314      * The set of network types a congested override applies to, set by onSubscriptionOverride
315      * and cleared when the device is rebooted or the override expires.
316      */
317     @NonNull
318     @NetworkType
319     private final Set<Integer> mCongestedOverrideNetworkTypes = new ArraySet<>();
320 
321     /**
322      * The list of all network requests.
323      */
324     @NonNull
325     private final NetworkRequestList mAllNetworkRequestList = new NetworkRequestList();
326 
327     /**
328      * The current data network list, including the ones that are connected, connecting, or
329      * disconnecting.
330      */
331     @NonNull
332     private final List<DataNetwork> mDataNetworkList = new ArrayList<>();
333 
334     /** {@code true} indicating at least one data network exists. */
335     private boolean mAnyDataNetworkExisting;
336 
337     /**
338      * Contain the last 10 data networks that were connected. This is for debugging purposes only.
339      */
340     @NonNull
341     private final List<DataNetwork> mPreviousConnectedDataNetworkList = new ArrayList<>();
342 
343     /**
344      * The internet data network state. Note that this is the best effort if more than one
345      * data network supports internet.
346      */
347     @DataState
348     private int mInternetDataNetworkState = TelephonyManager.DATA_DISCONNECTED;
349 
350     /** All the current connected/handover internet networks.  */
351     @NonNull
352     private Set<DataNetwork> mConnectedInternetNetworks = new HashSet<>();
353 
354     /**
355      * The IMS data network state. For now this is just for debugging purposes.
356      */
357     @DataState
358     private int mImsDataNetworkState = TelephonyManager.DATA_DISCONNECTED;
359 
360     /** Overall aggregated link status from internet data networks. */
361     @LinkStatus
362     private int mInternetLinkStatus = DataCallResponse.LINK_STATUS_UNKNOWN;
363 
364     /** Data network controller callbacks. */
365     @NonNull
366     private final Set<DataNetworkControllerCallback> mDataNetworkControllerCallbacks =
367             new ArraySet<>();
368 
369     /** Indicates if packet switch data is restricted by the cellular network. */
370     private boolean mPsRestricted = false;
371 
372     /** Indicates if NR advanced is allowed by PCO. */
373     private boolean mNrAdvancedCapableByPco = false;
374 
375     /** Indicates if srvcc is going on. */
376     private boolean mIsSrvccHandoverInProcess = false;
377 
378     /**
379      * Indicates if the data services are bound. Key if the transport type, and value is the boolean
380      * indicating service is bound or not.
381      */
382     @NonNull
383     private final SparseBooleanArray mDataServiceBound = new SparseBooleanArray();
384 
385     /** SIM state. */
386     @SimState
387     private int mSimState = TelephonyManager.SIM_STATE_UNKNOWN;
388 
389     /** Data activity. */
390     @DataActivityType
391     private int mDataActivity = TelephonyManager.DATA_ACTIVITY_NONE;
392 
393     /**
394      * IMS state callbacks. Key is the IMS feature, value is the callback.
395      */
396     @NonNull
397     private final SparseArray<ImsStateCallback> mImsStateCallbacks = new SparseArray<>();
398 
399     /** Registered IMS features. Unregistered IMS features are removed from the set. */
400     @NonNull
401     private final Set<Integer> mRegisteredImsFeatures = new ArraySet<>();
402 
403     /** IMS feature package names. Key is the IMS feature, value is the package name. */
404     @NonNull
405     private final SparseArray<String> mImsFeaturePackageName = new SparseArray<>();
406 
407     /**
408      * Networks that are pending IMS de-registration. Key is the data network, value is the function
409      * to tear down the network.
410      */
411     @NonNull
412     private final Map<DataNetwork, Runnable> mPendingImsDeregDataNetworks = new ArrayMap<>();
413 
414     /**
415      * IMS feature registration callback. The key is the IMS feature, the value is the registration
416      * callback. When new SIM inserted, the old callbacks associated with the old subscription index
417      * will be unregistered.
418      */
419     @NonNull
420     private final SparseArray<RegistrationManager.RegistrationCallback>
421             mImsFeatureRegistrationCallbacks = new SparseArray<>();
422 
423     /** The counter to detect back to back release/request IMS network. */
424     @NonNull
425     private SlidingWindowEventCounter mImsThrottleCounter;
426     /** Event counter for unwanted network within time window, is used to trigger anomaly report. */
427     @NonNull
428     private SlidingWindowEventCounter mNetworkUnwantedCounter;
429     /** Event counter for WLAN setup data failure within time window to trigger anomaly report. */
430     @NonNull
431     private SlidingWindowEventCounter mSetupDataCallWlanFailureCounter;
432     /** Event counter for WWAN setup data failure within time window to trigger anomaly report. */
433     @NonNull
434     private SlidingWindowEventCounter mSetupDataCallWwanFailureCounter;
435 
436     /**
437      * The capabilities of the latest released IMS request. To detect back to back release/request
438      * IMS network.
439      */
440     private int[] mLastReleasedImsRequestCapabilities;
441 
442     /** True after try to release an IMS network; False after try to request an IMS network. */
443     private boolean mLastImsOperationIsRelease;
444 
445     @NonNull
446     private final FeatureFlags mFeatureFlags;
447 
448     /** The broadcast receiver. */
449     private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
450         @Override
451         public void onReceive(Context context, Intent intent) {
452             switch(intent.getAction()) {
453                 case TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED:
454                 case TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED:
455                     if (mPhone.getPhoneId() == intent.getIntExtra(
456                             SubscriptionManager.EXTRA_SLOT_INDEX,
457                             SubscriptionManager.INVALID_SIM_SLOT_INDEX)) {
458                         int simState = intent.getIntExtra(TelephonyManager.EXTRA_SIM_STATE,
459                                 TelephonyManager.SIM_STATE_UNKNOWN);
460                         sendMessage(obtainMessage(EVENT_SIM_STATE_CHANGED, simState, 0));
461                     }
462             }
463         }
464     };
465 
hasCalling()466     private boolean hasCalling() {
467         if (!TelephonyCapabilities.minimalTelephonyCdmCheck(mFeatureFlags)) return true;
468         return mPhone.getContext().getPackageManager().hasSystemFeature(
469             PackageManager.FEATURE_TELEPHONY_CALLING);
470     }
471 
472     /**
473      * The sorted network request list by priority. The highest priority network request stays at
474      * the head of the list. The highest priority is 100, the lowest is 0.
475      * <p>
476      * Note this list is not thread-safe. Do not access the list from different threads.
477      */
478     @VisibleForTesting
479     public static class NetworkRequestList extends LinkedList<TelephonyNetworkRequest> {
480         /**
481          * Constructor
482          */
NetworkRequestList()483         public NetworkRequestList() {
484         }
485 
486         /**
487          * Copy constructor
488          *
489          * @param requestList The network request list.
490          */
NetworkRequestList(@onNull NetworkRequestList requestList)491         public NetworkRequestList(@NonNull NetworkRequestList requestList) {
492             addAll(requestList);
493         }
494 
495         /**
496          * Constructor
497          *
498          * @param requestList The network request list.
499          */
NetworkRequestList(@onNull List<TelephonyNetworkRequest> requestList)500         public NetworkRequestList(@NonNull List<TelephonyNetworkRequest> requestList) {
501             addAll(requestList);
502         }
503 
504         /**
505          * Constructor
506          *
507          * @param newRequest The initial request of the list.
508          */
NetworkRequestList(@onNull TelephonyNetworkRequest newRequest)509         public NetworkRequestList(@NonNull TelephonyNetworkRequest newRequest) {
510             this();
511             add(newRequest);
512         }
513 
514         /**
515          * Add the network request to the list. Note that the item will be inserted to the position
516          * based on the priority.
517          *
518          * @param newRequest The network request to be added.
519          * @return {@code true} if added successfully. {@code false} if the request already exists.
520          */
521         @Override
add(@onNull TelephonyNetworkRequest newRequest)522         public boolean add(@NonNull TelephonyNetworkRequest newRequest) {
523             int index = 0;
524             while (index < size()) {
525                 TelephonyNetworkRequest networkRequest = get(index);
526                 if (networkRequest.equals(newRequest)) {
527                     return false;   // Do not allow duplicate
528                 }
529                 if (newRequest.getPriority() > networkRequest.getPriority()) {
530                     break;
531                 }
532                 index++;
533             }
534             super.add(index, newRequest);
535             return true;
536         }
537 
538         @Override
add(int index, @NonNull TelephonyNetworkRequest newRequest)539         public void add(int index, @NonNull TelephonyNetworkRequest newRequest) {
540             throw new UnsupportedOperationException("Insertion to certain position is illegal.");
541         }
542 
543         @Override
addAll(Collection<? extends TelephonyNetworkRequest> requests)544         public boolean addAll(Collection<? extends TelephonyNetworkRequest> requests) {
545             for (TelephonyNetworkRequest networkRequest : requests) {
546                 add(networkRequest);
547             }
548             return true;
549         }
550 
551         /**
552          * Get the first network request that contains all the provided network capabilities.
553          *
554          * @param netCaps The network capabilities.
555          * @return The first network request in the list that contains all the provided
556          * capabilities.
557          */
558         @Nullable
get(@onNull @etCapability int[] netCaps)559         public TelephonyNetworkRequest get(@NonNull @NetCapability int[] netCaps) {
560             int index = 0;
561             while (index < size()) {
562                 TelephonyNetworkRequest networkRequest = get(index);
563                 // Check if any network requests contains all the provided capabilities.
564                 if (Arrays.stream(networkRequest.getCapabilities())
565                         .boxed()
566                         .collect(Collectors.toSet())
567                         .containsAll(Arrays.stream(netCaps).boxed()
568                                 .toList())) {
569                     return networkRequest;
570                 }
571                 index++;
572             }
573             return null;
574         }
575 
576         /**
577          * Check if any network request is requested by the specified package.
578          *
579          * @param packageName The package name.
580          * @return {@code true} if any request is originated from the specified package.
581          */
hasNetworkRequestsFromPackage(@onNull String packageName)582         public boolean hasNetworkRequestsFromPackage(@NonNull String packageName) {
583             for (TelephonyNetworkRequest networkRequest : this) {
584                 if (packageName.equals(
585                         networkRequest.getNativeNetworkRequest().getRequestorPackageName())) {
586                     return true;
587                 }
588             }
589             return false;
590         }
591 
592         @Override
toString()593         public String toString() {
594             return "[NetworkRequestList: size=" + size() + (size() > 0 ? ", leading by "
595                     + get(0) : "") + "]";
596         }
597 
598         /**
599          * Print "capabilities - connectivity transport". e.g. INTERNET|NOT_RESTRICTED-SATELLITE
600          */
601         @NonNull
toStringSimplified()602         public String toStringSimplified() {
603             return size() > 0 ? DataUtils.networkCapabilitiesToString(get(0).getCapabilities())
604                     + "-" + DataUtils.connectivityTransportsToString(get(0).getTransportTypes())
605                     : "";
606         }
607 
608         /**
609          * Dump the network request list.
610          *
611          * @param pw print writer.
612          */
dump(IndentingPrintWriter pw)613         public void dump(IndentingPrintWriter pw) {
614             pw.increaseIndent();
615             for (TelephonyNetworkRequest networkRequest : this) {
616                 pw.println(networkRequest);
617             }
618             pw.decreaseIndent();
619         }
620     }
621 
622     /**
623      * The data network controller callback. Note this is only used for passing information
624      * internally in the data stack, should not be used externally.
625      */
626     public static class DataNetworkControllerCallback extends DataCallback {
627         /**
628          * Constructor
629          *
630          * @param executor The executor of the callback.
631          */
DataNetworkControllerCallback(@onNull @allbackExecutor Executor executor)632         public DataNetworkControllerCallback(@NonNull @CallbackExecutor Executor executor) {
633             super(executor);
634         }
635 
636         /**
637          * Called when internet data network validation status changed.
638          *
639          * @param validationStatus The validation status.
640          */
onInternetDataNetworkValidationStatusChanged( @alidationStatus int validationStatus)641         public void onInternetDataNetworkValidationStatusChanged(
642                 @ValidationStatus int validationStatus) {}
643 
644         /**
645          * Called when a network that's capable of internet is newly connected or disconnected.
646          *
647          * @param internetNetworks The connected internet data network. It should be only one in
648          *                         most of the cases.
649          */
onConnectedInternetDataNetworksChanged(@onNull Set<DataNetwork> internetNetworks)650         public void onConnectedInternetDataNetworksChanged(@NonNull Set<DataNetwork>
651                 internetNetworks) {}
652 
653         /**
654          * Called when data network is connected.
655          *
656          * @param transport Transport for the connected network.
657          * @param dataProfile The data profile of the connected data network.
658          */
onDataNetworkConnected(@ransportType int transport, @NonNull DataProfile dataProfile)659         public void onDataNetworkConnected(@TransportType int transport,
660                 @NonNull DataProfile dataProfile) {}
661 
662         /**
663          * Called when any data network existing status changed.
664          *
665          * @param anyDataExisting {@code true} indicating there is at least one data network
666          * existing regardless of its state. {@code false} indicating all data networks are
667          * disconnected.
668          */
onAnyDataNetworkExistingChanged(boolean anyDataExisting)669         public void onAnyDataNetworkExistingChanged(boolean anyDataExisting) {}
670 
671         /**
672          * Called when {@link SubscriptionPlan}s change or an unmetered or congested subscription
673          * override is set.
674          */
onSubscriptionPlanOverride()675         public void onSubscriptionPlanOverride() {}
676 
677         /**
678          * Called when the physical link status changed.
679          *
680          * @param status The latest link status.
681          */
onPhysicalLinkStatusChanged(@inkStatus int status)682         public void onPhysicalLinkStatusChanged(@LinkStatus int status) {}
683 
684         /**
685          * Called when NR advanced capable by PCO changed.
686          *
687          * @param nrAdvancedCapable {@code true} if at least one of the data network is NR advanced
688          * capable.
689          */
onNrAdvancedCapableByPcoChanged(boolean nrAdvancedCapable)690         public void onNrAdvancedCapableByPcoChanged(boolean nrAdvancedCapable) {}
691 
692         /**
693          * Called when data service is bound.
694          *
695          * @param transport The transport of the data service.
696          */
onDataServiceBound(@ransportType int transport)697         public void onDataServiceBound(@TransportType int transport) {}
698 
699         /**
700          * Called when QosBearerSessions changed.
701          *
702          * @param qosBearerSessions The latest QOS bearer sessions.
703          */
onQosSessionsChanged(@onNull List<QosBearerSession> qosBearerSessions)704         public void onQosSessionsChanged(@NonNull List<QosBearerSession> qosBearerSessions) {}
705     }
706 
707     /**
708      * This class represent a rule allowing or disallowing handover between IWLAN and cellular
709      * networks.
710      *
711      * @see CarrierConfigManager#KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY
712      */
713     public static class HandoverRule {
714         @Retention(RetentionPolicy.SOURCE)
715         @IntDef(prefix = {"RULE_TYPE_"},
716                 value = {
717                         RULE_TYPE_ALLOWED,
718                         RULE_TYPE_DISALLOWED,
719                 })
720         public @interface HandoverRuleType {}
721 
722         /** Indicating this rule is for allowing handover. */
723         public static final int RULE_TYPE_ALLOWED = 1;
724 
725         /** Indicating this rule is for disallowing handover. */
726         public static final int RULE_TYPE_DISALLOWED = 2;
727 
728         private static final String RULE_TAG_SOURCE_ACCESS_NETWORKS = "source";
729 
730         private static final String RULE_TAG_TARGET_ACCESS_NETWORKS = "target";
731 
732         private static final String RULE_TAG_TYPE = "type";
733 
734         private static final String RULE_TAG_CAPABILITIES = "capabilities";
735 
736         private static final String RULE_TAG_ROAMING = "roaming";
737 
738         private static final String RULE_TAG_INCALL = "incall";
739 
740         /** Handover rule type. */
741         @HandoverRuleType
742         public final int type;
743 
744         /** The applicable source access networks for handover. */
745         @NonNull
746         @RadioAccessNetworkType
747         public final Set<Integer> sourceAccessNetworks;
748 
749         /** The applicable target access networks for handover. */
750         @NonNull
751         @RadioAccessNetworkType
752         public final Set<Integer> targetAccessNetworks;
753 
754         /**
755          * The network capabilities to any of which this handover rule applies.
756          * If is empty, then capability is ignored as a rule matcher.
757          */
758         @NonNull
759         @NetCapability
760         public final Set<Integer> networkCapabilities;
761 
762         /** {@code true} indicates this policy is only applicable when the device is roaming. */
763         public final boolean isOnlyForRoaming;
764 
765         /** {@code true} indicates this policy is only applicable when the device is incall. */
766         public final boolean isOnlyForIncall;
767 
768         /**
769          * Constructor
770          *
771          * @param ruleString The rule in string format.
772          *
773          * @see CarrierConfigManager#KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY
774          */
HandoverRule(@onNull String ruleString, @NonNull FeatureFlags featureFlags)775         public HandoverRule(@NonNull String ruleString, @NonNull FeatureFlags featureFlags) {
776             if (TextUtils.isEmpty(ruleString)) {
777                 throw new IllegalArgumentException("illegal rule " + ruleString);
778             }
779 
780             Set<Integer> source = null, target = null, capabilities = Collections.emptySet();
781             int type = 0;
782             boolean roaming = false;
783             boolean incall = false;
784 
785             ruleString = ruleString.trim().toLowerCase(Locale.ROOT);
786             String[] expressions = ruleString.split("\\s*,\\s*");
787             for (String expression : expressions) {
788                 String[] tokens = expression.trim().split("\\s*=\\s*");
789                 if (tokens.length != 2) {
790                     throw new IllegalArgumentException("illegal rule " + ruleString + ", tokens="
791                             + Arrays.toString(tokens));
792                 }
793                 String key = tokens[0].trim();
794                 String value = tokens[1].trim();
795                 try {
796                     switch (key) {
797                         case RULE_TAG_SOURCE_ACCESS_NETWORKS:
798                             source = Arrays.stream(value.split("\\s*\\|\\s*"))
799                                     .map(String::trim)
800                                     .map(AccessNetworkType::fromString)
801                                     .collect(Collectors.toSet());
802                             break;
803                         case RULE_TAG_TARGET_ACCESS_NETWORKS:
804                             target = Arrays.stream(value.split("\\s*\\|\\s*"))
805                                     .map(String::trim)
806                                     .map(AccessNetworkType::fromString)
807                                     .collect(Collectors.toSet());
808                             break;
809                         case RULE_TAG_TYPE:
810                             if (value.toLowerCase(Locale.ROOT).equals("allowed")) {
811                                 type = RULE_TYPE_ALLOWED;
812                             } else if (value.toLowerCase(Locale.ROOT).equals("disallowed")) {
813                                 type = RULE_TYPE_DISALLOWED;
814                             } else {
815                                 throw new IllegalArgumentException("unexpected rule type " + value);
816                             }
817                             break;
818                         case RULE_TAG_CAPABILITIES:
819                             capabilities = DataUtils.getNetworkCapabilitiesFromString(value);
820                             break;
821                         case RULE_TAG_ROAMING:
822                             roaming = Boolean.parseBoolean(value);
823                             break;
824                         case RULE_TAG_INCALL:
825                             if (featureFlags.incallHandoverPolicy()) {
826                                 incall = Boolean.parseBoolean(value);
827                             }
828                             break;
829                         default:
830                             throw new IllegalArgumentException("unexpected key " + key);
831                     }
832                 } catch (Exception e) {
833                     e.printStackTrace();
834                     throw new IllegalArgumentException("illegal rule \"" + ruleString + "\", e="
835                             + e);
836                 }
837             }
838 
839             if (source == null || target == null || source.isEmpty() || target.isEmpty()) {
840                 throw new IllegalArgumentException("Need to specify both source and target. "
841                         + "\"" + ruleString + "\"");
842             }
843 
844             if (source.contains(AccessNetworkType.UNKNOWN) && type != RULE_TYPE_DISALLOWED) {
845                 throw new IllegalArgumentException("Unknown access network can be only specified in"
846                         + " the disallowed rule. \"" + ruleString + "\"");
847             }
848 
849             if (target.contains(AccessNetworkType.UNKNOWN)) {
850                 throw new IllegalArgumentException("Target access networks contains unknown. "
851                         + "\"" + ruleString + "\"");
852             }
853 
854             if (type == 0) {
855                 throw new IllegalArgumentException("Rule type is not specified correctly. "
856                         + "\"" + ruleString + "\"");
857             }
858 
859             if (capabilities != null && capabilities.contains(-1)) {
860                 throw new IllegalArgumentException("Network capabilities contains unknown. "
861                             + "\"" + ruleString + "\"");
862             }
863 
864             if (!source.contains(AccessNetworkType.IWLAN)
865                     && !target.contains(AccessNetworkType.IWLAN)) {
866                 throw new IllegalArgumentException("IWLAN must be specified in either source or "
867                         + "target access networks.\"" + ruleString + "\"");
868             }
869 
870             sourceAccessNetworks = source;
871             targetAccessNetworks = target;
872             this.type = type;
873             networkCapabilities = capabilities;
874             isOnlyForRoaming = roaming;
875             isOnlyForIncall = incall;
876         }
877 
878         @Override
toString()879         public String toString() {
880             return "[HandoverRule: type=" + (type == RULE_TYPE_ALLOWED ? "allowed"
881                     : "disallowed") + ", source=" + sourceAccessNetworks.stream()
882                     .map(AccessNetworkType::toString).collect(Collectors.joining("|"))
883                     + ", target=" + targetAccessNetworks.stream().map(AccessNetworkType::toString)
884                     .collect(Collectors.joining("|")) + ", isRoaming=" + isOnlyForRoaming
885                     + ", isIncall=" + isOnlyForIncall + ", capabilities="
886                     + DataUtils.networkCapabilitiesToString(networkCapabilities) + "]";
887         }
888     }
889 
890     /**
891      * Constructor
892      *
893      * @param phone The phone instance.
894      * @param looper The looper to be used by the handler. Currently the handler thread is the
895      * phone process's main thread.
896      * @param featureFlags The feature flag.
897      */
DataNetworkController(@onNull Phone phone, @NonNull Looper looper, @NonNull FeatureFlags featureFlags)898     public DataNetworkController(@NonNull Phone phone, @NonNull Looper looper,
899             @NonNull FeatureFlags featureFlags) {
900         super(looper);
901         mPhone = phone;
902         mFeatureFlags = featureFlags;
903         mLogTag = "DNC-" + mPhone.getPhoneId();
904         log("DataNetworkController created.");
905 
906         mAccessNetworksManager = phone.getAccessNetworksManager();
907         for (int transport : mAccessNetworksManager.getAvailableTransports()) {
908             mDataServiceManagers.put(transport, new DataServiceManager(mPhone, looper, transport));
909         }
910 
911         mDataConfigManager = new DataConfigManager(mPhone, looper, featureFlags);
912 
913         // ========== Anomaly counters ==========
914         mImsThrottleCounter = new SlidingWindowEventCounter(
915                 mDataConfigManager.getAnomalyImsReleaseRequestThreshold().timeWindow,
916                 mDataConfigManager.getAnomalyImsReleaseRequestThreshold().eventNumOccurrence);
917         mNetworkUnwantedCounter = new SlidingWindowEventCounter(
918                 mDataConfigManager.getAnomalyNetworkUnwantedThreshold().timeWindow,
919                 mDataConfigManager.getAnomalyNetworkUnwantedThreshold().eventNumOccurrence);
920         mSetupDataCallWlanFailureCounter = new SlidingWindowEventCounter(
921                 mDataConfigManager.getAnomalySetupDataCallThreshold().timeWindow,
922                 mDataConfigManager.getAnomalySetupDataCallThreshold().eventNumOccurrence);
923         mSetupDataCallWwanFailureCounter = new SlidingWindowEventCounter(
924                 mDataConfigManager.getAnomalySetupDataCallThreshold().timeWindow,
925                 mDataConfigManager.getAnomalySetupDataCallThreshold().eventNumOccurrence);
926         // ========================================
927 
928         mDataSettingsManager = TelephonyComponentFactory.getInstance().inject(
929                 DataSettingsManager.class.getName())
930                 .makeDataSettingsManager(mPhone, this, mFeatureFlags, looper,
931                         new DataSettingsManagerCallback(this::post) {
932                             @Override
933                             public void onDataEnabledChanged(boolean enabled,
934                                     @TelephonyManager.DataEnabledChangedReason int reason,
935                                     @NonNull String callingPackage) {
936                                 // If mobile data is enabled by the user, evaluate the unsatisfied
937                                 // network requests and then attempt to setup data networks to
938                                 // satisfy them. If mobile data is disabled, evaluate the existing
939                                 // data networks and see if they need to be torn down.
940                                 logl("onDataEnabledChanged: enabled=" + enabled);
941                                 sendMessage(obtainMessage(enabled
942                                                 ? EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS
943                                                 : EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
944                                         DataEvaluationReason.DATA_ENABLED_CHANGED));
945                             }
946                             @Override
947                             public void onDataEnabledOverrideChanged(boolean enabled,
948                                     @TelephonyManager.MobileDataPolicy int policy) {
949                                 // If data enabled override is enabled by the user, evaluate the
950                                 // unsatisfied network requests and then attempt to setup data
951                                 // networks to satisfy them. If data enabled override is disabled,
952                                 // evaluate the existing data networks and see if they need to be
953                                 // torn down.
954                                 logl("onDataEnabledOverrideChanged: enabled=" + enabled);
955                                 sendMessage(obtainMessage(enabled
956                                                 ? EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS
957                                                 : EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
958                                         DataEvaluationReason.DATA_ENABLED_OVERRIDE_CHANGED));
959                             }
960                             @Override
961                             public void onDataRoamingEnabledChanged(boolean enabled) {
962                                 // If data roaming is enabled by the user, evaluate the unsatisfied
963                                 // network requests and then attempt to setup data networks to
964                                 // satisfy them. If data roaming is disabled, evaluate the existing
965                                 // data networks and see if they need to be torn down.
966                                 logl("onDataRoamingEnabledChanged: enabled=" + enabled);
967                                 sendMessage(obtainMessage(enabled
968                                                 ? EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS
969                                                 : EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
970                                         DataEvaluationReason.ROAMING_ENABLED_CHANGED));
971                             }
972                         });
973         mDataProfileManager = TelephonyComponentFactory.getInstance().inject(
974                 DataProfileManager.class.getName())
975                 .makeDataProfileManager(mPhone, this, mDataServiceManagers
976                                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), looper,
977                         mFeatureFlags,
978                         new DataProfileManagerCallback(this::post) {
979                             @Override
980                             public void onDataProfilesChanged() {
981                                 sendMessage(
982                                         obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
983                                         DataEvaluationReason.DATA_PROFILES_CHANGED));
984                                 sendMessage(
985                                         obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
986                                         DataEvaluationReason.DATA_PROFILES_CHANGED));
987                             }
988                         });
989         mDataStallRecoveryManager = new DataStallRecoveryManager(mPhone, this, mDataServiceManagers
990                 .get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN), mFeatureFlags, looper,
991                 new DataStallRecoveryManagerCallback(this::post) {
992                     @Override
993                     public void onDataStallReestablishInternet() {
994                         DataNetworkController.this.onDataStallReestablishInternet();
995                     }
996                 });
997         mDataRetryManager = new DataRetryManager(mPhone, this,
998                 mDataServiceManagers, looper, mFeatureFlags,
999                 new DataRetryManagerCallback(this::post) {
1000                     @Override
1001                     public void onDataNetworkSetupRetry(
1002                             @NonNull DataSetupRetryEntry dataSetupRetryEntry) {
1003                         Objects.requireNonNull(dataSetupRetryEntry);
1004                         DataNetworkController.this.onDataNetworkSetupRetry(dataSetupRetryEntry);
1005                     }
1006                     @Override
1007                     public void onDataNetworkHandoverRetry(
1008                             @NonNull DataHandoverRetryEntry dataHandoverRetryEntry) {
1009                         Objects.requireNonNull(dataHandoverRetryEntry);
1010                         DataNetworkController.this
1011                                 .onDataNetworkHandoverRetry(dataHandoverRetryEntry);
1012                     }
1013                     @Override
1014                     public void onDataNetworkHandoverRetryStopped(
1015                             @NonNull DataNetwork dataNetwork) {
1016                         Objects.requireNonNull(dataNetwork);
1017                         DataNetworkController.this.onDataNetworkHandoverRetryStopped(dataNetwork);
1018                     }
1019                 });
1020         mImsManager = mPhone.getContext().getSystemService(ImsManager.class);
1021         mNetworkPolicyManager = mPhone.getContext().getSystemService(NetworkPolicyManager.class);
1022         mTelecomManager = mPhone.getContext().getSystemService(TelecomManager.class);
1023 
1024         // Use the raw one from ServiceStateTracker instead of the combined one from
1025         // mPhone.getServiceState().
1026         mServiceState = mPhone.getServiceStateTracker().getServiceState();
1027 
1028         // Instead of calling onRegisterAllEvents directly from the constructor, send the event.
1029         // The reason is that getImsPhone is null when we are still in the constructor here.
1030         sendEmptyMessage(EVENT_REGISTER_ALL_EVENTS);
1031     }
1032 
1033     /**
1034      * Called when needed to register for all events that data network controller is interested.
1035      */
onRegisterAllEvents()1036     private void onRegisterAllEvents() {
1037         IntentFilter filter = new IntentFilter();
1038         filter.addAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED);
1039         filter.addAction(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED);
1040         mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
1041 
1042         mAccessNetworksManager.registerCallback(new AccessNetworksManagerCallback(this::post) {
1043             @Override
1044             public void onPreferredTransportChanged(
1045                     @NetCapability int capability, boolean forceReconnect) {
1046                 int preferredTransport = mAccessNetworksManager
1047                         .getPreferredTransportByNetworkCapability(capability);
1048                 logl("onPreferredTransportChanged: "
1049                         + DataUtils.networkCapabilityToString(capability) + " preferred on "
1050                         + AccessNetworkConstants.transportTypeToString(preferredTransport)
1051                         + (forceReconnect ? "forceReconnect:true" : ""));
1052 
1053                 DataNetworkController.this.onEvaluatePreferredTransport(capability, forceReconnect);
1054                 if (!hasMessages(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS)) {
1055                     sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1056                             DataEvaluationReason.PREFERRED_TRANSPORT_CHANGED));
1057                 } else {
1058                     log("onPreferredTransportChanged: Skipped evaluating unsatisfied network "
1059                             + "requests because another evaluation was already scheduled.");
1060                 }
1061             }
1062         });
1063 
1064         mNetworkPolicyManager.registerSubscriptionCallback(new SubscriptionCallback() {
1065             @Override
1066             public void onSubscriptionPlansChanged(int subId, SubscriptionPlan[] plans) {
1067                 if (mSubId != subId) return;
1068                 obtainMessage(EVENT_SUBSCRIPTION_PLANS_CHANGED, plans).sendToTarget();
1069             }
1070 
1071             @Override
1072             public void onSubscriptionOverride(int subId, int overrideMask, int overrideValue,
1073                     int[] networkTypes) {
1074                 if (mSubId != subId) return;
1075                 obtainMessage(EVENT_SUBSCRIPTION_OVERRIDE, overrideMask, overrideValue,
1076                         networkTypes).sendToTarget();
1077             }
1078         });
1079 
1080         mPhone.getServiceStateTracker().registerForServiceStateChanged(this,
1081                 EVENT_SERVICE_STATE_CHANGED, null);
1082         mDataConfigManager.registerCallback(new DataConfigManagerCallback(this::post) {
1083             @Override
1084             public void onCarrierConfigChanged() {
1085                 DataNetworkController.this.onCarrierConfigUpdated();
1086             }
1087             @Override
1088             public void onDeviceConfigChanged() {
1089                 DataNetworkController.this.onDeviceConfigUpdated();
1090             }
1091         });
1092         mPhone.getServiceStateTracker().registerForPsRestrictedEnabled(this,
1093                 EVENT_PS_RESTRICT_ENABLED, null);
1094         mPhone.getServiceStateTracker().registerForPsRestrictedDisabled(this,
1095                 EVENT_PS_RESTRICT_DISABLED, null);
1096         mPhone.getServiceStateTracker().registerForAreaCodeChanged(this, EVENT_TAC_CHANGED, null);
1097         mPhone.registerForEmergencyCallToggle(this, EVENT_EMERGENCY_CALL_CHANGED, null);
1098         mDataServiceManagers.get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
1099                 .registerForServiceBindingChanged(this, EVENT_DATA_SERVICE_BINDING_CHANGED);
1100 
1101         mPhone.getServiceStateTracker().registerForServiceStateChanged(this,
1102                 EVENT_SERVICE_STATE_CHANGED, null);
1103         mDataServiceManagers.get(AccessNetworkConstants.TRANSPORT_TYPE_WLAN)
1104                 .registerForServiceBindingChanged(this, EVENT_DATA_SERVICE_BINDING_CHANGED);
1105 
1106         mPhone.getContext().getSystemService(TelephonyRegistryManager.class)
1107                 .addOnSubscriptionsChangedListener(new OnSubscriptionsChangedListener() {
1108                     @Override
1109                     public void onSubscriptionsChanged() {
1110                         sendEmptyMessage(EVENT_SUBSCRIPTION_CHANGED);
1111                     }
1112                 }, this::post);
1113 
1114         if (hasCalling()) {
1115             // Register for call ended event for voice/data concurrent not supported case. It is
1116             // intended to only listen for events from the same phone as most of the telephony
1117             // modules are designed as per-SIM basis. For DSDS call ended on non-DDS sub, the
1118             // frameworks relies on service state on DDS sub change from out-of-service to
1119             // in-service to trigger data retry.
1120             mPhone.getCallTracker().registerForVoiceCallEnded(this, EVENT_VOICE_CALL_ENDED, null);
1121             // Check null for devices not supporting FEATURE_TELEPHONY_IMS.
1122             if (mPhone.getImsPhone() != null) {
1123                 mPhone.getImsPhone().getCallTracker().registerForVoiceCallEnded(
1124                         this, EVENT_VOICE_CALL_ENDED, null);
1125             }
1126         }
1127         mPhone.mCi.registerForSlicingConfigChanged(this, EVENT_SLICE_CONFIG_CHANGED, null);
1128         mPhone.mCi.registerForSrvccStateChanged(this, EVENT_SRVCC_STATE_CHANGED, null);
1129 
1130         mPhone.getLinkBandwidthEstimator().registerCallback(
1131                 new LinkBandwidthEstimatorCallback(this::post) {
1132                     @Override
1133                     public void onDataActivityChanged(@DataActivityType int dataActivity) {
1134                         DataNetworkController.this.updateDataActivity();
1135                     }
1136                 }
1137         );
1138     }
1139 
1140     @Override
handleMessage(@onNull Message msg)1141     public void handleMessage(@NonNull Message msg) {
1142         AsyncResult ar;
1143         switch (msg.what) {
1144             case EVENT_REGISTER_ALL_EVENTS:
1145                 onRegisterAllEvents();
1146                 break;
1147             case EVENT_ADD_NETWORK_REQUEST:
1148                 onAddNetworkRequest((TelephonyNetworkRequest) msg.obj);
1149                 break;
1150             case EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS:
1151                 DataEvaluationReason reason = (DataEvaluationReason) msg.obj;
1152                 onReevaluateUnsatisfiedNetworkRequests(reason);
1153                 break;
1154             case EVENT_REEVALUATE_EXISTING_DATA_NETWORKS:
1155                 reason = (DataEvaluationReason) msg.obj;
1156                 onReevaluateExistingDataNetworks(reason);
1157                 break;
1158             case EVENT_REMOVE_NETWORK_REQUEST:
1159                 onRemoveNetworkRequest((TelephonyNetworkRequest) msg.obj);
1160                 break;
1161             case EVENT_VOICE_CALL_ENDED:
1162                 // In some cases we need to tear down network after call ends. For example, when
1163                 // delay IMS tear down until call ends is turned on.
1164                 sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
1165                         DataEvaluationReason.VOICE_CALL_ENDED));
1166                 // Delay evaluating unsatisfied network requests. In temporary DDS switch case, it
1167                 // takes some time to switch DDS after call end. We do not want to bring up network
1168                 // before switch completes.
1169                 sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1170                         DataEvaluationReason.VOICE_CALL_ENDED),
1171                         REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_AFTER_CALL_END_DELAY_MILLIS);
1172                 break;
1173             case EVENT_SLICE_CONFIG_CHANGED:
1174                 sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1175                         DataEvaluationReason.SLICE_CONFIG_CHANGED));
1176                 break;
1177             case EVENT_SRVCC_STATE_CHANGED:
1178                 ar = (AsyncResult) msg.obj;
1179                 if (ar.exception == null) {
1180                     onSrvccStateChanged((int[]) ar.result);
1181                 }
1182                 break;
1183             case EVENT_PS_RESTRICT_ENABLED:
1184                 mPsRestricted = true;
1185                 break;
1186             case EVENT_PS_RESTRICT_DISABLED:
1187                 mPsRestricted = false;
1188                 sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1189                         DataEvaluationReason.DATA_RESTRICTED_CHANGED));
1190                 break;
1191             case EVENT_TAC_CHANGED:
1192                 // Re-evaluate unsatisfied network requests with some delays to let DataRetryManager
1193                 // clears the throttling record.
1194                 sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1195                         DataEvaluationReason.TAC_CHANGED),
1196                         REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_TAC_CHANGED_DELAY_MILLIS);
1197                 break;
1198             case EVENT_DATA_SERVICE_BINDING_CHANGED:
1199                 ar = (AsyncResult) msg.obj;
1200                 int transport = (int) ar.userObj;
1201                 boolean bound = (boolean) ar.result;
1202                 onDataServiceBindingChanged(transport, bound);
1203                 break;
1204             case EVENT_SIM_STATE_CHANGED:
1205                 int simState = msg.arg1;
1206                 onSimStateChanged(simState);
1207                 break;
1208             case EVENT_TEAR_DOWN_ALL_DATA_NETWORKS:
1209                 onTearDownAllDataNetworks(msg.arg1);
1210                 break;
1211             case EVENT_REGISTER_DATA_NETWORK_CONTROLLER_CALLBACK:
1212                 DataNetworkControllerCallback callback = (DataNetworkControllerCallback) msg.obj;
1213                 mDataNetworkControllerCallbacks.add(callback);
1214                 // Notify upon registering if no data networks currently exist.
1215                 if (mDataNetworkList.isEmpty()) {
1216                     callback.invokeFromExecutor(
1217                             () -> callback.onAnyDataNetworkExistingChanged(false));
1218                 }
1219                 break;
1220             case EVENT_UNREGISTER_DATA_NETWORK_CONTROLLER_CALLBACK:
1221                 mDataNetworkControllerCallbacks.remove((DataNetworkControllerCallback) msg.obj);
1222                 break;
1223             case EVENT_SUBSCRIPTION_CHANGED:
1224                 onSubscriptionChanged();
1225                 break;
1226             case EVENT_SERVICE_STATE_CHANGED:
1227                 onServiceStateChanged();
1228                 break;
1229             case EVENT_EMERGENCY_CALL_CHANGED:
1230                 if (mPhone.isInEcm()) {
1231                     sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
1232                             DataEvaluationReason.EMERGENCY_CALL_CHANGED));
1233                 } else {
1234                     sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
1235                             DataEvaluationReason.EMERGENCY_CALL_CHANGED));
1236                 }
1237                 break;
1238             case EVENT_EVALUATE_PREFERRED_TRANSPORT:
1239                 onEvaluatePreferredTransport(msg.arg1, msg.arg2 != 0 /* forceReconnect */);
1240                 break;
1241             case EVENT_SUBSCRIPTION_PLANS_CHANGED:
1242                 SubscriptionPlan[] plans = (SubscriptionPlan[]) msg.obj;
1243                 log("Subscription plans changed: " + Arrays.toString(plans));
1244                 mSubscriptionPlans.clear();
1245                 mSubscriptionPlans.addAll(Arrays.asList(plans));
1246                 mDataNetworkControllerCallbacks.forEach(cb -> cb.invokeFromExecutor(
1247                         cb::onSubscriptionPlanOverride));
1248                 break;
1249             case EVENT_SUBSCRIPTION_OVERRIDE:
1250                 int overrideMask = msg.arg1;
1251                 boolean override = msg.arg2 != 0;
1252                 int[] networkTypes = (int[]) msg.obj;
1253 
1254                 if (overrideMask == NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_UNMETERED) {
1255                     log("Unmetered subscription override: override=" + override
1256                             + ", networkTypes=" + Arrays.stream(networkTypes)
1257                             .mapToObj(TelephonyManager::getNetworkTypeName)
1258                             .collect(Collectors.joining(",")));
1259                     for (int networkType : networkTypes) {
1260                         if (override) {
1261                             mUnmeteredOverrideNetworkTypes.add(networkType);
1262                         } else {
1263                             mUnmeteredOverrideNetworkTypes.remove(networkType);
1264                         }
1265                     }
1266                     mDataNetworkControllerCallbacks.forEach(cb -> cb.invokeFromExecutor(
1267                             cb::onSubscriptionPlanOverride));
1268                 } else if (overrideMask == NetworkPolicyManager.SUBSCRIPTION_OVERRIDE_CONGESTED) {
1269                     log("Congested subscription override: override=" + override
1270                             + ", networkTypes=" + Arrays.stream(networkTypes)
1271                             .mapToObj(TelephonyManager::getNetworkTypeName)
1272                             .collect(Collectors.joining(",")));
1273                     for (int networkType : networkTypes) {
1274                         if (override) {
1275                             mCongestedOverrideNetworkTypes.add(networkType);
1276                         } else {
1277                             mCongestedOverrideNetworkTypes.remove(networkType);
1278                         }
1279                     }
1280                     mDataNetworkControllerCallbacks.forEach(cb -> cb.invokeFromExecutor(
1281                             cb::onSubscriptionPlanOverride));
1282                 } else {
1283                     loge("Unknown override mask: " + overrideMask);
1284                 }
1285                 break;
1286             default:
1287                 loge("Unexpected event " + msg.what);
1288         }
1289     }
1290 
1291     /**
1292      * Add a network request, which is originated from the apps. Note that add a network request
1293      * is not necessarily setting up a {@link DataNetwork}.
1294      *
1295      * @param networkRequest Network request
1296      *
1297      */
addNetworkRequest(@onNull TelephonyNetworkRequest networkRequest)1298     public void addNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest) {
1299         sendMessage(obtainMessage(EVENT_ADD_NETWORK_REQUEST, networkRequest));
1300     }
1301 
1302     /**
1303      * Called when a network request arrives data network controller.
1304      *
1305      * @param networkRequest The network request.
1306      */
onAddNetworkRequest(@onNull TelephonyNetworkRequest networkRequest)1307     private void onAddNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest) {
1308         // TelephonyNetworkRequest at TelephonyNetworkProvider layer does not have config assigned
1309         // (Because TelephonyNetworkProvider is a singleton across all SIMs. We are not able to
1310         // retrieve the right carrier config for it.). So as soon as the request arrives
1311         // DataNetworkController, we need to update the config in the request so it can update
1312         // some of its config-dependent properties like request priority.
1313         networkRequest.updateDataConfig(mDataConfigManager);
1314 
1315         // To detect IMS back-to-back release-request anomaly event
1316         if (mLastImsOperationIsRelease) {
1317             mLastImsOperationIsRelease = false;
1318             if (Arrays.equals(
1319                     mLastReleasedImsRequestCapabilities, networkRequest.getCapabilities())
1320                     && mImsThrottleCounter.addOccurrence()) {
1321                 reportAnomaly(networkRequest.getNativeNetworkRequest().getRequestorPackageName()
1322                                 + " requested with same capabilities "
1323                                 + mImsThrottleCounter.getFrequencyString(),
1324                         "ead6f8db-d2f2-4ed3-8da5-1d8560fe7daf");
1325             }
1326         }
1327         if (!mAllNetworkRequestList.add(networkRequest)) {
1328             loge("onAddNetworkRequest: Duplicate network request. " + networkRequest);
1329             return;
1330         }
1331         log("onAddNetworkRequest: added " + networkRequest);
1332         onSatisfyNetworkRequest(networkRequest);
1333     }
1334 
1335     /**
1336      * Called when attempting to satisfy a network request. If after evaluation, the network
1337      * request is determined that can be satisfied, the data network controller will establish
1338      * the data network. If the network request can't be satisfied, it will remain in the
1339      * unsatisfied pool until the environment changes.
1340      *
1341      * @param networkRequest The network request to be satisfied.
1342      */
onSatisfyNetworkRequest(@onNull TelephonyNetworkRequest networkRequest)1343     private void onSatisfyNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest) {
1344         if (networkRequest.getState() == TelephonyNetworkRequest.REQUEST_STATE_SATISFIED) {
1345             logv("Already satisfied. " + networkRequest);
1346             return;
1347         }
1348 
1349         // Check if there is any existing data network that can satisfy the network request, and
1350         // attempt to attach if possible.
1351         if (findCompatibleDataNetworkAndAttach(networkRequest)) {
1352             return;
1353         }
1354 
1355         // If no data network can satisfy the requests, then start the evaluation process. Since
1356         // all the requests in the list have the same capabilities, we can only evaluate one
1357         // of them.
1358         DataEvaluation evaluation = evaluateNetworkRequest(networkRequest,
1359                 DataEvaluationReason.NEW_REQUEST);
1360         if (!evaluation.containsDisallowedReasons()) {
1361             DataProfile dataProfile = evaluation.getCandidateDataProfile();
1362             if (dataProfile != null) {
1363                 setupDataNetwork(dataProfile, null,
1364                         evaluation.getDataAllowedReason());
1365             }
1366         } else if (evaluation.contains(DataDisallowedReason.ONLY_ALLOWED_SINGLE_NETWORK)) {
1367             // Re-evaluate the existing data networks. If this request's priority is higher than
1368             // the existing data network, the data network will be torn down so this request will
1369             // get a chance to be satisfied.
1370             sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
1371                     DataEvaluationReason.SINGLE_DATA_NETWORK_ARBITRATION));
1372         }
1373     }
1374 
1375     /**
1376      * Attempt to attach a network request to an existing data network that can satisfy the
1377      * network request.
1378      *
1379      * @param networkRequest The network request to attach.
1380      *
1381      * @return {@code false} if can't find the data network to to satisfy the network request.
1382      * {@code true} if the network request has been scheduled to attach to the data network.
1383      * If attach succeeds, the network request's state will be set to
1384      * {@link TelephonyNetworkRequest#REQUEST_STATE_SATISFIED}. If failed,
1385      * {@link #onAttachNetworkRequestsFailed(DataNetwork, NetworkRequestList)} will be invoked.
1386      */
findCompatibleDataNetworkAndAttach( @onNull TelephonyNetworkRequest networkRequest)1387     private boolean findCompatibleDataNetworkAndAttach(
1388             @NonNull TelephonyNetworkRequest networkRequest) {
1389         return findCompatibleDataNetworkAndAttach(new NetworkRequestList(networkRequest));
1390     }
1391 
1392     /**
1393      * Attempt to attach a network request list to an existing data network that can satisfy all the
1394      * network requests. Note this method does not support partial attach (i.e. Only attach some
1395      * of the satisfiable requests to the network). All requests must be satisfied so they can be
1396      * attached.
1397      *
1398      * @param requestList The network request list to attach. It is expected that every network
1399      * request in this list has the same network capabilities.
1400      *
1401      * @return {@code false} if can't find the data network to to satisfy the network requests, even
1402      * if only one of network request can't be satisfied. {@code true} if the network request
1403      * has been scheduled to attach to the data network. If attach succeeds, the network request's
1404      * state will be set to
1405      * {@link TelephonyNetworkRequest#REQUEST_STATE_SATISFIED}. If failed,
1406      * {@link #onAttachNetworkRequestsFailed(DataNetwork, NetworkRequestList)} will be invoked.
1407      */
findCompatibleDataNetworkAndAttach(@onNull NetworkRequestList requestList)1408     private boolean findCompatibleDataNetworkAndAttach(@NonNull NetworkRequestList requestList) {
1409         if (requestList.isEmpty()) return false;
1410         // Try to find a data network that can satisfy all the network requests.
1411         for (DataNetwork dataNetwork : mDataNetworkList) {
1412             TelephonyNetworkRequest networkRequest = requestList.stream()
1413                     .filter(request -> !request.canBeSatisfiedBy(
1414                             dataNetwork.getNetworkCapabilities()))
1415                     .findAny()
1416                     .orElse(null);
1417             // If found any request that can't be satisfied by this data network, continue to try
1418             // next data network. We must find a data network that can satisfy all the provided
1419             // network requests.
1420             if (networkRequest != null) {
1421                 continue;
1422             }
1423 
1424             // When reaching here, it means this data network can satisfy all the network requests.
1425             logv("Found a compatible data network " + dataNetwork + ". Attaching "
1426                     + requestList);
1427             return dataNetwork.attachNetworkRequests(requestList);
1428         }
1429         return false;
1430     }
1431 
1432     /**
1433      * @param ss The service state to be checked
1434      * @param transport The transport is used to determine the data registration state
1435      *
1436      * @return {@code true} if data is in service or if voice is in service on legacy CS
1437      * connections (2G/3G) on the non-DDS. In those cases we attempt to attach PS. We don't try for
1438      * newer RAT because for those PS attach already occurred.
1439      */
serviceStateAllowsPSAttach(@onNull ServiceState ss, @TransportType int transport)1440     private boolean serviceStateAllowsPSAttach(@NonNull ServiceState ss,
1441             @TransportType int transport) {
1442         // Use the data registration state from the modem instead of the current data registration
1443         // state, which can be overridden.
1444         int nriRegState = getDataRegistrationState(ss, transport);
1445         if (nriRegState == NetworkRegistrationInfo.REGISTRATION_STATE_HOME
1446                 || nriRegState == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING) return true;
1447 
1448         // If data is OOS as this device slot is not modem preferred(i.e. not active for internet),
1449         // attempt to attach PS on 2G/3G if CS connection is available.
1450         return ss.getVoiceRegState() == ServiceState.STATE_IN_SERVICE
1451                 && mPhone.getPhoneId() != PhoneSwitcher.getInstance().getPreferredDataPhoneId()
1452                 && isLegacyCs(ss.getVoiceNetworkType());
1453     }
1454 
1455     /**
1456      * @param voiceNetworkType The voice network type to be checked.
1457      * @return {@code true} if the network type is on legacy CS connection.
1458      */
isLegacyCs(@etworkType int voiceNetworkType)1459     private boolean isLegacyCs(@NetworkType int voiceNetworkType) {
1460         int voiceAccessNetworkType = DataUtils.networkTypeToAccessNetworkType(voiceNetworkType);
1461         return voiceAccessNetworkType == AccessNetworkType.GERAN
1462                 || voiceAccessNetworkType == AccessNetworkType.UTRAN
1463                 || voiceAccessNetworkType == AccessNetworkType.CDMA2000;
1464     }
1465 
1466     /**
1467      * @return {@code true} if the network only allows single data network at one time.
1468      */
isOnlySingleDataNetworkAllowed(@ransportType int transport)1469     private boolean isOnlySingleDataNetworkAllowed(@TransportType int transport) {
1470         if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) return false;
1471 
1472         return mDataConfigManager.getNetworkTypesOnlySupportSingleDataNetwork()
1473                 .contains(getDataNetworkType(transport));
1474     }
1475 
1476     /**
1477      * @param capabilities The Network Capabilities to be checked.
1478      * @return {@code true} if the capabilities contain any capability that's exempt from the single
1479      * PDN rule.
1480      */
hasCapabilityExemptsFromSinglePdnRule(@etCapability int[] capabilities)1481     private boolean hasCapabilityExemptsFromSinglePdnRule(@NetCapability int[] capabilities) {
1482         Set<Integer> exemptCapabilities =
1483                 mDataConfigManager.getCapabilitiesExemptFromSingleDataNetwork();
1484         return Arrays.stream(capabilities).anyMatch(exemptCapabilities::contains);
1485     }
1486 
1487     /**
1488      * Evaluate if telephony frameworks would allow data setup for internet in current environment.
1489      *
1490      * @param ignoreExistingNetworks {@code true} to skip the existing network check.
1491      * @return {@code true} if the environment is allowed for internet data. {@code false} if not
1492      * allowed. For example, if SIM is absent, or airplane mode is on, then data is NOT allowed.
1493      * This API does not reflect the currently internet data network status. It's possible there is
1494      * no internet data due to weak cellular signal or network side issue, but internet data is
1495      * still allowed in this case.
1496      */
isInternetDataAllowed(boolean ignoreExistingNetworks)1497     public boolean isInternetDataAllowed(boolean ignoreExistingNetworks) {
1498         return !getInternetEvaluation(ignoreExistingNetworks).containsDisallowedReasons();
1499     }
1500 
1501     /**
1502      * @param ignoreExistingNetworks {@code true} to skip the existing network check.
1503      * @return The internet evaluation result.
1504      * For example, if SIM is absent, or airplane mode is on, then data is NOT allowed.
1505      * This API does not reflect the currently internet data network status. It's possible there is
1506      * no internet data due to weak cellular signal or network side issue, but internet data is
1507      * still allowed in this case.
1508      */
1509     @NonNull
getInternetEvaluation(boolean ignoreExistingNetworks)1510     public DataEvaluation getInternetEvaluation(boolean ignoreExistingNetworks) {
1511         TelephonyNetworkRequest internetRequest = new TelephonyNetworkRequest(
1512                 new NetworkRequest.Builder()
1513                         .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1514                         .build(), mPhone, mFeatureFlags);
1515         // If we don't skip checking existing network, then we should check If one of the
1516         // existing networks can satisfy the internet request, then internet is allowed.
1517         if (!ignoreExistingNetworks && mDataNetworkList.stream().anyMatch(
1518                 dataNetwork -> internetRequest.canBeSatisfiedBy(
1519                         dataNetwork.getNetworkCapabilities()))) {
1520             return new DataEvaluation(DataEvaluationReason.EXTERNAL_QUERY);
1521         }
1522 
1523         // If no existing network can satisfy the request, then check if we can possibly setup
1524         // the internet network.
1525 
1526         DataEvaluation evaluation = evaluateNetworkRequest(internetRequest,
1527                 DataEvaluationReason.EXTERNAL_QUERY);
1528         if (evaluation.containsOnly(DataDisallowedReason.ONLY_ALLOWED_SINGLE_NETWORK)
1529                 && internetRequest.getPriority() > mDataNetworkList.stream()
1530                 .map(DataNetwork::getPriority)
1531                 .max(Comparator.comparing(Integer::valueOf))
1532                 .orElse(0)) {
1533             // If the only failed reason is only single network allowed, then check if the request
1534             // can trump the current network.
1535             evaluation.addDataAllowedReason(DataAllowedReason.NORMAL);
1536         }
1537         return evaluation;
1538     }
1539 
1540 
1541     /**
1542      * @return {@code true} if internet is unmetered.
1543      */
isInternetUnmetered()1544     public boolean isInternetUnmetered() {
1545         return mDataNetworkList.stream()
1546                 .filter(dataNetwork -> !dataNetwork.isConnecting() && !dataNetwork.isDisconnected())
1547                 .filter(DataNetwork::isInternetSupported)
1548                 .allMatch(dataNetwork -> dataNetwork.getNetworkCapabilities()
1549                         .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
1550                         || dataNetwork.getNetworkCapabilities()
1551                         .hasCapability(NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
1552     }
1553 
1554     /**
1555      * @return {@code true} if all data networks are disconnected.
1556      */
areAllDataDisconnected()1557     public boolean areAllDataDisconnected() {
1558         if (!mDataNetworkList.isEmpty()) {
1559             log("areAllDataDisconnected false due to: " + mDataNetworkList.stream()
1560                     .map(DataNetwork::name).collect(Collectors.joining(", ")));
1561         }
1562         return mDataNetworkList.isEmpty();
1563     }
1564 
1565     /**
1566      * @return List of the reasons why internet data is not allowed. An empty list if internet
1567      * is allowed.
1568      */
1569     @NonNull
getInternetDataDisallowedReasons()1570     public List<DataDisallowedReason> getInternetDataDisallowedReasons() {
1571         TelephonyNetworkRequest internetRequest = new TelephonyNetworkRequest(
1572                 new NetworkRequest.Builder()
1573                         .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1574                         .build(), mPhone, mFeatureFlags);
1575         DataEvaluation evaluation = evaluateNetworkRequest(internetRequest,
1576                 DataEvaluationReason.EXTERNAL_QUERY);
1577         return evaluation.getDataDisallowedReasons();
1578     }
1579 
1580     /**
1581      * Evaluate a network request. The goal is to find a suitable {@link DataProfile} that can be
1582      * used to setup the data network.
1583      *
1584      * @param networkRequest The network request to evaluate.
1585      * @param reason The reason for evaluation.
1586      * @return The data evaluation result.
1587      */
1588     @NonNull
1589     @VisibleForTesting
evaluateNetworkRequest( @onNull TelephonyNetworkRequest networkRequest, DataEvaluationReason reason)1590     public DataEvaluation evaluateNetworkRequest(
1591             @NonNull TelephonyNetworkRequest networkRequest, DataEvaluationReason reason) {
1592         DataEvaluation evaluation = new DataEvaluation(reason);
1593         int transport = mAccessNetworksManager.getPreferredTransportByNetworkCapability(
1594                 networkRequest.getHighestPriorityApnTypeNetworkCapability());
1595 
1596         // Check if the request can be satisfied by cellular network or satellite network.
1597         if (!canConnectivityTransportSatisfyNetworkRequest(networkRequest, transport)) {
1598             evaluation.addDataDisallowedReason(
1599                     DataDisallowedReason.DATA_NETWORK_TRANSPORT_NOT_ALLOWED);
1600         }
1601 
1602         // Bypass all checks for emergency network request.
1603         if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_EIMS)) {
1604             DataProfile emergencyProfile = mDataProfileManager.getDataProfileForNetworkRequest(
1605                     networkRequest, getDataNetworkType(transport),
1606                     mServiceState.isUsingNonTerrestrialNetwork(),
1607                     false /*isEsimBootStrapProvisioning*/, true);
1608 
1609             // Check if the profile is being throttled.
1610             if (mDataConfigManager.shouldHonorRetryTimerForEmergencyNetworkRequest()
1611                     && emergencyProfile != null
1612                     && mDataRetryManager.isDataProfileThrottled(emergencyProfile, transport)) {
1613                 evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_THROTTLED);
1614                 log("Emergency network request is throttled by the previous setup data "
1615                             + "call response.");
1616             }
1617 
1618             if (!evaluation.containsDisallowedReasons()) {
1619                 evaluation.addDataAllowedReason(DataAllowedReason.EMERGENCY_REQUEST);
1620                 if (emergencyProfile != null) {
1621                     evaluation.setCandidateDataProfile(emergencyProfile);
1622                 }
1623             }
1624             networkRequest.setEvaluation(evaluation);
1625             log(evaluation.toString());
1626             return evaluation;
1627         }
1628 
1629         if (!serviceStateAllowsPSAttach(mServiceState, transport)) {
1630             evaluation.addDataDisallowedReason(DataDisallowedReason.NOT_IN_SERVICE);
1631         }
1632 
1633         // Check SIM state
1634         if (mSimState != TelephonyManager.SIM_STATE_LOADED) {
1635             evaluation.addDataDisallowedReason(DataDisallowedReason.SIM_NOT_READY);
1636         }
1637 
1638         // Check if carrier specific config is loaded or not.
1639         if (!mDataConfigManager.isConfigCarrierSpecific()) {
1640             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_CONFIG_NOT_READY);
1641         }
1642 
1643         if (mFeatureFlags.dataServiceCheck()) {
1644             NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
1645                     NetworkRegistrationInfo.DOMAIN_PS, transport);
1646             if (nri != null && !nri.getAvailableServices().contains(
1647                     NetworkRegistrationInfo.SERVICE_TYPE_DATA)) {
1648                 evaluation.addDataDisallowedReason(
1649                         DataDisallowedReason.SERVICE_OPTION_NOT_SUPPORTED);
1650             }
1651         }
1652 
1653         // Check CS call state and see if concurrent voice/data is allowed.
1654         if (hasCalling() && mPhone.getCallTracker().getState() != PhoneConstants.State.IDLE
1655                 && !mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
1656             evaluation.addDataDisallowedReason(
1657                     DataDisallowedReason.CONCURRENT_VOICE_DATA_NOT_ALLOWED);
1658         }
1659 
1660         // Check VoPS support
1661         if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN
1662                 && networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL)) {
1663             NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
1664                     NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
1665             if (nri != null) {
1666                 DataSpecificRegistrationInfo dsri = nri.getDataSpecificInfo();
1667                 if (dsri != null && dsri.getVopsSupportInfo() != null
1668                         && !dsri.getVopsSupportInfo().isVopsSupported()
1669                         && !mDataConfigManager.allowBringUpNetworkInNonVops(
1670                                 nri.getNetworkRegistrationState())) {
1671                     evaluation.addDataDisallowedReason(DataDisallowedReason.VOPS_NOT_SUPPORTED);
1672                 }
1673             }
1674         }
1675 
1676         // Check if default data is selected.
1677         if (!SubscriptionManager.isValidSubscriptionId(
1678                 SubscriptionManager.getDefaultDataSubscriptionId())) {
1679             evaluation.addDataDisallowedReason(DataDisallowedReason.DEFAULT_DATA_UNSELECTED);
1680         }
1681 
1682         // Check if data roaming is disabled.
1683         // But if the data roaming setting for satellite connection is ignored as the satellite
1684         // data plan is included in the user mobile plan, then we should not disallow data due to
1685         // roaming disabled.
1686         if (mServiceState.getDataRoaming() && !mDataSettingsManager.isDataRoamingEnabled()
1687                     && !shouldIgnoreDataRoamingSettingForSatellite()) {
1688             evaluation.addDataDisallowedReason(DataDisallowedReason.ROAMING_DISABLED);
1689         }
1690 
1691         // Check if data is restricted by the cellular network.
1692         if (mPsRestricted && transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
1693             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_RESTRICTED_BY_NETWORK);
1694         }
1695 
1696         // Check if there are pending tear down all networks request.
1697         if (mPhone.getServiceStateTracker().isPendingRadioPowerOffAfterDataOff()) {
1698             evaluation.addDataDisallowedReason(DataDisallowedReason.PENDING_TEAR_DOWN_ALL);
1699         }
1700 
1701         // Check if the request is preferred on cellular and radio is/will be turned off.
1702         // We are using getDesiredPowerState() instead of isRadioOn() because we also don't want
1703         // to setup data network when radio power is about to be turned off.
1704         if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN
1705                 && (!mPhone.getServiceStateTracker().getDesiredPowerState()
1706                 || mPhone.mCi.getRadioState() != TelephonyManager.RADIO_POWER_ON)) {
1707             evaluation.addDataDisallowedReason(DataDisallowedReason.RADIO_POWER_OFF);
1708         }
1709 
1710         // Check if radio is/will be turned off by carrier.
1711         if (!mPhone.getServiceStateTracker().getPowerStateFromCarrier()) {
1712             evaluation.addDataDisallowedReason(DataDisallowedReason.RADIO_DISABLED_BY_CARRIER);
1713         }
1714 
1715         // Check if the underlying data service is bound.
1716         if (!mDataServiceBound.get(transport)) {
1717             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_SERVICE_NOT_READY);
1718         }
1719 
1720         // Check if device is in CDMA ECBM
1721         if (mPhone.isInCdmaEcm()) {
1722             evaluation.addDataDisallowedReason(DataDisallowedReason.CDMA_EMERGENCY_CALLBACK_MODE);
1723         }
1724 
1725         // Check if only one data network is allowed.
1726         if (isOnlySingleDataNetworkAllowed(transport)
1727                 && !hasCapabilityExemptsFromSinglePdnRule(networkRequest.getCapabilities())) {
1728             // if exists not-exempt network.
1729             if (mDataNetworkList.stream()
1730                     .anyMatch(dataNetwork -> !hasCapabilityExemptsFromSinglePdnRule(
1731                             dataNetwork.getNetworkCapabilities().getCapabilities()))) {
1732                 evaluation.addDataDisallowedReason(
1733                         DataDisallowedReason.ONLY_ALLOWED_SINGLE_NETWORK);
1734             }
1735         }
1736 
1737         if (mDataSettingsManager.isDataInitialized()) {
1738             if (!mDataSettingsManager.isDataEnabled(DataUtils.networkCapabilityToApnType(
1739                     networkRequest.getHighestPriorityApnTypeNetworkCapability()))) {
1740                 evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_DISABLED);
1741             }
1742         } else {
1743             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_SETTINGS_NOT_READY);
1744         }
1745 
1746         // Check whether to allow data in certain situations if data is disallowed for soft reasons
1747         if (!evaluation.containsDisallowedReasons()) {
1748             evaluation.addDataAllowedReason(DataAllowedReason.NORMAL);
1749 
1750             if (!mDataSettingsManager.isDataEnabled()
1751                     && networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
1752                     && mDataSettingsManager.isMobileDataPolicyEnabled(TelephonyManager
1753                     .MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED)) {
1754                 // We reach here when data is disabled, but MMS always-allowed is enabled.
1755                 // (Note that isDataEnabled(ApnSetting.TYPE_MMS) returns true in this case, so it
1756                 // would not generate any soft disallowed reason. We need to explicitly handle it.)
1757                 evaluation.addDataAllowedReason(DataAllowedReason.MMS_REQUEST);
1758             }
1759         } else if (!evaluation.containsHardDisallowedReasons()) {
1760             if ((mTelecomManager.isInEmergencyCall() || mPhone.isInEcm())
1761                     && networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1762                 // Check if it's SUPL during emergency call.
1763                 evaluation.addDataAllowedReason(DataAllowedReason.EMERGENCY_SUPL);
1764             } else if (!networkRequest.hasCapability(
1765                     NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
1766                     && isValidRestrictedRequest(networkRequest)) {
1767                 // Check if request is restricted and not for tethering, which always comes with
1768                 // a restricted network request.
1769                 evaluation.addDataAllowedReason(DataAllowedReason.RESTRICTED_REQUEST);
1770             } else if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
1771                 // Check if request is unmetered (WiFi or unmetered APN).
1772                 evaluation.addDataAllowedReason(DataAllowedReason.UNMETERED_USAGE);
1773             } else if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
1774                 boolean isMeteredRequest = mDataConfigManager.isAnyMeteredCapability(
1775                         networkRequest.getCapabilities(), mServiceState.getDataRoaming());
1776                 if (!isMeteredRequest) {
1777                     evaluation.addDataAllowedReason(DataAllowedReason.UNMETERED_USAGE);
1778                 }
1779             }
1780         }
1781 
1782         // Check if there is any compatible data profile
1783         int networkType = getDataNetworkType(transport);
1784         if (networkType == TelephonyManager.NETWORK_TYPE_UNKNOWN
1785                 && transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
1786             // reach here when data is OOS but serviceStateAllowsPSAttach == true, so we adopt the
1787             // voice RAT to select data profile
1788             networkType = mServiceState.getVoiceNetworkType();
1789         }
1790         DataProfile dataProfile = mDataProfileManager
1791                 .getDataProfileForNetworkRequest(networkRequest, networkType,
1792                         mServiceState.isUsingNonTerrestrialNetwork(),
1793                         isEsimBootStrapProvisioningActivated(),
1794                         // If the evaluation is due to environmental changes, then we should ignore
1795                         // the permanent failure reached earlier.
1796                         reason.isConditionBased());
1797         if (dataProfile == null) {
1798             evaluation.addDataDisallowedReason(DataDisallowedReason.NO_SUITABLE_DATA_PROFILE);
1799         } else if (// Check for new requests if we already self-scheduled(as opposed to modem
1800             // demanded) retry for similar requests.
1801                 reason == DataEvaluationReason.NEW_REQUEST
1802                         &&  mDataRetryManager.isSimilarNetworkRequestRetryScheduled(
1803                         networkRequest, transport)) {
1804             evaluation.addDataDisallowedReason(DataDisallowedReason.RETRY_SCHEDULED);
1805         } else if (mDataRetryManager.isDataProfileThrottled(dataProfile, transport)) {
1806             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_THROTTLED);
1807         }
1808 
1809         if (!evaluation.containsDisallowedReasons()) {
1810             if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN
1811                     && isEsimBootStrapProvisioningActivated()
1812                     && isEsimBootStrapMaxDataLimitReached()) {
1813                 log("BootStrap Sim Data Usage limit reached");
1814                 evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_LIMIT_REACHED);
1815             } else {
1816                 evaluation.setCandidateDataProfile(dataProfile);
1817             }
1818         }
1819 
1820         networkRequest.setEvaluation(evaluation);
1821         // EXTERNAL_QUERY generates too many log spam.
1822         if (reason != DataEvaluationReason.EXTERNAL_QUERY) {
1823             log(evaluation + ", network type="
1824                     + TelephonyManager.getNetworkTypeName(getDataNetworkType(transport))
1825                     + ", reg state="
1826                     + NetworkRegistrationInfo.registrationStateToString(
1827                     getDataRegistrationState(mServiceState, transport))
1828                     + ", " + networkRequest);
1829         }
1830         return evaluation;
1831     }
1832 
1833     /**
1834      * Returns whether the data roaming setting should be ignored for satellite connection,
1835      * as the satellite data plan is included in the user mobile plan.
1836      *
1837      * @return {@code true} if the data roaming setting should be ignored for satellite connection.
1838      * {@code false} otherwise.
1839      */
shouldIgnoreDataRoamingSettingForSatellite()1840     private boolean shouldIgnoreDataRoamingSettingForSatellite() {
1841         return mServiceState.isUsingNonTerrestrialNetwork()
1842                 && mDataConfigManager.isIgnoringDataRoamingSettingForSatellite();
1843     }
1844 
1845     /**
1846      * This method
1847      *  - At evaluation network request and evaluation data network determines, if
1848      *    bootstrap sim current data usage reached bootstrap sim max data limit allowed set
1849      *    at {@link DataConfigManager#getEsimBootStrapMaxDataLimitBytes()}
1850      *  - Query the current data usage at {@link #getDataUsage()}, if last data usage query guarding
1851      *    interval as expired.
1852      *
1853      * @return true, if bootstrap sim data limit is reached
1854      *         else false, if bootstrap sim max data limit allowed set is -1(Unlimited) or current
1855      *         bootstrap sim total data usage is less than bootstrap sim max data limit allowed.
1856      *
1857      */
isEsimBootStrapMaxDataLimitReached()1858     private boolean isEsimBootStrapMaxDataLimitReached() {
1859         long esimBootStrapMaxDataLimitBytes =
1860                 mDataConfigManager.getEsimBootStrapMaxDataLimitBytes();
1861 
1862         if (esimBootStrapMaxDataLimitBytes < 0L) {
1863             return false;
1864         }
1865 
1866         if (mBootStrapSimTotalDataUsageBytes < esimBootStrapMaxDataLimitBytes
1867                 && (mBootstrapSimLastDataUsageQueryTime == 0
1868                 || SystemClock.elapsedRealtime() - mBootstrapSimLastDataUsageQueryTime
1869                 > GUARD_TIMER_INTERVAL_TO_QUERY_DATA_USAGE_API_STATS_MILLIS)) {
1870             mBootStrapSimTotalDataUsageBytes = getDataUsage();
1871             log("current bootstrap sim data usage: " + mBootStrapSimTotalDataUsageBytes);
1872             mBootstrapSimLastDataUsageQueryTime =  SystemClock.elapsedRealtime();
1873         }
1874         return mBootStrapSimTotalDataUsageBytes >= esimBootStrapMaxDataLimitBytes;
1875     }
1876 
1877     /**
1878      * Query network usage statistics summaries based on {@link
1879      * NetworkStatsManager#querySummaryForDevice(NetworkTemplate, long, long)}
1880      *
1881      * @return Data usage in bytes for the connected networks related to the current subscription
1882      */
getDataUsage()1883     private long getDataUsage() {
1884         NetworkStatsManager networkStatsManager =
1885                         mPhone.getContext().getSystemService(NetworkStatsManager.class);
1886 
1887         if (networkStatsManager != null) {
1888             final NetworkTemplate.Builder builder =
1889                     new NetworkTemplate.Builder(NetworkTemplate.MATCH_MOBILE);
1890             final String subscriberId = mPhone.getSubscriberId();
1891 
1892             if (!TextUtils.isEmpty(subscriberId)) {
1893                 builder.setSubscriberIds(Set.of(subscriberId));
1894                 // Consider data usage calculation of only metered capabilities / data network
1895                 builder.setMeteredness(android.net.NetworkStats.METERED_YES);
1896                 NetworkTemplate template = builder.build();
1897                 final NetworkStats.Bucket ret = networkStatsManager
1898                         .querySummaryForDevice(template, 0L, System.currentTimeMillis());
1899                 return ret.getRxBytes() + ret.getTxBytes();
1900             }
1901         }
1902         return 0L;
1903     }
1904 
1905     /**
1906      * @return The grouped unsatisfied network requests. The network requests that have the same
1907      * network capabilities is grouped into one {@link NetworkRequestList}.
1908      */
1909     @NonNull
getGroupedUnsatisfiedNetworkRequests()1910     private List<NetworkRequestList> getGroupedUnsatisfiedNetworkRequests() {
1911         NetworkRequestList networkRequestList = new NetworkRequestList();
1912         for (TelephonyNetworkRequest networkRequest : mAllNetworkRequestList) {
1913             if (networkRequest.getState() == TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED) {
1914                 networkRequestList.add(networkRequest);
1915             }
1916         }
1917         return DataUtils.getGroupedNetworkRequestList(networkRequestList, mFeatureFlags);
1918     }
1919 
1920     /**
1921      * Called when it's needed to evaluate all unsatisfied network requests.
1922      *
1923      * @param reason The reason for evaluation.
1924      */
onReevaluateUnsatisfiedNetworkRequests(@onNull DataEvaluationReason reason)1925     private void onReevaluateUnsatisfiedNetworkRequests(@NonNull DataEvaluationReason reason) {
1926         // First, try to group similar network request together.
1927         List<NetworkRequestList> networkRequestLists = getGroupedUnsatisfiedNetworkRequests();
1928         log("Re-evaluating " + networkRequestLists.stream().mapToInt(List::size).sum()
1929                 + " unsatisfied network requests in " + networkRequestLists.size()
1930                 + " groups, " + networkRequestLists.stream().map(
1931                         NetworkRequestList::toStringSimplified)
1932                 .collect(Collectors.joining(", ")) + " due to " + reason);
1933 
1934         // Second, see if any existing network can satisfy those network requests.
1935         for (NetworkRequestList requestList : networkRequestLists) {
1936             if (findCompatibleDataNetworkAndAttach(requestList)) {
1937                 continue;
1938             }
1939 
1940             // If no data network can satisfy the requests, then start the evaluation process. Since
1941             // all the requests in the list have the same capabilities, we can only evaluate one
1942             // of them.
1943             DataEvaluation evaluation = evaluateNetworkRequest(requestList.get(0), reason);
1944             if (!evaluation.containsDisallowedReasons()) {
1945                 DataProfile dataProfile = evaluation.getCandidateDataProfile();
1946                 if (dataProfile != null) {
1947                     setupDataNetwork(dataProfile, null,
1948                             evaluation.getDataAllowedReason());
1949                 }
1950             }
1951         }
1952     }
1953 
1954     /**
1955      * Evaluate an existing data network to see if it is still allowed to exist. For example, if
1956      * RAT changes from LTE to UMTS, an IMS data network is not allowed anymore. Or when SIM is
1957      * removal, all data networks (except emergency) should be torn down.
1958      *
1959      * @param dataNetwork The data network to evaluate.
1960      * @param reason The reason for evaluation.
1961      *
1962      * @return The data evaluation result.
1963      */
1964     @NonNull
evaluateDataNetwork(@onNull DataNetwork dataNetwork, @NonNull DataEvaluationReason reason)1965     private DataEvaluation evaluateDataNetwork(@NonNull DataNetwork dataNetwork,
1966             @NonNull DataEvaluationReason reason) {
1967         DataEvaluation evaluation = new DataEvaluation(reason);
1968         // Bypass all checks for emergency data network.
1969         if (dataNetwork.getNetworkCapabilities().hasCapability(
1970                 NetworkCapabilities.NET_CAPABILITY_EIMS)) {
1971             evaluation.addDataAllowedReason(DataAllowedReason.EMERGENCY_REQUEST);
1972             log(evaluation.toString());
1973             return evaluation;
1974         }
1975 
1976         // Check SIM state
1977         if (mSimState != TelephonyManager.SIM_STATE_LOADED) {
1978             evaluation.addDataDisallowedReason(DataDisallowedReason.SIM_NOT_READY);
1979         }
1980 
1981         // Check if device is in CDMA ECBM
1982         if (mPhone.isInCdmaEcm()) {
1983             evaluation.addDataDisallowedReason(DataDisallowedReason.CDMA_EMERGENCY_CALLBACK_MODE);
1984         }
1985 
1986         if (mFeatureFlags.dataServiceCheck()) {
1987             NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
1988                     NetworkRegistrationInfo.DOMAIN_PS, dataNetwork.getTransport());
1989             if (nri != null && nri.isInService() && !nri.getAvailableServices().contains(
1990                     NetworkRegistrationInfo.SERVICE_TYPE_DATA)) {
1991                 evaluation.addDataDisallowedReason(
1992                         DataDisallowedReason.SERVICE_OPTION_NOT_SUPPORTED);
1993             }
1994         }
1995 
1996         // If the network is satellite, then the network must be restricted.
1997         // The IWLAN data network should remain intact even when satellite is connected.
1998         if (dataNetwork.getTransport() != AccessNetworkConstants.TRANSPORT_TYPE_WLAN
1999                 && mServiceState.isUsingNonTerrestrialNetwork() != dataNetwork.isSatellite()) {
2000             // Since we don't support satellite/cellular network handover, we should always
2001             // tear down the network when transport changes.
2002             evaluation.addDataDisallowedReason(
2003                     DataDisallowedReason.DATA_NETWORK_TRANSPORT_NOT_ALLOWED);
2004         }
2005 
2006         // Check whether data limit reached for bootstrap sim, else re-evaluate based on the timer
2007         // set.
2008         if (isEsimBootStrapProvisioningActivated()
2009                 && dataNetwork.getTransport() == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
2010             if (isEsimBootStrapMaxDataLimitReached()) {
2011                 log("BootStrap Sim Data Usage limit reached");
2012                 evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_LIMIT_REACHED);
2013             } else {
2014                 if (!hasMessages(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)) {
2015                     sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
2016                             DataEvaluationReason.CHECK_DATA_USAGE),
2017                             mDataConfigManager.getReevaluateBootstrapSimDataUsageMillis());
2018                 } else {
2019                     log("skip scheduling evaluating existing data networks since already"
2020                             + "scheduled");
2021                 }
2022             }
2023         }
2024 
2025         // Check if there are other network that has higher priority, and only single data network
2026         // is allowed.
2027         if (isOnlySingleDataNetworkAllowed(dataNetwork.getTransport())
2028                 && !hasCapabilityExemptsFromSinglePdnRule(
2029                         dataNetwork.getNetworkCapabilities().getCapabilities())) {
2030             // If there is network request that has higher priority than this data network, then
2031             // tear down the network, regardless that network request is satisfied or not.
2032             if (mAllNetworkRequestList.stream()
2033                     .filter(request -> dataNetwork.getTransport()
2034                             == mAccessNetworksManager.getPreferredTransportByNetworkCapability(
2035                                     request.getHighestPriorityApnTypeNetworkCapability()))
2036                     .filter(request
2037                             -> !hasCapabilityExemptsFromSinglePdnRule(request.getCapabilities()))
2038                     .anyMatch(request -> request.getPriority() > dataNetwork.getPriority())) {
2039                 evaluation.addDataDisallowedReason(
2040                         DataDisallowedReason.ONLY_ALLOWED_SINGLE_NETWORK);
2041             } else {
2042                 log("evaluateDataNetwork: " + dataNetwork + " has the highest priority. "
2043                         + "No need to tear down");
2044             }
2045         }
2046 
2047         // It's recommended for IMS service not requesting MMTEL capability, so that MMTEL
2048         // capability is dynamically added when moving between vops and nonvops area.
2049         boolean vopsIsRequired = dataNetwork.hasNetworkCapabilityInNetworkRequests(
2050                 NetworkCapabilities.NET_CAPABILITY_MMTEL);
2051 
2052         // Check an active call relying on this network and config for "delay tear down due to vops
2053         // call" is enabled.
2054         if (dataNetwork.shouldDelayImsTearDownDueToInCall()) {
2055             if (vopsIsRequired) {
2056                 log("Ignored VoPS check due to delay IMS tear down until call ends.");
2057             }
2058         } else {
2059             // Reach here means we should ignore active calls even if there are any.
2060 
2061             // Check if VoPS requirement is met.
2062             if (vopsIsRequired) {
2063                 if (dataNetwork.getTransport() == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
2064                     NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
2065                             NetworkRegistrationInfo.DOMAIN_PS,
2066                             AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2067                     if (nri != null) {
2068                         DataSpecificRegistrationInfo dsri = nri.getDataSpecificInfo();
2069                         if (dsri != null && dsri.getVopsSupportInfo() != null
2070                                 && !dsri.getVopsSupportInfo().isVopsSupported()
2071                                 && !mDataConfigManager.shouldKeepNetworkUpInNonVops(
2072                                         nri.getNetworkRegistrationState())) {
2073                             evaluation.addDataDisallowedReason(
2074                                     DataDisallowedReason.VOPS_NOT_SUPPORTED);
2075                         }
2076                     }
2077                 }
2078             }
2079 
2080             // Check if handover retry stopped and preferred transport still not matched.
2081             int preferredTransport = mAccessNetworksManager
2082                     .getPreferredTransportByNetworkCapability(
2083                             dataNetwork.getApnTypeNetworkCapability());
2084             if (preferredTransport != dataNetwork.getTransport()
2085                     && mDataRetryManager.isDataNetworkHandoverRetryStopped(dataNetwork)) {
2086                 evaluation.addDataDisallowedReason(DataDisallowedReason.HANDOVER_RETRY_STOPPED);
2087             }
2088         }
2089 
2090         // Check if data is disabled
2091         boolean dataDisabled = !mDataSettingsManager.isDataEnabled();
2092 
2093         // Check if data roaming is disabled
2094         if (mServiceState.getDataRoaming() && !mDataSettingsManager.isDataRoamingEnabled()) {
2095             evaluation.addDataDisallowedReason(DataDisallowedReason.ROAMING_DISABLED);
2096         }
2097 
2098         // Check if current data network type is allowed by the data profile. Use the lingering
2099         // network type. Some data network is allowed to create on certain RATs, but can linger
2100         // to extended RATs. For example, IMS is allowed to be created on LTE only, but can
2101         // extend its life cycle to 3G.
2102         int networkType = getDataNetworkType(dataNetwork.getTransport());
2103         DataProfile dataProfile = dataNetwork.getDataProfile();
2104         if (dataProfile.getApnSetting() != null) {
2105             // Check if data is disabled for the APN type
2106             dataDisabled = !mDataSettingsManager.isDataEnabled(
2107                     DataUtils.networkCapabilityToApnType(
2108                             dataNetwork.getApnTypeNetworkCapability()));
2109 
2110             // Sometimes network temporarily OOS and network type becomes UNKNOWN. We don't
2111             // tear down network in that case.
2112             if (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN
2113                     && !dataProfile.getApnSetting().canSupportLingeringNetworkType(networkType)) {
2114                 log("networkType=" + TelephonyManager.getNetworkTypeName(networkType)
2115                         + ", networkTypeBitmask="
2116                         + TelephonyManager.convertNetworkTypeBitmaskToString(
2117                                 dataProfile.getApnSetting().getNetworkTypeBitmask())
2118                         + ", lingeringNetworkTypeBitmask="
2119                         + TelephonyManager.convertNetworkTypeBitmaskToString(
2120                                 dataProfile.getApnSetting().getLingeringNetworkTypeBitmask()));
2121                 evaluation.addDataDisallowedReason(
2122                         DataDisallowedReason.DATA_NETWORK_TYPE_NOT_ALLOWED);
2123             }
2124         }
2125 
2126         if (dataDisabled) {
2127             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_DISABLED);
2128         }
2129 
2130         // Check if the data profile is still compatible, sometimes the users can remove it from the
2131         // APN editor. If some of the important fields are changed in APN settings, we need to
2132         // tear down the network. Note traffic descriptor from the data profile will not be checked.
2133         if (!mDataProfileManager.isDataProfileCompatible(dataProfile)) {
2134             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_PROFILE_INVALID);
2135         }
2136 
2137         // If users switch preferred profile in APN editor, we need to tear down network.
2138         if (dataNetwork.isInternetSupported()
2139                 && !mDataProfileManager.isDataProfilePreferred(dataProfile)
2140                 && mDataProfileManager.canPreferredDataProfileSatisfy(
2141                         dataNetwork.getAttachedNetworkRequestList())) {
2142             evaluation.addDataDisallowedReason(DataDisallowedReason.DATA_PROFILE_NOT_PREFERRED);
2143         }
2144 
2145         // Check whether if there are any reason we should tear down the network.
2146         if (!evaluation.containsDisallowedReasons()) {
2147             // The data is allowed in the current condition.
2148             evaluation.addDataAllowedReason(DataAllowedReason.NORMAL);
2149         } else if (!evaluation.containsHardDisallowedReasons()) {
2150             // If there are reasons we should tear down the network, check if those are hard reasons
2151             // or soft reasons. In some scenarios, we can make exceptions if they are soft
2152             // disallowed reasons.
2153             if ((mTelecomManager.isInEmergencyCall() || mPhone.isInEcm())
2154                     && dataNetwork.isEmergencySupl()) {
2155                 // Check if it's SUPL during emergency call.
2156                 evaluation.addDataAllowedReason(DataAllowedReason.EMERGENCY_SUPL);
2157             } else if (!dataNetwork.getNetworkCapabilities().hasCapability(
2158                     NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
2159                     && dataNetwork.getAttachedNetworkRequestList().stream()
2160                             .allMatch(this::isValidRestrictedRequest)) {
2161                 // Check if request is restricted and there are no exceptional requests attached to
2162                 // the network.
2163                 evaluation.addDataAllowedReason(DataAllowedReason.RESTRICTED_REQUEST);
2164             } else if (dataNetwork.getTransport() == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
2165                 // Check if request is unmetered (WiFi or unmetered APN)
2166                 evaluation.addDataAllowedReason(DataAllowedReason.UNMETERED_USAGE);
2167             } else {
2168                 boolean unmeteredNetwork = !mDataConfigManager.isAnyMeteredCapability(
2169                         dataNetwork.getNetworkCapabilities()
2170                                 .getCapabilities(), mServiceState.getDataRoaming());
2171                 if (unmeteredNetwork) {
2172                     evaluation.addDataAllowedReason(DataAllowedReason.UNMETERED_USAGE);
2173                 }
2174             }
2175         }
2176 
2177         // Check if we allow additional lingering for active VoPS call network if
2178         // a. this network is SRVCC handover in progress
2179         // or b. "delay tear down due to active VoPS call" is enabled
2180         boolean isInSrvcc = vopsIsRequired && mIsSrvccHandoverInProcess;
2181         if (evaluation.containsOnly(DataDisallowedReason.DATA_NETWORK_TYPE_NOT_ALLOWED)
2182                 && (dataNetwork.shouldDelayImsTearDownDueToInCall() || isInSrvcc)) {
2183             evaluation.addDataAllowedReason(DataAllowedReason.IN_VOICE_CALL);
2184         }
2185 
2186         log("Evaluated " + dataNetwork + ", " + evaluation);
2187         return evaluation;
2188     }
2189 
2190     /**
2191      * Check if the transport from connectivity service can satisfy the network request. Note the
2192      * transport here is connectivity service's transport (Wifi, cellular, satellite, etc..), not
2193      * the widely used {@link AccessNetworkConstants#TRANSPORT_TYPE_WLAN WLAN},
2194      * {@link AccessNetworkConstants#TRANSPORT_TYPE_WWAN WWAN} transport in telephony.
2195      *
2196      * @param networkRequest Network request
2197      * @param transport The preferred transport type for the request. The transport here is
2198      * WWAN/WLAN.
2199      * @return {@code true} if the connectivity transport can satisfy the network request, otherwise
2200      * {@code false}.
2201      */
canConnectivityTransportSatisfyNetworkRequest( @onNull TelephonyNetworkRequest networkRequest, @TransportType int transport)2202     private boolean canConnectivityTransportSatisfyNetworkRequest(
2203             @NonNull TelephonyNetworkRequest networkRequest, @TransportType int transport) {
2204         // Check if this is a IWLAN network request.
2205         if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
2206             // If the request would result in bringing up network on IWLAN, then no
2207             // need to check if the device is using satellite network.
2208             return true;
2209         }
2210 
2211         // When the device is on satellite, allow network request without bandwidth not constrained
2212         // to enable data connection with constrained network.
2213         if (mServiceState.isUsingNonTerrestrialNetwork() && networkRequest.hasCapability(
2214                 NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)) {
2215 
2216             int dataPolicy;
2217             if (mFeatureFlags.dataServiceCheck()) {
2218                 final SatelliteController satelliteController = SatelliteController.getInstance();
2219                 dataPolicy = satelliteController.getSatelliteDataServicePolicyForPlmn(mSubId,
2220                         mPhone.getServiceState().getOperatorNumeric());
2221             } else {
2222                 dataPolicy = mDataConfigManager.getSatelliteDataSupportMode();
2223             }
2224             switch (dataPolicy) {
2225                 case CarrierConfigManager.SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED -> {
2226                     return false;
2227                 }
2228                 case CarrierConfigManager.SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED -> {
2229                     try {
2230                         if (networkRequest.hasCapability(DataUtils
2231                                 .NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED)) {
2232                             return false;
2233                         }
2234                     } catch (Exception ignored) { }
2235                 }
2236                 // default case CarrierConfigManager.SATELLITE_DATA_SUPPORT_ALL
2237             }
2238         }
2239 
2240         // If the network request does not specify cellular or satellite, then it can be
2241         // satisfied when the device is either on cellular ot satellite.
2242         if (!networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
2243                 && !networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_SATELLITE)) {
2244             return true;
2245         }
2246 
2247         // As a short term solution, allowing some networks to be always marked as cellular
2248         // transport if certain capabilities are in the network request.
2249         if (networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) && Arrays.stream(
2250                         networkRequest.getCapabilities())
2251                 .anyMatch(mDataConfigManager.getForcedCellularTransportCapabilities()::contains)) {
2252             return true;
2253         }
2254 
2255         // If the network is cellular, then the request must specify cellular transport. Or if the
2256         // the network is satellite, then the request must specify satellite transport and
2257         // restricted.
2258         return (mServiceState.isUsingNonTerrestrialNetwork()
2259                 && networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_SATELLITE))
2260                 || (!mServiceState.isUsingNonTerrestrialNetwork()
2261                         && networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
2262     }
2263 
2264     /**
2265      * Check if a network request should be treated as a valid restricted network request that
2266      * can bypass soft disallowed reasons, for example, mobile data off.
2267      *
2268      * @param networkRequest The network request to evaluate.
2269      * @return {@code true} if the request can be considered as a valid restricted network request
2270      * that can bypass any soft disallowed reasons, otherwise {@code false}.
2271      */
isValidRestrictedRequest(@onNull TelephonyNetworkRequest networkRequest)2272     private boolean isValidRestrictedRequest(@NonNull TelephonyNetworkRequest networkRequest) {
2273         // tethering, enterprise and mms with restricted capabilities always honor soft
2274         // disallowed reasons and not respected as restricted request
2275         if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)
2276                 || networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE)
2277                 || networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2278             return false;
2279         }
2280         // When the device is on satellite, internet with restricted capabilities always honor
2281         // soft disallowed reasons and not respected as restricted request
2282         // Note - ping test are performed with restricted request on satellite assuming they cannot
2283         // bypass any checks. If below is removed, reevaluate the ping request in
2284         // CellularNetworkValidator and the getInternetEvaluation in AutoDataSwitchController
2285         return !(mServiceState.isUsingNonTerrestrialNetwork()
2286                 && networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));
2287     }
2288 
2289     /**
2290      * Called when needed to re-evaluate existing data networks and tear down networks if needed.
2291      *
2292      * @param reason The reason for this data evaluation.
2293      */
onReevaluateExistingDataNetworks(@onNull DataEvaluationReason reason)2294     private void onReevaluateExistingDataNetworks(@NonNull DataEvaluationReason reason) {
2295         if (mDataNetworkList.isEmpty()) {
2296             log("onReevaluateExistingDataNetworks: No existing data networks to re-evaluate.");
2297             return;
2298         }
2299         log("Re-evaluating " + mDataNetworkList.size() + " existing data networks due to "
2300                 + reason);
2301         for (DataNetwork dataNetwork : mDataNetworkList) {
2302             if (dataNetwork.isConnecting() || dataNetwork.isConnected()) {
2303                 DataEvaluation dataEvaluation = evaluateDataNetwork(dataNetwork, reason);
2304                 if (dataEvaluation.containsDisallowedReasons()) {
2305                     tearDownGracefully(dataNetwork, getTearDownReason(dataEvaluation));
2306                 }
2307             }
2308         }
2309     }
2310 
2311     /**
2312      * Evaluate if it is allowed to handover the data network between IWLAN and cellular. Some
2313      * carriers do not allow handover in certain conditions.
2314      *
2315      * @param dataNetwork The data network to be handover.
2316      * @return The evaluation result.
2317      *
2318      * @see CarrierConfigManager#KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY
2319      */
2320     @NonNull
evaluateDataNetworkHandover(@onNull DataNetwork dataNetwork)2321     private DataEvaluation evaluateDataNetworkHandover(@NonNull DataNetwork dataNetwork) {
2322         DataEvaluation dataEvaluation = new DataEvaluation(DataEvaluationReason.DATA_HANDOVER);
2323         if (!dataNetwork.isConnecting() && !dataNetwork.isConnected()) {
2324             dataEvaluation.addDataDisallowedReason(DataDisallowedReason.ILLEGAL_STATE);
2325             return dataEvaluation;
2326         }
2327 
2328         // If enhanced handover check is enabled, perform extra checks.
2329         if (mDataConfigManager.isEnhancedIwlanHandoverCheckEnabled()) {
2330             int targetTransport = DataUtils.getTargetTransport(dataNetwork.getTransport());
2331             NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
2332                     NetworkRegistrationInfo.DOMAIN_PS, targetTransport);
2333             if (nri != null) {
2334                 // Check if OOS on target transport.
2335                 if (!nri.isInService()) {
2336                     dataEvaluation.addDataDisallowedReason(DataDisallowedReason.NOT_IN_SERVICE);
2337                 }
2338 
2339                 // Check if VoPS is required, but the target transport is non-VoPS.
2340                 // It's recommended for IMS service not requesting MMTEL capability, so that MMTEL
2341                 // capability is dynamically added when moving between vops and nonvops area.
2342                 NetworkRequestList networkRequestList =
2343                         dataNetwork.getAttachedNetworkRequestList();
2344                 if (networkRequestList.stream().anyMatch(request
2345                         -> request.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL))) {
2346                     DataSpecificRegistrationInfo dsri = nri.getDataSpecificInfo();
2347                     // Check if the network is non-VoPS.
2348                     if (dsri != null && dsri.getVopsSupportInfo() != null
2349                             && !dsri.getVopsSupportInfo().isVopsSupported()
2350                             && !mDataConfigManager.shouldKeepNetworkUpInNonVops(
2351                                     nri.getNetworkRegistrationState())) {
2352                         dataEvaluation.addDataDisallowedReason(
2353                                 DataDisallowedReason.VOPS_NOT_SUPPORTED);
2354                     }
2355                 }
2356 
2357                 if (dataEvaluation.containsDisallowedReasons()) {
2358                     return dataEvaluation;
2359                 }
2360             }
2361         }
2362 
2363         if (mDataConfigManager.isIwlanHandoverPolicyEnabled()) {
2364             List<HandoverRule> handoverRules = mDataConfigManager.getHandoverRules();
2365 
2366             int sourceNetworkType = getDataNetworkType(dataNetwork.getTransport());
2367             if (sourceNetworkType == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
2368                 // Using the data network type stored in the data network. We
2369                 // cache the last known network type in data network controller
2370                 // because data network has much shorter life cycle. It can prevent
2371                 // the obsolete last known network type cached in data network
2372                 // type controller.
2373                 sourceNetworkType = dataNetwork.getLastKnownDataNetworkType();
2374             }
2375             int sourceAccessNetwork = DataUtils.networkTypeToAccessNetworkType(
2376                     sourceNetworkType);
2377             NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
2378                     NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
2379             boolean isWwanInService = nri != null && nri.isInService();
2380             // If WWAN is inService, use the real roaming state reported by modem instead of
2381             // using the overridden roaming state, otherwise get last known roaming state stored
2382             // in data network.
2383             boolean isRoaming = isWwanInService ? mServiceState.getDataRoamingFromRegistration()
2384                     : dataNetwork.getLastKnownRoamingState();
2385             Phone imsPhone = mPhone.getImsPhone();
2386             boolean isIncall = mFeatureFlags.incallHandoverPolicy() && imsPhone != null
2387                     && (imsPhone.getCallTracker().getState() != PhoneConstants.State.IDLE);
2388             int targetAccessNetwork = DataUtils.networkTypeToAccessNetworkType(
2389                     getDataNetworkType(DataUtils.getTargetTransport(dataNetwork.getTransport())));
2390             NetworkCapabilities capabilities = dataNetwork.getNetworkCapabilities();
2391             log("evaluateDataNetworkHandover: "
2392                     + "source=" + AccessNetworkType.toString(sourceAccessNetwork)
2393                     + ", target=" + AccessNetworkType.toString(targetAccessNetwork)
2394                     + ", roaming=" + isRoaming
2395                     + ", incall=" + isIncall
2396                     + ", ServiceState=" + mServiceState
2397                     + ", capabilities=" + capabilities);
2398 
2399             // Matching the rules by the configured order. Bail out if find first matching rule.
2400             for (HandoverRule rule : handoverRules) {
2401                 // Check if the rule is only for roaming and we are not  aroaming.
2402                 if (rule.isOnlyForRoaming && !isRoaming) {
2403                     // If the rule is for roaming only, and the device is not roaming, then bypass
2404                     // this rule.
2405                     continue;
2406                 }
2407                 if (rule.isOnlyForIncall && (!mFeatureFlags.incallHandoverPolicy() || !isIncall)) {
2408                     // If the rule is for incall only, and the device is not incall, then bypass
2409                     // this rule.
2410                     continue;
2411                 }
2412 
2413                 if (rule.sourceAccessNetworks.contains(sourceAccessNetwork)
2414                         && rule.targetAccessNetworks.contains(targetAccessNetwork)) {
2415                     // if no capability rule specified,
2416                     // data network capability is considered matched.
2417                     // otherwise, any capabilities overlap is also considered matched.
2418                     if (rule.networkCapabilities.isEmpty()
2419                             || rule.networkCapabilities.stream()
2420                             .anyMatch(capabilities::hasCapability)) {
2421                         log("evaluateDataNetworkHandover: Matched " + rule);
2422                         if (rule.type == HandoverRule.RULE_TYPE_DISALLOWED) {
2423                             dataEvaluation.addDataDisallowedReason(
2424                                     DataDisallowedReason.NOT_ALLOWED_BY_POLICY);
2425                         } else {
2426                             dataEvaluation.addDataAllowedReason(DataAllowedReason.NORMAL);
2427                         }
2428                         log("evaluateDataNetworkHandover: " + dataEvaluation);
2429                         return dataEvaluation;
2430                     }
2431                 }
2432             }
2433             log("evaluateDataNetworkHandover: Did not find matching rule.");
2434         } else {
2435             log("evaluateDataNetworkHandover: IWLAN handover policy not enabled.");
2436         }
2437 
2438         // Allow handover by default if no rule is found/not enabled by config.
2439         dataEvaluation.addDataAllowedReason(DataAllowedReason.NORMAL);
2440         return dataEvaluation;
2441     }
2442 
2443     /**
2444      * Get tear down reason from the evaluation result.
2445      *
2446      * @param dataEvaluation The evaluation result from
2447      * {@link #evaluateDataNetwork(DataNetwork, DataEvaluationReason)}.
2448      * @return The tear down reason.
2449      */
2450     @TearDownReason
getTearDownReason(@onNull DataEvaluation dataEvaluation)2451     private static int getTearDownReason(@NonNull DataEvaluation dataEvaluation) {
2452         if (dataEvaluation.containsDisallowedReasons()) {
2453             switch (dataEvaluation.getDataDisallowedReasons().get(0)) {
2454                 case DATA_DISABLED:
2455                     return DataNetwork.TEAR_DOWN_REASON_DATA_DISABLED;
2456                 case ROAMING_DISABLED:
2457                     return DataNetwork.TEAR_DOWN_REASON_ROAMING_DISABLED;
2458                 case DEFAULT_DATA_UNSELECTED:
2459                     return DataNetwork.TEAR_DOWN_REASON_DEFAULT_DATA_UNSELECTED;
2460                 case NOT_IN_SERVICE:
2461                     return DataNetwork.TEAR_DOWN_REASON_NOT_IN_SERVICE;
2462                 case DATA_CONFIG_NOT_READY:
2463                     return DataNetwork.TEAR_DOWN_REASON_DATA_CONFIG_NOT_READY;
2464                 case SIM_NOT_READY:
2465                     return DataNetwork.TEAR_DOWN_REASON_SIM_REMOVAL;
2466                 case CONCURRENT_VOICE_DATA_NOT_ALLOWED:
2467                     return DataNetwork.TEAR_DOWN_REASON_CONCURRENT_VOICE_DATA_NOT_ALLOWED;
2468                 case SERVICE_OPTION_NOT_SUPPORTED:
2469                     return DataNetwork.TEAR_DOWN_REASON_SERVICE_OPTION_NOT_SUPPORTED;
2470                 case RADIO_POWER_OFF:
2471                     return DataNetwork.TEAR_DOWN_REASON_AIRPLANE_MODE_ON;
2472                 case PENDING_TEAR_DOWN_ALL:
2473                     return DataNetwork.TEAR_DOWN_REASON_PENDING_TEAR_DOWN_ALL;
2474                 case RADIO_DISABLED_BY_CARRIER:
2475                     return DataNetwork.TEAR_DOWN_REASON_POWER_OFF_BY_CARRIER;
2476                 case DATA_SERVICE_NOT_READY:
2477                     return DataNetwork.TEAR_DOWN_REASON_DATA_SERVICE_NOT_READY;
2478                 case NO_SUITABLE_DATA_PROFILE:
2479                     return DataNetwork.TEAR_DOWN_REASON_NO_SUITABLE_DATA_PROFILE;
2480                 case DATA_NETWORK_TYPE_NOT_ALLOWED:
2481                     return DataNetwork.TEAR_DOWN_REASON_RAT_NOT_ALLOWED;
2482                 case CDMA_EMERGENCY_CALLBACK_MODE:
2483                     return DataNetwork.TEAR_DOWN_REASON_CDMA_EMERGENCY_CALLBACK_MODE;
2484                 case RETRY_SCHEDULED:
2485                     return DataNetwork.TEAR_DOWN_REASON_RETRY_SCHEDULED;
2486                 case DATA_THROTTLED:
2487                     return DataNetwork.TEAR_DOWN_REASON_DATA_THROTTLED;
2488                 case DATA_PROFILE_INVALID:
2489                     return DataNetwork.TEAR_DOWN_REASON_DATA_PROFILE_INVALID;
2490                 case DATA_PROFILE_NOT_PREFERRED:
2491                     return DataNetwork.TEAR_DOWN_REASON_DATA_PROFILE_NOT_PREFERRED;
2492                 case NOT_ALLOWED_BY_POLICY:
2493                     return DataNetwork.TEAR_DOWN_REASON_NOT_ALLOWED_BY_POLICY;
2494                 case ILLEGAL_STATE:
2495                     return DataNetwork.TEAR_DOWN_REASON_ILLEGAL_STATE;
2496                 case VOPS_NOT_SUPPORTED:
2497                     return DataNetwork.TEAR_DOWN_REASON_VOPS_NOT_SUPPORTED;
2498                 case ONLY_ALLOWED_SINGLE_NETWORK:
2499                     return DataNetwork.TEAR_DOWN_REASON_ONLY_ALLOWED_SINGLE_NETWORK;
2500                 case HANDOVER_RETRY_STOPPED:
2501                     return DataNetwork.TEAR_DOWN_REASON_HANDOVER_FAILED;
2502                 case DATA_LIMIT_REACHED:
2503                     return DataNetwork.TEAR_DOWN_REASON_DATA_LIMIT_REACHED;
2504                 case DATA_NETWORK_TRANSPORT_NOT_ALLOWED:
2505                     return DataNetwork.TEAR_DOWN_REASON_DATA_NETWORK_TRANSPORT_NOT_ALLOWED;
2506             }
2507         }
2508         return DataNetwork.TEAR_DOWN_REASON_NONE;
2509     }
2510 
2511     /**
2512      * Check whether a dataNetwork is actively capable of internet connection
2513      * @param cid dataNetwork unique identifier
2514      * @return true if the dataNetwork is connected and capable of internet connection
2515      */
isInternetNetwork(int cid)2516     public boolean isInternetNetwork(int cid) {
2517         for (DataNetwork dataNetwork : mDataNetworkList) {
2518             if (dataNetwork.getId() == cid
2519                     && dataNetwork.isConnected()
2520                     && dataNetwork.isInternetSupported()) {
2521                 return true;
2522             }
2523         }
2524         return false;
2525     }
2526 
2527     /**
2528      * @return {@code true} if data is dormant.
2529      */
isDataDormant()2530     private boolean isDataDormant() {
2531         return mDataNetworkList.stream().anyMatch(
2532                 dataNetwork -> dataNetwork.getLinkStatus()
2533                         == DataCallResponse.LINK_STATUS_DORMANT)
2534                 && mDataNetworkList.stream().noneMatch(
2535                         dataNetwork -> dataNetwork.getLinkStatus()
2536                                 == DataCallResponse.LINK_STATUS_ACTIVE);
2537     }
2538 
2539     /**
2540      * Update data activity.
2541      */
updateDataActivity()2542     private void updateDataActivity() {
2543         int dataActivity = TelephonyManager.DATA_ACTIVITY_NONE;
2544         if (isDataDormant()) {
2545             dataActivity = TelephonyManager.DATA_ACTIVITY_DORMANT;
2546         } else if (mPhone.getLinkBandwidthEstimator() != null) {
2547             dataActivity = mPhone.getLinkBandwidthEstimator().getDataActivity();
2548         }
2549 
2550         if (mDataActivity != dataActivity) {
2551             logv("updateDataActivity: dataActivity="
2552                     + DataUtils.dataActivityToString(dataActivity));
2553             mDataActivity = dataActivity;
2554             mPhone.notifyDataActivity();
2555         }
2556     }
2557 
2558     /**
2559      * Remove a network request, which is originated from the apps. Note that remove a network
2560      * will not result in tearing down the network. The tear down request directly comes from
2561      * {@link com.android.server.ConnectivityService} through
2562      * {@link NetworkAgent#onNetworkUnwanted()}.
2563      *
2564      * @param networkRequest Network request
2565      */
removeNetworkRequest(@onNull TelephonyNetworkRequest networkRequest)2566     public void removeNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest) {
2567         sendMessage(obtainMessage(EVENT_REMOVE_NETWORK_REQUEST, networkRequest));
2568     }
2569 
onRemoveNetworkRequest(@onNull TelephonyNetworkRequest request)2570     private void onRemoveNetworkRequest(@NonNull TelephonyNetworkRequest request) {
2571         if (!mAllNetworkRequestList.remove(request)) {
2572             loge("onRemoveNetworkRequest: Network request does not exist. " + request);
2573             return;
2574         }
2575 
2576         if (request.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2577             mImsThrottleCounter.addOccurrence();
2578             mLastReleasedImsRequestCapabilities = request.getCapabilities();
2579             mLastImsOperationIsRelease = true;
2580         }
2581 
2582         if (request.getAttachedNetwork() != null) {
2583             request.getAttachedNetwork().detachNetworkRequest(
2584                     request, false /* shouldRetry */);
2585         }
2586 
2587         request.setState(TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED);
2588         request.setEvaluation(null);
2589 
2590         log("onRemoveNetworkRequest: Removed " + request);
2591         return;
2592     }
2593 
2594     /**
2595      * Check if the network request is existing. Note this method is not thread safe so can be only
2596      * called within the modules in {@link com.android.internal.telephony.data}.
2597      *
2598      * @param networkRequest Telephony network request to check.
2599      * @return {@code true} if the network request exists.
2600      */
isNetworkRequestExisting(@onNull TelephonyNetworkRequest networkRequest)2601     public boolean isNetworkRequestExisting(@NonNull TelephonyNetworkRequest networkRequest) {
2602         return mAllNetworkRequestList.contains(networkRequest);
2603     }
2604 
2605     /**
2606      * Get data network by interface name.
2607      *
2608      * @param interfaceName The network interface name.
2609      * @return The data network if found.
2610      */
2611     @Nullable
getDataNetworkByInterface(@onNull String interfaceName)2612     public DataNetwork getDataNetworkByInterface(@NonNull String interfaceName) {
2613         return mDataNetworkList.stream()
2614                 .filter(dataNetwork -> !(dataNetwork.isDisconnecting()
2615                         || dataNetwork.isDisconnected()))
2616                 .filter(dataNetwork -> interfaceName.equals(
2617                         dataNetwork.getLinkProperties().getInterfaceName()))
2618                 .findFirst()
2619                 .orElse(null);
2620     }
2621 
2622     /**
2623      * Check if the device is in eSIM bootstrap provisioning state.
2624      *
2625      * @return {@code true} if the device is under eSIM bootstrap provisioning.
2626      */
isEsimBootStrapProvisioningActivated()2627     public boolean isEsimBootStrapProvisioningActivated() {
2628         if (!mFeatureFlags.esimBootstrapProvisioningFlag()) {
2629             return false;
2630         }
2631 
2632         SubscriptionInfoInternal subInfo = SubscriptionManagerService.getInstance()
2633                 .getSubscriptionInfoInternal(mPhone.getSubId());
2634         return subInfo != null
2635                 && subInfo.getProfileClass() == SubscriptionManager.PROFILE_CLASS_PROVISIONING;
2636     }
2637 
2638     /**
2639      * Register for IMS feature registration state.
2640      *
2641      * @param subId The subscription index.
2642      * @param imsFeature The IMS feature. Only {@link ImsFeature#FEATURE_MMTEL} and
2643      * {@link ImsFeature#FEATURE_RCS} are supported at this point.
2644      */
registerImsFeatureRegistrationState(int subId, @ImsFeature.FeatureType int imsFeature)2645     private void registerImsFeatureRegistrationState(int subId,
2646             @ImsFeature.FeatureType int imsFeature) {
2647         RegistrationManager.RegistrationCallback callback =
2648                 new RegistrationManager.RegistrationCallback() {
2649                     @Override
2650                     public void onRegistered(@NonNull ImsRegistrationAttributes attributes) {
2651                         log("IMS " + DataUtils.imsFeatureToString(imsFeature)
2652                                 + " registered. Attributes=" + attributes);
2653                         mRegisteredImsFeatures.add(imsFeature);
2654                     }
2655 
2656                     @Override
2657                     public void onUnregistered(@NonNull ImsReasonInfo info) {
2658                         log("IMS " + DataUtils.imsFeatureToString(imsFeature)
2659                                 + " deregistered. Info=" + info);
2660                         mRegisteredImsFeatures.remove(imsFeature);
2661                         evaluatePendingImsDeregDataNetworks();
2662                     }
2663                 };
2664 
2665         try {
2666             // Use switch here as we can't make a generic callback registration logic because
2667             // RcsManager does not implement RegistrationManager.
2668             switch (imsFeature) {
2669                 case ImsFeature.FEATURE_MMTEL:
2670                     mImsManager.getImsMmTelManager(subId).registerImsRegistrationCallback(
2671                             DataNetworkController.this::post, callback);
2672                     break;
2673                 case ImsFeature.FEATURE_RCS:
2674                     mImsManager.getImsRcsManager(subId).registerImsRegistrationCallback(
2675                             DataNetworkController.this::post, callback);
2676                     break;
2677             }
2678 
2679             // Store the callback so that we can unregister in the future.
2680             mImsFeatureRegistrationCallbacks.put(imsFeature, callback);
2681             log("Successfully register " + DataUtils.imsFeatureToString(imsFeature)
2682                     + " registration state. subId=" + subId);
2683         } catch (ImsException e) {
2684             loge("updateImsFeatureRegistrationStateListening: subId=" + subId
2685                     + ", imsFeature=" + DataUtils.imsFeatureToString(imsFeature) + ", " + e);
2686         }
2687     }
2688 
2689     /**
2690      * Unregister IMS feature callback.
2691      *
2692      * @param subId The subscription index.
2693      * @param imsFeature The IMS feature. Only {@link ImsFeature#FEATURE_MMTEL} and
2694      * {@link ImsFeature#FEATURE_RCS} are supported at this point.
2695      */
unregisterImsFeatureRegistrationState(int subId, @ImsFeature.FeatureType int imsFeature)2696     private void unregisterImsFeatureRegistrationState(int subId,
2697             @ImsFeature.FeatureType int imsFeature) {
2698         RegistrationManager.RegistrationCallback oldCallback =
2699                 mImsFeatureRegistrationCallbacks.get(imsFeature);
2700         if (oldCallback != null) {
2701             if (imsFeature == ImsFeature.FEATURE_MMTEL) {
2702                 mImsManager.getImsMmTelManager(subId)
2703                         .unregisterImsRegistrationCallback(oldCallback);
2704             } else if (imsFeature == ImsFeature.FEATURE_RCS) {
2705                 mImsManager.getImsRcsManager(subId)
2706                         .unregisterImsRegistrationCallback(oldCallback);
2707             }
2708             log("Successfully unregistered " + DataUtils.imsFeatureToString(imsFeature)
2709                     + " registration state. subId=" + subId);
2710             mImsFeatureRegistrationCallbacks.remove(imsFeature);
2711         }
2712     }
2713 
2714     /**
2715      * Register IMS state callback.
2716      *
2717      * @param subId Subscription index.
2718      */
registerImsStateCallback(int subId)2719     private void registerImsStateCallback(int subId) {
2720         if (isImsSupportedOnDevice()) {
2721             Function<Integer, ImsStateCallback> imsFeatureStateCallbackFactory =
2722                     imsFeature -> new ImsStateCallback() {
2723                         @Override
2724                         public void onUnavailable(int reason) {
2725                             // Unregister registration state update when IMS service is unbound.
2726                             unregisterImsFeatureRegistrationState(subId, imsFeature);
2727                         }
2728 
2729                         @Override
2730                         public void onAvailable() {
2731                             mImsFeaturePackageName.put(imsFeature, ImsResolver.getInstance()
2732                                     .getConfiguredImsServicePackageName(mPhone.getPhoneId(),
2733                                             imsFeature));
2734                             // Once IMS service is bound, register for registration state update.
2735                             registerImsFeatureRegistrationState(subId, imsFeature);
2736                         }
2737 
2738                         @Override
2739                         public void onError() {
2740                         }
2741                     };
2742 
2743             try {
2744                 ImsStateCallback callback = imsFeatureStateCallbackFactory
2745                         .apply(ImsFeature.FEATURE_MMTEL);
2746                 mImsManager.getImsMmTelManager(subId).registerImsStateCallback(this::post,
2747                         callback);
2748                 mImsStateCallbacks.put(ImsFeature.FEATURE_MMTEL, callback);
2749                 log("Successfully register MMTEL state on sub " + subId);
2750 
2751                 callback = imsFeatureStateCallbackFactory.apply(ImsFeature.FEATURE_RCS);
2752                 mImsManager.getImsRcsManager(subId).registerImsStateCallback(this::post, callback);
2753                 mImsStateCallbacks.put(ImsFeature.FEATURE_RCS, callback);
2754                 log("Successfully register RCS state on sub " + subId);
2755             } catch (ImsException e) {
2756                 loge("Exception when registering IMS state callback. " + e);
2757             }
2758         } else {
2759             log("IMS is not supported on this device, skipping registerImsStateCallback");
2760         }
2761     }
2762 
2763     /**
2764      * Unregister IMS feature state callbacks.
2765      *
2766      * @param subId Subscription index.
2767      */
unregisterImsStateCallbacks(int subId)2768     private void unregisterImsStateCallbacks(int subId) {
2769         if (isImsSupportedOnDevice()) {
2770             ImsStateCallback callback = mImsStateCallbacks.get(ImsFeature.FEATURE_MMTEL);
2771             if (callback != null) {
2772                 mImsManager.getImsMmTelManager(subId).unregisterImsStateCallback(callback);
2773                 mImsStateCallbacks.remove(ImsFeature.FEATURE_MMTEL);
2774                 log("Unregister MMTEL state on sub " + subId);
2775             }
2776 
2777             callback = mImsStateCallbacks.get(ImsFeature.FEATURE_RCS);
2778             if (callback != null) {
2779                 mImsManager.getImsRcsManager(subId).unregisterImsStateCallback(callback);
2780                 mImsStateCallbacks.remove(ImsFeature.FEATURE_RCS);
2781                 log("Unregister RCS state on sub " + subId);
2782             }
2783         } else {
2784             log("IMS is not supported on this device, skipping unregisterImsStateCallbacks");
2785         }
2786     }
2787 
2788     /**
2789      * called to check if FEATURE_TELEPHONY_IMS feature is available
2790      */
isImsSupportedOnDevice()2791     private boolean isImsSupportedOnDevice() {
2792         return mPhone.getContext().getPackageManager()
2793                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY_IMS);
2794     }
2795 
2796     /** Called when subscription info changed. */
onSubscriptionChanged()2797     private void onSubscriptionChanged() {
2798         if (mSubId != mPhone.getSubId()) {
2799             log("onDataConfigUpdated: mSubId changed from " + mSubId + " to "
2800                     + mPhone.getSubId());
2801             if (isImsGracefulTearDownSupported()) {
2802                 if (SubscriptionManager.isValidSubscriptionId(mPhone.getSubId())) {
2803                     registerImsStateCallback(mPhone.getSubId());
2804                 } else {
2805                     unregisterImsStateCallbacks(mSubId);
2806                 }
2807             }
2808             mSubId = mPhone.getSubId();
2809             updateSubscriptionPlans();
2810         }
2811     }
2812 
2813     /**
2814      * Called when carrier config was updated.
2815      */
onCarrierConfigUpdated()2816     private void onCarrierConfigUpdated() {
2817         log("onCarrierConfigUpdated: config is "
2818                 + (mDataConfigManager.isConfigCarrierSpecific() ? "" : "not ")
2819                 + "carrier specific. mSimState="
2820                 + TelephonyManager.simStateToString(mSimState));
2821         updateNetworkRequestsPriority();
2822         onReevaluateUnsatisfiedNetworkRequests(DataEvaluationReason.DATA_CONFIG_CHANGED);
2823     }
2824 
2825     /**
2826      * Called when device config was updated.
2827      */
onDeviceConfigUpdated()2828     private void onDeviceConfigUpdated() {
2829         log("onDeviceConfigUpdated: DeviceConfig updated.");
2830         updateAnomalySlidingWindowCounters();
2831     }
2832 
2833     /**
2834      * Update each network request's priority.
2835      */
updateNetworkRequestsPriority()2836     private void updateNetworkRequestsPriority() {
2837         for (TelephonyNetworkRequest networkRequest : mAllNetworkRequestList) {
2838             networkRequest.updatePriority();
2839         }
2840     }
2841 
2842     /**
2843      * Update the threshold of anomaly report counters
2844      */
updateAnomalySlidingWindowCounters()2845     private void updateAnomalySlidingWindowCounters() {
2846         mImsThrottleCounter = new SlidingWindowEventCounter(
2847                 mDataConfigManager.getAnomalyImsReleaseRequestThreshold().timeWindow,
2848                 mDataConfigManager.getAnomalyImsReleaseRequestThreshold().eventNumOccurrence);
2849         mNetworkUnwantedCounter = new SlidingWindowEventCounter(
2850                 mDataConfigManager.getAnomalyNetworkUnwantedThreshold().timeWindow,
2851                 mDataConfigManager.getAnomalyNetworkUnwantedThreshold().eventNumOccurrence);
2852         mSetupDataCallWwanFailureCounter = new SlidingWindowEventCounter(
2853                 mDataConfigManager.getAnomalySetupDataCallThreshold().timeWindow,
2854                 mDataConfigManager.getAnomalySetupDataCallThreshold().eventNumOccurrence);
2855         mSetupDataCallWlanFailureCounter = new SlidingWindowEventCounter(
2856                 mDataConfigManager.getAnomalySetupDataCallThreshold().timeWindow,
2857                 mDataConfigManager.getAnomalySetupDataCallThreshold().eventNumOccurrence);
2858     }
2859 
2860     /**
2861      * There have been several bugs where a RECONNECT loop kicks off where a data network
2862      * is brought up, but connectivity service indicates that the network is unwanted so telephony
2863      * tears down the network. But later telephony bring up the data network again and becomes an
2864      * infinite loop. By the time we get the bug report it's too late because there have already
2865      * been hundreds of bring up/tear down. This is meant to capture the issue when it first starts.
2866      */
onTrackNetworkUnwanted()2867     private void onTrackNetworkUnwanted() {
2868         if (mNetworkUnwantedCounter.addOccurrence()) {
2869             reportAnomaly("Network Unwanted called "
2870                             + mNetworkUnwantedCounter.getFrequencyString(),
2871                     "9f3bc55b-bfa6-4e26-afaa-5031426a66d3");
2872         }
2873     }
2874 
2875     /**
2876      * Find unsatisfied network requests that can be satisfied by the given data profile.
2877      *
2878      * @param dataProfile The data profile.
2879      * @return The network requests list.
2880      */
2881     @NonNull
findSatisfiableNetworkRequests(@onNull DataProfile dataProfile)2882     private NetworkRequestList findSatisfiableNetworkRequests(@NonNull DataProfile dataProfile) {
2883         return new NetworkRequestList(mAllNetworkRequestList.stream()
2884                 .filter(request -> request.getState()
2885                         == TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED)
2886                 .filter(request -> request.canBeSatisfiedBy(dataProfile))
2887                 .collect(Collectors.toList()));
2888     }
2889 
2890     /**
2891      * Setup data network.
2892      *
2893      * @param dataProfile The data profile to setup the data network.
2894      * @param dataSetupRetryEntry Data retry entry. {@code null} if this data network setup is not
2895      * initiated by a data retry.
2896      * @param allowedReason The reason that why setting up this data network is allowed.
2897      */
setupDataNetwork(@onNull DataProfile dataProfile, @Nullable DataSetupRetryEntry dataSetupRetryEntry, @NonNull DataAllowedReason allowedReason)2898     private void setupDataNetwork(@NonNull DataProfile dataProfile,
2899             @Nullable DataSetupRetryEntry dataSetupRetryEntry,
2900             @NonNull DataAllowedReason allowedReason) {
2901         log("onSetupDataNetwork: dataProfile=" + dataProfile + ", retryEntry="
2902                 + dataSetupRetryEntry + ", allowed reason=" + allowedReason + ", service state="
2903                 + mServiceState);
2904         for (DataNetwork dataNetwork : mDataNetworkList) {
2905             DataProfile currentDataProfile = dataNetwork.getDataProfile();
2906             if (dataProfile.equals(currentDataProfile)
2907                     || mDataProfileManager.areDataProfilesSharingApn(
2908                             dataProfile, currentDataProfile)) {
2909                 log("onSetupDataNetwork: Found existing data network " + dataNetwork
2910                         + " using the same or a similar data profile.");
2911                 if (dataSetupRetryEntry != null) {
2912                     dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
2913                 }
2914                 return;
2915             }
2916         }
2917 
2918         NetworkRequestList networkRequestList = findSatisfiableNetworkRequests(dataProfile);
2919 
2920         if (networkRequestList.isEmpty()) {
2921             log("Can't find any unsatisfied network requests that can be satisfied by this data "
2922                     + "profile.");
2923             if (dataSetupRetryEntry != null) {
2924                 dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
2925             }
2926 
2927             return;
2928         }
2929 
2930         int transport = mAccessNetworksManager.getPreferredTransportByNetworkCapability(
2931                 networkRequestList.get(0).getHighestPriorityApnTypeNetworkCapability());
2932         logl("Creating data network on "
2933                 + AccessNetworkConstants.transportTypeToString(transport) + " with " + dataProfile
2934                 + ", and attaching " + networkRequestList.size() + " network requests to it.");
2935 
2936         mDataNetworkList.add(new DataNetwork(mPhone, mFeatureFlags, getLooper(),
2937                 mDataServiceManagers, dataProfile, networkRequestList, transport, allowedReason,
2938                 new DataNetworkCallback(this::post) {
2939                     @Override
2940                     public void onSetupDataFailed(@NonNull DataNetwork dataNetwork,
2941                             @NonNull NetworkRequestList requestList, @DataFailureCause int cause,
2942                             long retryDelayMillis) {
2943                         if (dataSetupRetryEntry != null) {
2944                             dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_FAILED);
2945                         }
2946                         DataNetworkController.this.onDataNetworkSetupFailed(
2947                                 dataNetwork, requestList, cause, retryDelayMillis);
2948                     }
2949 
2950                     @Override
2951                     public void onConnected(@NonNull DataNetwork dataNetwork) {
2952                         if (dataSetupRetryEntry != null) {
2953                             dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_SUCCEEDED);
2954                         }
2955                         DataNetworkController.this.onDataNetworkConnected(dataNetwork);
2956                     }
2957 
2958                     @Override
2959                     public void onAttachFailed(@NonNull DataNetwork dataNetwork,
2960                             @NonNull NetworkRequestList requestList) {
2961                         DataNetworkController.this.onAttachNetworkRequestsFailed(
2962                                 dataNetwork, requestList);
2963                     }
2964 
2965                     @Override
2966                     public void onValidationStatusChanged(@NonNull DataNetwork dataNetwork,
2967                             @ValidationStatus int status, @Nullable Uri redirectUri) {
2968                         DataNetworkController.this.onDataNetworkValidationStatusChanged(
2969                                 dataNetwork, status, redirectUri);
2970                     }
2971 
2972                     @Override
2973                     public void onSuspendedStateChanged(@NonNull DataNetwork dataNetwork,
2974                             boolean suspended) {
2975                         DataNetworkController.this.onDataNetworkSuspendedStateChanged(
2976                                 dataNetwork, suspended);
2977                     }
2978 
2979                     @Override
2980                     public void onDisconnected(@NonNull DataNetwork dataNetwork,
2981                             @DataFailureCause int cause, @TearDownReason int tearDownReason) {
2982                         DataNetworkController.this.onDataNetworkDisconnected(
2983                                 dataNetwork, cause, tearDownReason);
2984                     }
2985 
2986                     @Override
2987                     public void onHandoverSucceeded(@NonNull DataNetwork dataNetwork) {
2988                         DataNetworkController.this.onDataNetworkHandoverSucceeded(dataNetwork);
2989                     }
2990 
2991                     @Override
2992                     public void onHandoverFailed(@NonNull DataNetwork dataNetwork,
2993                             @DataFailureCause int cause, long retryDelayMillis,
2994                             @HandoverFailureMode int handoverFailureMode) {
2995                         DataNetworkController.this.onDataNetworkHandoverFailed(
2996                                 dataNetwork, cause, retryDelayMillis, handoverFailureMode);
2997                     }
2998 
2999                     @Override
3000                     public void onLinkStatusChanged(@NonNull DataNetwork dataNetwork,
3001                             @LinkStatus int linkStatus) {
3002                         DataNetworkController.this.onLinkStatusChanged(dataNetwork, linkStatus);
3003                     }
3004 
3005                     @Override
3006                     public void onPcoDataChanged(@NonNull DataNetwork dataNetwork) {
3007                         DataNetworkController.this.onPcoDataChanged(dataNetwork);
3008                     }
3009 
3010                     @Override
3011                     public void onNetworkCapabilitiesChanged(@NonNull DataNetwork dataNetwork) {
3012                         DataNetworkController.this.onNetworkCapabilitiesChanged(dataNetwork);
3013                     }
3014 
3015                     @Override
3016                     public void onTrackNetworkUnwanted(@NonNull DataNetwork dataNetwork) {
3017                         DataNetworkController.this.onTrackNetworkUnwanted();
3018                     }
3019 
3020                     @Override
3021                     public void onRetryUnsatisfiedNetworkRequest(
3022                             @NonNull TelephonyNetworkRequest networkRequest) {
3023                         DataNetworkController.this.onRetryUnsatisfiedNetworkRequest(
3024                                 networkRequest);
3025                     }
3026 
3027                     @Override
3028                     public void onQosSessionsChanged(
3029                             @NonNull List<QosBearerSession> qosBearerSessions) {
3030                         mDataNetworkControllerCallbacks.forEach(
3031                                 callback -> callback.invokeFromExecutor(() ->
3032                                         callback.onQosSessionsChanged(qosBearerSessions)));
3033                     }
3034                 }
3035         ));
3036         if (!mAnyDataNetworkExisting) {
3037             mAnyDataNetworkExisting = true;
3038             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3039                     () -> callback.onAnyDataNetworkExistingChanged(mAnyDataNetworkExisting)));
3040         }
3041     }
3042 
3043     /**
3044      * Called when setup data network failed.
3045      *
3046      * @param dataNetwork The data network.
3047      * @param requestList The network requests attached to the data network.
3048      * @param cause The fail cause
3049      * @param retryDelayMillis The retry timer suggested by the network/data service.
3050      */
onDataNetworkSetupFailed(@onNull DataNetwork dataNetwork, @NonNull NetworkRequestList requestList, @DataFailureCause int cause, long retryDelayMillis)3051     private void onDataNetworkSetupFailed(@NonNull DataNetwork dataNetwork,
3052             @NonNull NetworkRequestList requestList, @DataFailureCause int cause,
3053             long retryDelayMillis) {
3054         logl("onDataNetworkSetupDataFailed: " + dataNetwork + ", cause="
3055                 + DataFailCause.toString(cause) + ", retryDelayMillis=" + retryDelayMillis + "ms.");
3056         mDataNetworkList.remove(dataNetwork);
3057         trackSetupDataCallFailure(dataNetwork.getTransport(), cause);
3058         if (mAnyDataNetworkExisting && mDataNetworkList.isEmpty()) {
3059             mAnyDataNetworkExisting = false;
3060             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3061                     () -> callback.onAnyDataNetworkExistingChanged(mAnyDataNetworkExisting)));
3062         }
3063 
3064         requestList.removeIf(request -> !mAllNetworkRequestList.contains(request));
3065         if (requestList.isEmpty()) {
3066             log("onDataNetworkSetupFailed: All requests have been released. "
3067                     + "Will not evaluate retry.");
3068             return;
3069         }
3070 
3071         // Data retry manager will determine if retry is needed. If needed, retry will be scheduled.
3072         mDataRetryManager.evaluateDataSetupRetry(dataNetwork.getDataProfile(),
3073                 dataNetwork.getTransport(), requestList, cause, retryDelayMillis);
3074     }
3075 
3076     /**
3077      * Track the frequency of setup data failure on each
3078      * {@link AccessNetworkConstants.TransportType} data service.
3079      *
3080      * @param transport The transport of the data service.
3081      * @param cause The fail cause
3082      */
trackSetupDataCallFailure(@ransportType int transport, @DataFailureCause int cause)3083     private void trackSetupDataCallFailure(@TransportType int transport,
3084             @DataFailureCause int cause) {
3085         switch (transport) {
3086             case AccessNetworkConstants.TRANSPORT_TYPE_WWAN:
3087                 // Skip when poor signal strength
3088                 if (mPhone.getSignalStrength().getLevel()
3089                         <= CellSignalStrength.SIGNAL_STRENGTH_POOR) {
3090                     return;
3091                 }
3092                 if (cause == DataFailCause.ERROR_UNSPECIFIED || cause == DataFailCause.UNKNOWN) {
3093                     reportAnomaly("RIL set up data call fails: unknown/unspecified error",
3094                             "ce7d1465-d8e4-404a-b76f-de2c60bee843");
3095                 }
3096                 if (mSetupDataCallWwanFailureCounter.addOccurrence()) {
3097                     reportAnomaly("RIL fails setup data call request "
3098                                     + mSetupDataCallWwanFailureCounter.getFrequencyString(),
3099                             "e6a98b97-9e34-4977-9a92-01d52a6691f6");
3100                 }
3101                 break;
3102             case AccessNetworkConstants.TRANSPORT_TYPE_WLAN:
3103                 if (cause == DataFailCause.ERROR_UNSPECIFIED || cause == DataFailCause.UNKNOWN) {
3104                     reportAnomaly("IWLAN set up data call fails: unknown/unspecified error",
3105                             "a16fc15c-815b-4908-b8e6-5f3bc7cbc20b");
3106                 }
3107                 if (mSetupDataCallWlanFailureCounter.addOccurrence()) {
3108                     reportAnomaly("IWLAN data service fails setup data call request "
3109                                     + mSetupDataCallWlanFailureCounter.getFrequencyString(),
3110                             "e2248d8b-d55f-42bd-871c-0cfd80c3ddd1");
3111                 }
3112                 break;
3113             default:
3114                 loge("trackSetupDataCallFailure: INVALID transport.");
3115         }
3116     }
3117 
3118     /**
3119      * Trigger the anomaly report with the specified UUID.
3120      *
3121      * @param anomalyMsg Description of the event
3122      * @param uuid UUID associated with that event
3123      */
reportAnomaly(@onNull String anomalyMsg, @NonNull String uuid)3124     private void reportAnomaly(@NonNull String anomalyMsg, @NonNull String uuid) {
3125         logl(anomalyMsg);
3126         AnomalyReporter.reportAnomaly(UUID.fromString(uuid), anomalyMsg, mPhone.getCarrierId());
3127     }
3128 
3129     /**
3130      * Called when data network is connected.
3131      *
3132      * @param dataNetwork The data network.
3133      */
onDataNetworkConnected(@onNull DataNetwork dataNetwork)3134     private void onDataNetworkConnected(@NonNull DataNetwork dataNetwork) {
3135         logl("onDataNetworkConnected: " + dataNetwork);
3136 
3137         mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3138                 () -> callback.onDataNetworkConnected(dataNetwork.getTransport(),
3139                         dataNetwork.getDataProfile())));
3140 
3141         mPreviousConnectedDataNetworkList.add(0, dataNetwork);
3142         // Preserve the connected data networks for debugging purposes.
3143         if (mPreviousConnectedDataNetworkList.size() > MAX_HISTORICAL_CONNECTED_DATA_NETWORKS) {
3144             mPreviousConnectedDataNetworkList.remove(MAX_HISTORICAL_CONNECTED_DATA_NETWORKS);
3145         }
3146 
3147         if (dataNetwork.isInternetSupported()) updateOverallInternetDataState();
3148 
3149         if (dataNetwork.getNetworkCapabilities().hasCapability(
3150                 NetworkCapabilities.NET_CAPABILITY_IMS)) {
3151             logl("IMS data state changed from "
3152                     + TelephonyUtils.dataStateToString(mImsDataNetworkState) + " to CONNECTED.");
3153             mImsDataNetworkState = TelephonyManager.DATA_CONNECTED;
3154         }
3155 
3156         if (isEsimBootStrapProvisioningActivated()) {
3157             sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3158                     DataEvaluationReason.CHECK_DATA_USAGE),
3159                     mDataConfigManager.getReevaluateBootstrapSimDataUsageMillis());
3160         }
3161     }
3162 
3163     /**
3164      * Called when needed to retry data setup.
3165      *
3166      * @param dataSetupRetryEntry The data setup retry entry scheduled by {@link DataRetryManager}.
3167      */
onDataNetworkSetupRetry(@onNull DataSetupRetryEntry dataSetupRetryEntry)3168     private void onDataNetworkSetupRetry(@NonNull DataSetupRetryEntry dataSetupRetryEntry) {
3169         // The request might be already removed before retry happens. Remove them from the list
3170         // if that's the case. Copy the list first. We don't want to remove the requests from
3171         // the retry entry. They can be later used to determine what kind of retry it is.
3172         NetworkRequestList requestList = new NetworkRequestList(
3173                 dataSetupRetryEntry.networkRequestList);
3174         requestList.removeIf(request -> !mAllNetworkRequestList.contains(request));
3175         // Retrieves the newly added unsatisfied NetworkRequest if all NetworkRequests in the
3176         // DataSetupRetryEntry have already been removed.
3177         if (requestList.isEmpty()) {
3178             List<NetworkRequestList> groupRequestLists = getGroupedUnsatisfiedNetworkRequests();
3179             dataSetupRetryEntry.networkRequestList.stream()
3180                     .filter(request -> groupRequestLists.stream()
3181                             .anyMatch(groupRequestList -> {
3182                                 // The unsatisfied request has all the requested capabilities.
3183                                 if (groupRequestList.get(request.getCapabilities()) == null) {
3184                                     return false;
3185                                 }
3186                                 TelephonyNetworkRequest leading = groupRequestList.getFirst();
3187                                 // The unsatisfied request covers all the requested transports.
3188                                 return leading.getTransportTypes().length == 0
3189                                         || request.getTransportTypes().length == 0
3190                                         || Arrays.stream(request.getTransportTypes())
3191                                         .allMatch(leading::hasTransport);
3192                             }))
3193                     .forEach(requestList::add);
3194         }
3195         if (requestList.isEmpty()) {
3196             loge("onDataNetworkSetupRetry: Request list is empty. Abort retry.");
3197             dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3198             return;
3199         }
3200         log("onDataNetworkSetupRetry: Request list:" + requestList);
3201         TelephonyNetworkRequest telephonyNetworkRequest = requestList.get(0);
3202 
3203         int networkCapability = telephonyNetworkRequest
3204                 .getHighestPriorityApnTypeNetworkCapability();
3205         int preferredTransport = mAccessNetworksManager.getPreferredTransportByNetworkCapability(
3206                 networkCapability);
3207         if (preferredTransport != dataSetupRetryEntry.transport) {
3208             log("Cannot re-satisfy " + telephonyNetworkRequest + " on "
3209                     + AccessNetworkConstants.transportTypeToString(dataSetupRetryEntry.transport)
3210                     + ". The preferred transport has switched to "
3211                     + AccessNetworkConstants.transportTypeToString(preferredTransport)
3212                     + ". " + dataSetupRetryEntry);
3213             // Cancel the retry since the preferred transport has already changed, but then
3214             // re-evaluate the unsatisfied network requests again so the new network can be brought
3215             // up on the new target transport later.
3216             dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3217             sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
3218                     DataEvaluationReason.PREFERRED_TRANSPORT_CHANGED));
3219             return;
3220         }
3221 
3222         DataEvaluation evaluation = evaluateNetworkRequest(
3223                 telephonyNetworkRequest, DataEvaluationReason.DATA_RETRY);
3224         if (!evaluation.containsDisallowedReasons()) {
3225             DataProfile dataProfile = dataSetupRetryEntry.dataProfile;
3226             if (dataProfile == null || !mDataProfileManager.isDataProfileCompatible(dataProfile)) {
3227                 dataProfile = evaluation.getCandidateDataProfile();
3228             }
3229             if (dataProfile != null) {
3230                 setupDataNetwork(dataProfile, dataSetupRetryEntry,
3231                         evaluation.getDataAllowedReason());
3232             } else {
3233                 loge("onDataNetworkSetupRetry: Not able to find a suitable data profile to retry.");
3234                 dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_FAILED);
3235             }
3236         } else {
3237             dataSetupRetryEntry.setState(DataRetryEntry.RETRY_STATE_FAILED);
3238         }
3239     }
3240 
3241     /**
3242      * Called when needed to retry data network handover.
3243      *
3244      * @param dataHandoverRetryEntry The handover entry.
3245      */
onDataNetworkHandoverRetry( @onNull DataHandoverRetryEntry dataHandoverRetryEntry)3246     private void onDataNetworkHandoverRetry(
3247             @NonNull DataHandoverRetryEntry dataHandoverRetryEntry) {
3248         DataNetwork dataNetwork = dataHandoverRetryEntry.dataNetwork;
3249         if (!mDataNetworkList.contains(dataNetwork)) {
3250             log("onDataNetworkHandoverRetry: " + dataNetwork + " no longer exists.");
3251             dataHandoverRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3252             return;
3253         }
3254 
3255         if (!dataNetwork.isConnected()) {
3256             log("onDataNetworkHandoverRetry: " + dataNetwork + " is not in the right state.");
3257             dataHandoverRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3258             return;
3259         }
3260 
3261         int preferredTransport = mAccessNetworksManager.getPreferredTransportByNetworkCapability(
3262                 dataNetwork.getApnTypeNetworkCapability());
3263         if (dataNetwork.getTransport() == preferredTransport) {
3264             log("onDataNetworkHandoverRetry: " + dataNetwork + " is already on the preferred "
3265                     + "transport " + AccessNetworkConstants.transportTypeToString(
3266                             preferredTransport) + ".");
3267             dataHandoverRetryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3268             return;
3269         }
3270 
3271         logl("onDataNetworkHandoverRetry: Start handover " + dataNetwork + " to "
3272                 + AccessNetworkConstants.transportTypeToString(preferredTransport)
3273                 + ", " + dataHandoverRetryEntry);
3274         tryHandoverDataNetwork(dataNetwork, preferredTransport, dataHandoverRetryEntry);
3275     }
3276 
3277     /**
3278      * Called when data network reached max handover retry count.
3279      *
3280      * @param dataNetwork The data network.
3281      */
onDataNetworkHandoverRetryStopped(@onNull DataNetwork dataNetwork)3282     private void onDataNetworkHandoverRetryStopped(@NonNull DataNetwork dataNetwork) {
3283         int preferredTransport = mAccessNetworksManager
3284                 .getPreferredTransportByNetworkCapability(
3285                         dataNetwork.getApnTypeNetworkCapability());
3286         if (dataNetwork.getTransport() == preferredTransport) {
3287             log("onDataNetworkHandoverRetryStopped: " + dataNetwork + " is already "
3288                     + "on the preferred transport "
3289                     + AccessNetworkConstants.transportTypeToString(
3290                     preferredTransport));
3291             return;
3292         }
3293         if (dataNetwork.shouldDelayImsTearDownDueToInCall()) {
3294             log("onDataNetworkHandoverRetryStopped: Delay IMS tear down until call "
3295                     + "ends. " + dataNetwork);
3296             return;
3297         }
3298 
3299         tearDownGracefully(dataNetwork,
3300                 DataNetwork.TEAR_DOWN_REASON_HANDOVER_FAILED);
3301     }
3302 
3303     /**
3304      * Called when data network validation status changed.
3305      *
3306      * @param status one of {@link NetworkAgent#VALIDATION_STATUS_VALID} or
3307      * {@link NetworkAgent#VALIDATION_STATUS_NOT_VALID}.
3308      * @param redirectUri If internet connectivity is being redirected (e.g., on a captive portal),
3309      * this is the destination the probes are being redirected to, otherwise {@code null}.
3310      *
3311      * @param dataNetwork The data network.
3312      */
onDataNetworkValidationStatusChanged(@onNull DataNetwork dataNetwork, @ValidationStatus int status, @Nullable Uri redirectUri)3313     private void onDataNetworkValidationStatusChanged(@NonNull DataNetwork dataNetwork,
3314             @ValidationStatus int status, @Nullable Uri redirectUri) {
3315         log("onDataNetworkValidationStatusChanged: " + dataNetwork + ", validation status="
3316                 + DataUtils.validationStatusToString(status)
3317                 + (redirectUri != null ? ", " + redirectUri : ""));
3318         if (!TextUtils.isEmpty(redirectUri.toString())) {
3319             Intent intent = new Intent(TelephonyManager.ACTION_CARRIER_SIGNAL_REDIRECTED);
3320             intent.putExtra(TelephonyManager.EXTRA_REDIRECTION_URL, redirectUri);
3321             mPhone.getCarrierSignalAgent().notifyCarrierSignalReceivers(intent);
3322             log("Notify carrier signal receivers with redirectUri: " + redirectUri);
3323         }
3324 
3325         if (status != NetworkAgent.VALIDATION_STATUS_VALID
3326                 && status != NetworkAgent.VALIDATION_STATUS_NOT_VALID) {
3327             loge("Invalid validation status " + status + " received.");
3328             return;
3329         }
3330 
3331         if (!mDataSettingsManager.isRecoveryOnBadNetworkEnabled()) {
3332             log("Ignore data network validation status changed because "
3333                     + "data stall recovery is disabled.");
3334             return;
3335         }
3336 
3337         // Only track the networks that require validation.
3338         // The criteria is base on NetworkMonitorUtils.java.
3339         NetworkCapabilities capabilities = dataNetwork.getNetworkCapabilities();
3340         if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
3341                 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3342                 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
3343                 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
3344             if (status == NetworkAgent.VALIDATION_STATUS_NOT_VALID
3345                     && (dataNetwork.getCurrentState() == null || dataNetwork.isDisconnected())) {
3346                 log("Ignoring invalid validation status for disconnected DataNetwork");
3347                 return;
3348             }
3349             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3350                     () -> callback.onInternetDataNetworkValidationStatusChanged(status)));
3351         }
3352     }
3353 
3354     /**
3355      * Called when data network suspended state changed.
3356      *
3357      * @param dataNetwork The data network.
3358      * @param suspended {@code true} if data is suspended.
3359      */
onDataNetworkSuspendedStateChanged(@onNull DataNetwork dataNetwork, boolean suspended)3360     private void onDataNetworkSuspendedStateChanged(@NonNull DataNetwork dataNetwork,
3361             boolean suspended) {
3362         if (dataNetwork.isInternetSupported()) updateOverallInternetDataState();
3363 
3364         if (dataNetwork.getNetworkCapabilities().hasCapability(
3365                 NetworkCapabilities.NET_CAPABILITY_IMS)) {
3366             logl("IMS data state changed from "
3367                     + TelephonyUtils.dataStateToString(mImsDataNetworkState) + " to "
3368                     + (suspended ? "SUSPENDED" : "CONNECTED"));
3369             mImsDataNetworkState = suspended
3370                     ? TelephonyManager.DATA_SUSPENDED : TelephonyManager.DATA_CONNECTED;
3371         }
3372     }
3373 
3374     /**
3375      * Called when data network disconnected.
3376      *
3377      * @param dataNetwork The data network.
3378      * @param cause The disconnect cause.
3379      * @param tearDownReason The reason the network was torn down
3380      */
onDataNetworkDisconnected(@onNull DataNetwork dataNetwork, @DataFailureCause int cause, @TearDownReason int tearDownReason)3381     private void onDataNetworkDisconnected(@NonNull DataNetwork dataNetwork,
3382             @DataFailureCause int cause, @TearDownReason int tearDownReason) {
3383         logl("onDataNetworkDisconnected: " + dataNetwork + ", cause="
3384                 + DataFailCause.toString(cause) + "(" + cause + "), tearDownReason="
3385                 + DataNetwork.tearDownReasonToString(tearDownReason));
3386         mDataNetworkList.remove(dataNetwork);
3387         mPendingImsDeregDataNetworks.remove(dataNetwork);
3388         mDataRetryManager.cancelPendingHandoverRetry(dataNetwork);
3389         if (dataNetwork.isInternetSupported()) updateOverallInternetDataState();
3390         onPcoDataChanged(dataNetwork);
3391 
3392         if (dataNetwork.getNetworkCapabilities().hasCapability(
3393                 NetworkCapabilities.NET_CAPABILITY_IMS)) {
3394             logl("IMS data state changed from "
3395                     + TelephonyUtils.dataStateToString(mImsDataNetworkState) + " to DISCONNECTED.");
3396             mImsDataNetworkState = TelephonyManager.DATA_DISCONNECTED;
3397         }
3398 
3399         if (mAnyDataNetworkExisting && mDataNetworkList.isEmpty()) {
3400             log("All data networks disconnected now.");
3401             mAnyDataNetworkExisting = false;
3402             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3403                     () -> callback.onAnyDataNetworkExistingChanged(mAnyDataNetworkExisting)));
3404         }
3405 
3406         // Immediately reestablish on target transport if network was torn down due to policy
3407         long delayMillis = tearDownReason == DataNetwork.TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED
3408                 ? 0 : mDataConfigManager.getRetrySetupAfterDisconnectMillis();
3409         // Sometimes network was unsolicitedly reported lost for reasons. We should re-evaluate
3410         // and see if data network can be re-established again.
3411         sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
3412                         DataEvaluationReason.RETRY_AFTER_DISCONNECTED), delayMillis);
3413     }
3414 
3415     /**
3416      * Called when handover between IWLAN and cellular network succeeded.
3417      *
3418      * @param dataNetwork The data network.
3419      */
onDataNetworkHandoverSucceeded(@onNull DataNetwork dataNetwork)3420     private void onDataNetworkHandoverSucceeded(@NonNull DataNetwork dataNetwork) {
3421         logl("Handover successfully. " + dataNetwork + " to " + AccessNetworkConstants
3422                 .transportTypeToString(dataNetwork.getTransport()));
3423         // The preferred transport might be changed when handover was in progress. We need to
3424         // evaluate again to make sure we are not out-of-sync with the input from access network
3425         // manager.
3426         sendMessage(obtainMessage(EVENT_EVALUATE_PREFERRED_TRANSPORT,
3427                 dataNetwork.getApnTypeNetworkCapability(), 0));
3428 
3429         // There might be network we didn't tear down in the last evaluation due to handover in
3430         // progress. We should evaluate again.
3431         sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3432                 DataEvaluationReason.DATA_HANDOVER));
3433     }
3434 
3435     /**
3436      * Called when data network handover between IWLAN and cellular network failed.
3437      *
3438      * @param dataNetwork The data network.
3439      * @param cause The fail cause.
3440      * @param retryDelayMillis Network suggested retry time in milliseconds.
3441      * {@link Long#MAX_VALUE} indicates data retry should not occur.
3442      * {@link DataCallResponse#RETRY_DURATION_UNDEFINED} indicates network did not suggest any
3443      * retry duration.
3444      * @param handoverFailureMode The handover failure mode that determine the behavior of
3445      * how frameworks should handle the handover failure.
3446      */
onDataNetworkHandoverFailed(@onNull DataNetwork dataNetwork, @DataFailureCause int cause, long retryDelayMillis, @HandoverFailureMode int handoverFailureMode)3447     private void onDataNetworkHandoverFailed(@NonNull DataNetwork dataNetwork,
3448             @DataFailureCause int cause, long retryDelayMillis,
3449             @HandoverFailureMode int handoverFailureMode) {
3450         logl("Handover failed. " + dataNetwork + ", cause=" + DataFailCause.toString(cause)
3451                 + ", retryDelayMillis=" + retryDelayMillis + "ms, handoverFailureMode="
3452                 + DataCallResponse.failureModeToString(handoverFailureMode));
3453         // There might be network we didn't tear down in the last evaluation due to handover in
3454         // progress. We should evaluate again.
3455         sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3456                 DataEvaluationReason.DATA_HANDOVER));
3457 
3458         if (dataNetwork.getAttachedNetworkRequestList().isEmpty()) {
3459             log("onDataNetworkHandoverFailed: No network requests attached to " + dataNetwork
3460                     + ". No need to retry since the network will be torn down soon.");
3461             return;
3462         }
3463 
3464         if (handoverFailureMode == DataCallResponse.HANDOVER_FAILURE_MODE_DO_FALLBACK
3465                 || (handoverFailureMode == DataCallResponse.HANDOVER_FAILURE_MODE_LEGACY
3466                 && cause == DataFailCause.HANDOFF_PREFERENCE_CHANGED)) {
3467             // Don't retry handover anymore. Give QNS some time to switch the preferred transport
3468             // to the original one, but we should re-evaluate the preferred transport again to
3469             // make sure QNS does change it back, if not, we still need to perform handover at that
3470             // time.
3471             sendMessageDelayed(obtainMessage(EVENT_EVALUATE_PREFERRED_TRANSPORT,
3472                     dataNetwork.getApnTypeNetworkCapability(), 0),
3473                     REEVALUATE_PREFERRED_TRANSPORT_DELAY_MILLIS);
3474         } else if (handoverFailureMode == DataCallResponse
3475                 .HANDOVER_FAILURE_MODE_NO_FALLBACK_RETRY_SETUP_NORMAL || handoverFailureMode
3476                 == DataCallResponse.HANDOVER_FAILURE_MODE_LEGACY) {
3477             int preferredTransport = mAccessNetworksManager
3478                     .getPreferredTransportByNetworkCapability(
3479                             dataNetwork.getApnTypeNetworkCapability());
3480             if (dataNetwork.getTransport() == preferredTransport) {
3481                 log("onDataNetworkHandoverFailed: Already on preferred transport "
3482                         + AccessNetworkConstants.transportTypeToString(preferredTransport)
3483                         + ". No further actions needed.");
3484                 return;
3485             }
3486 
3487             int targetTransport = DataUtils.getTargetTransport(dataNetwork.getTransport());
3488             mDataRetryManager.evaluateDataSetupRetry(dataNetwork.getDataProfile(), targetTransport,
3489                     dataNetwork.getAttachedNetworkRequestList(), cause, retryDelayMillis);
3490             // Tear down the data network on source transport. Retry manager will schedule
3491             // setup a new data network on the target transport.
3492             tearDownGracefully(dataNetwork, DataNetwork.TEAR_DOWN_REASON_HANDOVER_FAILED);
3493         } else {
3494             mDataRetryManager.evaluateDataHandoverRetry(dataNetwork, cause, retryDelayMillis);
3495         }
3496     }
3497 
3498     /**
3499      * Called when network requests failed to attach to the data network.
3500      *
3501      * @param dataNetwork The data network that can't be attached.
3502      * @param requestList The requests failed to attach to the network.
3503      */
onAttachNetworkRequestsFailed(@onNull DataNetwork dataNetwork, @NonNull NetworkRequestList requestList)3504     private void onAttachNetworkRequestsFailed(@NonNull DataNetwork dataNetwork,
3505             @NonNull NetworkRequestList requestList) {
3506         log("Failed to attach " + requestList + " to " + dataNetwork);
3507     }
3508 
3509     /**
3510      * Called when a network request is detached from the data network and should be retried.
3511      *
3512      * @param networkRequest The detached network request.
3513      */
onRetryUnsatisfiedNetworkRequest( @onNull TelephonyNetworkRequest networkRequest)3514     private void onRetryUnsatisfiedNetworkRequest(
3515             @NonNull TelephonyNetworkRequest networkRequest) {
3516         if (!mAllNetworkRequestList.contains(networkRequest)) return;
3517 
3518         sendMessageDelayed(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
3519                         DataEvaluationReason.UNSATISFIED_REQUEST_DETACHED),
3520                 REEVALUATE_UNSATISFIED_NETWORK_REQUESTS_AFTER_DETACHED_DELAY_MILLIS);
3521     }
3522 
3523     /**
3524      * Called when data stall occurs and needed to tear down / setup a new data network for
3525      * internet. This event is from {@link DataStallRecoveryManager}.
3526      */
onDataStallReestablishInternet()3527     private void onDataStallReestablishInternet() {
3528         log("onDataStallReestablishInternet: Tear down data networks that support internet.");
3529         // Tear down all data networks that support internet. After data disconnected, unsatisfied
3530         // network requests will be re-evaluate again and data network controller will attempt to
3531         // setup data networks to satisfy them.
3532         mDataNetworkList.stream()
3533                 .filter(DataNetwork::isInternetSupported)
3534                 .forEach(dataNetwork -> dataNetwork.tearDown(
3535                         DataNetwork.TEAR_DOWN_REASON_DATA_STALL));
3536     }
3537 
3538     /**
3539      * Called when SRVCC handover state changes. To preserve the voice call, we don't tear down the
3540      * IMS network while handover in process. We reevaluate the network when handover ends.
3541      *
3542      * @param state The handover state of SRVCC
3543      */
onSrvccStateChanged(@onNull int[] state)3544     private void onSrvccStateChanged(@NonNull int[] state) {
3545         if (state != null && state.length != 0) {
3546             log("onSrvccStateChanged: " + TelephonyManager.srvccStateToString(state[0]));
3547             mIsSrvccHandoverInProcess = state[0] == TelephonyManager.SRVCC_STATE_HANDOVER_STARTED;
3548             // Reevaluate networks if SRVCC ends.
3549             if (!mIsSrvccHandoverInProcess
3550                     && !hasMessages(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)) {
3551                 sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3552                         DataEvaluationReason.SRVCC_STATE_CHANGED));
3553             }
3554         }
3555     }
3556 
3557     /**
3558      * Called when data service binding changed.
3559      *
3560      * @param transport The transport of the changed data service.
3561      * @param bound {@code true} if data service is bound.
3562      */
onDataServiceBindingChanged(@ransportType int transport, boolean bound)3563     private void onDataServiceBindingChanged(@TransportType int transport, boolean bound) {
3564         log("onDataServiceBindingChanged: " + AccessNetworkConstants
3565                 .transportTypeToString(transport) + " data service is "
3566                 + (bound ? "bound." : "unbound."));
3567         if (bound) {
3568             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3569                     () -> callback.onDataServiceBound(transport)));
3570         }
3571         mDataServiceBound.put(transport, bound);
3572     }
3573 
3574     /**
3575      * Called when SIM is absent.
3576      */
onSimAbsent()3577     private void onSimAbsent() {
3578         log("onSimAbsent");
3579         sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3580                 DataEvaluationReason.SIM_REMOVAL));
3581     }
3582 
3583     /**
3584      * Called when SIM state changes.
3585      *
3586      * @param simState SIM state. (Note this is mixed with card state and application state.)
3587      */
onSimStateChanged(@imState int simState)3588     private void onSimStateChanged(@SimState int simState) {
3589         log("onSimStateChanged: state=" + TelephonyManager.simStateToString(simState));
3590         if (mSimState != simState) {
3591             mSimState = simState;
3592             if (simState == TelephonyManager.SIM_STATE_ABSENT) {
3593                 onSimAbsent();
3594             } else if (simState == TelephonyManager.SIM_STATE_LOADED) {
3595                 sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
3596                         DataEvaluationReason.SIM_LOADED));
3597             }
3598         }
3599     }
3600 
3601     /**
3602      * Called when needed to evaluate the preferred transport for certain capability.
3603      *
3604      * @param capability The network capability to evaluate.
3605      * @param forceReconnect indicates whether enforce reconnection to move to the preferred
3606      *                       transport type.
3607      *
3608      */
onEvaluatePreferredTransport( @etCapability int capability, boolean forceReconnect)3609     private void onEvaluatePreferredTransport(
3610             @NetCapability int capability, boolean forceReconnect) {
3611         int preferredTransport = mAccessNetworksManager
3612                 .getPreferredTransportByNetworkCapability(capability);
3613         log("onEvaluatePreferredTransport: " + DataUtils.networkCapabilityToString(capability)
3614                 + " preferred on "
3615                 + AccessNetworkConstants.transportTypeToString(preferredTransport));
3616         for (DataNetwork dataNetwork : mDataNetworkList) {
3617             if (dataNetwork.getApnTypeNetworkCapability() == capability) {
3618                 // Check if the data network's current transport is different than from the
3619                 // preferred transport. If it's different, then handover is needed.
3620                 if (dataNetwork.getTransport() == preferredTransport) {
3621                     log("onEvaluatePreferredTransport:" + dataNetwork + " already on "
3622                             + AccessNetworkConstants.transportTypeToString(preferredTransport));
3623                     continue;
3624                 }
3625 
3626                 // If handover is ongoing, ignore the preference change for now. After handover
3627                 // succeeds or fails, preferred transport will be re-evaluate again. Handover will
3628                 // be performed at that time if needed.
3629                 if (dataNetwork.isHandoverInProgress()) {
3630                     log("onEvaluatePreferredTransport: " + dataNetwork + " handover in progress.");
3631                     continue;
3632                 }
3633 
3634                 if (forceReconnect) {
3635                     tearDownGracefully(
3636                             dataNetwork, DataNetwork.TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED);
3637                 } else {
3638                     tryHandoverDataNetwork(
3639                             dataNetwork, preferredTransport, null/*handoverRetryEntry*/);
3640                 }
3641             }
3642         }
3643     }
3644 
3645     /**
3646      * Perform data network handover if condition allows, otherwise tear down the network to allow
3647      * new network setup on the target transport.
3648      *
3649      * @param dataNetwork The network on which the handover occurs
3650      * @param targetTransport The target transport of the handover
3651      * @param dataHandoverRetryEntry {@code null} if the handover attempt is not due to scheduled
3652      *                                           retry
3653      */
tryHandoverDataNetwork(@onNull DataNetwork dataNetwork, @TransportType int targetTransport, @Nullable DataHandoverRetryEntry dataHandoverRetryEntry)3654     private void tryHandoverDataNetwork(@NonNull DataNetwork dataNetwork,
3655             @TransportType int targetTransport,
3656             @Nullable DataHandoverRetryEntry dataHandoverRetryEntry) {
3657         if (dataHandoverRetryEntry == null // This handover is a new request
3658                 && mDataRetryManager.isAnyHandoverRetryScheduled(dataNetwork)) {
3659             log("tryHandoverDataNetwork: retry scheduled for" + dataNetwork
3660                     + ", ignore this attempt");
3661             return;
3662         }
3663         DataEvaluation dataEvaluation = evaluateDataNetworkHandover(dataNetwork);
3664         log("tryHandoverDataNetwork: " + dataEvaluation + ", " + dataNetwork);
3665         if (!dataEvaluation.containsDisallowedReasons()) {
3666             logl("Start handover " + dataNetwork + " to "
3667                     + AccessNetworkConstants.transportTypeToString(targetTransport));
3668             dataNetwork.startHandover(targetTransport, dataHandoverRetryEntry);
3669         } else if (dataNetwork.shouldDelayImsTearDownDueToInCall()
3670                 && (dataEvaluation.containsOnly(DataDisallowedReason.NOT_IN_SERVICE)
3671                 || dataEvaluation.isSubsetOf(DataDisallowedReason.NOT_IN_SERVICE,
3672                         DataDisallowedReason.NOT_ALLOWED_BY_POLICY))) {
3673             // We try our best to preserve the voice call by retrying later
3674             if (dataHandoverRetryEntry != null) {
3675                 dataHandoverRetryEntry.setState(DataRetryEntry.RETRY_STATE_FAILED);
3676             }
3677             mDataRetryManager.evaluateDataHandoverRetry(dataNetwork,
3678                     DataFailCause.HANDOVER_FAILED,
3679                     DataCallResponse.RETRY_DURATION_UNDEFINED /* retry mills */);
3680             logl("tryHandoverDataNetwork: Scheduled retry due to in voice call and target OOS");
3681         } else if (dataEvaluation.containsAny(DataDisallowedReason.NOT_ALLOWED_BY_POLICY,
3682                 DataDisallowedReason.NOT_IN_SERVICE,
3683                 DataDisallowedReason.VOPS_NOT_SUPPORTED)) {
3684             logl("tryHandoverDataNetwork: Handover not allowed. Tear down"
3685                     + dataNetwork + " so a new network can be setup on "
3686                     + AccessNetworkConstants.transportTypeToString(targetTransport));
3687             tearDownGracefully(dataNetwork,
3688                     DataNetwork.TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED);
3689         } else if (dataEvaluation.containsAny(DataDisallowedReason.ILLEGAL_STATE,
3690                 DataDisallowedReason.RETRY_SCHEDULED)) {
3691             logl("tryHandoverDataNetwork: Handover not allowed. " + dataNetwork
3692                     + " will remain on " + AccessNetworkConstants.transportTypeToString(
3693                     dataNetwork.getTransport()));
3694         } else {
3695             loge("tryHandoverDataNetwork: Unexpected handover evaluation result.");
3696         }
3697     }
3698 
3699     /**
3700      * Update {@link SubscriptionPlan}s from {@link NetworkPolicyManager}.
3701      */
updateSubscriptionPlans()3702     private void updateSubscriptionPlans() {
3703         SubscriptionPlan[] plans = mNetworkPolicyManager.getSubscriptionPlans(
3704                 mSubId, mPhone.getContext().getOpPackageName());
3705         mSubscriptionPlans.clear();
3706         mSubscriptionPlans.addAll(plans != null ? Arrays.asList(plans) : Collections.emptyList());
3707         mCongestedOverrideNetworkTypes.clear();
3708         mUnmeteredOverrideNetworkTypes.clear();
3709         log("Subscription plans initialized: " + mSubscriptionPlans);
3710     }
3711 
3712     /**
3713      * Called when data network's link status changed.
3714      *
3715      * @param dataNetwork The data network that has link status changed.
3716      * @param linkStatus The link status (i.e. RRC state).
3717      */
onLinkStatusChanged(@onNull DataNetwork dataNetwork, @LinkStatus int linkStatus)3718     private void onLinkStatusChanged(@NonNull DataNetwork dataNetwork, @LinkStatus int linkStatus) {
3719         // TODO: Since this is only used for 5G icon display logic, so we only use internet data
3720         //   data network's link status. Consider expanding to all data networks if needed, and
3721         //   should use CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL
3722         //   to determine if using all data networks or only internet data networks.
3723         int status = DataCallResponse.LINK_STATUS_INACTIVE;
3724         boolean anyInternet = mDataNetworkList.stream()
3725                 .anyMatch(network -> network.isInternetSupported() && network.isConnected());
3726         if (anyInternet) {
3727             status = mDataNetworkList.stream()
3728                     .anyMatch(network -> network.isInternetSupported()
3729                             && network.isConnected() && network.getLinkStatus()
3730                             == DataCallResponse.LINK_STATUS_ACTIVE)
3731                     ? DataCallResponse.LINK_STATUS_ACTIVE
3732                     : DataCallResponse.LINK_STATUS_DORMANT;
3733         }
3734 
3735         if (mInternetLinkStatus != status) {
3736             log("Internet link status changed to " + DataUtils.linkStatusToString(status));
3737             mInternetLinkStatus = status;
3738             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3739                     () -> callback.onPhysicalLinkStatusChanged(mInternetLinkStatus)));
3740         }
3741 
3742         updateDataActivity();
3743     }
3744 
3745     /**
3746      * Called when PCO data changed.
3747      *
3748      * @param dataNetwork The data network.
3749      */
onPcoDataChanged(@onNull DataNetwork dataNetwork)3750     private void onPcoDataChanged(@NonNull DataNetwork dataNetwork) {
3751         // Check if any data network is using NR advanced bands.
3752         int nrAdvancedPcoId = mDataConfigManager.getNrAdvancedCapablePcoId();
3753         if (nrAdvancedPcoId != 0) {
3754             boolean nrAdvancedCapableByPco = false;
3755             for (DataNetwork network : mDataNetworkList) {
3756                 PcoData pcoData = network.getPcoData().get(nrAdvancedPcoId);
3757                 if (pcoData != null && pcoData.contents.length > 0
3758                         && pcoData.contents[pcoData.contents.length - 1] == 1) {
3759                     nrAdvancedCapableByPco = true;
3760                     break;
3761                 }
3762             }
3763 
3764             if (nrAdvancedCapableByPco != mNrAdvancedCapableByPco) {
3765                 log("onPcoDataChanged: mNrAdvancedCapableByPco = " + nrAdvancedCapableByPco);
3766                 mNrAdvancedCapableByPco = nrAdvancedCapableByPco;
3767                 mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
3768                         () -> callback.onNrAdvancedCapableByPcoChanged(mNrAdvancedCapableByPco)));
3769             }
3770         }
3771     }
3772 
3773     /**
3774      * Called when network capabilities changed.
3775      *
3776      * @param dataNetwork The data network.
3777      */
onNetworkCapabilitiesChanged(@onNull DataNetwork dataNetwork)3778     private void onNetworkCapabilitiesChanged(@NonNull DataNetwork dataNetwork) {
3779         // The network capabilities changed. See if there are unsatisfied network requests that
3780         // become satisfiable.
3781         NetworkRequestList networkRequestList = new NetworkRequestList();
3782         for (TelephonyNetworkRequest networkRequest : mAllNetworkRequestList) {
3783             if (networkRequest.getState() == TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED) {
3784                 if (networkRequest.canBeSatisfiedBy(dataNetwork.getNetworkCapabilities())) {
3785                     networkRequestList.add(networkRequest);
3786                 }
3787             }
3788         }
3789 
3790         if (!networkRequestList.isEmpty()) {
3791             log("Found more network requests that can be satisfied. " + networkRequestList);
3792             dataNetwork.attachNetworkRequests(networkRequestList);
3793         }
3794 
3795         if (dataNetwork.isInternetSupported()) {
3796             // Update because DataNetwork#isInternetSupported might have changed with capabilities.
3797             updateOverallInternetDataState();
3798         }
3799     }
3800 
3801     /**
3802      * Check if network available services list is changed
3803      *
3804      * @param oldNri Previous network registration info.
3805      * @param newNri Current network registration info.
3806      * @return {@code true} if available services list is changed else return false
3807      */
areNetworkAvailableServicesChanged(@onNull NetworkRegistrationInfo oldNri, @NonNull NetworkRegistrationInfo newNri)3808     private boolean areNetworkAvailableServicesChanged(@NonNull NetworkRegistrationInfo oldNri,
3809             @NonNull NetworkRegistrationInfo newNri) {
3810         List<Integer> oldAvailableServicesList = oldNri.getAvailableServices();
3811         List<Integer> newAvailableServicesList = newNri.getAvailableServices();
3812 
3813         return !(oldAvailableServicesList.size() == newAvailableServicesList.size()
3814                 && oldAvailableServicesList.stream().allMatch(newAvailableServicesList::contains));
3815     }
3816 
3817     /**
3818      * Check if needed to re-evaluate the existing data networks.
3819      *
3820      * @param oldNri Previous network registration info.
3821      * @param newNri Current network registration info.
3822      * @return {@code true} if needed to re-evaluate the existing data networks.
3823      */
shouldReevaluateDataNetworks(@ullable NetworkRegistrationInfo oldNri, @Nullable NetworkRegistrationInfo newNri)3824     private boolean shouldReevaluateDataNetworks(@Nullable NetworkRegistrationInfo oldNri,
3825             @Nullable NetworkRegistrationInfo newNri) {
3826         if (oldNri == null || newNri == null) return false;
3827         if (newNri.getAccessNetworkTechnology() == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
3828             // Sometimes devices temporarily lose signal and RAT becomes unknown. We don't tear
3829             // down data network in this case.
3830             return false;
3831         }
3832 
3833         if (areNetworkAvailableServicesChanged(oldNri, newNri)) {
3834             return true;
3835         }
3836 
3837         if (oldNri.getAccessNetworkTechnology() != newNri.getAccessNetworkTechnology()
3838                 // Some CarrierConfig disallows vops in nonVops area for specified home/roaming.
3839                 || (oldNri.isRoaming() != newNri.isRoaming())) {
3840             return true;
3841         }
3842 
3843         if (oldNri.isNonTerrestrialNetwork() != newNri.isNonTerrestrialNetwork()) {
3844             return true;
3845         }
3846 
3847         DataSpecificRegistrationInfo oldDsri = oldNri.getDataSpecificInfo();
3848         DataSpecificRegistrationInfo newDsri = newNri.getDataSpecificInfo();
3849 
3850         if (newDsri == null) return false;
3851         // If previously VoPS was supported (or does not exist), and now the network reports
3852         // VoPS not supported, we should evaluate existing data networks to see if they need
3853         // to be torn down.
3854         return (oldDsri == null || oldDsri.getVopsSupportInfo() == null
3855                 || oldDsri.getVopsSupportInfo().isVopsSupported())
3856                 && (newDsri.getVopsSupportInfo() != null && !newDsri.getVopsSupportInfo()
3857                 .isVopsSupported());
3858     }
3859 
3860     /**
3861      * Check if needed to re-evaluate the unsatisfied network requests.
3862      *
3863      * @param oldSS Previous raw service state.
3864      * @param newSS Current raw service state.
3865      * @param transport The network transport to be checked.
3866      * @return {@code true} if needed to re-evaluate the unsatisfied network requests.
3867      */
shouldReevaluateNetworkRequests(@onNull ServiceState oldSS, @NonNull ServiceState newSS, @TransportType int transport)3868     private boolean shouldReevaluateNetworkRequests(@NonNull ServiceState oldSS,
3869             @NonNull ServiceState newSS, @TransportType int transport)  {
3870         NetworkRegistrationInfo oldPsNri = oldSS.getNetworkRegistrationInfo(
3871                 NetworkRegistrationInfo.DOMAIN_PS, transport);
3872         NetworkRegistrationInfo newPsNri = newSS.getNetworkRegistrationInfo(
3873                 NetworkRegistrationInfo.DOMAIN_PS, transport);
3874 
3875         if (newPsNri == null) return false;
3876         if (newPsNri.getAccessNetworkTechnology() == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
3877             // Sometimes devices temporarily lose signal and RAT becomes unknown. We don't setup
3878             // data in this case.
3879             return false;
3880         }
3881 
3882         if (areNetworkAvailableServicesChanged(oldPsNri, newPsNri)) {
3883             return true;
3884         }
3885 
3886         if (oldPsNri == null
3887                 || oldPsNri.getAccessNetworkTechnology() != newPsNri.getAccessNetworkTechnology()
3888                 || (!oldPsNri.isInService() && newPsNri.isInService())
3889                 // Some CarrierConfig allows vops in nonVops area for specified home/roaming.
3890                 || (oldPsNri.isRoaming() != newPsNri.isRoaming())) {
3891             return true;
3892         }
3893 
3894         // If CS connection is back to service on non-DDS, reevaluate for potential PS
3895         if (!serviceStateAllowsPSAttach(oldSS, transport)
3896                 && serviceStateAllowsPSAttach(newSS, transport)) {
3897             return true;
3898         }
3899 
3900         if (oldSS.isUsingNonTerrestrialNetwork() != newSS.isUsingNonTerrestrialNetwork()) {
3901             return true;
3902         }
3903 
3904         DataSpecificRegistrationInfo oldDsri = oldPsNri.getDataSpecificInfo();
3905         DataSpecificRegistrationInfo newDsri = newPsNri.getDataSpecificInfo();
3906 
3907         if (oldDsri == null) return false;
3908         // If previously VoPS was not supported, and now the network reports
3909         // VoPS supported (or does not report), we should evaluate the unsatisfied network
3910         // request to see if the can be satisfied again.
3911         return (newDsri == null || newDsri.getVopsSupportInfo() == null
3912                 || newDsri.getVopsSupportInfo().isVopsSupported())
3913                 && (oldDsri.getVopsSupportInfo() != null && !oldDsri.getVopsSupportInfo()
3914                 .isVopsSupported());
3915     }
3916 
3917     /**
3918      * Called when service state changed.
3919      */
3920     // Note that this is only called when data RAT or data registration changed. If we need to know
3921     // more "changed" events other than data RAT and data registration state, we should add
3922     // a new listening ServiceStateTracker.registerForServiceStateChanged().
onServiceStateChanged()3923     private void onServiceStateChanged() {
3924         // Use the raw service state instead of the mPhone.getServiceState().
3925         ServiceState newServiceState = mPhone.getServiceStateTracker().getServiceState();
3926         StringBuilder debugMessage = new StringBuilder("onServiceStateChanged: ");
3927         boolean evaluateNetworkRequests = false, evaluateDataNetworks = false;
3928 
3929         if (!mServiceState.equals(newServiceState)) {
3930             log("onServiceStateChanged: changed to " + newServiceState);
3931             for (int transport : mAccessNetworksManager.getAvailableTransports()) {
3932                 NetworkRegistrationInfo oldNri = mServiceState.getNetworkRegistrationInfo(
3933                         NetworkRegistrationInfo.DOMAIN_PS, transport);
3934                 NetworkRegistrationInfo newNri = newServiceState.getNetworkRegistrationInfo(
3935                         NetworkRegistrationInfo.DOMAIN_PS, transport);
3936                 debugMessage.append("[").append(
3937                         AccessNetworkConstants.transportTypeToString(transport)).append(": ");
3938                 debugMessage.append(oldNri != null ? TelephonyManager.getNetworkTypeName(
3939                         oldNri.getAccessNetworkTechnology()) : null);
3940                 debugMessage.append("->").append(
3941                         newNri != null ? TelephonyManager.getNetworkTypeName(
3942                                 newNri.getAccessNetworkTechnology()) : null).append(", ");
3943                 debugMessage.append(
3944                         oldNri != null ? NetworkRegistrationInfo.registrationStateToString(
3945                                 oldNri.getRegistrationState()) : null);
3946                 debugMessage.append("->").append(newNri != null
3947                         ? NetworkRegistrationInfo.registrationStateToString(
3948                         newNri.getRegistrationState()) : null).append(", ");
3949                 debugMessage.append(oldNri != null ? NetworkRegistrationInfo
3950                         .isNonTerrestrialNetworkToString(oldNri.isNonTerrestrialNetwork()) : null);
3951                 debugMessage.append("->").append(newNri != null ? NetworkRegistrationInfo
3952                         .isNonTerrestrialNetworkToString(newNri.isNonTerrestrialNetwork()) : null)
3953                         .append("] ");
3954                 if (shouldReevaluateDataNetworks(oldNri, newNri)) {
3955                     if (!hasMessages(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS)) {
3956                         sendMessage(obtainMessage(EVENT_REEVALUATE_EXISTING_DATA_NETWORKS,
3957                                 DataEvaluationReason.DATA_SERVICE_STATE_CHANGED));
3958                         evaluateDataNetworks = true;
3959                     }
3960                 }
3961                 if (shouldReevaluateNetworkRequests(mServiceState, newServiceState, transport)) {
3962                     if (!hasMessages(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS)) {
3963                         sendMessage(obtainMessage(EVENT_REEVALUATE_UNSATISFIED_NETWORK_REQUESTS,
3964                                 DataEvaluationReason.DATA_SERVICE_STATE_CHANGED));
3965                         evaluateNetworkRequests = true;
3966                     }
3967                 }
3968             }
3969             mServiceState = newServiceState;
3970         } else {
3971             debugMessage.append("not changed");
3972         }
3973         debugMessage.append(". Evaluating network requests is ").append(
3974                 evaluateNetworkRequests ? "" : "not ").append(
3975                 "needed, evaluating existing data networks is ").append(
3976                 evaluateDataNetworks ? "" : "not ").append("needed.");
3977         log(debugMessage.toString());
3978     }
3979 
3980     /**
3981      * Update the internet data network state. For now only {@link TelephonyManager#DATA_CONNECTED},
3982      * {@link TelephonyManager#DATA_SUSPENDED}, and {@link TelephonyManager#DATA_DISCONNECTED}
3983      * are supported.
3984      */
updateOverallInternetDataState()3985     private void updateOverallInternetDataState() {
3986         boolean anyInternetConnected = mDataNetworkList.stream()
3987                 .anyMatch(dataNetwork -> dataNetwork.isInternetSupported()
3988                         && (dataNetwork.isConnected() || dataNetwork.isHandoverInProgress()));
3989         // If any one is not suspended, then the overall is not suspended.
3990         Set<DataNetwork> allConnectedInternetDataNetworks = mDataNetworkList.stream()
3991                 .filter(DataNetwork::isInternetSupported)
3992                 .filter(dataNetwork -> dataNetwork.isConnected()
3993                         || dataNetwork.isHandoverInProgress())
3994                 .collect(Collectors.toSet());
3995         boolean isSuspended = !allConnectedInternetDataNetworks.isEmpty()
3996                 && allConnectedInternetDataNetworks.stream().allMatch(DataNetwork::isSuspended);
3997         logv("isSuspended=" + isSuspended + ", anyInternetConnected=" + anyInternetConnected
3998                 + ", mDataNetworkList=" + mDataNetworkList);
3999 
4000         int dataNetworkState = TelephonyManager.DATA_DISCONNECTED;
4001         if (isSuspended) {
4002             dataNetworkState = TelephonyManager.DATA_SUSPENDED;
4003         } else if (anyInternetConnected) {
4004             dataNetworkState = TelephonyManager.DATA_CONNECTED;
4005         }
4006 
4007         if (mInternetDataNetworkState != dataNetworkState) {
4008             logl("Internet data state changed from "
4009                     + TelephonyUtils.dataStateToString(mInternetDataNetworkState) + " to "
4010                     + TelephonyUtils.dataStateToString(dataNetworkState) + ".");
4011             mInternetDataNetworkState = dataNetworkState;
4012         }
4013         // Check data network reference equality to update current connected internet networks.
4014         if (!mConnectedInternetNetworks.equals(allConnectedInternetDataNetworks)) {
4015             mConnectedInternetNetworks = allConnectedInternetDataNetworks;
4016             mDataNetworkControllerCallbacks.forEach(callback -> callback.invokeFromExecutor(
4017                     () -> callback.onConnectedInternetDataNetworksChanged(
4018                             allConnectedInternetDataNetworks)));
4019         }
4020     }
4021 
4022     /**
4023      * @return Data config manager instance.
4024      */
4025     @NonNull
getDataConfigManager()4026     public DataConfigManager getDataConfigManager() {
4027         return mDataConfigManager;
4028     }
4029 
4030     /**
4031      * @return Data profile manager instance.
4032      */
4033     @NonNull
getDataProfileManager()4034     public DataProfileManager getDataProfileManager() {
4035         return mDataProfileManager;
4036     }
4037 
4038     /**
4039      * @return Data settings manager instance.
4040      */
4041     @NonNull
getDataSettingsManager()4042     public DataSettingsManager getDataSettingsManager() {
4043         return mDataSettingsManager;
4044     }
4045 
4046     /**
4047      * @return Data retry manager instance.
4048      */
4049     @NonNull
getDataRetryManager()4050     public DataRetryManager getDataRetryManager() {
4051         return mDataRetryManager;
4052     }
4053 
4054     /**
4055      * @return The list of SubscriptionPlans
4056      */
4057     @VisibleForTesting
4058     @NonNull
getSubscriptionPlans()4059     public List<SubscriptionPlan> getSubscriptionPlans() {
4060         return mSubscriptionPlans;
4061     }
4062 
4063     /**
4064      * @return The set of network types an unmetered override applies to
4065      */
4066     @VisibleForTesting
4067     @NonNull
4068     @NetworkType
getUnmeteredOverrideNetworkTypes()4069     public Set<Integer> getUnmeteredOverrideNetworkTypes() {
4070         return mUnmeteredOverrideNetworkTypes;
4071     }
4072 
4073     /**
4074      * @return The set of network types a congested override applies to
4075      */
4076     @VisibleForTesting
4077     @NonNull
4078     @NetworkType
getCongestedOverrideNetworkTypes()4079     public Set<Integer> getCongestedOverrideNetworkTypes() {
4080         return mCongestedOverrideNetworkTypes;
4081     }
4082 
4083     /**
4084      * Get data network type based on transport.
4085      *
4086      * @param transport The transport.
4087      * @return The current network type.
4088      */
4089     @NetworkType
getDataNetworkType(@ransportType int transport)4090     private int getDataNetworkType(@TransportType int transport) {
4091         NetworkRegistrationInfo nri = mServiceState.getNetworkRegistrationInfo(
4092                 NetworkRegistrationInfo.DOMAIN_PS, transport);
4093         if (nri != null) {
4094             return nri.getAccessNetworkTechnology();
4095         }
4096         return TelephonyManager.NETWORK_TYPE_UNKNOWN;
4097     }
4098 
4099     /**
4100      * Get data registration state based on transport.
4101      *
4102      * @param ss The service state from which to extract the data registration state.
4103      * @param transport The transport.
4104      * @return The registration state.
4105      */
4106     @RegistrationState
getDataRegistrationState(@onNull ServiceState ss, @TransportType int transport)4107     private int getDataRegistrationState(@NonNull ServiceState ss, @TransportType int transport) {
4108         NetworkRegistrationInfo nri = ss.getNetworkRegistrationInfo(
4109                 NetworkRegistrationInfo.DOMAIN_PS, transport);
4110         if (nri != null) {
4111             return nri.getRegistrationState();
4112         }
4113         return NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN;
4114     }
4115 
4116     /**
4117      * @return The data activity. Note this is only updated when screen is on.
4118      */
4119     @DataActivityType
getDataActivity()4120     public int getDataActivity() {
4121         return mDataActivity;
4122     }
4123 
4124     /**
4125      * Register data network controller callback.
4126      *
4127      * @param callback The callback.
4128      */
registerDataNetworkControllerCallback( @onNull DataNetworkControllerCallback callback)4129     public void registerDataNetworkControllerCallback(
4130             @NonNull DataNetworkControllerCallback callback) {
4131         sendMessage(obtainMessage(EVENT_REGISTER_DATA_NETWORK_CONTROLLER_CALLBACK, callback));
4132     }
4133 
4134     /**
4135      * Unregister data network controller callback.
4136      *
4137      * @param callback The callback.
4138      */
unregisterDataNetworkControllerCallback( @onNull DataNetworkControllerCallback callback)4139     public void unregisterDataNetworkControllerCallback(
4140             @NonNull DataNetworkControllerCallback callback) {
4141         sendMessage(obtainMessage(EVENT_UNREGISTER_DATA_NETWORK_CONTROLLER_CALLBACK, callback));
4142     }
4143 
4144     /**
4145      * Tear down all data networks.
4146      *
4147      * @param reason The reason to tear down.
4148      */
tearDownAllDataNetworks(@earDownReason int reason)4149     public void tearDownAllDataNetworks(@TearDownReason int reason) {
4150         sendMessage(obtainMessage(EVENT_TEAR_DOWN_ALL_DATA_NETWORKS, reason, 0));
4151     }
4152 
4153     /**
4154      * Called when needed to tear down all data networks.
4155      *
4156      * @param reason The reason to tear down.
4157      */
onTearDownAllDataNetworks(@earDownReason int reason)4158     private void onTearDownAllDataNetworks(@TearDownReason int reason) {
4159         log("onTearDownAllDataNetworks: reason=" + DataNetwork.tearDownReasonToString(reason));
4160         if (mDataNetworkList.isEmpty()) {
4161             log("tearDownAllDataNetworks: No pending networks. All disconnected now.");
4162             return;
4163         }
4164 
4165         for (DataNetwork dataNetwork : mDataNetworkList) {
4166             if (!dataNetwork.isDisconnecting()) {
4167                 tearDownGracefully(dataNetwork, reason);
4168             }
4169         }
4170     }
4171 
4172     /**
4173      * Evaluate the pending IMS de-registration networks and tear it down if it is safe to do that.
4174      */
evaluatePendingImsDeregDataNetworks()4175     private void evaluatePendingImsDeregDataNetworks() {
4176         Iterator<Map.Entry<DataNetwork, Runnable>> it =
4177                 mPendingImsDeregDataNetworks.entrySet().iterator();
4178         while (it.hasNext()) {
4179             Map.Entry<DataNetwork, Runnable> entry = it.next();
4180             if (isSafeToTearDown(entry.getKey())) {
4181                 // Now tear down the network.
4182                 log("evaluatePendingImsDeregDataNetworks: Safe to tear down data network "
4183                         + entry.getKey() + " now.");
4184                 entry.getValue().run();
4185                 it.remove();
4186             } else {
4187                 log("Still not safe to tear down " + entry.getKey() + ".");
4188             }
4189         }
4190     }
4191 
4192     /**
4193      * Check if the data network is safe to tear down at this moment.
4194      *
4195      * @param dataNetwork The data network.
4196      * @return {@code true} if the data network is safe to tear down. {@code false} indicates this
4197      * data network has requests originated from the IMS/RCS service and IMS/RCS is not
4198      * de-registered yet.
4199      */
isSafeToTearDown(@onNull DataNetwork dataNetwork)4200     private boolean isSafeToTearDown(@NonNull DataNetwork dataNetwork) {
4201         if (dataNetwork.hasNetworkCapabilityInNetworkRequests(
4202                 NetworkCapabilities.NET_CAPABILITY_EIMS)) {
4203             // FWK currently doesn't track emergency registration state for graceful tear down.
4204             return true;
4205         }
4206         for (int imsFeature : SUPPORTED_IMS_FEATURES) {
4207             String imsFeaturePackage = mImsFeaturePackageName.get(imsFeature);
4208             if (imsFeaturePackage != null) {
4209                 if (dataNetwork.getAttachedNetworkRequestList()
4210                         .hasNetworkRequestsFromPackage(imsFeaturePackage)) {
4211                     if (mRegisteredImsFeatures.contains(imsFeature)) {
4212                         return false;
4213                     }
4214                 }
4215             }
4216         }
4217         // All IMS features are de-registered (or this data network has no requests from IMS feature
4218         // packages.
4219         return true;
4220     }
4221 
4222     /**
4223      * @return {@code true} if IMS graceful tear down is supported by frameworks.
4224      */
isImsGracefulTearDownSupported()4225     private boolean isImsGracefulTearDownSupported() {
4226         return mDataConfigManager.getImsDeregistrationDelay() > 0;
4227     }
4228 
4229     /**
4230      * Tear down the data network gracefully.
4231      *
4232      * @param dataNetwork The data network.
4233      */
tearDownGracefully(@onNull DataNetwork dataNetwork, @TearDownReason int reason)4234     private void tearDownGracefully(@NonNull DataNetwork dataNetwork, @TearDownReason int reason) {
4235         long deregDelay = mDataConfigManager.getImsDeregistrationDelay();
4236         if (isImsGracefulTearDownSupported() && !isSafeToTearDown(dataNetwork)) {
4237             log("tearDownGracefully: Not safe to tear down " + dataNetwork
4238                     + " at this point. Wait for IMS de-registration or timeout. MMTEL="
4239                     + (mRegisteredImsFeatures.contains(ImsFeature.FEATURE_MMTEL)
4240                     ? "registered" : "not registered")
4241                     + ", RCS="
4242                     + (mRegisteredImsFeatures.contains(ImsFeature.FEATURE_RCS)
4243                     ? "registered" : "not registered")
4244             );
4245             Runnable runnable = dataNetwork.tearDownWhenConditionMet(reason, deregDelay);
4246             if (runnable != null) {
4247                 mPendingImsDeregDataNetworks.put(dataNetwork, runnable);
4248             } else {
4249                 log(dataNetwork + " is being torn down already.");
4250             }
4251         } else {
4252             // Graceful tear down is not turned on. Tear down the network immediately.
4253             log("tearDownGracefully: Safe to tear down " + dataNetwork);
4254             dataNetwork.tearDown(reason);
4255         }
4256     }
4257 
4258     /**
4259      * Get the internet data network state. Note that this is the best effort if more than one
4260      * data network supports internet. For now only {@link TelephonyManager#DATA_CONNECTED},
4261      * {@link TelephonyManager#DATA_SUSPENDED}, and {@link TelephonyManager#DATA_DISCONNECTED}
4262      * are supported.
4263      *
4264      * @return The data network state.
4265      */
4266     @DataState
getInternetDataNetworkState()4267     public int getInternetDataNetworkState() {
4268         return mInternetDataNetworkState;
4269     }
4270 
4271     /**
4272      * @return List of bound data service packages name on WWAN and WLAN.
4273      */
4274     @NonNull
getDataServicePackages()4275     public List<String> getDataServicePackages() {
4276         List<String> packages = new ArrayList<>();
4277         for (int i = 0; i < mDataServiceManagers.size(); i++) {
4278             packages.add(mDataServiceManagers.valueAt(i).getDataServicePackageName());
4279         }
4280         return packages;
4281     }
4282 
4283     /**
4284      * Request network validation.
4285      * <p>
4286      * Network validation request is sent to the DataNetwork that matches the network capability
4287      * in the list of DataNetwork owned by the DNC.
4288      *
4289      * @param capability network capability {@link NetCapability}
4290      */
requestNetworkValidation(@etCapability int capability, @NonNull Consumer<Integer> resultCodeCallback)4291     public void requestNetworkValidation(@NetCapability int capability,
4292             @NonNull Consumer<Integer> resultCodeCallback) {
4293 
4294         if (DataUtils.networkCapabilityToApnType(capability) == ApnSetting.TYPE_NONE) {
4295             // If the capability is not an apn type based capability, sent an invalid argument.
4296             loge("requestNetworkValidation: the capability is not an apn type based. capability:"
4297                     + capability);
4298             FunctionalUtils.ignoreRemoteException(resultCodeCallback::accept)
4299                     .accept(DataServiceCallback.RESULT_ERROR_INVALID_ARG);
4300             return;
4301         }
4302 
4303         // Find DataNetwork that matches the capability.
4304         List<DataNetwork> list = mDataNetworkList.stream()
4305                 .filter(dataNetwork ->
4306                         dataNetwork.getNetworkCapabilities().hasCapability(capability))
4307                 .toList();
4308 
4309         if (!list.isEmpty()) {
4310             // request network validation.
4311             list.forEach(dataNetwork -> dataNetwork.requestNetworkValidation(resultCodeCallback));
4312         } else {
4313             // If not found, sent an invalid argument.
4314             loge("requestNetworkValidation: No matching DataNetwork was found");
4315             FunctionalUtils.ignoreRemoteException(resultCodeCallback::accept)
4316                     .accept(DataServiceCallback.RESULT_ERROR_INVALID_ARG);
4317         }
4318     }
4319 
4320     /**
4321      * Log debug messages.
4322      * @param s debug messages
4323      */
log(@onNull String s)4324     private void log(@NonNull String s) {
4325         Rlog.d(mLogTag, s);
4326     }
4327 
4328     /**
4329      * Log error messages.
4330      * @param s error messages
4331      */
loge(@onNull String s)4332     private void loge(@NonNull String s) {
4333         Rlog.e(mLogTag, s);
4334     }
4335 
4336     /**
4337      * Log verbose messages.
4338      * @param s debug messages.
4339      */
logv(@onNull String s)4340     private void logv(@NonNull String s) {
4341         if (VDBG) Rlog.v(mLogTag, s);
4342     }
4343 
4344     /**
4345      * Log debug messages and also log into the local log.
4346      * @param s debug messages
4347      */
logl(@onNull String s)4348     private void logl(@NonNull String s) {
4349         log(s);
4350         mLocalLog.log(s);
4351     }
4352 
4353     /**
4354      * Dump the state of DataNetworkController
4355      *
4356      * @param fd File descriptor
4357      * @param printWriter Print writer
4358      * @param args Arguments
4359      */
dump(FileDescriptor fd, PrintWriter printWriter, String[] args)4360     public void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
4361         IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ");
4362         pw.println(DataNetworkController.class.getSimpleName() + "-" + mPhone.getPhoneId() + ":");
4363         pw.increaseIndent();
4364         pw.println("Current data networks:");
4365         pw.increaseIndent();
4366         for (DataNetwork dn : mDataNetworkList) {
4367             dn.dump(fd, pw, args);
4368         }
4369         pw.decreaseIndent();
4370 
4371         pw.println("Pending tear down data networks:");
4372         pw.increaseIndent();
4373         for (DataNetwork dn : mPendingImsDeregDataNetworks.keySet()) {
4374             dn.dump(fd, pw, args);
4375         }
4376         pw.decreaseIndent();
4377 
4378         pw.println("Previously connected data networks: (up to "
4379                 + MAX_HISTORICAL_CONNECTED_DATA_NETWORKS + ")");
4380         pw.increaseIndent();
4381         for (DataNetwork dn: mPreviousConnectedDataNetworkList) {
4382             // Do not print networks which is already in current network list.
4383             if (!mDataNetworkList.contains(dn)) {
4384                 dn.dump(fd, pw, args);
4385             }
4386         }
4387         pw.decreaseIndent();
4388 
4389         pw.println("All telephony network requests:");
4390         pw.increaseIndent();
4391         for (TelephonyNetworkRequest networkRequest : mAllNetworkRequestList) {
4392             pw.println(networkRequest);
4393         }
4394         pw.decreaseIndent();
4395 
4396         pw.println("IMS features registration state: MMTEL="
4397                 + (mRegisteredImsFeatures.contains(ImsFeature.FEATURE_MMTEL)
4398                 ? "registered" : "not registered")
4399                 + ", RCS="
4400                 + (mRegisteredImsFeatures.contains(ImsFeature.FEATURE_RCS)
4401                 ? "registered" : "not registered"));
4402         pw.println("mServiceState=" + mServiceState);
4403         pw.println("mPsRestricted=" + mPsRestricted);
4404         pw.println("mAnyDataNetworkExisting=" + mAnyDataNetworkExisting);
4405         pw.println("mInternetDataNetworkState="
4406                 + TelephonyUtils.dataStateToString(mInternetDataNetworkState));
4407         pw.println("mImsDataNetworkState="
4408                 + TelephonyUtils.dataStateToString(mImsDataNetworkState));
4409         pw.println("mDataServiceBound=" + mDataServiceBound);
4410         pw.println("mIsSrvccHandoverInProcess=" + mIsSrvccHandoverInProcess);
4411         pw.println("mSimState=" + TelephonyManager.simStateToString(mSimState));
4412         pw.println("mDataNetworkControllerCallbacks=" + mDataNetworkControllerCallbacks);
4413         pw.println("Subscription plans:");
4414         pw.increaseIndent();
4415         mSubscriptionPlans.forEach(pw::println);
4416         pw.decreaseIndent();
4417         pw.println("Unmetered override network types=" + mUnmeteredOverrideNetworkTypes.stream()
4418                 .map(TelephonyManager::getNetworkTypeName).collect(Collectors.joining(",")));
4419         pw.println("Congested override network types=" + mCongestedOverrideNetworkTypes.stream()
4420                 .map(TelephonyManager::getNetworkTypeName).collect(Collectors.joining(",")));
4421         pw.println("mImsThrottleCounter=" + mImsThrottleCounter);
4422         pw.println("mNetworkUnwantedCounter=" + mNetworkUnwantedCounter);
4423         pw.println("mBootStrapSimTotalDataUsageBytes=" + mBootStrapSimTotalDataUsageBytes);
4424         pw.println("Local logs:");
4425         pw.increaseIndent();
4426         mLocalLog.dump(fd, pw, args);
4427         pw.decreaseIndent();
4428 
4429         pw.println("-------------------------------------");
4430         mDataProfileManager.dump(fd, pw, args);
4431         pw.println("-------------------------------------");
4432         mDataRetryManager.dump(fd, pw, args);
4433         pw.println("-------------------------------------");
4434         mDataSettingsManager.dump(fd, pw, args);
4435         pw.println("-------------------------------------");
4436         mDataStallRecoveryManager.dump(fd, pw, args);
4437         pw.println("-------------------------------------");
4438         mDataConfigManager.dump(fd, pw, args);
4439 
4440         pw.decreaseIndent();
4441     }
4442 }
4443