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 static android.telephony.TelephonyManager.HAL_SERVICE_DATA;
20 
21 import android.annotation.CallbackExecutor;
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.content.Intent;
26 import android.net.ConnectivityManager;
27 import android.net.LinkAddress;
28 import android.net.LinkProperties;
29 import android.net.NetworkAgent;
30 import android.net.NetworkAgentConfig;
31 import android.net.NetworkCapabilities;
32 import android.net.NetworkFactory;
33 import android.net.NetworkProvider;
34 import android.net.NetworkRequest;
35 import android.net.NetworkScore;
36 import android.net.ProxyInfo;
37 import android.net.RouteInfo;
38 import android.net.TelephonyNetworkSpecifier;
39 import android.net.Uri;
40 import android.net.vcn.VcnManager;
41 import android.net.vcn.VcnManager.VcnNetworkPolicyChangeListener;
42 import android.net.vcn.VcnNetworkPolicyResult;
43 import android.os.AsyncResult;
44 import android.os.Looper;
45 import android.os.Message;
46 import android.os.Process;
47 import android.os.SystemClock;
48 import android.provider.Telephony;
49 import android.telephony.AccessNetworkConstants;
50 import android.telephony.AccessNetworkConstants.AccessNetworkType;
51 import android.telephony.AccessNetworkConstants.TransportType;
52 import android.telephony.Annotation.DataFailureCause;
53 import android.telephony.Annotation.DataState;
54 import android.telephony.Annotation.NetCapability;
55 import android.telephony.Annotation.NetworkType;
56 import android.telephony.Annotation.ValidationStatus;
57 import android.telephony.AnomalyReporter;
58 import android.telephony.CarrierConfigManager;
59 import android.telephony.DataFailCause;
60 import android.telephony.DataSpecificRegistrationInfo;
61 import android.telephony.LinkCapacityEstimate;
62 import android.telephony.NetworkRegistrationInfo;
63 import android.telephony.PcoData;
64 import android.telephony.PreciseDataConnectionState;
65 import android.telephony.ServiceState;
66 import android.telephony.SubscriptionManager;
67 import android.telephony.SubscriptionPlan;
68 import android.telephony.TelephonyDisplayInfo;
69 import android.telephony.TelephonyManager;
70 import android.telephony.data.ApnSetting;
71 import android.telephony.data.DataCallResponse;
72 import android.telephony.data.DataCallResponse.HandoverFailureMode;
73 import android.telephony.data.DataCallResponse.LinkStatus;
74 import android.telephony.data.DataProfile;
75 import android.telephony.data.DataService;
76 import android.telephony.data.DataServiceCallback;
77 import android.telephony.data.NetworkSliceInfo;
78 import android.telephony.data.Qos;
79 import android.telephony.data.QosBearerSession;
80 import android.telephony.data.TrafficDescriptor;
81 import android.telephony.data.TrafficDescriptor.OsAppId;
82 import android.text.TextUtils;
83 import android.util.ArrayMap;
84 import android.util.IndentingPrintWriter;
85 import android.util.LocalLog;
86 import android.util.SparseArray;
87 import android.util.SparseIntArray;
88 
89 import com.android.internal.telephony.CarrierSignalAgent;
90 import com.android.internal.telephony.CommandsInterface;
91 import com.android.internal.telephony.Phone;
92 import com.android.internal.telephony.PhoneConstants;
93 import com.android.internal.telephony.PhoneFactory;
94 import com.android.internal.telephony.RIL;
95 import com.android.internal.telephony.data.AccessNetworksManager.AccessNetworksManagerCallback;
96 import com.android.internal.telephony.data.DataConfigManager.DataConfigManagerCallback;
97 import com.android.internal.telephony.data.DataEvaluation.DataAllowedReason;
98 import com.android.internal.telephony.data.DataNetworkController.NetworkRequestList;
99 import com.android.internal.telephony.data.DataRetryManager.DataHandoverRetryEntry;
100 import com.android.internal.telephony.data.DataRetryManager.DataRetryEntry;
101 import com.android.internal.telephony.data.DataSettingsManager.DataSettingsManagerCallback;
102 import com.android.internal.telephony.data.LinkBandwidthEstimator.LinkBandwidthEstimatorCallback;
103 import com.android.internal.telephony.data.TelephonyNetworkAgent.TelephonyNetworkAgentCallback;
104 import com.android.internal.telephony.flags.FeatureFlags;
105 import com.android.internal.telephony.metrics.DataCallSessionStats;
106 import com.android.internal.telephony.metrics.DataNetworkValidationStats;
107 import com.android.internal.telephony.metrics.TelephonyMetrics;
108 import com.android.internal.util.ArrayUtils;
109 import com.android.internal.util.FunctionalUtils;
110 import com.android.internal.util.IState;
111 import com.android.internal.util.State;
112 import com.android.internal.util.StateMachine;
113 import com.android.net.module.util.LinkPropertiesUtils;
114 import com.android.net.module.util.NetUtils;
115 import com.android.net.module.util.NetworkCapabilitiesUtils;
116 import com.android.telephony.Rlog;
117 
118 import java.io.FileDescriptor;
119 import java.io.PrintWriter;
120 import java.math.BigInteger;
121 import java.net.InetAddress;
122 import java.util.ArrayList;
123 import java.util.Arrays;
124 import java.util.Collections;
125 import java.util.Comparator;
126 import java.util.HashSet;
127 import java.util.List;
128 import java.util.ListIterator;
129 import java.util.Map;
130 import java.util.Objects;
131 import java.util.Set;
132 import java.util.UUID;
133 import java.util.concurrent.Executor;
134 import java.util.concurrent.TimeUnit;
135 import java.util.function.Consumer;
136 import java.util.stream.Collectors;
137 
138 /**
139  * DataNetwork class represents a single PDN (Packet Data Network).
140  * <p>
141  * The life cycle of a data network starts from {@link ConnectingState}. If setup data request
142  * succeeds, then it enters {@link ConnectedState}, otherwise it enters
143  * {@link DisconnectedState}.
144  * <p>
145  * When data network is in {@link ConnectingState}, it can enter {@link HandoverState} if handover
146  * between IWLAN and cellular occurs. After handover completes or fails, it return back to
147  * {@link ConnectedState}. When the data network is about to be disconnected, it first enters
148  * {@link DisconnectingState} when performing graceful tear down or when sending the data
149  * deactivation request. At the end, it enters {@link DisconnectedState} when {@link DataService}
150  * notifies data disconnected. Note that an unsolicited disconnected event from {@link DataService}
151  * or any vendor HAL failure response can immediately move data network from {@link ConnectedState}
152  * to {@link DisconnectedState}. {@link DisconnectedState} is the final state of a data network.
153  * <p>
154  * State machine diagram:
155  * <p>
156  *
157  *                                  ┌─────────┐
158  *                                  │Handover │
159  *                                  └─▲────┬──┘
160  *                                    │    │
161  *             ┌───────────┐        ┌─┴────▼──┐        ┌──────────────┐
162  *             │Connecting ├────────►Connected├────────►Disconnecting │
163  *             └─────┬─────┘        └────┬────┘        └───────┬──────┘
164  *                   │                   │                     │
165  *                   │             ┌─────▼──────┐              │
166  *                   └─────────────►Disconnected◄──────────────┘
167  *                                 └────────────┘
168  *
169  */
170 public class DataNetwork extends StateMachine {
171     private static final boolean VDBG = false;
172     /** Event for data config updated. */
173     private static final int EVENT_DATA_CONFIG_UPDATED = 1;
174 
175     /** Event for attaching a network request. */
176     private static final int EVENT_ATTACH_NETWORK_REQUEST = 2;
177 
178     /** Event for detaching a network request. */
179     private static final int EVENT_DETACH_NETWORK_REQUEST = 3;
180 
181     /** Event when detect radio not available. */
182     private static final int  EVENT_RADIO_NOT_AVAILABLE = 4;
183 
184     /** Event for allocating PDU session id response. */
185     private static final int EVENT_ALLOCATE_PDU_SESSION_ID_RESPONSE = 5;
186 
187     /** Event for setup data network response. */
188     private static final int EVENT_SETUP_DATA_NETWORK_RESPONSE = 6;
189 
190     /** Event for tearing down data network. */
191     private static final int EVENT_TEAR_DOWN_NETWORK = 7;
192 
193     /** Event triggered by {@link DataServiceCallback#onDataCallListChanged(List)}. */
194     private static final int EVENT_DATA_STATE_CHANGED = 8;
195 
196     /** Data network service state changed event. */
197     private static final int EVENT_SERVICE_STATE_CHANGED = 9;
198 
199     /** Event for detaching all network requests. */
200     private static final int EVENT_DETACH_ALL_NETWORK_REQUESTS = 10;
201 
202     /** Event for bandwidth estimation from the modem changed. */
203     private static final int EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED = 11;
204 
205     /** Event to report anomaly {@link #EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE} not received. */
206     private static final int EVENT_CANCEL_HANDOVER_NO_RESPONSE = 12;
207 
208     /** Event for display info changed. This is for getting 5G NSA or mmwave information. */
209     private static final int EVENT_DISPLAY_INFO_CHANGED = 13;
210 
211     /** Event for setup data call (for handover) response from the data service. */
212     private static final int EVENT_HANDOVER_RESPONSE = 15;
213 
214     /** Event for subscription plan changed or unmetered/congested override set. */
215     private static final int EVENT_SUBSCRIPTION_PLAN_OVERRIDE = 16;
216 
217     /** Event for PCO data received from network. */
218     private static final int EVENT_PCO_DATA_RECEIVED = 17;
219 
220     /** Event for carrier privileged UIDs changed. */
221     private static final int EVENT_CARRIER_PRIVILEGED_UIDS_CHANGED = 18;
222 
223     /** Event for deactivate data network response. */
224     private static final int EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE = 19;
225 
226     /**
227      * Event for data network stuck in transient (i.e. connecting/disconnecting/handover) state for
228      * too long time. Timeout value specified in
229      * {@link DataConfigManager#getAnomalyNetworkConnectingTimeoutMs()},
230      * {@link DataConfigManager#getAnomalyNetworkDisconnectingTimeoutMs()},
231      * {@link DataConfigManager#getNetworkHandoverTimeoutMs()}.
232      */
233     private static final int EVENT_STUCK_IN_TRANSIENT_STATE = 20;
234 
235     /**
236      * Event for waiting for tearing down condition met. This will cause data network entering
237      * disconnecting state.
238      */
239     private static final int EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET = 21;
240 
241     /** Event for call started. */
242     private static final int EVENT_VOICE_CALL_STARTED = 22;
243 
244     /** Event for call ended. */
245     private static final int EVENT_VOICE_CALL_ENDED = 23;
246 
247     /** Event for CSS indicator changed. */
248     private static final int EVENT_CSS_INDICATOR_CHANGED = 24;
249 
250     /**
251      * Event for notifying source transport that handover is about to be initiated on target
252      * transport.
253      */
254     private static final int EVENT_NOTIFY_HANDOVER_STARTED = 25;
255 
256     /**
257      * Event for the response of notifying source transport that handover is about to be initiated
258      * on target transport.
259      */
260     private static final int EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE = 26;
261 
262     /**
263      * Event for the response of notifying source transport that handover is cancelled/failed on the
264      * target transport.
265      */
266     private static final int EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE = 27;
267 
268     /** Event for data network validation request from the AccessNetworksManager. */
269     private static final int EVENT_DATA_NETWORK_VALIDATION_REQUESTED = 28;
270 
271     /** Event for response to data network validation request. */
272     private static final int EVENT_DATA_NETWORK_VALIDATION_RESPONSE = 29;
273 
274     /** Invalid context id. */
275     private static final int INVALID_CID = -1;
276 
277     @IntDef(prefix = {"TEAR_DOWN_REASON_"},
278             value = {
279                     TEAR_DOWN_REASON_NONE,
280                     TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED,
281                     TEAR_DOWN_REASON_SIM_REMOVAL,
282                     TEAR_DOWN_REASON_AIRPLANE_MODE_ON,
283                     TEAR_DOWN_REASON_DATA_DISABLED,
284                     TEAR_DOWN_REASON_NO_LIVE_REQUEST,
285                     TEAR_DOWN_REASON_RAT_NOT_ALLOWED,
286                     TEAR_DOWN_REASON_ROAMING_DISABLED,
287                     TEAR_DOWN_REASON_CONCURRENT_VOICE_DATA_NOT_ALLOWED,
288                     TEAR_DOWN_REASON_SERVICE_OPTION_NOT_SUPPORTED,
289                     TEAR_DOWN_REASON_DATA_SERVICE_NOT_READY,
290                     TEAR_DOWN_REASON_POWER_OFF_BY_CARRIER,
291                     TEAR_DOWN_REASON_DATA_STALL,
292                     TEAR_DOWN_REASON_HANDOVER_FAILED,
293                     TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED,
294                     TEAR_DOWN_REASON_VCN_REQUESTED,
295                     TEAR_DOWN_REASON_VOPS_NOT_SUPPORTED,
296                     TEAR_DOWN_REASON_DEFAULT_DATA_UNSELECTED,
297                     TEAR_DOWN_REASON_NOT_IN_SERVICE,
298                     TEAR_DOWN_REASON_DATA_CONFIG_NOT_READY,
299                     TEAR_DOWN_REASON_PENDING_TEAR_DOWN_ALL,
300                     TEAR_DOWN_REASON_NO_SUITABLE_DATA_PROFILE,
301                     TEAR_DOWN_REASON_CDMA_EMERGENCY_CALLBACK_MODE,
302                     TEAR_DOWN_REASON_RETRY_SCHEDULED,
303                     TEAR_DOWN_REASON_DATA_THROTTLED,
304                     TEAR_DOWN_REASON_DATA_PROFILE_INVALID,
305                     TEAR_DOWN_REASON_DATA_PROFILE_NOT_PREFERRED,
306                     TEAR_DOWN_REASON_NOT_ALLOWED_BY_POLICY,
307                     TEAR_DOWN_REASON_ILLEGAL_STATE,
308                     TEAR_DOWN_REASON_ONLY_ALLOWED_SINGLE_NETWORK,
309                     TEAR_DOWN_REASON_PREFERRED_DATA_SWITCHED,
310                     TEAR_DOWN_REASON_DATA_LIMIT_REACHED,
311                     TEAR_DOWN_REASON_DATA_NETWORK_TRANSPORT_NOT_ALLOWED,
312             })
313     public @interface TearDownReason {}
314 
315     /** Data network was not torn down. */
316     public static final int TEAR_DOWN_REASON_NONE = 0;
317 
318     /** Data network tear down requested by connectivity service. */
319     public static final int TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED = 1;
320 
321     /** Data network tear down due to SIM removal. */
322     public static final int TEAR_DOWN_REASON_SIM_REMOVAL = 2;
323 
324     /** Data network tear down due to airplane mode turned on. */
325     public static final int TEAR_DOWN_REASON_AIRPLANE_MODE_ON = 3;
326 
327     /** Data network tear down due to data disabled (by user, policy, carrier, etc...). */
328     public static final int TEAR_DOWN_REASON_DATA_DISABLED = 4;
329 
330     /** Data network tear down due to no live network request. */
331     public static final int TEAR_DOWN_REASON_NO_LIVE_REQUEST = 5;
332 
333     /** Data network tear down due to current RAT is not allowed by the data profile. */
334     public static final int TEAR_DOWN_REASON_RAT_NOT_ALLOWED = 6;
335 
336     /** Data network tear down due to data roaming not enabled. */
337     public static final int TEAR_DOWN_REASON_ROAMING_DISABLED = 7;
338 
339     /** Data network tear down due to concurrent voice/data not allowed. */
340     public static final int TEAR_DOWN_REASON_CONCURRENT_VOICE_DATA_NOT_ALLOWED = 8;
341 
342     /** Data network tear down due to service option is not supported. */
343     public static final int TEAR_DOWN_REASON_SERVICE_OPTION_NOT_SUPPORTED = 9;
344 
345     /** Data network tear down due to data service unbound. */
346     public static final int TEAR_DOWN_REASON_DATA_SERVICE_NOT_READY = 10;
347 
348     /** Data network tear down due to radio turned off by the carrier. */
349     public static final int TEAR_DOWN_REASON_POWER_OFF_BY_CARRIER = 11;
350 
351     /** Data network tear down due to data stall. */
352     public static final int TEAR_DOWN_REASON_DATA_STALL = 12;
353 
354     /** Data network tear down due to handover failed. */
355     public static final int TEAR_DOWN_REASON_HANDOVER_FAILED = 13;
356 
357     /** Data network tear down due to handover not allowed. */
358     public static final int TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED = 14;
359 
360     /** Data network tear down due to VCN service requested. */
361     public static final int TEAR_DOWN_REASON_VCN_REQUESTED = 15;
362 
363     /** Data network tear down due to VOPS no longer supported. */
364     public static final int TEAR_DOWN_REASON_VOPS_NOT_SUPPORTED = 16;
365 
366     /** Data network tear down due to default data unselected. */
367     public static final int TEAR_DOWN_REASON_DEFAULT_DATA_UNSELECTED = 17;
368 
369     /** Data network tear down due to device not in service. */
370     public static final int TEAR_DOWN_REASON_NOT_IN_SERVICE = 18;
371 
372     /** Data network tear down due to data config not ready. */
373     public static final int TEAR_DOWN_REASON_DATA_CONFIG_NOT_READY = 19;
374 
375     /** Data network tear down due to tear down all pending. */
376     public static final int TEAR_DOWN_REASON_PENDING_TEAR_DOWN_ALL = 20;
377 
378     /** Data network tear down due to no suitable data profile. */
379     public static final int TEAR_DOWN_REASON_NO_SUITABLE_DATA_PROFILE = 21;
380 
381     /** Data network tear down due to CDMA ECBM. */
382     public static final int TEAR_DOWN_REASON_CDMA_EMERGENCY_CALLBACK_MODE = 22;
383 
384     /** Data network tear down due to retry scheduled. */
385     public static final int TEAR_DOWN_REASON_RETRY_SCHEDULED = 23;
386 
387     /** Data network tear down due to data throttled. */
388     public static final int TEAR_DOWN_REASON_DATA_THROTTLED = 24;
389 
390     /** Data network tear down due to data profile invalid. */
391     public static final int TEAR_DOWN_REASON_DATA_PROFILE_INVALID = 25;
392 
393     /** Data network tear down due to data profile not preferred. */
394     public static final int TEAR_DOWN_REASON_DATA_PROFILE_NOT_PREFERRED = 26;
395 
396     /** Data network tear down due to handover not allowed by policy. */
397     public static final int TEAR_DOWN_REASON_NOT_ALLOWED_BY_POLICY = 27;
398 
399     /** Data network tear down due to illegal state. */
400     public static final int TEAR_DOWN_REASON_ILLEGAL_STATE = 28;
401 
402     /** Data network tear down due to only allowed single network. */
403     public static final int TEAR_DOWN_REASON_ONLY_ALLOWED_SINGLE_NETWORK = 29;
404 
405     /** Data network tear down due to preferred data switched to another phone. */
406     public static final int TEAR_DOWN_REASON_PREFERRED_DATA_SWITCHED = 30;
407 
408     /** Data network tear down due to bootstrap sim data limit reached. */
409     public static final int TEAR_DOWN_REASON_DATA_LIMIT_REACHED = 31;
410 
411     /** Data network tear down due to current data network transport mismatch. */
412     public static final int TEAR_DOWN_REASON_DATA_NETWORK_TRANSPORT_NOT_ALLOWED = 32;
413 
414     //********************************************************************************************//
415     // WHENEVER ADD A NEW TEAR DOWN REASON, PLEASE UPDATE DataDeactivateReasonEnum in enums.proto //
416     //********************************************************************************************//
417 
418     @IntDef(prefix = {"BANDWIDTH_SOURCE_"},
419             value = {
420                     BANDWIDTH_SOURCE_UNKNOWN,
421                     BANDWIDTH_SOURCE_MODEM,
422                     BANDWIDTH_SOURCE_CARRIER_CONFIG,
423                     BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR,
424             })
425     public @interface BandwidthEstimationSource {}
426 
427     /** Indicates the bandwidth estimation source is unknown. This must be a configuration error. */
428     public static final int BANDWIDTH_SOURCE_UNKNOWN = 0;
429 
430     /** Indicates the bandwidth estimation source is from the modem. */
431     public static final int BANDWIDTH_SOURCE_MODEM = 1;
432 
433     /** Indicates the bandwidth estimation source is from the static carrier config. */
434     public static final int BANDWIDTH_SOURCE_CARRIER_CONFIG = 2;
435 
436     /** Indicates the bandwidth estimation source is from {@link LinkBandwidthEstimator}. */
437     public static final int BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR = 3;
438 
439     /**
440      * The capabilities that are allowed to changed dynamically during the life cycle of network.
441      * This is copied from {@code NetworkCapabilities#MUTABLE_CAPABILITIES}. There is no plan to
442      * make this a connectivity manager API since in the future, immutable network capabilities
443      * would be allowed to changed dynamically. (i.e. not immutable anymore.)
444      */
445     private static final List<Integer> MUTABLE_CAPABILITIES = List.of(
446             NetworkCapabilities.NET_CAPABILITY_TRUSTED,
447             NetworkCapabilities.NET_CAPABILITY_VALIDATED,
448             NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL,
449             NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
450             NetworkCapabilities.NET_CAPABILITY_FOREGROUND,
451             NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED,
452             NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED,
453             NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY,
454             NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED,
455             NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED,
456             NetworkCapabilities.NET_CAPABILITY_HEAD_UNIT,
457             // Connectivity service will support NOT_METERED as a mutable and requestable
458             // capability.
459             NetworkCapabilities.NET_CAPABILITY_NOT_METERED,
460             // Dynamically add and remove MMTEL capability when network transition between VoPS
461             // and non-VoPS network if the request is not MMTEL. For MMTEL, we retain the capability
462             // to prevent immediate tear down.
463             NetworkCapabilities.NET_CAPABILITY_MMTEL
464     );
465 
466     /** The parent state. Any messages not handled by the child state fallback to this. */
467     private final DefaultState mDefaultState = new DefaultState();
468 
469     /**
470      * The connecting state. This is the initial state of a data network.
471      *
472      * @see DataNetwork for the state machine diagram.
473      */
474     private final ConnectingState mConnectingState = new ConnectingState();
475 
476     /**
477      * The connected state. This is the state when data network becomes usable.
478      *
479      * @see DataNetwork for the state machine diagram.
480      */
481     private final ConnectedState mConnectedState = new ConnectedState();
482 
483     /**
484      * The handover state. This is the state when data network handover between IWLAN and cellular.
485      *
486      * @see DataNetwork for the state machine diagram.
487      */
488     private final HandoverState mHandoverState = new HandoverState();
489 
490     /**
491      * The disconnecting state. This is the state when data network is about to be disconnected.
492      * The network is still usable in this state, but the clients should be prepared to lose the
493      * network in any moment. This state is particular useful for IMS graceful tear down, where
494      * the network enters disconnecting state while waiting for IMS de-registration signal.
495      *
496      * @see DataNetwork for the state machine diagram.
497      */
498     private final DisconnectingState mDisconnectingState = new DisconnectingState();
499 
500     /**
501      * The disconnected state. This is the final state of a data network.
502      *
503      * @see DataNetwork for the state machine diagram.
504      */
505     private final DisconnectedState mDisconnectedState = new DisconnectedState();
506 
507     /** The phone instance. */
508     @NonNull
509     private final Phone mPhone;
510 
511     /** Feature flags */
512     @NonNull
513     private final FeatureFlags mFlags;
514 
515     /**
516      * The subscription id. This is assigned when the network is created, and not supposed to
517      * change afterwards.
518      */
519     private final int mSubId;
520 
521     /** The network score of this network. */
522     @NonNull
523     private NetworkScore mNetworkScore;
524 
525     /**
526      * Indicates that
527      * {@link DataService.DataServiceProvider#deactivateDataCall(int, int, DataServiceCallback)}
528      * has been called. This flag can be only changed from {@code false} to {@code true}.
529      */
530     private boolean mInvokedDataDeactivation = false;
531 
532     /**
533      * Indicates that if the data network has ever entered {@link ConnectedState}.
534      */
535     private boolean mEverConnected = false;
536 
537     /** RIL interface. */
538     @NonNull
539     private final CommandsInterface mRil;
540 
541     /** Local log. */
542     private final LocalLog mLocalLog = new LocalLog(128);
543 
544     /** The callback to receives data network state update. */
545     @NonNull
546     private final DataNetworkCallback mDataNetworkCallback;
547 
548     /** The log tag. */
549     private String mLogTag;
550 
551     /** Metrics of per data network connection. */
552     private final DataCallSessionStats mDataCallSessionStats;
553 
554     /** Metrics of per data network validation. */
555     @NonNull
556     private final DataNetworkValidationStats mDataNetworkValidationStats;
557 
558     /**
559      * The unique context id assigned by the data service in {@link DataCallResponse#getId()}. One
560      * for {@link AccessNetworkConstants#TRANSPORT_TYPE_WWAN} and one for
561      * {@link AccessNetworkConstants#TRANSPORT_TYPE_WLAN}. The reason for storing both is that
562      * during handover, both cid will be used.
563      */
564     private final SparseIntArray mCid = new SparseIntArray(2);
565 
566     /**
567      * The initial network agent id. The network agent can be re-created due to immutable capability
568      * changed. This is to preserve the initial network agent id so the id in the logging tag won't
569      * change for the entire life cycle of data network.
570      */
571     private int mInitialNetworkAgentId;
572 
573     /** PDU session id. */
574     private int mPduSessionId = DataCallResponse.PDU_SESSION_ID_NOT_SET;
575 
576     /**
577      * Data service managers for accessing {@link AccessNetworkConstants#TRANSPORT_TYPE_WWAN} and
578      * {@link AccessNetworkConstants#TRANSPORT_TYPE_WLAN} data services.
579      */
580     @NonNull
581     private final SparseArray<DataServiceManager> mDataServiceManagers;
582 
583     /** Access networks manager. */
584     @NonNull
585     private final AccessNetworksManager mAccessNetworksManager;
586 
587     /** Data network controller. */
588     @NonNull
589     private final DataNetworkController mDataNetworkController;
590 
591     /** Data network controller callback. */
592     @NonNull
593     private final DataNetworkController.DataNetworkControllerCallback
594             mDataNetworkControllerCallback;
595 
596     /** Data settings manager callback. */
597     @NonNull
598     private DataSettingsManagerCallback mDataSettingsManagerCallback;
599 
600     /** Data config manager. */
601     @NonNull
602     private final DataConfigManager mDataConfigManager;
603 
604     /** VCN manager. */
605     @Nullable
606     private final VcnManager mVcnManager;
607 
608     /** VCN policy changed listener. */
609     @Nullable
610     private VcnNetworkPolicyChangeListener mVcnPolicyChangeListener;
611 
612     /** The network agent associated with this data network. */
613     @NonNull
614     private TelephonyNetworkAgent mNetworkAgent;
615 
616     /** QOS callback tracker. This is only created after network connected on WWAN. */
617     @Nullable
618     private QosCallbackTracker mQosCallbackTracker;
619 
620     /** NAT keepalive tracker. */
621     @Nullable
622     private KeepaliveTracker mKeepaliveTracker;
623 
624     /** The data profile used to establish this data network. */
625     @NonNull
626     private DataProfile mDataProfile;
627 
628     /**
629      * The data profile used for data handover. Some carriers might use different data profile
630      * between IWLAN and cellular. Only set before handover started.
631      */
632     @Nullable
633     private DataProfile mHandoverDataProfile;
634 
635     /** The network capabilities of this data network. */
636     @NonNull
637     private NetworkCapabilities mNetworkCapabilities;
638 
639     /** The matched traffic descriptor returned from setup data call request. */
640     @NonNull
641     private final List<TrafficDescriptor> mTrafficDescriptors = new ArrayList<>();
642 
643     /** The link properties of this data network. */
644     @NonNull
645     private LinkProperties mLinkProperties;
646 
647     /** The network slice info. */
648     @Nullable
649     private NetworkSliceInfo mNetworkSliceInfo;
650 
651     /** The link status (i.e. RRC state). */
652     @LinkStatus
653     private int mLinkStatus = DataCallResponse.LINK_STATUS_UNKNOWN;
654 
655     /** The network bandwidth. */
656     @NonNull
657     private NetworkBandwidth mNetworkBandwidth = new NetworkBandwidth(14, 14);
658 
659     /** The TCP buffer sizes config. */
660     @NonNull
661     private String mTcpBufferSizes;
662 
663     /** The telephony display info. */
664     @NonNull
665     private TelephonyDisplayInfo mTelephonyDisplayInfo;
666 
667     /** Whether {@link NetworkCapabilities#NET_CAPABILITY_TEMPORARILY_NOT_METERED} is supported. */
668     private boolean mTempNotMeteredSupported = false;
669 
670     /** Whether the current data network is temporarily not metered. */
671     private boolean mTempNotMetered = false;
672 
673     /** Whether the current data network is congested. */
674     private boolean mCongested = false;
675 
676     /** The network requests associated with this data network */
677     @NonNull
678     private final NetworkRequestList mAttachedNetworkRequestList =
679             new NetworkRequestList();
680 
681     /**
682      * The latest data call response received from either
683      * {@link DataServiceCallback#onSetupDataCallComplete(int, DataCallResponse)} or
684      * {@link DataServiceCallback#onDataCallListChanged(List)}. The very first update must be
685      * from {@link DataServiceCallback#onSetupDataCallComplete(int, DataCallResponse)}.
686      */
687     @Nullable
688     private DataCallResponse mDataCallResponse = null;
689 
690     /**
691      * The fail cause from either setup data failure or unsolicited disconnect reported by data
692      * service.
693      */
694     @DataFailureCause
695     private int mFailCause = DataFailCause.NONE;
696 
697     /**
698      * The tear down reason if the data call is voluntarily deactivated, not due to failure.
699      */
700     @TearDownReason
701     private int mTearDownReason = TEAR_DOWN_REASON_NONE;
702 
703     /**
704      * The retry delay in milliseconds from setup data failure.
705      */
706     private long mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
707 
708     /**
709      * Indicates if data network is suspended. Note this is slightly different from the
710      * {@link TelephonyManager#DATA_SUSPENDED}, which is only possible when data network is in
711      * connected state. This flag reflects to the
712      * {@link NetworkCapabilities#NET_CAPABILITY_NOT_SUSPENDED} which can happen when data network
713      * is in connected or disconnecting state.
714      */
715     private boolean mSuspended = false;
716 
717     /**
718      * The current transport of the data network. For handover, the current transport will be set
719      * after handover completes.
720      */
721     @TransportType
722     private int mTransport;
723 
724     /**
725      * The last known data network type.
726      */
727     @NetworkType
728     private int mLastKnownDataNetworkType;
729 
730     /**
731      * The last known roaming state of this data network.
732      */
733     private boolean mLastKnownRoamingState;
734 
735     /**
736      * The non-terrestrial status
737      */
738     private final boolean mIsSatellite;
739 
740     /** The reason that why setting up this data network is allowed. */
741     @NonNull
742     private final DataAllowedReason mDataAllowedReason;
743 
744     /**
745      * PCO (Protocol Configuration Options) data received from the network. The first key is the
746      * cid of the PCO data, the second key is the PCO id, the value is the PCO data.
747      */
748     @NonNull
749     private final Map<Integer, Map<Integer, PcoData>> mPcoData = new ArrayMap<>();
750 
751     /** The QOS bearer sessions. */
752     @NonNull
753     private final List<QosBearerSession> mQosBearerSessions = new ArrayList<>();
754 
755     /** The QOS for the Default Bearer, should be non-null on LTE and NR */
756     @Nullable
757     private Qos mDefaultQos;
758 
759     /**
760      * The UIDs of packages that have carrier privilege.
761      */
762     @NonNull
763     private int[] mAdministratorUids = new int[0];
764 
765     /** Carrier privileges callback to monitor administrator UID change. */
766     @Nullable
767     private TelephonyManager.CarrierPrivilegesCallback mCarrierPrivilegesCallback;
768 
769     /**
770      * Carrier service package uid. This UID will not change through the life cycle of data network.
771      */
772     private int mCarrierServicePackageUid = Process.INVALID_UID;
773 
774     /**
775      * Link bandwidth estimator callback for receiving latest link bandwidth information.
776      */
777     @Nullable
778     private LinkBandwidthEstimatorCallback mLinkBandwidthEstimatorCallback;
779 
780     /**
781      * Data config callback for carrier config update.
782      */
783     @Nullable
784     private DataConfigManagerCallback mDataConfigManagerCallback;
785 
786     /**
787      * Network validation status for this data network. If the data service provider does not
788      * support the network validation feature, should be UNSUPPORTED.
789      */
790     @PreciseDataConnectionState.NetworkValidationStatus
791     private int mNetworkValidationStatus =
792             PreciseDataConnectionState.NETWORK_VALIDATION_UNSUPPORTED;
793 
794     /**
795      * Callback used to respond to a network validation request to determine whether the request is
796      * successfully submitted. If the request has been submitted, change it to null.
797      */
798     @Nullable
799     private Consumer<Integer> mNetworkValidationResultCodeCallback;
800 
801     /**
802      * Callback used to listen QNS preference changes.
803      */
804     @Nullable
805     private AccessNetworksManagerCallback mAccessNetworksManagerCallback;
806 
807     /**
808      * PreciseDataConnectionState, the most recently notified. If it has never been notified, it is
809      * null.
810      */
811     @Nullable
812     private PreciseDataConnectionState mPreciseDataConnectionState;
813 
814     /**
815      * The network bandwidth.
816      */
817     public static class NetworkBandwidth {
818         /** The downlink bandwidth in Kbps. */
819         public final int downlinkBandwidthKbps;
820 
821         /** The uplink Bandwidth in Kbps. */
822         public final int uplinkBandwidthKbps;
823 
824         /**
825          * Constructor.
826          *
827          * @param downlinkBandwidthKbps The downlink bandwidth in Kbps.
828          * @param uplinkBandwidthKbps The uplink Bandwidth in Kbps.
829          */
NetworkBandwidth(int downlinkBandwidthKbps, int uplinkBandwidthKbps)830         public NetworkBandwidth(int downlinkBandwidthKbps, int uplinkBandwidthKbps) {
831             this.downlinkBandwidthKbps = downlinkBandwidthKbps;
832             this.uplinkBandwidthKbps = uplinkBandwidthKbps;
833         }
834 
835         @Override
toString()836         public String toString() {
837             return String.format("NetworkBandwidth=[downlink=%d, uplink=%d]",
838                     downlinkBandwidthKbps, uplinkBandwidthKbps);
839         }
840     }
841 
842     /**
843      * Data network callback. Should only be used by {@link DataNetworkController}.
844      */
845     public abstract static class DataNetworkCallback extends DataCallback {
846         /**
847          * Constructor
848          *
849          * @param executor The executor of the callback.
850          */
DataNetworkCallback(@onNull @allbackExecutor Executor executor)851         public DataNetworkCallback(@NonNull @CallbackExecutor Executor executor) {
852             super(executor);
853         }
854 
855         /**
856          * Called when data setup failed.
857          *
858          * @param dataNetwork The data network.
859          * @param requestList The network requests attached to this data network.
860          * @param cause The fail cause of setup data network.
861          * @param retryDurationMillis The network suggested data retry duration in milliseconds as
862          * specified in 3GPP TS 24.302 section 8.2.9.1. The {@link DataProfile} associated to this
863          * data network will be throttled for the specified duration unless
864          * {@link DataServiceCallback#onApnUnthrottled} is called. {@link Long#MAX_VALUE} indicates
865          * data retry should not occur. {@link DataCallResponse#RETRY_DURATION_UNDEFINED} indicates
866          * network did not suggest any retry duration.
867          */
onSetupDataFailed(@onNull DataNetwork dataNetwork, @NonNull NetworkRequestList requestList, @DataFailureCause int cause, long retryDurationMillis)868         public abstract void onSetupDataFailed(@NonNull DataNetwork dataNetwork,
869                 @NonNull NetworkRequestList requestList, @DataFailureCause int cause,
870                 long retryDurationMillis);
871 
872         /**
873          * Called when data network enters {@link ConnectedState}.
874          *
875          * @param dataNetwork The data network.
876          */
onConnected(@onNull DataNetwork dataNetwork)877         public abstract void onConnected(@NonNull DataNetwork dataNetwork);
878 
879         /**
880          * Called when data network validation status changed.
881          *
882          * @param dataNetwork The data network.
883          * @param status one of {@link NetworkAgent#VALIDATION_STATUS_VALID} or
884          * {@link NetworkAgent#VALIDATION_STATUS_NOT_VALID}.
885          * @param redirectUri If internet connectivity is being redirected (e.g., on a captive
886          * portal), this is the destination the probes are being redirected to, otherwise
887          * {@code null}.
888          */
onValidationStatusChanged(@onNull DataNetwork dataNetwork, @ValidationStatus int status, @Nullable Uri redirectUri)889         public abstract void onValidationStatusChanged(@NonNull DataNetwork dataNetwork,
890                 @ValidationStatus int status, @Nullable Uri redirectUri);
891 
892         /**
893          * Called when data network suspended state changed.
894          *
895          * @param dataNetwork The data network.
896          * @param suspended {@code true} if data is suspended.
897          */
onSuspendedStateChanged(@onNull DataNetwork dataNetwork, boolean suspended)898         public abstract void onSuspendedStateChanged(@NonNull DataNetwork dataNetwork,
899                 boolean suspended);
900 
901         /**
902          * Called when network requests were failed to attach to the data network.
903          *
904          * @param dataNetwork The data network.
905          * @param requestList The requests failed to attach.
906          */
onAttachFailed(@onNull DataNetwork dataNetwork, @NonNull NetworkRequestList requestList)907         public abstract void onAttachFailed(@NonNull DataNetwork dataNetwork,
908                 @NonNull NetworkRequestList requestList);
909 
910         /**
911          * Called when data network enters {@link DisconnectedState}. Note this is only called
912          * when the data network was previously connected. For setup data network failed,
913          * {@link #onSetupDataFailed(DataNetwork, NetworkRequestList, int, long)} is called.
914          *
915          * @param dataNetwork The data network.
916          * @param cause The disconnect cause.
917          * @param tearDownReason The reason the network was torn down
918          */
onDisconnected(@onNull DataNetwork dataNetwork, @DataFailureCause int cause, @TearDownReason int tearDownReason)919         public abstract void onDisconnected(@NonNull DataNetwork dataNetwork,
920                 @DataFailureCause int cause, @TearDownReason int tearDownReason);
921 
922         /**
923          * Called when handover between IWLAN and cellular network succeeded.
924          *
925          * @param dataNetwork The data network.
926          */
onHandoverSucceeded(@onNull DataNetwork dataNetwork)927         public abstract void onHandoverSucceeded(@NonNull DataNetwork dataNetwork);
928 
929         /**
930          * Called when data network handover between IWLAN and cellular network failed.
931          *
932          * @param dataNetwork The data network.
933          * @param cause The fail cause.
934          * @param retryDurationMillis Network suggested retry time in milliseconds.
935          * {@link Long#MAX_VALUE} indicates data retry should not occur.
936          * {@link DataCallResponse#RETRY_DURATION_UNDEFINED} indicates network did not suggest any
937          * retry duration.
938          * @param handoverFailureMode The handover failure mode that determine the behavior of
939          * how frameworks should handle the handover failure.
940          */
onHandoverFailed(@onNull DataNetwork dataNetwork, @DataFailureCause int cause, long retryDurationMillis, @HandoverFailureMode int handoverFailureMode)941         public abstract void onHandoverFailed(@NonNull DataNetwork dataNetwork,
942                 @DataFailureCause int cause, long retryDurationMillis,
943                 @HandoverFailureMode int handoverFailureMode);
944 
945         /**
946          * Called when data network link status (i.e. RRC state) changed.
947          *
948          * @param dataNetwork The data network.
949          * @param linkStatus The link status (i.e. RRC state).
950          */
onLinkStatusChanged(@onNull DataNetwork dataNetwork, @LinkStatus int linkStatus)951         public abstract void onLinkStatusChanged(@NonNull DataNetwork dataNetwork,
952                 @LinkStatus int linkStatus);
953 
954         /**
955          * Called when PCO data changed.
956          *
957          * @param dataNetwork The data network.
958          */
onPcoDataChanged(@onNull DataNetwork dataNetwork)959         public abstract void onPcoDataChanged(@NonNull DataNetwork dataNetwork);
960 
961         /**
962          * Called when network capabilities changed.
963          *
964          * @param dataNetwork The data network.
965          */
onNetworkCapabilitiesChanged(@onNull DataNetwork dataNetwork)966         public abstract void onNetworkCapabilitiesChanged(@NonNull DataNetwork dataNetwork);
967 
968         /**
969          * Called when attempt to tear down a data network
970          *
971          * @param dataNetwork The data network.
972          */
onTrackNetworkUnwanted(@onNull DataNetwork dataNetwork)973         public abstract void onTrackNetworkUnwanted(@NonNull DataNetwork dataNetwork);
974 
975         /**
976          * Called when a network request is detached after no longer satisfied.
977          *
978          * @param networkRequest The detached network request.
979          */
onRetryUnsatisfiedNetworkRequest( @onNull TelephonyNetworkRequest networkRequest)980         public abstract void onRetryUnsatisfiedNetworkRequest(
981                 @NonNull TelephonyNetworkRequest networkRequest);
982 
983         /**
984          * Called when QosBearerSessions bearer changed, which indicates VoNr or VoLte calls.
985          *
986          * @param qosBearerSessions The current qosBearerSessions.
987          */
onQosSessionsChanged( @onNull List<QosBearerSession> qosBearerSessions)988         public abstract void onQosSessionsChanged(
989                 @NonNull List<QosBearerSession> qosBearerSessions);
990     }
991 
992     /**
993      * Constructor
994      *
995      * @param phone The phone instance.
996      * @param looper The looper to be used by the state machine. Currently the handler thread is the
997      * phone process's main thread.
998      * @param dataServiceManagers Data service managers.
999      * @param dataProfile The data profile for establishing the data network.
1000      * @param networkRequestList The initial network requests attached to this data network.
1001      * @param transport The initial transport of the data network.
1002      * @param dataAllowedReason The reason that why setting up this data network is allowed.
1003      * @param callback The callback to receives data network state update.
1004      */
DataNetwork(@onNull Phone phone, FeatureFlags featureFlags, @NonNull Looper looper, @NonNull SparseArray<DataServiceManager> dataServiceManagers, @NonNull DataProfile dataProfile, @NonNull NetworkRequestList networkRequestList, @TransportType int transport, @NonNull DataAllowedReason dataAllowedReason, @NonNull DataNetworkCallback callback)1005     public DataNetwork(@NonNull Phone phone, FeatureFlags featureFlags, @NonNull Looper looper,
1006             @NonNull SparseArray<DataServiceManager> dataServiceManagers,
1007             @NonNull DataProfile dataProfile,
1008             @NonNull NetworkRequestList networkRequestList,
1009             @TransportType int transport,
1010             @NonNull DataAllowedReason dataAllowedReason,
1011             @NonNull DataNetworkCallback callback) {
1012         super("DataNetwork", looper);
1013         // State machine should be initialized at the top of constructor. log() can be only used
1014         // after state machine initialized (because getCurrentState() crashes if state machine has
1015         // not started.)
1016         initializeStateMachine();
1017 
1018         mPhone = phone;
1019         mFlags = featureFlags;
1020         mSubId = phone.getSubId();
1021         mRil = mPhone.mCi;
1022         mLinkProperties = new LinkProperties();
1023         mDataServiceManagers = dataServiceManagers;
1024         mAccessNetworksManager = phone.getAccessNetworksManager();
1025         mVcnManager = mPhone.getContext().getSystemService(VcnManager.class);
1026         mDataNetworkController = phone.getDataNetworkController();
1027         mDataNetworkControllerCallback = new DataNetworkController.DataNetworkControllerCallback(
1028                 getHandler()::post) {
1029             @Override
1030             public void onSubscriptionPlanOverride() {
1031                 sendMessage(EVENT_SUBSCRIPTION_PLAN_OVERRIDE);
1032             }};
1033         mDataNetworkController.registerDataNetworkControllerCallback(
1034                 mDataNetworkControllerCallback);
1035         mDataConfigManager = mDataNetworkController.getDataConfigManager();
1036         mDataCallSessionStats = new DataCallSessionStats(mPhone);
1037         mDataNetworkValidationStats = new DataNetworkValidationStats(mPhone);
1038         mDataNetworkCallback = callback;
1039         mDataProfile = dataProfile;
1040         if (dataProfile.getTrafficDescriptor() != null) {
1041             // The initial traffic descriptor is from the data profile. After that traffic
1042             // descriptors will be updated by modem through setup data call response and data call
1043             // list changed event.
1044             mTrafficDescriptors.add(dataProfile.getTrafficDescriptor());
1045         }
1046         mTransport = transport;
1047         mLastKnownDataNetworkType = getDataNetworkType();
1048         mLastKnownRoamingState = mPhone.getServiceState().getDataRoamingFromRegistration();
1049         mIsSatellite = mPhone.getServiceState().isUsingNonTerrestrialNetwork()
1050                 && transport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN;
1051         mDataAllowedReason = dataAllowedReason;
1052         dataProfile.setLastSetupTimestamp(SystemClock.elapsedRealtime());
1053         for (int transportType : mAccessNetworksManager.getAvailableTransports()) {
1054             mCid.put(transportType, INVALID_CID);
1055         }
1056         mTelephonyDisplayInfo = mPhone.getDisplayInfoController().getTelephonyDisplayInfo();
1057         mTcpBufferSizes = mDataConfigManager.getTcpConfigString(mTelephonyDisplayInfo);
1058 
1059         // network capabilities infer connectivity transport and MMTEL from the requested
1060         // capabilities.
1061         // TODO: Ideally we shouldn't infer network capabilities base on the requested capabilities,
1062         // but currently there are 2 hacks associated with getForcedCellularTransportCapabilities
1063         // and IMS service requesting IMS|MMTEL that need to support. When we stop supporting these
1064         // cases, we shouldn't consider the requests when determining the network capabilities.
1065         mAttachedNetworkRequestList.addAll(networkRequestList);
1066         // Update the capabilities in the constructor is to make sure the data network has initial
1067         // capability immediately after created. Doing this connecting state creates the window that
1068         // DataNetworkController might check if existing data network's capability can satisfy the
1069         // next network request within this window.
1070         updateNetworkCapabilities();
1071 
1072         // Remove the requests that can't use the initial capabilities
1073         ListIterator<TelephonyNetworkRequest> iter = mAttachedNetworkRequestList.listIterator();
1074         while (iter.hasNext()) {
1075             TelephonyNetworkRequest request = iter.next();
1076             if (request.canBeSatisfiedBy(mNetworkCapabilities)) {
1077                 request.setAttachedNetwork(DataNetwork.this);
1078                 request.setState(TelephonyNetworkRequest.REQUEST_STATE_SATISFIED);
1079             } else {
1080                 iter.remove();
1081             }
1082         }
1083     }
1084 
1085     /**
1086      * Initialize and start the state machine.
1087      */
initializeStateMachine()1088     private void initializeStateMachine() {
1089         addState(mDefaultState);
1090         addState(mConnectingState, mDefaultState);
1091         addState(mConnectedState, mDefaultState);
1092         addState(mHandoverState, mDefaultState);
1093         addState(mDisconnectingState, mDefaultState);
1094         addState(mDisconnectedState, mDefaultState);
1095         setInitialState(mConnectingState);
1096         start();
1097     }
1098 
1099     /**
1100      * @return {@code true} if 464xlat should be skipped.
1101      */
shouldSkip464Xlat()1102     private boolean shouldSkip464Xlat() {
1103         if (mDataProfile.getApnSetting() != null) {
1104             switch (mDataProfile.getApnSetting().getSkip464Xlat()) {
1105                 case Telephony.Carriers.SKIP_464XLAT_ENABLE:
1106                     return true;
1107                 case Telephony.Carriers.SKIP_464XLAT_DISABLE:
1108                     return false;
1109                 case Telephony.Carriers.SKIP_464XLAT_DEFAULT:
1110                 default:
1111                     break;
1112             }
1113         }
1114 
1115         // As default, return true if ims and no internet
1116         final NetworkCapabilities nc = getNetworkCapabilities();
1117         return nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)
1118                 && !nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1119     }
1120 
1121     /**
1122      * Create the telephony network agent.
1123      *
1124      * @return The telephony network agent.
1125      */
1126     @NonNull
createNetworkAgent()1127     private TelephonyNetworkAgent createNetworkAgent() {
1128         final NetworkAgentConfig.Builder configBuilder = new NetworkAgentConfig.Builder();
1129         configBuilder.setLegacyType(ConnectivityManager.TYPE_MOBILE);
1130         configBuilder.setLegacyTypeName("MOBILE");
1131         int networkType = getDataNetworkType();
1132         configBuilder.setLegacySubType(networkType);
1133         configBuilder.setLegacySubTypeName(TelephonyManager.getNetworkTypeName(networkType));
1134         if (mDataProfile.getApnSetting() != null) {
1135             configBuilder.setLegacyExtraInfo(mDataProfile.getApnSetting().getApnName());
1136         }
1137 
1138         final CarrierSignalAgent carrierSignalAgent = mPhone.getCarrierSignalAgent();
1139         if (carrierSignalAgent.hasRegisteredReceivers(TelephonyManager
1140                 .ACTION_CARRIER_SIGNAL_REDIRECTED)) {
1141             // carrierSignal Receivers will place the carrier-specific provisioning notification
1142             configBuilder.setProvisioningNotificationEnabled(false);
1143         }
1144 
1145         // Fill the IMSI
1146         final String subscriberId = mPhone.getSubscriberId();
1147         if (!TextUtils.isEmpty(subscriberId)) {
1148             configBuilder.setSubscriberId(subscriberId);
1149         }
1150 
1151         // set skip464xlat if it is not default otherwise
1152         if (shouldSkip464Xlat()) {
1153             configBuilder.setNat64DetectionEnabled(false);
1154         }
1155 
1156         final NetworkFactory factory = PhoneFactory.getNetworkFactory(
1157                 mPhone.getPhoneId());
1158         final NetworkProvider provider = (null == factory) ? null : factory.getProvider();
1159 
1160         mNetworkScore = new NetworkScore.Builder()
1161                .setKeepConnectedReason(isHandoverInProgress()
1162                         ? NetworkScore.KEEP_CONNECTED_FOR_HANDOVER
1163                         : NetworkScore.KEEP_CONNECTED_NONE).build();
1164 
1165         return new TelephonyNetworkAgent(mPhone, getHandler().getLooper(), this,
1166                 mNetworkScore, configBuilder.build(), provider,
1167                 new TelephonyNetworkAgentCallback(getHandler()::post) {
1168                     @Override
1169                     public void onValidationStatus(@ValidationStatus int status,
1170                             @Nullable Uri redirectUri) {
1171                         mDataNetworkCallback.invokeFromExecutor(
1172                                 () -> mDataNetworkCallback.onValidationStatusChanged(
1173                                         DataNetwork.this, status, redirectUri));
1174                     }
1175                 });
1176     }
1177 
1178     /**
1179      * The default state. Any events that were not handled by the child states fallback to this
1180      * state.
1181      *
1182      * @see DataNetwork for the state machine diagram.
1183      */
1184     private final class DefaultState extends State {
1185         @Override
1186         public void enter() {
1187             logv("Registering all events.");
1188             mDataConfigManagerCallback = new DataConfigManagerCallback(getHandler()::post) {
1189                 @Override
1190                 public void onCarrierConfigChanged() {
1191                     sendMessage(EVENT_DATA_CONFIG_UPDATED);
1192                 }
1193             };
1194             mRil.registerForPcoData(getHandler(), EVENT_PCO_DATA_RECEIVED, null);
1195 
1196             mDataConfigManager.registerCallback(mDataConfigManagerCallback);
1197 
1198             mDataSettingsManagerCallback = new DataSettingsManagerCallback(getHandler()::post) {
1199                 @Override
1200                 public void onDataEnabledChanged(boolean enabled,
1201                         @TelephonyManager.DataEnabledChangedReason int reason,
1202                         @NonNull String callingPackage) {
1203                     if (enabled) {
1204                         // The NOT_RESTRICTED capability might be changed after data enabled. We
1205                         // need to update the capabilities again.
1206                         log("Data enabled. update network capabilities.");
1207                         updateNetworkCapabilities();
1208                     }
1209                 }
1210 
1211                 @Override
1212                 public void onDataRoamingEnabledChanged(boolean enabled) {
1213                     if (enabled) {
1214                         // The NOT_RESTRICTED capability might be changed after data roaming
1215                         // enabled. We need to update the capabilities again.
1216                         log("Data roaming enabled. update network capabilities.");
1217                         updateNetworkCapabilities();
1218                     }
1219                 }
1220             };
1221 
1222             mDataNetworkController.getDataSettingsManager()
1223                     .registerCallback(mDataSettingsManagerCallback);
1224 
1225             mPhone.getDisplayInfoController().registerForTelephonyDisplayInfoChanged(
1226                     getHandler(), EVENT_DISPLAY_INFO_CHANGED, null);
1227             mPhone.getServiceStateTracker().registerForServiceStateChanged(getHandler(),
1228                     EVENT_SERVICE_STATE_CHANGED, null);
1229             for (int transport : mAccessNetworksManager.getAvailableTransports()) {
1230                 mDataServiceManagers.get(transport)
1231                         .registerForDataCallListChanged(getHandler(), EVENT_DATA_STATE_CHANGED);
1232             }
1233 
1234             mCarrierPrivilegesCallback =
1235                     (Set<String> privilegedPackageNames, Set<Integer> privilegedUids) -> {
1236                         log("onCarrierPrivilegesChanged, Uids=" + privilegedUids);
1237                         Message message = obtainMessage(EVENT_CARRIER_PRIVILEGED_UIDS_CHANGED);
1238                         AsyncResult.forMessage(
1239                                 message,
1240                                 privilegedUids.stream().mapToInt(i -> i).toArray(),
1241                                 null /* ex */);
1242                         sendMessage(message);
1243                     };
1244             TelephonyManager tm = mPhone.getContext().getSystemService(TelephonyManager.class);
1245             if (tm != null) {
1246                 tm.registerCarrierPrivilegesCallback(
1247                         mPhone.getPhoneId(), getHandler()::post, mCarrierPrivilegesCallback);
1248             }
1249 
1250             mPhone.getServiceStateTracker().registerForCssIndicatorChanged(
1251                     getHandler(), EVENT_CSS_INDICATOR_CHANGED, null);
1252             if (mPhone.getCallTracker() != null) {
1253                 mPhone.getCallTracker().registerForVoiceCallStarted(
1254                         getHandler(), EVENT_VOICE_CALL_STARTED, null);
1255                 mPhone.getCallTracker().registerForVoiceCallEnded(
1256                         getHandler(), EVENT_VOICE_CALL_ENDED, null);
1257             }
1258             // Check null for devices not supporting FEATURE_TELEPHONY_IMS.
1259             if (mPhone.getImsPhone() != null && mPhone.getImsPhone().getCallTracker() != null) {
1260                 mPhone.getImsPhone().getCallTracker().registerForVoiceCallStarted(
1261                         getHandler(), EVENT_VOICE_CALL_STARTED, null);
1262                 mPhone.getImsPhone().getCallTracker().registerForVoiceCallEnded(
1263                         getHandler(), EVENT_VOICE_CALL_ENDED, null);
1264             }
1265 
1266             if (mFlags.forceIwlanMms() && mDataConfigManager.isForceIwlanMmsFeatureEnabled()) {
1267                 if (mDataProfile.canSatisfy(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1268                     mAccessNetworksManagerCallback = new AccessNetworksManagerCallback(
1269                             getHandler()::post) {
1270                         @Override
1271                         public void onPreferredTransportChanged(
1272                                 @NetCapability int networkCapability, boolean forceReconnect) {
1273                             if (networkCapability == NetworkCapabilities.NET_CAPABILITY_MMS) {
1274                                 log("MMS preference changed.");
1275                                 updateNetworkCapabilities();
1276                             }
1277                         }
1278                     };
1279                     mAccessNetworksManager.registerCallback(mAccessNetworksManagerCallback);
1280                 }
1281             }
1282 
1283             // Only add symmetric code here, for example, registering and unregistering.
1284             // DefaultState.enter() is the starting point in the life cycle of the DataNetwork,
1285             // and DefaultState.exit() is the end. For non-symmetric initializing works, put them
1286             // in ConnectingState.enter().
1287         }
1288 
1289         @Override
1290         public void exit() {
1291             logv("Unregistering all events.");
1292             if (mFlags.forceIwlanMms() && mAccessNetworksManagerCallback != null
1293                     && mDataConfigManager.isForceIwlanMmsFeatureEnabled()) {
1294                 mAccessNetworksManager.unregisterCallback(mAccessNetworksManagerCallback);
1295             }
1296 
1297             // Check null for devices not supporting FEATURE_TELEPHONY_IMS.
1298             if (mPhone.getImsPhone() != null && mPhone.getImsPhone().getCallTracker() != null) {
1299                 mPhone.getImsPhone().getCallTracker().unregisterForVoiceCallStarted(getHandler());
1300                 mPhone.getImsPhone().getCallTracker().unregisterForVoiceCallEnded(getHandler());
1301             }
1302             if (mPhone.getCallTracker() != null) {
1303                 mPhone.getCallTracker().unregisterForVoiceCallStarted(getHandler());
1304                 mPhone.getCallTracker().unregisterForVoiceCallEnded(getHandler());
1305             }
1306 
1307             mPhone.getServiceStateTracker().unregisterForCssIndicatorChanged(getHandler());
1308             TelephonyManager tm = mPhone.getContext().getSystemService(TelephonyManager.class);
1309             if (tm != null && mCarrierPrivilegesCallback != null) {
1310                 tm.unregisterCarrierPrivilegesCallback(mCarrierPrivilegesCallback);
1311             }
1312             for (int transport : mAccessNetworksManager.getAvailableTransports()) {
1313                 mDataServiceManagers.get(transport)
1314                         .unregisterForDataCallListChanged(getHandler());
1315             }
1316             mPhone.getServiceStateTracker().unregisterForServiceStateChanged(getHandler());
1317             mPhone.getDisplayInfoController().unregisterForTelephonyDisplayInfoChanged(
1318                     getHandler());
1319             mDataNetworkController.getDataSettingsManager()
1320                     .unregisterCallback(mDataSettingsManagerCallback);
1321             mRil.unregisterForPcoData(getHandler());
1322             mDataConfigManager.unregisterCallback(mDataConfigManagerCallback);
1323         }
1324 
1325         @Override
1326         public boolean processMessage(Message msg) {
1327             switch (msg.what) {
1328                 case EVENT_DATA_CONFIG_UPDATED:
1329                     onCarrierConfigUpdated();
1330                     break;
1331                 case EVENT_SERVICE_STATE_CHANGED: {
1332                     int networkType = getDataNetworkType();
1333                     mDataCallSessionStats.onDrsOrRatChanged(networkType);
1334                     if (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
1335                         mLastKnownDataNetworkType = networkType;
1336                     }
1337                     NetworkRegistrationInfo nri =
1338                             mPhone.getServiceState()
1339                                     .getNetworkRegistrationInfo(
1340                                             NetworkRegistrationInfo.DOMAIN_PS,
1341                                             AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
1342                     if (nri != null && nri.isInService()) {
1343                         mLastKnownRoamingState = nri.getNetworkRegistrationState()
1344                                 == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING;
1345                     }
1346                     updateSuspendState();
1347                     updateNetworkCapabilities();
1348                     break;
1349                 }
1350                 case EVENT_ATTACH_NETWORK_REQUEST: {
1351                     onAttachNetworkRequests((NetworkRequestList) msg.obj);
1352                     updateNetworkScore(isHandoverInProgress());
1353                     break;
1354                 }
1355                 case EVENT_DETACH_NETWORK_REQUEST: {
1356                     onDetachNetworkRequest((TelephonyNetworkRequest) msg.obj,
1357                             msg.arg1 != 0 /* shouldRetry */);
1358                     updateNetworkScore(isHandoverInProgress());
1359                     break;
1360                 }
1361                 case EVENT_DETACH_ALL_NETWORK_REQUESTS: {
1362                     for (TelephonyNetworkRequest networkRequest : mAttachedNetworkRequestList) {
1363                         networkRequest.setState(TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED);
1364                         networkRequest.setAttachedNetwork(null);
1365                     }
1366                     log("All network requests detached.");
1367                     mAttachedNetworkRequestList.clear();
1368                     break;
1369                 }
1370                 case EVENT_DATA_STATE_CHANGED: {
1371                     AsyncResult ar = (AsyncResult) msg.obj;
1372                     int transport = (int) ar.userObj;
1373                     onDataStateChanged(transport, (List<DataCallResponse>) ar.result);
1374                     break;
1375                 }
1376                 case EVENT_CARRIER_PRIVILEGED_UIDS_CHANGED: {
1377                     AsyncResult asyncResult = (AsyncResult) msg.obj;
1378                     int[] administratorUids = (int[]) asyncResult.result;
1379                     mAdministratorUids = Arrays.copyOf(administratorUids, administratorUids.length);
1380                     updateNetworkCapabilities();
1381                     break;
1382                 }
1383                 case EVENT_PCO_DATA_RECEIVED: {
1384                     AsyncResult ar = (AsyncResult) msg.obj;
1385                     onPcoDataReceived((PcoData) ar.result);
1386                     break;
1387                 }
1388                 case EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE:
1389                     removeMessages(EVENT_CANCEL_HANDOVER_NO_RESPONSE);
1390                     log("Notified handover cancelled.");
1391                     break;
1392                 case EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED:
1393                 case EVENT_TEAR_DOWN_NETWORK:
1394                 case EVENT_STUCK_IN_TRANSIENT_STATE:
1395                 case EVENT_CANCEL_HANDOVER_NO_RESPONSE:
1396                 case EVENT_DISPLAY_INFO_CHANGED:
1397                 case EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET:
1398                 case EVENT_CSS_INDICATOR_CHANGED:
1399                 case EVENT_VOICE_CALL_STARTED:
1400                 case EVENT_VOICE_CALL_ENDED:
1401                     // Ignore the events when not in the correct state.
1402                     log("Ignored " + eventToString(msg.what));
1403                     break;
1404                 case EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE:
1405                 case EVENT_NOTIFY_HANDOVER_STARTED:
1406                     // We reach here if network is not in the right state.
1407                     if (msg.obj != null) {
1408                         // Cancel it because it's either HO in progress or will soon disconnect.
1409                         // Either case we want to clean up obsolete retry attempts.
1410                         DataHandoverRetryEntry retryEntry = (DataHandoverRetryEntry) msg.obj;
1411                         retryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
1412                     }
1413                     log("Ignore handover to " + AccessNetworkConstants
1414                             .transportTypeToString(msg.arg1) + " request.");
1415                     break;
1416                 case EVENT_RADIO_NOT_AVAILABLE:
1417                     mFailCause = DataFailCause.RADIO_NOT_AVAILABLE;
1418                     loge(eventToString(msg.what) + ": transition to disconnected state");
1419                     transitionTo(mDisconnectedState);
1420                     break;
1421                 case EVENT_DATA_NETWORK_VALIDATION_REQUESTED:
1422                     // If the data network is not connected, the request should be ignored.
1423                     handleErrorDataNetworkValidationRequest((Consumer<Integer>) msg.obj);
1424                     break;
1425                 case EVENT_DATA_NETWORK_VALIDATION_RESPONSE:
1426                     // handle the resultCode in response for the request.
1427                     handleDataNetworkValidationRequestResultCode(msg.arg1 /* resultCode */);
1428                     break;
1429                 default:
1430                     loge("Unhandled event " + eventToString(msg.what));
1431                     break;
1432             }
1433             return HANDLED;
1434         }
1435     }
1436 
1437     /**
1438      * The connecting state. This is the initial state of a data network.
1439      *
1440      * @see DataNetwork for the state machine diagram.
1441      */
1442     private final class ConnectingState extends State {
1443         /** Used for checking setup response IP mismatch. */
1444         @NetworkRegistrationInfo.RegistrationState private int mRegStateWhenSetup;
1445         @Override
1446         public void enter() {
1447             sendMessageDelayed(EVENT_STUCK_IN_TRANSIENT_STATE,
1448                     mDataConfigManager.getAnomalyNetworkConnectingTimeoutMs());
1449             mNetworkAgent = createNetworkAgent();
1450             mInitialNetworkAgentId = mNetworkAgent.getId();
1451             mLogTag = "DN-" + mInitialNetworkAgentId + "-"
1452                     + ((mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) ? "C" : "I");
1453 
1454             // Get carrier config package uid. Note that this uid will not change through the life
1455             // cycle of this data network. So there is no need to listen to the change event.
1456             mCarrierServicePackageUid = mPhone.getCarrierPrivilegesTracker()
1457                     .getCarrierServicePackageUid();
1458 
1459             notifyPreciseDataConnectionState();
1460             if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
1461                 // Defer setupData until we get the PDU session ID response
1462                 allocatePduSessionId();
1463                 return;
1464             }
1465 
1466             setupData();
1467         }
1468 
1469         @Override
1470         public void exit() {
1471             removeMessages(EVENT_STUCK_IN_TRANSIENT_STATE);
1472         }
1473 
1474         @Override
1475         public boolean processMessage(Message msg) {
1476             logv("event=" + eventToString(msg.what));
1477             switch (msg.what) {
1478                 case EVENT_ALLOCATE_PDU_SESSION_ID_RESPONSE:
1479                     AsyncResult ar = (AsyncResult) msg.obj;
1480                     if (ar.exception == null) {
1481                         mPduSessionId = (int) ar.result;
1482                         log("Set PDU session id to " + mPduSessionId);
1483                     } else {
1484                         loge("Failed to allocate PDU session id. e=" + ar.exception);
1485                     }
1486                     //Check whether all network requests were removed before setupData.
1487                     if (!mAttachedNetworkRequestList.isEmpty()) {
1488                         setupData();
1489                     } else {
1490                         mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
1491                         if (!mFlags.keepEmptyRequestsNetwork()) {
1492                             // This will mark the data profile as no retry perm failure.
1493                             mFailCause = DataFailCause.NO_RETRY_FAILURE;
1494                         }
1495                         transitionTo(mDisconnectedState);
1496                     }
1497                     break;
1498                 case EVENT_SETUP_DATA_NETWORK_RESPONSE:
1499                     int resultCode = msg.arg1;
1500                     DataCallResponse dataCallResponse =
1501                             msg.getData().getParcelable(DataServiceManager.DATA_CALL_RESPONSE);
1502                     onSetupResponse(resultCode, dataCallResponse);
1503                     break;
1504                 case EVENT_NOTIFY_HANDOVER_STARTED:
1505                 case EVENT_TEAR_DOWN_NETWORK:
1506                 case EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET:
1507                     // Defer the request until connected or disconnected.
1508                     log("Defer message " + eventToString(msg.what));
1509                     deferMessage(msg);
1510                     break;
1511                 case EVENT_STUCK_IN_TRANSIENT_STATE:
1512                     reportAnomaly("Data network stuck in connecting state for "
1513                             + TimeUnit.MILLISECONDS.toSeconds(
1514                             mDataConfigManager.getAnomalyNetworkConnectingTimeoutMs())
1515                             + " seconds.", "58c56403-7ea7-4e56-a0c7-e467114d09b8");
1516                     // Setup data failed. Use the retry logic defined in
1517                     // CarrierConfigManager.KEY_TELEPHONY_DATA_SETUP_RETRY_RULES_STRING_ARRAY.
1518                     mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
1519                     mFailCause = DataFailCause.NO_RETRY_FAILURE;
1520                     transitionTo(mDisconnectedState);
1521                     break;
1522                 case EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE:
1523                     int responseCode = msg.arg1;
1524                     onDeactivateResponse(responseCode);
1525                     break;
1526                 default:
1527                     return NOT_HANDLED;
1528             }
1529             return HANDLED;
1530         }
1531 
1532         /**
1533          * Setup a data network.
1534          */
1535         private void setupData() {
1536             int dataNetworkType = getDataNetworkType();
1537 
1538             NetworkRegistrationInfo nri = getNetworkRegistrationInfo();
1539             mRegStateWhenSetup = nri != null
1540                     ? nri.getNetworkRegistrationState()
1541                     : NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN;
1542             // We need to use the actual modem roaming state instead of the framework roaming state
1543             // here. This flag is only passed down to ril_service for picking the correct protocol
1544             // (for old modem backward compatibility).
1545             boolean isModemRoaming = mPhone.getServiceState().getDataRoamingFromRegistration();
1546 
1547             // Set this flag to true if the user turns on data roaming. Or if we override the
1548             // roaming state in framework, we should set this flag to true as well so the modem will
1549             // not reject the data call setup (because the modem thinks the device is roaming).
1550             boolean allowRoaming = mPhone.getDataRoamingEnabled()
1551                     || (isModemRoaming && (!mPhone.getServiceState().getDataRoaming()
1552                     /*|| isUnmeteredUseOnly()*/));
1553 
1554             TrafficDescriptor trafficDescriptor = mDataProfile.getTrafficDescriptor();
1555             final boolean matchAllRuleAllowed = trafficDescriptor == null
1556                     || !TextUtils.isEmpty(trafficDescriptor.getDataNetworkName())
1557                     // Both OsAppId and APN name are null. This helps for modem to handle when we
1558                     // are on 5G or LTE with URSP support in falling back to default network.
1559                     || (TextUtils.isEmpty(trafficDescriptor.getDataNetworkName())
1560                     && trafficDescriptor.getOsAppId() == null);
1561 
1562             int accessNetwork = DataUtils.networkTypeToAccessNetworkType(dataNetworkType);
1563 
1564             mDataServiceManagers.get(mTransport)
1565                     .setupDataCall(accessNetwork, mDataProfile, isModemRoaming, allowRoaming,
1566                             DataService.REQUEST_REASON_NORMAL, null, mPduSessionId, null,
1567                             trafficDescriptor, matchAllRuleAllowed,
1568                             obtainMessage(EVENT_SETUP_DATA_NETWORK_RESPONSE));
1569 
1570             int apnTypeBitmask = mDataProfile.getApnSetting() != null
1571                     ? mDataProfile.getApnSetting().getApnTypeBitmask() : ApnSetting.TYPE_NONE;
1572             mDataCallSessionStats.onSetupDataCall(apnTypeBitmask, isSatellite());
1573 
1574             logl("setupData: accessNetwork="
1575                     + AccessNetworkType.toString(accessNetwork) + ", " + mDataProfile
1576                     + ", isModemRoaming=" + isModemRoaming + ", allowRoaming=" + allowRoaming
1577                     + ", PDU session id=" + mPduSessionId + ", matchAllRuleAllowed="
1578                     + matchAllRuleAllowed);
1579             TelephonyMetrics.getInstance().writeSetupDataCall(mPhone.getPhoneId(),
1580                     ServiceState.networkTypeToRilRadioTechnology(dataNetworkType),
1581                     mDataProfile.getProfileId(), mDataProfile.getApn(),
1582                     mDataProfile.getProtocolType());
1583         }
1584 
1585         /**
1586          * Called when receiving setup data network response from the data service.
1587          *
1588          * @param resultCode The result code.
1589          * @param response The response.
1590          */
1591         private void onSetupResponse(@DataServiceCallback.ResultCode int resultCode,
1592                 @Nullable DataCallResponse response) {
1593             logl("onSetupResponse: resultCode=" + DataServiceCallback.resultCodeToString(resultCode)
1594                     + ", response=" + response);
1595             mFailCause = getFailCauseFromDataCallResponse(resultCode, response);
1596             validateDataCallResponse(response, mRegStateWhenSetup);
1597             if (mFailCause == DataFailCause.NONE) {
1598                 DataNetwork dataNetwork = mDataNetworkController.getDataNetworkByInterface(
1599                         response.getInterfaceName());
1600                 if (dataNetwork != null) {
1601                     logl("Interface " + response.getInterfaceName() + " has been already used by "
1602                             + dataNetwork + ". Silently tear down now.");
1603                     // If this is a pre-5G data setup, that means APN database has some problems.
1604                     // For example, different APN settings have the same APN name.
1605                     if (response.getTrafficDescriptors().isEmpty() && dataNetwork.isConnected()) {
1606                         reportAnomaly("Duplicate network interface " + response.getInterfaceName()
1607                                 + " detected.", "62f66e7e-8d71-45de-a57b-dc5c78223fd5");
1608                     }
1609 
1610                     // Do not actually invoke onTearDown, otherwise the existing data network will
1611                     // be torn down.
1612                     mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
1613                     mFailCause = DataFailCause.NO_RETRY_FAILURE;
1614                     transitionTo(mDisconnectedState);
1615                     return;
1616                 }
1617 
1618                 updateDataNetwork(response);
1619 
1620                 if (!mFlags.keepEmptyRequestsNetwork() && mAttachedNetworkRequestList.isEmpty()) {
1621                     log("Tear down the network since there is no live network request.");
1622                     // Directly call onTearDown here. Calling tearDown will cause deadlock because
1623                     // EVENT_TEAR_DOWN_NETWORK is deferred until state machine enters connected
1624                     // state, which will never happen in this case.
1625                     onTearDown(TEAR_DOWN_REASON_NO_LIVE_REQUEST);
1626                     return;
1627                 }
1628 
1629                 if (mVcnManager != null && mVcnManager.applyVcnNetworkPolicy(mNetworkCapabilities,
1630                         mLinkProperties).isTeardownRequested()) {
1631                     log("VCN service requested to tear down the network.");
1632                     // Directly call onTearDown here. Calling tearDown will cause deadlock because
1633                     // EVENT_TEAR_DOWN_NETWORK is deferred until state machine enters connected
1634                     // state, which will never happen in this case.
1635                     onTearDown(TEAR_DOWN_REASON_VCN_REQUESTED);
1636                     return;
1637                 }
1638 
1639                 transitionTo(mConnectedState);
1640             } else {
1641                 // Setup data failed.
1642                 mRetryDelayMillis = response != null ? response.getRetryDurationMillis()
1643                         : DataCallResponse.RETRY_DURATION_UNDEFINED;
1644                 transitionTo(mDisconnectedState);
1645             }
1646 
1647             int apnTypeBitmask = ApnSetting.TYPE_NONE;
1648             int protocol = ApnSetting.PROTOCOL_UNKNOWN;
1649             if (mDataProfile.getApnSetting() != null) {
1650                 apnTypeBitmask = mDataProfile.getApnSetting().getApnTypeBitmask();
1651                 protocol = mDataProfile.getApnSetting().getProtocol();
1652             }
1653             mDataCallSessionStats.onSetupDataCallResponse(response,
1654                     getDataNetworkType(),
1655                     apnTypeBitmask,
1656                     protocol,
1657                     // Log the raw fail cause to avoid large amount of UNKNOWN showing on metrics.
1658                     response != null ? response.getCause() : mFailCause);
1659         }
1660     }
1661 
1662     /**
1663      * The connected state. This is the state when data network becomes usable.
1664      *
1665      * @see DataNetwork for the state machine diagram.
1666      */
1667     private final class ConnectedState extends State {
1668         @Override
1669         public void enter() {
1670             // Note that reaching here could mean from connecting -> connected, or from
1671             // handover -> connected.
1672             if (!mEverConnected) {
1673                 // Transited from ConnectingState
1674                 log("network connected.");
1675                 mEverConnected = true;
1676                 mNetworkAgent.markConnected();
1677                 mDataNetworkCallback.invokeFromExecutor(
1678                         () -> mDataNetworkCallback.onConnected(DataNetwork.this));
1679 
1680                 mQosCallbackTracker = new QosCallbackTracker(mNetworkAgent, mPhone);
1681                 mQosCallbackTracker.updateSessions(mQosBearerSessions);
1682                 mKeepaliveTracker = new KeepaliveTracker(mPhone,
1683                         getHandler().getLooper(), DataNetwork.this, mNetworkAgent);
1684                 if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
1685                     registerForWwanEvents();
1686                 }
1687 
1688                 // Create the VCN policy changed listener. When the policy changed, we might need
1689                 // to tear down the VCN-managed network.
1690                 if (mVcnManager != null) {
1691                     mVcnPolicyChangeListener = () -> {
1692                         log("VCN policy changed.");
1693                         if (mVcnManager.applyVcnNetworkPolicy(mNetworkCapabilities, mLinkProperties)
1694                                 .isTeardownRequested()) {
1695                             tearDown(TEAR_DOWN_REASON_VCN_REQUESTED);
1696                         } else {
1697                             updateNetworkCapabilities();
1698                         }
1699                     };
1700                     mVcnManager.addVcnNetworkPolicyChangeListener(
1701                             getHandler()::post, mVcnPolicyChangeListener);
1702                 }
1703             }
1704 
1705             // If we've ever received PCO data before connected, now it's the time to process it.
1706             mPcoData.getOrDefault(mCid.get(mTransport), Collections.emptyMap())
1707                     .forEach((pcoId, pcoData) -> onPcoDataChanged(pcoData));
1708 
1709             mDataNetworkCallback.invokeFromExecutor(
1710                     () -> mDataNetworkCallback.onLinkStatusChanged(DataNetwork.this, mLinkStatus));
1711             notifyPreciseDataConnectionState();
1712             updateSuspendState();
1713         }
1714 
1715         @Override
1716         public boolean processMessage(Message msg) {
1717             logv("event=" + eventToString(msg.what));
1718             switch (msg.what) {
1719                 case EVENT_TEAR_DOWN_NETWORK:
1720                     if (mInvokedDataDeactivation) {
1721                         log("Ignore tear down request because network is being torn down.");
1722                         break;
1723                     }
1724 
1725                     int tearDownReason = msg.arg1;
1726 
1727                     removeMessages(EVENT_TEAR_DOWN_NETWORK);
1728                     removeDeferredMessages(EVENT_TEAR_DOWN_NETWORK);
1729                     transitionTo(mDisconnectingState);
1730                     onTearDown(tearDownReason);
1731                     break;
1732                 case EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED:
1733                     AsyncResult ar = (AsyncResult) msg.obj;
1734                     if (ar.exception != null) {
1735                         log("EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED: error ignoring, e="
1736                                 + ar.exception);
1737                         break;
1738                     }
1739                     onBandwidthUpdatedFromModem((List<LinkCapacityEstimate>) ar.result);
1740                     break;
1741                 case EVENT_DISPLAY_INFO_CHANGED:
1742                     onDisplayInfoChanged();
1743                     break;
1744                 case EVENT_NOTIFY_HANDOVER_STARTED:
1745                     // Notify source transport that handover is about to start. Note this will not
1746                     // initiate the handover process on target transport, but more for notifying
1747                     // the source transport so that PDU session id can be preserved if network
1748                     // notifies PDN lost during handover. The real handover process will kick off
1749                     // after receiving EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE.
1750                     log("Notifying source transport "
1751                             + AccessNetworkConstants.transportTypeToString(mTransport)
1752                             + " that handover is about to start.");
1753                     mDataServiceManagers.get(mTransport).startHandover(mCid.get(mTransport),
1754                             obtainMessage(EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE, 0, msg.arg2,
1755                                     msg.obj));
1756                     // We enter handover state here because this is the first action we do for
1757                     // handover.
1758                     transitionTo(mHandoverState);
1759                     break;
1760                 case EVENT_SUBSCRIPTION_PLAN_OVERRIDE:
1761                     updateMeteredAndCongested();
1762                     break;
1763                 case EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE:
1764                     int resultCode = msg.arg1;
1765                     onDeactivateResponse(resultCode);
1766                     break;
1767                 case EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET:
1768                     transitionTo(mDisconnectingState);
1769                     sendMessageDelayed(EVENT_TEAR_DOWN_NETWORK, msg.arg1, msg.arg2);
1770                     break;
1771                 case EVENT_VOICE_CALL_STARTED:
1772                 case EVENT_VOICE_CALL_ENDED:
1773                 case EVENT_CSS_INDICATOR_CHANGED:
1774                     updateSuspendState();
1775                     updateNetworkCapabilities();
1776                     break;
1777                 case EVENT_DATA_NETWORK_VALIDATION_REQUESTED:
1778                     // Network validation request can be accepted if the data is in connected state
1779                     handleDataNetworkValidationRequest((Consumer<Integer>) msg.obj);
1780                     break;
1781                 case EVENT_CANCEL_HANDOVER_NO_RESPONSE:
1782                     reportAnomaly("Cancel handover no response within "
1783                             + TimeUnit.MILLISECONDS.toSeconds(
1784                             mDataConfigManager.getNetworkHandoverTimeoutMs())
1785                             + " seconds.", "ad320988-0601-4955-836a-e6b67289c294");
1786                     break;
1787                 default:
1788                     return NOT_HANDLED;
1789             }
1790             return HANDLED;
1791         }
1792     }
1793 
1794     /**
1795      * The handover state. This is the state when data network handover between IWLAN and cellular.
1796      *
1797      * @see DataNetwork for the state machine diagram.
1798      */
1799     private final class HandoverState extends State {
1800         @Override
1801         public void enter() {
1802             removeMessages(EVENT_CANCEL_HANDOVER_NO_RESPONSE);
1803             sendMessageDelayed(EVENT_STUCK_IN_TRANSIENT_STATE,
1804                     mDataConfigManager.getNetworkHandoverTimeoutMs());
1805             notifyPreciseDataConnectionState();
1806             updateNetworkScore(true /* keepConnectedForHandover */);
1807         }
1808 
1809         @Override
1810         public void exit() {
1811             removeMessages(EVENT_STUCK_IN_TRANSIENT_STATE);
1812             updateNetworkScore(false /* keepConnectedForHandover */);
1813         }
1814 
1815         @Override
1816         public boolean processMessage(Message msg) {
1817             logv("event=" + eventToString(msg.what));
1818             switch (msg.what) {
1819                 case EVENT_DATA_STATE_CHANGED:
1820                     // The data call list changed event should be conditionally deferred.
1821                     // Otherwise the deferred message might be incorrectly treated as "disconnected"
1822                     // signal. So we only defer the related data call list changed event, and drop
1823                     // the unrelated.
1824                     AsyncResult ar = (AsyncResult) msg.obj;
1825                     int transport = (int) ar.userObj;
1826                     List<DataCallResponse> responseList = (List<DataCallResponse>) ar.result;
1827                     if (transport != mTransport) {
1828                         log("Dropped unrelated "
1829                                 + AccessNetworkConstants.transportTypeToString(transport)
1830                                 + " data call list changed event. " + responseList);
1831                     } else {
1832                         log("Defer message " + eventToString(msg.what) + ":" + responseList);
1833                         deferMessage(msg);
1834                     }
1835                     break;
1836                 case EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET:
1837                 case EVENT_DISPLAY_INFO_CHANGED:
1838                 case EVENT_TEAR_DOWN_NETWORK:
1839                 case EVENT_CSS_INDICATOR_CHANGED:
1840                 case EVENT_VOICE_CALL_ENDED:
1841                 case EVENT_VOICE_CALL_STARTED:
1842                 case EVENT_DATA_NETWORK_VALIDATION_REQUESTED:
1843                     // Defer the request until handover succeeds or fails.
1844                     log("Defer message " + eventToString(msg.what));
1845                     deferMessage(msg);
1846                     break;
1847                 case EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE:
1848                     onStartHandover(msg.arg2, (DataHandoverRetryEntry) msg.obj);
1849                     break;
1850                 case EVENT_HANDOVER_RESPONSE:
1851                     int resultCode = msg.arg1;
1852                     DataCallResponse dataCallResponse =
1853                             msg.getData().getParcelable(DataServiceManager.DATA_CALL_RESPONSE);
1854                     onHandoverResponse(resultCode, dataCallResponse,
1855                             (DataHandoverRetryEntry) msg.obj);
1856                     break;
1857                 case EVENT_STUCK_IN_TRANSIENT_STATE:
1858                     // enable detection only for valid timeout range
1859                     reportAnomaly("Data service did not respond the handover request within "
1860                                     + TimeUnit.MILLISECONDS.toSeconds(
1861                             mDataConfigManager.getNetworkHandoverTimeoutMs()) + " seconds.",
1862                             "1afe68cb-8b41-4964-a737-4f34372429ea");
1863                     // Handover failed. Use the retry logic defined in
1864                     // CarrierConfigManager.KEY_TELEPHONY_DATA_HANDOVER_RETRY_RULES_STRING_ARRAY.
1865                     long retry = DataCallResponse.RETRY_DURATION_UNDEFINED;
1866                     int handoverFailureMode =
1867                             DataCallResponse.HANDOVER_FAILURE_MODE_NO_FALLBACK_RETRY_SETUP_NORMAL;
1868                     mFailCause = DataFailCause.ERROR_UNSPECIFIED;
1869                     mDataNetworkCallback.invokeFromExecutor(
1870                             () -> mDataNetworkCallback.onHandoverFailed(DataNetwork.this,
1871                                     mFailCause, retry, handoverFailureMode));
1872                     // No matter handover succeeded or not, transit back to connected state.
1873                     transitionTo(mConnectedState);
1874                     break;
1875                 default:
1876                     return NOT_HANDLED;
1877             }
1878             return HANDLED;
1879         }
1880     }
1881 
1882     /**
1883      * The disconnecting state. This is the state when data network is about to be disconnected.
1884      * The network is still usable in this state, but the clients should be prepared to lose the
1885      * network in any moment. This state is particular useful for IMS graceful tear down, where
1886      * the network enters disconnecting state while waiting for IMS de-registration signal.
1887      *
1888      * @see DataNetwork for the state machine diagram.
1889      */
1890     private final class DisconnectingState extends State {
1891         @Override
1892         public void enter() {
1893             sendMessageDelayed(EVENT_STUCK_IN_TRANSIENT_STATE,
1894                     mDataConfigManager.getAnomalyNetworkDisconnectingTimeoutMs());
1895             notifyPreciseDataConnectionState();
1896         }
1897 
1898         @Override
1899         public void exit() {
1900             removeMessages(EVENT_STUCK_IN_TRANSIENT_STATE);
1901         }
1902 
1903         @Override
1904         public boolean processMessage(Message msg) {
1905             logv("event=" + eventToString(msg.what));
1906             switch (msg.what) {
1907                 case EVENT_TEAR_DOWN_NETWORK:
1908                     if (mInvokedDataDeactivation) {
1909                         log("Ignore tear down request because network is being torn down.");
1910                         break;
1911                     }
1912                     removeMessages(EVENT_TEAR_DOWN_NETWORK);
1913                     removeDeferredMessages(EVENT_TEAR_DOWN_NETWORK);
1914                     onTearDown(msg.arg1);
1915                     break;
1916                 case EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE:
1917                     int resultCode = msg.arg1;
1918                     onDeactivateResponse(resultCode);
1919                     break;
1920                 case EVENT_STUCK_IN_TRANSIENT_STATE:
1921                     // After frameworks issues deactivate data call request, RIL should report
1922                     // data disconnected through data call list changed event subsequently.
1923 
1924                     reportAnomaly("RIL did not send data call list changed event after "
1925                             + "deactivate data call request within "
1926                             + TimeUnit.MILLISECONDS.toSeconds(
1927                             mDataConfigManager.getAnomalyNetworkDisconnectingTimeoutMs())
1928                             + " seconds.", "d0e4fa1c-c57b-4ba5-b4b6-8955487012cc");
1929                     mFailCause = DataFailCause.LOST_CONNECTION;
1930                     transitionTo(mDisconnectedState);
1931                     break;
1932                 case EVENT_DISPLAY_INFO_CHANGED:
1933                     onDisplayInfoChanged();
1934                     break;
1935                 case EVENT_CSS_INDICATOR_CHANGED:
1936                 case EVENT_VOICE_CALL_STARTED:
1937                 case EVENT_VOICE_CALL_ENDED:
1938                     updateSuspendState();
1939                     updateNetworkCapabilities();
1940                     break;
1941                 default:
1942                     return NOT_HANDLED;
1943             }
1944             return HANDLED;
1945         }
1946     }
1947 
1948     /**
1949      * The disconnected state. This is the final state of a data network.
1950      *
1951      * @see DataNetwork for the state machine diagram.
1952      */
1953     private final class DisconnectedState extends State {
1954         @Override
1955         public void enter() {
1956             logl("Data network disconnected. mEverConnected=" + mEverConnected);
1957             // Preserve the list for onSetupDataFailed callback, because we need to pass that list
1958             // back to DataNetworkController, but after EVENT_DETACH_ALL_NETWORK_REQUESTS gets
1959             // processed, the network request list would become empty.
1960             NetworkRequestList requestList = new NetworkRequestList(mAttachedNetworkRequestList);
1961 
1962             // The detach all network requests must be the last message to handle.
1963             sendMessage(EVENT_DETACH_ALL_NETWORK_REQUESTS);
1964             // Gracefully handle all the un-processed events then quit the state machine.
1965             // quit() throws a QUIT event to the end of message queue. All the events before quit()
1966             // will be processed. Events after quit() will not be processed.
1967             quit();
1968 
1969             //************************************************************//
1970             // DO NOT POST ANY EVENTS AFTER HERE.                         //
1971             // THE STATE MACHINE WONT PROCESS EVENTS AFTER QUIT.          //
1972             // ONLY CLEANUP SHOULD BE PERFORMED AFTER THIS.               //
1973             //************************************************************//
1974 
1975             if (mEverConnected) {
1976                 mLinkStatus = DataCallResponse.LINK_STATUS_INACTIVE;
1977                 mNetworkValidationStatus =
1978                         PreciseDataConnectionState.NETWORK_VALIDATION_UNSUPPORTED;
1979                 mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
1980                         .onLinkStatusChanged(DataNetwork.this, mLinkStatus));
1981                 mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
1982                         .onDisconnected(DataNetwork.this, mFailCause, mTearDownReason));
1983                 if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
1984                     unregisterForWwanEvents();
1985                 }
1986                 // Since NetworkValidation is able to request only in the Connected state,
1987                 // if ever connected, log for onDataNetworkDisconnected.
1988                 mDataNetworkValidationStats.onDataNetworkDisconnected(getDataNetworkType());
1989             } else {
1990                 mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
1991                         .onSetupDataFailed(DataNetwork.this,
1992                                 requestList, mFailCause, mRetryDelayMillis));
1993             }
1994             notifyPreciseDataConnectionState();
1995             mNetworkAgent.unregister();
1996             mDataNetworkController.unregisterDataNetworkControllerCallback(
1997                     mDataNetworkControllerCallback);
1998             mDataCallSessionStats.onDataCallDisconnected(mFailCause);
1999 
2000             if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN
2001                     && mPduSessionId != DataCallResponse.PDU_SESSION_ID_NOT_SET) {
2002                 mRil.releasePduSessionId(null, mPduSessionId);
2003             }
2004 
2005             if (mVcnManager != null && mVcnPolicyChangeListener != null) {
2006                 mVcnManager.removeVcnNetworkPolicyChangeListener(mVcnPolicyChangeListener);
2007             }
2008         }
2009 
2010         @Override
2011         public boolean processMessage(Message msg) {
2012             logv("event=" + eventToString(msg.what));
2013             return NOT_HANDLED;
2014         }
2015     }
2016 
2017     /**
2018      * Register for events that can only happen on cellular networks.
2019      */
2020     private void registerForWwanEvents() {
2021         registerForBandwidthUpdate();
2022         mKeepaliveTracker.registerForKeepaliveStatus();
2023         mRil.registerForNotAvailable(this.getHandler(), EVENT_RADIO_NOT_AVAILABLE, null);
2024     }
2025 
2026     /**
2027      * Unregister for events that can only happen on cellular networks.
2028      */
2029     private void unregisterForWwanEvents() {
2030         unregisterForBandwidthUpdate();
2031         mKeepaliveTracker.unregisterForKeepaliveStatus();
2032         mRil.unregisterForNotAvailable(this.getHandler());
2033     }
2034 
2035     @Override
2036     protected void unhandledMessage(Message msg) {
2037         IState state = getCurrentState();
2038         loge("Unhandled message " + msg.what + " in state "
2039                 + (state == null ? "null" : state.getName()));
2040     }
2041 
2042     /**
2043      * Attempt to attach the network request list to this data network. Whether the network can
2044      * satisfy the request or not will be checked when EVENT_ATTACH_NETWORK_REQUEST is processed.
2045      * If the request can't be attached, {@link DataNetworkCallback#onAttachFailed(
2046      * DataNetwork, NetworkRequestList)}.
2047      *
2048      * @param requestList Network request list to attach.
2049      * @return {@code false} if the network is already disconnected. {@code true} means the request
2050      * has been scheduled to attach to the network. If attach succeeds, the network request's state
2051      * will be set to {@link TelephonyNetworkRequest#REQUEST_STATE_SATISFIED}. If failed, the
2052      * callback {@link DataNetworkCallback#onAttachFailed(DataNetwork, NetworkRequestList)} will
2053      * be called.
2054      */
2055     public boolean attachNetworkRequests(@NonNull NetworkRequestList requestList) {
2056         // If the network is already ended, we still attach the network request to the data network,
2057         // so it can be retried later by data network controller.
2058         if (getCurrentState() == null || isDisconnected()) {
2059             // The state machine has already stopped. This is due to data network is disconnected.
2060             return false;
2061         }
2062         sendMessage(obtainMessage(EVENT_ATTACH_NETWORK_REQUEST, requestList));
2063         return true;
2064     }
2065 
2066     /**
2067      * Called when attaching network request list to this data network.
2068      *
2069      * @param requestList Network request list to attach.
2070      */
2071     public void onAttachNetworkRequests(@NonNull NetworkRequestList requestList) {
2072         NetworkRequestList failedList = new NetworkRequestList();
2073         for (TelephonyNetworkRequest networkRequest : requestList) {
2074             if (!mDataNetworkController.isNetworkRequestExisting(networkRequest)) {
2075                 failedList.add(networkRequest);
2076                 log("Attached failed. Network request was already removed. " + networkRequest);
2077             } else if (!networkRequest.canBeSatisfiedBy(getNetworkCapabilities())) {
2078                 failedList.add(networkRequest);
2079                 log("Attached failed. Cannot satisfy the network request "
2080                         + networkRequest);
2081             } else {
2082                 mAttachedNetworkRequestList.add(networkRequest);
2083                 networkRequest.setAttachedNetwork(DataNetwork.this);
2084                 networkRequest.setState(
2085                         TelephonyNetworkRequest.REQUEST_STATE_SATISFIED);
2086                 log("Successfully attached network request " + networkRequest);
2087             }
2088         }
2089         if (!failedList.isEmpty()) {
2090             mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
2091                     .onAttachFailed(DataNetwork.this, failedList));
2092         }
2093     }
2094 
2095     /**
2096      * Called when detaching the network request from this data network.
2097      *
2098      * @param networkRequest Network request to detach.
2099      * @param shouldRetry {@code true} if the detached network request should be retried.
2100      */
2101     private void onDetachNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest,
2102             boolean shouldRetry) {
2103         mAttachedNetworkRequestList.remove(networkRequest);
2104         networkRequest.setState(TelephonyNetworkRequest.REQUEST_STATE_UNSATISFIED);
2105         networkRequest.setAttachedNetwork(null);
2106 
2107         if (shouldRetry) {
2108             // Inform DataNetworkController that a network request was detached and should be
2109             // scheduled to retry.
2110             mDataNetworkCallback.invokeFromExecutor(
2111                     () -> mDataNetworkCallback.onRetryUnsatisfiedNetworkRequest(networkRequest));
2112         }
2113 
2114         if (mAttachedNetworkRequestList.isEmpty()) {
2115             log("All network requests are detached.");
2116 
2117             // If there is no network request attached, and we are not preferred data phone, then
2118             // this detach is likely due to temp DDS switch. We should tear down the network when
2119             // all requests are detached so the other network on preferred data sub can be
2120             // established properly.
2121             int preferredDataPhoneId = PhoneSwitcher.getInstance().getPreferredDataPhoneId();
2122             if (preferredDataPhoneId != SubscriptionManager.INVALID_PHONE_INDEX
2123                     && preferredDataPhoneId != mPhone.getPhoneId()) {
2124                 tearDown(TEAR_DOWN_REASON_PREFERRED_DATA_SWITCHED);
2125             }
2126         }
2127     }
2128 
2129     /**
2130      * Detach the network request from this data network. Note that this will not tear down the
2131      * network.
2132      *
2133      * @param networkRequest Network request to detach.
2134      * @param shouldRetry {@code true} if the detached network request should be retried.
2135      */
2136     public void detachNetworkRequest(@NonNull TelephonyNetworkRequest networkRequest,
2137             boolean shouldRetry) {
2138         if (getCurrentState() == null || isDisconnected()) {
2139             return;
2140         }
2141         sendMessage(obtainMessage(EVENT_DETACH_NETWORK_REQUEST, shouldRetry ? 1 : 0, 0,
2142                 networkRequest));
2143     }
2144 
2145     /**
2146      * Register for bandwidth update.
2147      */
2148     private void registerForBandwidthUpdate() {
2149         int bandwidthEstimateSource = mDataConfigManager.getBandwidthEstimateSource();
2150         if (bandwidthEstimateSource == BANDWIDTH_SOURCE_MODEM) {
2151             mPhone.mCi.registerForLceInfo(
2152                     getHandler(), EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED, null);
2153         } else if (bandwidthEstimateSource == BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR) {
2154             if (mLinkBandwidthEstimatorCallback == null) {
2155                 mLinkBandwidthEstimatorCallback =
2156                         new LinkBandwidthEstimatorCallback(getHandler()::post) {
2157                             @Override
2158                             public void onBandwidthChanged(int uplinkBandwidthKbps,
2159                                     int downlinkBandwidthKbps) {
2160                                 if (isConnected()) {
2161                                     onBandwidthUpdated(uplinkBandwidthKbps, downlinkBandwidthKbps);
2162                                 }
2163                             }
2164                         };
2165                 mPhone.getLinkBandwidthEstimator().registerCallback(
2166                         mLinkBandwidthEstimatorCallback);
2167             }
2168         } else {
2169             loge("Invalid bandwidth source configuration: " + bandwidthEstimateSource);
2170         }
2171     }
2172 
2173     /**
2174      * Unregister bandwidth update.
2175      */
2176     private void unregisterForBandwidthUpdate() {
2177         int bandwidthEstimateSource = mDataConfigManager.getBandwidthEstimateSource();
2178         if (bandwidthEstimateSource == BANDWIDTH_SOURCE_MODEM) {
2179             mPhone.mCi.unregisterForLceInfo(getHandler());
2180         } else if (bandwidthEstimateSource == BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR) {
2181             if (mLinkBandwidthEstimatorCallback != null) {
2182                 mPhone.getLinkBandwidthEstimator()
2183                         .unregisterCallback(mLinkBandwidthEstimatorCallback);
2184                 mLinkBandwidthEstimatorCallback = null;
2185             }
2186         } else {
2187             loge("Invalid bandwidth source configuration: " + bandwidthEstimateSource);
2188         }
2189     }
2190 
2191     /**
2192      * Remove network requests that can't be satisfied anymore.
2193      *
2194      * @param shouldRetry {@code true} if the detached network requests should be retried.
2195      */
2196     private void removeUnsatisfiedNetworkRequests(boolean shouldRetry) {
2197         for (TelephonyNetworkRequest networkRequest : mAttachedNetworkRequestList) {
2198             if (!networkRequest.canBeSatisfiedBy(mNetworkCapabilities)) {
2199                 log("removeUnsatisfiedNetworkRequests: " + networkRequest
2200                         + " can't be satisfied anymore. Will be detached.");
2201                 detachNetworkRequest(networkRequest, shouldRetry);
2202             }
2203         }
2204     }
2205 
2206     /**
2207      * Check if the new link properties are compatible with the old link properties. For example,
2208      * if IP changes, that's considered incompatible.
2209      *
2210      * @param oldLinkProperties Old link properties.
2211      * @param newLinkProperties New Link properties.
2212      *
2213      * @return {@code true} if the new link properties is compatible with the old link properties.
2214      */
2215     private boolean isLinkPropertiesCompatible(@NonNull LinkProperties oldLinkProperties,
2216             @NonNull LinkProperties newLinkProperties) {
2217         if (Objects.equals(oldLinkProperties, newLinkProperties)) return true;
2218 
2219         if (!LinkPropertiesUtils.isIdenticalAddresses(oldLinkProperties, newLinkProperties)) {
2220             // If the same address type was removed and added we need to cleanup.
2221             LinkPropertiesUtils.CompareOrUpdateResult<Integer, LinkAddress> result =
2222                     new LinkPropertiesUtils.CompareOrUpdateResult<>(
2223                             oldLinkProperties.getLinkAddresses(),
2224                             newLinkProperties.getLinkAddresses(),
2225                             linkAddress -> Objects.hash(linkAddress.getAddress(),
2226                                     linkAddress.getPrefixLength(), linkAddress.getScope()));
2227             log("isLinkPropertiesCompatible: old=" + oldLinkProperties
2228                     + " new=" + newLinkProperties + " result=" + result);
2229             for (LinkAddress added : result.added) {
2230                 for (LinkAddress removed : result.removed) {
2231                     if (NetUtils.addressTypeMatches(removed.getAddress(), added.getAddress())) {
2232                         return false;
2233                     }
2234                 }
2235             }
2236         }
2237 
2238         return true;
2239     }
2240 
2241     /**
2242      * Check if there are immutable capabilities changed. The connectivity service is not able
2243      * to handle immutable capabilities changed, but in very rare scenarios, immutable capabilities
2244      * need to be changed dynamically, such as in setup data call response, modem responded with the
2245      * same cid. In that case, we need to merge the new capabilities into the existing data network.
2246      *
2247      * @param oldCapabilities The old network capabilities.
2248      * @param newCapabilities The new network capabilities.
2249      * @return {@code true} if there are immutable network capabilities changed.
2250      */
2251     private static boolean areImmutableCapabilitiesChanged(
2252             @NonNull NetworkCapabilities oldCapabilities,
2253             @NonNull NetworkCapabilities newCapabilities) {
2254         if (ArrayUtils.isEmpty(oldCapabilities.getCapabilities())) return false;
2255 
2256         // Remove mutable capabilities from both old and new capabilities, the remaining
2257         // capabilities would be immutable capabilities.
2258         List<Integer> oldImmutableCapabilities = Arrays.stream(oldCapabilities.getCapabilities())
2259                 .boxed().collect(Collectors.toList());
2260         oldImmutableCapabilities.removeAll(MUTABLE_CAPABILITIES);
2261         List<Integer> newImmutableCapabilities = Arrays.stream(newCapabilities.getCapabilities())
2262                 .boxed().collect(Collectors.toList());
2263         newImmutableCapabilities.removeAll(MUTABLE_CAPABILITIES);
2264         return oldImmutableCapabilities.size() != newImmutableCapabilities.size()
2265                 || !oldImmutableCapabilities.containsAll(newImmutableCapabilities);
2266     }
2267 
2268     /**
2269      * In some rare cases we need to re-create the network agent, for example, underlying network
2270      * IP changed, or when we unfortunately need to remove/add a immutable network capability.
2271      */
2272     private void recreateNetworkAgent() {
2273         if (isConnecting() || isDisconnected() || isDisconnecting()) {
2274             loge("Incorrect state for re-creating the network agent.");
2275             return;
2276         }
2277 
2278         // Abandon the network agent because we are going to create a new one.
2279         mNetworkAgent.abandon();
2280         // Create a new network agent and register with connectivity service. Note that the agent
2281         // will always be registered with NOT_SUSPENDED capability.
2282         mNetworkAgent = createNetworkAgent();
2283         mNetworkAgent.markConnected();
2284         notifyPreciseDataConnectionState();
2285         // Because network agent is always created with NOT_SUSPENDED, we need to update
2286         // the suspended if it's was in suspended state.
2287         if (mSuspended) {
2288             log("recreateNetworkAgent: The network is in suspended state. Update the network"
2289                     + " capability again. nc=" + mNetworkCapabilities);
2290             mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
2291         }
2292     }
2293 
2294     /**
2295      * @return {@code true} if this is a satellite data network.
2296      */
2297     public boolean isSatellite() {
2298         return mIsSatellite;
2299     }
2300 
2301     /**
2302      * Update the network capabilities.
2303      */
2304     private void updateNetworkCapabilities() {
2305         final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder();
2306 
2307         if (mFlags.satelliteInternet() && mIsSatellite
2308                 && mDataConfigManager.getForcedCellularTransportCapabilities().stream()
2309                 .noneMatch(this::hasNetworkCapabilityInNetworkRequests)) {
2310             // TODO: b/328622096 remove the try/catch
2311             try {
2312                 builder.addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE);
2313             } catch (IllegalArgumentException exception) {
2314                 loge("TRANSPORT_SATELLITE is not supported.");
2315                 builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
2316             }
2317         } else {
2318             builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
2319         }
2320 
2321         boolean roaming = mPhone.getServiceState().getDataRoaming();
2322 
2323         builder.setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder()
2324                 .setSubscriptionId(mSubId).build());
2325         builder.setSubscriptionIds(Collections.singleton(mSubId));
2326 
2327         ApnSetting apnSetting = mDataProfile.getApnSetting();
2328 
2329         if (apnSetting != null) {
2330             apnSetting.getApnTypes().stream()
2331                     .map(DataUtils::apnTypeToNetworkCapability)
2332                     .filter(cap -> cap >= 0)
2333                     .forEach(builder::addCapability);
2334             if (apnSetting.getApnTypes().contains(ApnSetting.TYPE_ENTERPRISE)) {
2335                 builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2336             }
2337         }
2338 
2339         // If MMTEL capability is requested, we should not remove it because it's an immutable
2340         // capability defined by connectivity service. When the device enters from VoPS to non-VoPS,
2341         // we should perform grace tear down from data network controller if needed.
2342         if (hasNetworkCapabilityInNetworkRequests(NetworkCapabilities.NET_CAPABILITY_MMTEL)) {
2343             // Request has MMTEL, add it again so the network won't be unwanted by connectivity.
2344             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
2345         } else if (mDataProfile.canSatisfy(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2346             // Request has IMS capability only.
2347             // Always add MMTEL capability on IMS network unless network explicitly indicates VoPS
2348             // not supported.
2349             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
2350             if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
2351                 NetworkRegistrationInfo nri = getNetworkRegistrationInfo();
2352                 if (nri != null) {
2353                     DataSpecificRegistrationInfo dsri = nri.getDataSpecificInfo();
2354                     // Check if the network is non-VoPS.
2355                     if (dsri != null && dsri.getVopsSupportInfo() != null
2356                             && !dsri.getVopsSupportInfo().isVopsSupported()
2357                             // Reflect the actual MMTEL if flag on.
2358                             && (mFlags.allowMmtelInNonVops()
2359                             // Deceive Connectivity service to satisfy an MMTEL request, this should
2360                             // be useless because we reach here if no MMTEL request, then removing
2361                             // MMTEL capability shouldn't have any impacts.
2362                             || !mDataConfigManager.shouldKeepNetworkUpInNonVops(
2363                                     nri.getNetworkRegistrationState()))) {
2364                         builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL);
2365                     }
2366                     log("updateNetworkCapabilities: dsri=" + dsri);
2367                 }
2368             }
2369         }
2370 
2371         // Extract network capabilities from the traffic descriptor.
2372         for (TrafficDescriptor trafficDescriptor : mTrafficDescriptors) {
2373             try {
2374                 if (trafficDescriptor.getOsAppId() == null) continue;
2375                 OsAppId osAppId = new OsAppId(trafficDescriptor.getOsAppId());
2376                 if (!osAppId.getOsId().equals(OsAppId.ANDROID_OS_ID)) {
2377                     loge("Received non-Android OS id " + osAppId.getOsId());
2378                     continue;
2379                 }
2380                 int networkCapability = DataUtils.getNetworkCapabilityFromString(
2381                         osAppId.getAppId());
2382                 switch (networkCapability) {
2383                     case NetworkCapabilities.NET_CAPABILITY_ENTERPRISE:
2384                         builder.addCapability(networkCapability);
2385                         // Always add internet if TD contains enterprise.
2386                         builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
2387                         builder.addEnterpriseId(osAppId.getDifferentiator());
2388                         break;
2389                     case NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY:
2390                     case NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH:
2391                     case NetworkCapabilities.NET_CAPABILITY_CBS:
2392                         builder.addCapability(networkCapability);
2393                         break;
2394                     default:
2395                         loge("Invalid app id " + osAppId.getAppId());
2396                 }
2397             } catch (Exception e) {
2398                 loge("Exception: " + e + ". Failed to create osAppId from "
2399                         + new BigInteger(1, trafficDescriptor.getOsAppId()).toString(16));
2400             }
2401         }
2402 
2403         if (!mCongested) {
2404             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED);
2405         }
2406 
2407         if (mTempNotMeteredSupported && mTempNotMetered) {
2408             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED);
2409         }
2410 
2411         // Always start with NOT_VCN_MANAGED, then remove if VcnManager indicates this is part of a
2412         // VCN.
2413         builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED);
2414         final VcnNetworkPolicyResult vcnPolicy = getVcnPolicy(builder.build());
2415         if (vcnPolicy != null && !vcnPolicy.getNetworkCapabilities()
2416                 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)) {
2417             builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED);
2418         }
2419 
2420         if (!roaming) {
2421             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
2422         }
2423 
2424         if (!mSuspended) {
2425             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED);
2426         }
2427 
2428         if (mCarrierServicePackageUid != Process.INVALID_UID
2429                 && ArrayUtils.contains(mAdministratorUids, mCarrierServicePackageUid)) {
2430             builder.setOwnerUid(mCarrierServicePackageUid);
2431             builder.setAllowedUids(Collections.singleton(mCarrierServicePackageUid));
2432         }
2433         builder.setAdministratorUids(mAdministratorUids);
2434 
2435         Set<Integer> meteredCapabilities = mDataConfigManager
2436                 .getMeteredNetworkCapabilities(roaming).stream()
2437                 .filter(cap -> mAccessNetworksManager.getPreferredTransportByNetworkCapability(cap)
2438                         == AccessNetworkConstants.TRANSPORT_TYPE_WWAN)
2439                 .collect(Collectors.toSet());
2440         boolean unmeteredNetwork = meteredCapabilities.stream().noneMatch(
2441                 Arrays.stream(builder.build().getCapabilities()).boxed()
2442                         .collect(Collectors.toSet())::contains);
2443 
2444         if (unmeteredNetwork) {
2445             builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2446         }
2447 
2448         // Always start with not-restricted, and then remove if needed.
2449         // By default, NET_CAPABILITY_NOT_RESTRICTED and NET_CAPABILITY_NOT_CONSTRAINED are included
2450         builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
2451 
2452         // When data is disabled, or data roaming is disabled and the device is roaming, we need
2453         // to remove certain capabilities depending on scenarios.
2454         if (!mDataNetworkController.getDataSettingsManager().isDataEnabled()
2455                 || (mPhone.getServiceState().getDataRoaming()
2456                 && !mDataNetworkController.getDataSettingsManager().isDataRoamingEnabled())) {
2457             // If data is allowed because the request is a restricted network request, we need
2458             // to mark the network as restricted when data is disabled or data roaming is disabled
2459             // and the device is roaming. If we don't do that, non-privileged apps will be able
2460             // to use this network when data is disabled.
2461             if (mDataAllowedReason == DataAllowedReason.RESTRICTED_REQUEST) {
2462                 builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
2463             } else if (mDataAllowedReason == DataAllowedReason.UNMETERED_USAGE
2464                     || mDataAllowedReason == DataAllowedReason.MMS_REQUEST
2465                     || mDataAllowedReason == DataAllowedReason.EMERGENCY_SUPL) {
2466                 // If data is allowed due to unmetered usage, or MMS always-allowed, we need to
2467                 // remove unrelated-but-metered capabilities.
2468                 for (int capability : meteredCapabilities) {
2469                     // 1. If it's unmetered usage, remove all metered capabilities.
2470                     // 2. If it's MMS always-allowed, then remove all metered capabilities but MMS.
2471                     // 3/ If it's for emergency SUPL, then remove all metered capabilities but SUPL.
2472                     if ((capability == NetworkCapabilities.NET_CAPABILITY_MMS
2473                             && mDataAllowedReason == DataAllowedReason.MMS_REQUEST)
2474                             || (capability == NetworkCapabilities.NET_CAPABILITY_SUPL
2475                             && mDataAllowedReason == DataAllowedReason.EMERGENCY_SUPL)) {
2476                         // Not removing the capability for special uses.
2477                         continue;
2478                     }
2479                     builder.removeCapability(capability);
2480                 }
2481             }
2482         }
2483 
2484         if (mDataNetworkController.isEsimBootStrapProvisioningActivated()) {
2485             builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
2486         }
2487 
2488         // Check if the feature force MMS on IWLAN is enabled. When the feature is enabled, MMS
2489         // will be attempted on IWLAN if possible, even if existing cellular networks already
2490         // supports IWLAN.
2491         if (mFlags.forceIwlanMms() && builder.build()
2492                 .hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
2493                 && mDataConfigManager.isForceIwlanMmsFeatureEnabled()) {
2494             // If QNS sets MMS preferred on IWLAN, and it is possible to setup an MMS network on
2495             // IWLAN, then we need to remove the MMS capability on the cellular network. This will
2496             // allow the new MMS network to be brought up on IWLAN when MMS network request arrives.
2497             if (mAccessNetworksManager.getPreferredTransportByNetworkCapability(
2498                     NetworkCapabilities.NET_CAPABILITY_MMS)
2499                     == AccessNetworkConstants.TRANSPORT_TYPE_WLAN && mTransport
2500                     == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
2501 
2502                 DataProfile dataProfile = mDataNetworkController.getDataProfileManager()
2503                         .getDataProfileForNetworkRequest(new TelephonyNetworkRequest(
2504                                 new NetworkRequest.Builder().addCapability(
2505                                 NetworkCapabilities.NET_CAPABILITY_MMS).build(), mPhone, mFlags),
2506                         TelephonyManager.NETWORK_TYPE_IWLAN, false, false, false);
2507                 // If we find another data data profile that can support MMS on IWLAN, then remove
2508                 // the MMS capability from this cellular network. This will allow IWLAN to be
2509                 // brought up for MMS later.
2510                 if (dataProfile != null && !dataProfile.getApn().equals(mDataProfile.getApn())) {
2511                     log("Found a different apn name " + mDataProfile.getApn()
2512                             + " that can serve MMS on IWLAN.");
2513                     builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
2514                 }
2515             }
2516         }
2517 
2518         // If one of the capabilities are for special use, for example, IMS, CBS, then this
2519         // network should be restricted, regardless data is enabled or not.
2520         if (NetworkCapabilitiesUtils.inferRestrictedCapability(builder.build())
2521                 || (vcnPolicy != null && !vcnPolicy.getNetworkCapabilities()
2522                         .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED))) {
2523             builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
2524         }
2525 
2526         // Set the bandwidth information.
2527         builder.setLinkDownstreamBandwidthKbps(mNetworkBandwidth.downlinkBandwidthKbps);
2528         builder.setLinkUpstreamBandwidthKbps(mNetworkBandwidth.uplinkBandwidthKbps);
2529 
2530         // Configure the network as restricted/constrained for unrestricted satellite network.
2531         if (mFlags.satelliteInternet() && mIsSatellite && builder.build()
2532                 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)) {
2533             switch (mDataConfigManager.getSatelliteDataSupportMode()) {
2534                 case CarrierConfigManager.SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED
2535                         -> builder.removeCapability(
2536                                 NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
2537                 case CarrierConfigManager.SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED -> {
2538                     try {
2539                         builder.removeCapability(DataUtils
2540                                 .NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
2541                     } catch (Exception ignored) { }
2542                 }
2543                 // default case CarrierConfigManager.SATELLITE_DATA_SUPPORT_ALL
2544             }
2545         }
2546 
2547         NetworkCapabilities nc = builder.build();
2548         if (mNetworkCapabilities == null || mNetworkAgent == null) {
2549             // This is the first time when network capabilities is created. The agent is not created
2550             // at this time. Just return here. The network capabilities will be used when network
2551             // agent is created.
2552             mNetworkCapabilities = nc;
2553             logl("Initial capabilities " + mNetworkCapabilities);
2554             return;
2555         }
2556 
2557         if (!nc.equals(mNetworkCapabilities)) {
2558             // Check if we are changing the immutable capabilities. Note that we should be very
2559             // careful and limit the use cases of changing immutable capabilities. Connectivity
2560             // service would not close sockets for clients if a network request becomes
2561             // unsatisfiable.
2562             if (mEverConnected && areImmutableCapabilitiesChanged(mNetworkCapabilities, nc)
2563                     && (isConnected() || isHandoverInProgress())) {
2564                 // Before connectivity service supports making all capabilities mutable, it is
2565                 // suggested to de-register and re-register the network agent if it is needed to
2566                 // add/remove immutable capabilities.
2567                 logl("updateNetworkCapabilities: Immutable capabilities changed. Re-create the "
2568                         + "network agent. Attempted to change from " + mNetworkCapabilities + " to "
2569                         + nc);
2570                 mNetworkCapabilities = nc;
2571                 recreateNetworkAgent();
2572             } else {
2573                 // Now we need to inform connectivity service and data network controller
2574                 // about the capabilities changed.
2575                 mNetworkCapabilities = nc;
2576                 log("Capabilities changed to " + mNetworkCapabilities);
2577                 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
2578             }
2579 
2580             // Only retry the request when the network is in connected or handover state. This is to
2581             // prevent request is detached during connecting state, and then become a setup/detach
2582             // infinite loop.
2583             boolean shouldRetry = isConnected() || isHandoverInProgress();
2584             removeUnsatisfiedNetworkRequests(shouldRetry);
2585             mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
2586                     .onNetworkCapabilitiesChanged(DataNetwork.this));
2587         } else {
2588             log("updateNetworkCapabilities: Capabilities not changed.");
2589         }
2590     }
2591 
2592     /**
2593      * @return The network capabilities of this data network.
2594      */
2595     @NonNull
2596     public NetworkCapabilities getNetworkCapabilities() {
2597         return mNetworkCapabilities;
2598     }
2599 
2600     /**
2601      * @return The link properties of this data network.
2602      */
2603     @NonNull
2604     public LinkProperties getLinkProperties() {
2605         return mLinkProperties;
2606     }
2607 
2608     /**
2609      * @return The data profile of this data network.
2610      */
2611     @NonNull
2612     public DataProfile getDataProfile() {
2613         return mDataProfile;
2614     }
2615 
2616     /**
2617      * Update data suspended state.
2618      */
2619     private void updateSuspendState() {
2620         if (isConnecting() || isDisconnected()) {
2621             // Return if not in the right state.
2622             return;
2623         }
2624 
2625         boolean newSuspendedState = false;
2626         // Get the uncombined service state directly.
2627         NetworkRegistrationInfo nri = getNetworkRegistrationInfo();
2628         if (nri == null) return;
2629 
2630         // Never set suspended for emergency apn. Emergency data connection
2631         // can work while device is not in service.
2632         if (mNetworkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_EIMS)) {
2633             // If we are not in service, change to suspended.
2634         } else if (nri.getRegistrationState()
2635                 != NetworkRegistrationInfo.REGISTRATION_STATE_HOME
2636                 && nri.getRegistrationState()
2637                 != NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING) {
2638             newSuspendedState = true;
2639             // Check voice/data concurrency.
2640         } else if (!mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()
2641                 && mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN
2642                 && mPhone.getCallTracker() != null) {
2643             newSuspendedState = mPhone.getCallTracker().getState() != PhoneConstants.State.IDLE;
2644         }
2645 
2646         // Only notify when there is a change.
2647         if (mSuspended != newSuspendedState) {
2648             mSuspended = newSuspendedState;
2649             logl("Network becomes " + (mSuspended ? "suspended" : "unsuspended"));
2650             // To update NOT_SUSPENDED capability.
2651             updateNetworkCapabilities();
2652             notifyPreciseDataConnectionState();
2653             mDataNetworkCallback.invokeFromExecutor(() ->
2654                     mDataNetworkCallback.onSuspendedStateChanged(DataNetwork.this, mSuspended));
2655         }
2656     }
2657 
2658     /**
2659      * Allocate PDU session ID from the modem. This is only needed when the data network is
2660      * initiated on IWLAN.
2661      */
2662     private void allocatePduSessionId() {
2663         mRil.allocatePduSessionId(obtainMessage(EVENT_ALLOCATE_PDU_SESSION_ID_RESPONSE));
2664     }
2665 
2666     /**
2667      * Get fail cause from {@link DataCallResponse} and the result code.
2668      *
2669      * @param resultCode The result code returned from
2670      * {@link DataServiceCallback#onSetupDataCallComplete(int, DataCallResponse)}.
2671      * @param response The data call response returned from
2672      * {@link DataServiceCallback#onSetupDataCallComplete(int, DataCallResponse)}.
2673      *
2674      * @return The fail cause. {@link DataFailCause#NONE} if succeeds.
2675      */
2676     @DataFailureCause
2677     private int getFailCauseFromDataCallResponse(
2678             @DataServiceCallback.ResultCode int resultCode, @Nullable DataCallResponse response) {
2679         int failCause = DataFailCause.NONE;
2680         switch (resultCode) {
2681             case DataServiceCallback.RESULT_ERROR_ILLEGAL_STATE:
2682                 failCause = DataFailCause.RADIO_NOT_AVAILABLE;
2683                 break;
2684             case DataServiceCallback.RESULT_ERROR_BUSY:
2685             case DataServiceCallback.RESULT_ERROR_TEMPORARILY_UNAVAILABLE:
2686                 failCause = DataFailCause.SERVICE_TEMPORARILY_UNAVAILABLE;
2687                 break;
2688             case DataServiceCallback.RESULT_ERROR_INVALID_ARG:
2689                 failCause = DataFailCause.UNACCEPTABLE_NETWORK_PARAMETER;
2690                 break;
2691             case DataServiceCallback.RESULT_ERROR_UNSUPPORTED:
2692                 failCause = DataFailCause.REQUEST_NOT_SUPPORTED;
2693                 break;
2694             case DataServiceCallback.RESULT_SUCCESS:
2695                 if (response != null) {
2696                     failCause = DataFailCause.getFailCause(response.getCause());
2697                 }
2698                 break;
2699         }
2700         return failCause;
2701     }
2702 
2703     /**
2704      * Update data network based on the latest {@link DataCallResponse}.
2705      *
2706      * @param response The data call response from data service.
2707      */
2708     private void updateDataNetwork(@Nullable DataCallResponse response) {
2709         if (response == null) return;
2710         mCid.put(mTransport, response.getId());
2711         LinkProperties linkProperties = new LinkProperties();
2712 
2713         // Set interface name
2714         linkProperties.setInterfaceName(response.getInterfaceName());
2715 
2716         // Set PDU session id
2717         if (mPduSessionId != response.getPduSessionId()) {
2718             mPduSessionId = response.getPduSessionId();
2719             log("PDU session id updated to " + mPduSessionId);
2720         }
2721 
2722         // Set the link status
2723         if (mLinkStatus != response.getLinkStatus()) {
2724             mLinkStatus = response.getLinkStatus();
2725             log("Link status updated to " + DataUtils.linkStatusToString(mLinkStatus));
2726             if (isConnected()) {
2727                 // If the data network is in a transition state, the link status will be notified
2728                 // upon entering connected or disconnected state. If the data network is already
2729                 // connected, send the updated link status from the updated data call response.
2730                 mDataNetworkCallback.invokeFromExecutor(() -> mDataNetworkCallback
2731                         .onLinkStatusChanged(DataNetwork.this, mLinkStatus));
2732             }
2733         }
2734 
2735         // Set link addresses
2736         if (!response.getAddresses().isEmpty()) {
2737             for (LinkAddress la : response.getAddresses()) {
2738                 if (!la.getAddress().isAnyLocalAddress()) {
2739                     logv("addr/pl=" + la.getAddress() + "/" + la.getPrefixLength());
2740                     linkProperties.addLinkAddress(la);
2741                 }
2742             }
2743         } else {
2744             loge("no address for ifname=" + response.getInterfaceName());
2745         }
2746 
2747         // Set DNS servers
2748         if (!response.getDnsAddresses().isEmpty()) {
2749             for (InetAddress dns : response.getDnsAddresses()) {
2750                 if (!dns.isAnyLocalAddress()) {
2751                     linkProperties.addDnsServer(dns);
2752                 }
2753             }
2754         } else {
2755             loge("Empty dns response");
2756         }
2757 
2758         // Set PCSCF
2759         if (!response.getPcscfAddresses().isEmpty()) {
2760             for (InetAddress pcscf : response.getPcscfAddresses()) {
2761                 linkProperties.addPcscfServer(pcscf);
2762             }
2763         }
2764 
2765         // For backwards compatibility, use getMtu() if getMtuV4() is not available.
2766         int mtuV4 = response.getMtuV4() > 0 ? response.getMtuV4() : response.getMtu();
2767 
2768         if (mtuV4 <= 0) {
2769             // Use back up value from data profile.
2770             if (mDataProfile.getApnSetting() != null) {
2771                 mtuV4 = mDataProfile.getApnSetting().getMtuV4();
2772             }
2773             if (mtuV4 <= 0) {
2774                 mtuV4 = mDataConfigManager.getDefaultMtu();
2775             }
2776         }
2777 
2778         // For backwards compatibility, use getMtu() if getMtuV6() is not available.
2779         int mtuV6 = response.getMtuV6() > 0 ? response.getMtuV6() : response.getMtu();
2780         if (mtuV6 <= 0) {
2781             // Use back up value from data profile.
2782             if (mDataProfile.getApnSetting() != null) {
2783                 mtuV6 = mDataProfile.getApnSetting().getMtuV6();
2784             }
2785             if (mtuV6 <= 0) {
2786                 mtuV6 = mDataConfigManager.getDefaultMtu();
2787             }
2788         }
2789 
2790         // Set MTU for each route.
2791         for (InetAddress gateway : response.getGatewayAddresses()) {
2792             int mtu = gateway instanceof java.net.Inet6Address ? mtuV6 : mtuV4;
2793             linkProperties.addRoute(new RouteInfo(null, gateway, null,
2794                     RouteInfo.RTN_UNICAST, mtu));
2795         }
2796 
2797         // LinkProperties.setMtu should be deprecated. The mtu for each route has been already
2798         // provided in addRoute() above. For backwards compatibility, we still need to provide
2799         // a value for the legacy MTU. Use the higher value of v4 and v6 value here.
2800         linkProperties.setMtu(Math.max(mtuV4, mtuV6));
2801 
2802         if (mDataProfile.getApnSetting() != null
2803                 && !TextUtils.isEmpty(mDataProfile.getApnSetting().getProxyAddressAsString())) {
2804             int port = mDataProfile.getApnSetting().getProxyPort();
2805             if (port == -1) {
2806                 port = 8080;
2807             }
2808             ProxyInfo proxy = ProxyInfo.buildDirectProxy(
2809                     mDataProfile.getApnSetting().getProxyAddressAsString(), port);
2810             linkProperties.setHttpProxy(proxy);
2811         }
2812 
2813         linkProperties.setTcpBufferSizes(mTcpBufferSizes);
2814 
2815         mNetworkSliceInfo = response.getSliceInfo();
2816 
2817         mTrafficDescriptors.clear();
2818         mTrafficDescriptors.addAll(response.getTrafficDescriptors());
2819 
2820         mDefaultQos = response.getDefaultQos();
2821 
2822 
2823         Set<QosBearerSession> newSessions = new HashSet<>(response.getQosBearerSessions());
2824         if (newSessions.size() != mQosBearerSessions.size()
2825                 || !newSessions.containsAll(mQosBearerSessions)) {
2826             mDataNetworkCallback.onQosSessionsChanged(response.getQosBearerSessions());
2827         }
2828         mQosBearerSessions.clear();
2829         mQosBearerSessions.addAll(response.getQosBearerSessions());
2830         if (mQosCallbackTracker != null) {
2831             mQosCallbackTracker.updateSessions(mQosBearerSessions);
2832         }
2833 
2834         if (!linkProperties.equals(mLinkProperties)) {
2835             // If the new link properties is not compatible (e.g. IP changes, interface changes),
2836             // then we should de-register the network agent and re-create a new one.
2837             if ((isConnected() || isHandoverInProgress())
2838                     && !isLinkPropertiesCompatible(mLinkProperties, linkProperties)) {
2839                 logl("updateDataNetwork: Incompatible link properties detected. Re-create the "
2840                         + "network agent. Changed from " + mLinkProperties + " to "
2841                         + linkProperties);
2842 
2843                 mLinkProperties = linkProperties;
2844                 recreateNetworkAgent();
2845             } else {
2846                 mLinkProperties = linkProperties;
2847                 log("sendLinkProperties " + mLinkProperties);
2848                 mNetworkAgent.sendLinkProperties(mLinkProperties);
2849             }
2850         }
2851 
2852         updateNetworkCapabilities();
2853         updateValidationStatus(response.getNetworkValidationStatus());
2854     }
2855 
2856     /**
2857      * If the {@link DataCallResponse} contains invalid info, triggers an anomaly report.
2858      *
2859      * @param response The response to be validated
2860      * @param setupRegState Registration state if the response is for initial data call setup.
2861      */
2862     private void validateDataCallResponse(@Nullable DataCallResponse response,
2863             @NetworkRegistrationInfo.RegistrationState int setupRegState) {
2864         if (response == null
2865                 || response.getLinkStatus() == DataCallResponse.LINK_STATUS_INACTIVE) return;
2866         int failCause = response.getCause();
2867         if (failCause == DataFailCause.NONE) {
2868             if (TextUtils.isEmpty(response.getInterfaceName())
2869                     || response.getAddresses().isEmpty()
2870                     // if out of range
2871                     || response.getLinkStatus() < DataCallResponse.LINK_STATUS_UNKNOWN
2872                     || response.getLinkStatus() > DataCallResponse.LINK_STATUS_ACTIVE
2873                     || response.getProtocolType() < ApnSetting.PROTOCOL_UNKNOWN
2874                     || response.getProtocolType() > ApnSetting.PROTOCOL_UNSTRUCTURED
2875                     || response.getHandoverFailureMode()
2876                     < DataCallResponse.HANDOVER_FAILURE_MODE_UNKNOWN
2877                     || response.getHandoverFailureMode()
2878                     > DataCallResponse.HANDOVER_FAILURE_MODE_NO_FALLBACK_RETRY_SETUP_NORMAL) {
2879                 loge("Invalid DataCallResponse:" + response);
2880                 reportAnomaly("Invalid DataCallResponse detected",
2881                         "1f273e9d-b09c-46eb-ad1c-421d01f61164");
2882             }
2883             // Check IP for initial setup response
2884             NetworkRegistrationInfo nri = getNetworkRegistrationInfo();
2885             if (setupRegState != -1 // Is setup response
2886                     && mDataProfile.getApnSetting() != null && nri != null && nri.isInService()) {
2887                 boolean wasRoaming = setupRegState
2888                         == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING;
2889                 boolean isRoaming = nri.getNetworkRegistrationState()
2890                         == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING;
2891                 if (wasRoaming == isRoaming) { // Ignore check if in race condition.
2892                     int protocol = isRoaming ? mDataProfile.getApnSetting().getRoamingProtocol()
2893                             : mDataProfile.getApnSetting().getProtocol();
2894                     String underlyingDataService = mTransport
2895                             == AccessNetworkConstants.TRANSPORT_TYPE_WWAN
2896                             ? "RIL" : "IWLAN data service";
2897                     if (protocol == ApnSetting.PROTOCOL_IP) {
2898                         if (response.getAddresses().stream().noneMatch(
2899                                 la -> la.getAddress() instanceof java.net.Inet4Address)) {
2900                             loge("Invalid DataCallResponse. Requested IPv4 but didn't get an "
2901                                     + "IPv4 address." + response);
2902                             reportAnomaly(underlyingDataService + " reported mismatched IP "
2903                                     + "type. Requested IPv4 but didn't get an IPv4 "
2904                                     + "address.", "7744f920-fb64-4db0-ba47-de0eae485a82");
2905                         }
2906                     } else if (protocol == ApnSetting.PROTOCOL_IPV6) {
2907                         if (response.getAddresses().stream().noneMatch(
2908                                 la -> la.getAddress() instanceof java.net.Inet6Address)) {
2909                             loge("Invalid DataCallResponse. Requested IPv6 but didn't get an "
2910                                     + "IPv6 address." + response);
2911                             reportAnomaly(underlyingDataService + " reported mismatched IP "
2912                                     + "type. Requested IPv6 but didn't get an IPv6 "
2913                                     + "address.", "7744f920-fb64-4db0-ba47-de0eae485a82");
2914                         }
2915                     }
2916                 }
2917             }
2918         } else if (!DataFailCause.isFailCauseExisting(failCause)) { // Setup data failed.
2919             loge("Invalid DataFailCause in " + response);
2920             reportAnomaly("Invalid DataFailCause: (0x" + Integer.toHexString(failCause)
2921                             + ")",
2922                     "6b264f28-9f58-4cbd-9e0e-d7624ba30879");
2923         }
2924     }
2925 
2926     /**
2927      * Called when receiving deactivate data network response from the data service.
2928      *
2929      * @param resultCode The result code.
2930      */
2931     private void onDeactivateResponse(@DataServiceCallback.ResultCode int resultCode) {
2932         logl("onDeactivateResponse: resultCode="
2933                 + DataServiceCallback.resultCodeToString(resultCode));
2934         if (resultCode == DataServiceCallback.RESULT_ERROR_ILLEGAL_STATE) {
2935             log("Remove network since deactivate request returned an error.");
2936             mFailCause = DataFailCause.RADIO_NOT_AVAILABLE;
2937             transitionTo(mDisconnectedState);
2938         } else if (mPhone.getHalVersion(HAL_SERVICE_DATA).less(RIL.RADIO_HAL_VERSION_2_0)) {
2939             log("Remove network on deactivate data response on old HAL "
2940                     + mPhone.getHalVersion(HAL_SERVICE_DATA));
2941             mFailCause = DataFailCause.LOST_CONNECTION;
2942             transitionTo(mDisconnectedState);
2943         }
2944     }
2945 
2946     /**
2947      * Tear down the data network immediately.
2948      *
2949      * @param reason The reason of tearing down the network.
2950      */
2951     public void tearDown(@TearDownReason int reason) {
2952         if (getCurrentState() == null || isDisconnected()) {
2953             return;
2954         }
2955         mTearDownReason = reason;
2956         sendMessage(obtainMessage(EVENT_TEAR_DOWN_NETWORK, reason));
2957     }
2958 
2959     private void onTearDown(@TearDownReason int reason) {
2960         logl("onTearDown: reason=" + tearDownReasonToString(reason));
2961 
2962         // track frequent NetworkAgent.onNetworkUnwanted() call of IMS and INTERNET
2963         if (reason == TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED
2964                 && isConnected()
2965                 && (mNetworkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)
2966                 || mNetworkCapabilities.hasCapability(
2967                         NetworkCapabilities.NET_CAPABILITY_INTERNET))) {
2968             mDataNetworkCallback.onTrackNetworkUnwanted(this);
2969         }
2970 
2971         mDataServiceManagers.get(mTransport).deactivateDataCall(mCid.get(mTransport),
2972                 reason == TEAR_DOWN_REASON_AIRPLANE_MODE_ON ? DataService.REQUEST_REASON_SHUTDOWN
2973                         : DataService.REQUEST_REASON_NORMAL,
2974                 obtainMessage(EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE));
2975         mDataCallSessionStats.setDeactivateDataCallReason(reason);
2976         mInvokedDataDeactivation = true;
2977     }
2978 
2979     /**
2980      * @return {@code true} if we shall delay tear down this network because an active voice call is
2981      * relying on it and
2982      * {@link CarrierConfigManager#KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL} is enabled.
2983      */
2984     public boolean shouldDelayImsTearDownDueToInCall() {
2985         return mDataConfigManager.isImsDelayTearDownUntilVoiceCallEndEnabled()
2986                 && mNetworkCapabilities != null
2987                 && mNetworkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)
2988                 && mPhone.getImsPhone() != null
2989                 && mPhone.getImsPhone().getCallTracker().getState()
2990                 != PhoneConstants.State.IDLE;
2991     }
2992 
2993     /**
2994      * Tear down the data network when condition is met or timed out. Data network will enter
2995      * {@link DisconnectingState} immediately and waiting for condition met. When condition is met,
2996      * {@link DataNetworkController} should invoke {@link Consumer#accept(Object)} so the actual
2997      * tear down work can be performed.
2998      *
2999      * This is primarily used for IMS graceful tear down. {@link DataNetworkController} inform
3000      * {@link DataNetwork} to enter {@link DisconnectingState}. IMS service can observe this
3001      * through {@link PreciseDataConnectionState#getState()} and then perform IMS de-registration
3002      * work. After IMS de-registered, {@link DataNetworkController} informs {@link DataNetwork}
3003      * that it's okay to tear down the network.
3004      *
3005      * @param reason The tear down reason.
3006      *
3007      * @param timeoutMillis Timeout in milliseconds. Within the time window, clients will have to
3008      * call {@link Consumer#accept(Object)}, otherwise, data network will be torn down when
3009      * timed out.
3010      *
3011      * @return The runnable for client to execute when condition is met. When executed, tear down
3012      * will be performed. {@code null} if the data network is already disconnected or being
3013      * disconnected.
3014      */
3015     @Nullable
3016     public Runnable tearDownWhenConditionMet(@TearDownReason int reason, long timeoutMillis) {
3017         if (getCurrentState() == null || isDisconnected() || isDisconnecting()) {
3018             loge("tearDownWhenConditionMet: Not in the right state. State=" + getCurrentState());
3019             return null;
3020         }
3021         logl("tearDownWhenConditionMet: reason=" + tearDownReasonToString(reason) + ", timeout="
3022                 + timeoutMillis + "ms.");
3023         sendMessage(EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET, reason, (int) timeoutMillis);
3024         return () -> this.tearDown(reason);
3025     }
3026 
3027     /**
3028      * Called when receiving {@link DataServiceCallback#onDataCallListChanged(List)} from the data
3029      * service.
3030      *
3031      * @param transport The transport where this event from.
3032      * @param responseList The data call response list.
3033      */
3034     private void onDataStateChanged(@TransportType int transport,
3035             @NonNull List<DataCallResponse> responseList) {
3036         // Ignore the update if it's not from the data service on the right transport.
3037         // Also if never received data call response from setup call response, which updates the
3038         // cid, ignore the update here.
3039         logv("onDataStateChanged: " + responseList);
3040         if (transport != mTransport || mCid.get(mTransport) == INVALID_CID || isDisconnected()) {
3041             return;
3042         }
3043 
3044         DataCallResponse response = responseList.stream()
3045                 .filter(r -> mCid.get(mTransport) == r.getId())
3046                 .findFirst()
3047                 .orElse(null);
3048         if (response != null) {
3049             if (!response.equals(mDataCallResponse)) {
3050                 log("onDataStateChanged: " + response);
3051                 validateDataCallResponse(response, -1 /*setupRegState setup only*/);
3052                 mDataCallResponse = response;
3053                 if (response.getLinkStatus() != DataCallResponse.LINK_STATUS_INACTIVE) {
3054                     updateDataNetwork(response);
3055                     notifyPreciseDataConnectionState();
3056                 } else {
3057                     log("onDataStateChanged: PDN inactive reported by "
3058                             + AccessNetworkConstants.transportTypeToString(mTransport)
3059                             + " data service.");
3060                     mFailCause = mEverConnected ? response.getCause()
3061                             : DataFailCause.NO_RETRY_FAILURE;
3062                     mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
3063                     transitionTo(mDisconnectedState);
3064                 }
3065             }
3066         } else {
3067             // The data call response is missing from the list. This means the PDN is gone. This
3068             // is the PDN lost reported by the modem. We don't send another DEACTIVATE_DATA request
3069             // for that
3070             log("onDataStateChanged: PDN disconnected reported by "
3071                     + AccessNetworkConstants.transportTypeToString(mTransport) + " data service.");
3072             mFailCause = mEverConnected ? DataFailCause.LOST_CONNECTION
3073                     : DataFailCause.NO_RETRY_FAILURE;
3074             mRetryDelayMillis = DataCallResponse.RETRY_DURATION_UNDEFINED;
3075             transitionTo(mDisconnectedState);
3076         }
3077     }
3078 
3079     /**
3080      * Called when carrier config updated.
3081      */
3082     private void onCarrierConfigUpdated() {
3083         log("onCarrierConfigUpdated");
3084 
3085         updateBandwidthFromDataConfig();
3086         updateTcpBufferSizes();
3087         updateMeteredAndCongested();
3088     }
3089 
3090     /**
3091      * Called when receiving bandwidth update from the modem.
3092      *
3093      * @param linkCapacityEstimates The link capacity estimate list from the modem.
3094      */
3095     private void onBandwidthUpdatedFromModem(
3096             @NonNull List<LinkCapacityEstimate> linkCapacityEstimates) {
3097         Objects.requireNonNull(linkCapacityEstimates);
3098         if (linkCapacityEstimates.isEmpty()) return;
3099 
3100         int uplinkBandwidthKbps = 0, downlinkBandwidthKbps = 0;
3101         for (LinkCapacityEstimate linkCapacityEstimate : linkCapacityEstimates) {
3102             if (linkCapacityEstimate.getType() == LinkCapacityEstimate.LCE_TYPE_COMBINED) {
3103                 uplinkBandwidthKbps = linkCapacityEstimate.getUplinkCapacityKbps();
3104                 downlinkBandwidthKbps = linkCapacityEstimate.getDownlinkCapacityKbps();
3105                 break;
3106             } else if (linkCapacityEstimate.getType() == LinkCapacityEstimate.LCE_TYPE_PRIMARY
3107                     || linkCapacityEstimate.getType() == LinkCapacityEstimate.LCE_TYPE_SECONDARY) {
3108                 uplinkBandwidthKbps += linkCapacityEstimate.getUplinkCapacityKbps();
3109                 downlinkBandwidthKbps += linkCapacityEstimate.getDownlinkCapacityKbps();
3110             } else {
3111                 loge("Invalid LinkCapacityEstimate type " + linkCapacityEstimate.getType());
3112             }
3113         }
3114         onBandwidthUpdated(uplinkBandwidthKbps, downlinkBandwidthKbps);
3115     }
3116 
3117     /**
3118      * Called when bandwidth estimation updated from either modem or the bandwidth estimator.
3119      *
3120      * @param uplinkBandwidthKbps Uplink bandwidth estimate in Kbps.
3121      * @param downlinkBandwidthKbps Downlink bandwidth estimate in Kbps.
3122      */
3123     private void onBandwidthUpdated(int uplinkBandwidthKbps, int downlinkBandwidthKbps) {
3124         log("onBandwidthUpdated: downlinkBandwidthKbps=" + downlinkBandwidthKbps
3125                 + ", uplinkBandwidthKbps=" + uplinkBandwidthKbps);
3126         NetworkBandwidth bandwidthFromConfig = mDataConfigManager.getBandwidthForNetworkType(
3127                 mTelephonyDisplayInfo);
3128 
3129         if (downlinkBandwidthKbps == LinkCapacityEstimate.INVALID) {
3130             // Fallback to carrier config.
3131             downlinkBandwidthKbps = bandwidthFromConfig.downlinkBandwidthKbps;
3132         }
3133 
3134         if (uplinkBandwidthKbps == LinkCapacityEstimate.INVALID) {
3135             // Fallback to carrier config.
3136             uplinkBandwidthKbps = bandwidthFromConfig.uplinkBandwidthKbps;
3137         }
3138 
3139         // Make sure uplink is not greater than downlink.
3140         uplinkBandwidthKbps = Math.min(uplinkBandwidthKbps, downlinkBandwidthKbps);
3141         mNetworkBandwidth = new NetworkBandwidth(downlinkBandwidthKbps, uplinkBandwidthKbps);
3142 
3143         updateNetworkCapabilities();
3144     }
3145 
3146     /**
3147      * Called when {@link TelephonyDisplayInfo} changed. This can happen when network types or
3148      * override network types (5G NSA, 5G MMWAVE) change.
3149      */
3150     private void onDisplayInfoChanged() {
3151         mTelephonyDisplayInfo = mPhone.getDisplayInfoController().getTelephonyDisplayInfo();
3152         updateBandwidthFromDataConfig();
3153         updateTcpBufferSizes();
3154         updateMeteredAndCongested();
3155     }
3156 
3157     /**
3158      * Update the bandwidth from carrier config. Note this is no-op if the bandwidth source is not
3159      * carrier config.
3160      */
3161     private void updateBandwidthFromDataConfig() {
3162         if (mDataConfigManager.getBandwidthEstimateSource() != BANDWIDTH_SOURCE_CARRIER_CONFIG) {
3163             return;
3164         }
3165         log("updateBandwidthFromDataConfig");
3166         mNetworkBandwidth = mDataConfigManager.getBandwidthForNetworkType(mTelephonyDisplayInfo);
3167         updateNetworkCapabilities();
3168     }
3169 
3170     /**
3171      * Update the TCP buffer sizes from resource overlays.
3172      */
3173     private void updateTcpBufferSizes() {
3174         log("updateTcpBufferSizes");
3175         mTcpBufferSizes = mDataConfigManager.getTcpConfigString(mTelephonyDisplayInfo);
3176         LinkProperties linkProperties = new LinkProperties(mLinkProperties);
3177         linkProperties.setTcpBufferSizes(mTcpBufferSizes);
3178         if (!linkProperties.equals(mLinkProperties)) {
3179             mLinkProperties = linkProperties;
3180             log("sendLinkProperties " + mLinkProperties);
3181             mNetworkAgent.sendLinkProperties(mLinkProperties);
3182         }
3183     }
3184 
3185     /**
3186      * Update the metered and congested values from carrier configs and subscription overrides
3187      */
3188     private void updateMeteredAndCongested() {
3189         int networkType = mTelephonyDisplayInfo.getNetworkType();
3190         switch (mTelephonyDisplayInfo.getOverrideNetworkType()) {
3191             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED:
3192             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA:
3193                 networkType = TelephonyManager.NETWORK_TYPE_NR;
3194                 break;
3195             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO:
3196             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA:
3197                 networkType = TelephonyManager.NETWORK_TYPE_LTE_CA;
3198                 break;
3199         }
3200         log("updateMeteredAndCongested: networkType="
3201                 + TelephonyManager.getNetworkTypeName(networkType));
3202         boolean changed = false;
3203         if (mDataConfigManager.isTempNotMeteredSupportedByCarrier() != mTempNotMeteredSupported) {
3204             mTempNotMeteredSupported = !mTempNotMeteredSupported;
3205             changed = true;
3206             log("updateMeteredAndCongested: mTempNotMeteredSupported changed to "
3207                     + mTempNotMeteredSupported);
3208         }
3209         boolean isTempNotMetered = mDataConfigManager.isNetworkTypeUnmetered(
3210                 mTelephonyDisplayInfo, mPhone.getServiceState())
3211                 && (mDataNetworkController.getUnmeteredOverrideNetworkTypes().contains(networkType)
3212                 || isNetworkTypeUnmetered(networkType));
3213         if (isTempNotMetered != mTempNotMetered) {
3214             mTempNotMetered = isTempNotMetered;
3215             changed = true;
3216             log("updateMeteredAndCongested: mTempNotMetered changed to " + mTempNotMetered);
3217         }
3218         if (mDataNetworkController.getCongestedOverrideNetworkTypes().contains(networkType)
3219                 != mCongested) {
3220             mCongested = !mCongested;
3221             changed = true;
3222             log("updateMeteredAndCongested: mCongested changed to " + mCongested);
3223         }
3224         if (changed) {
3225             updateNetworkCapabilities();
3226         }
3227         if (mTempNotMetered && isInternetSupported()) {
3228             // NR NSA and NR have the same network type: NR
3229             mDataCallSessionStats.onUnmeteredUpdate(networkType);
3230         }
3231     }
3232 
3233     /**
3234      * Get whether the network type is unmetered from SubscriptionPlans, from either an unmetered
3235      * general plan or specific plan for the given network type.
3236      *
3237      * @param networkType The network type to check meteredness for
3238      * @return Whether the given network type is unmetered based on SubscriptionPlans
3239      */
3240     private boolean isNetworkTypeUnmetered(@NetworkType int networkType) {
3241         List<SubscriptionPlan> plans = mDataNetworkController.getSubscriptionPlans();
3242         if (plans.isEmpty()) return false;
3243         boolean isGeneralUnmetered = true;
3244         Set<Integer> allNetworkTypes = Arrays.stream(TelephonyManager.getAllNetworkTypes())
3245                 .boxed().collect(Collectors.toSet());
3246         for (SubscriptionPlan plan : plans) {
3247             // Check if plan is general (applies to all network types) or specific
3248             if (Arrays.stream(plan.getNetworkTypes()).boxed().collect(Collectors.toSet())
3249                     .containsAll(allNetworkTypes)) {
3250                 if (plan.getDataLimitBytes() != SubscriptionPlan.BYTES_UNLIMITED) {
3251                     // Metered takes precedence over unmetered for safety
3252                     isGeneralUnmetered = false;
3253                 }
3254             } else {
3255                 // Check if plan applies to given network type
3256                 if (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
3257                     for (int planNetworkType : plan.getNetworkTypes()) {
3258                         if (planNetworkType == networkType) {
3259                             return plan.getDataLimitBytes() == SubscriptionPlan.BYTES_UNLIMITED;
3260                         }
3261                     }
3262                 }
3263             }
3264         }
3265         return isGeneralUnmetered;
3266     }
3267 
3268     /**
3269      * @return The unique context id assigned by the data service in
3270      * {@link DataCallResponse#getId()}.
3271      */
3272     public int getId() {
3273         return mCid.get(mTransport);
3274     }
3275 
3276     /**
3277      * @return The current network type reported by the network service.
3278      */
3279     @NetworkType
3280     private int getDataNetworkType() {
3281         return getDataNetworkType(mTransport);
3282     }
3283 
3284     /**
3285      * Get the data network type on the specified transport.
3286      *
3287      * @param transport The transport.
3288      * @return The data network type.
3289      */
3290     @NetworkType
3291     private int getDataNetworkType(@TransportType int transport) {
3292         // WLAN transport can't have network type other than IWLAN. Ideally service state tracker
3293         // should report the correct RAT, but sometimes race condition could happen that service
3294         // state is reset to out of service and RAT not updated to IWLAN yet.
3295         if (transport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
3296             return TelephonyManager.NETWORK_TYPE_IWLAN;
3297         }
3298 
3299         ServiceState ss = mPhone.getServiceState();
3300         NetworkRegistrationInfo nrs = ss.getNetworkRegistrationInfo(
3301                 NetworkRegistrationInfo.DOMAIN_PS, transport);
3302         if (nrs != null) {
3303             return nrs.getAccessNetworkTechnology();
3304         }
3305         return TelephonyManager.NETWORK_TYPE_UNKNOWN;
3306     }
3307 
3308     /**
3309      * @return The physical link status (i.e. RRC state).
3310      */
3311     @LinkStatus
3312     public int getLinkStatus() {
3313         return mLinkStatus;
3314     }
3315 
3316 
3317     /**
3318      * Update the network score and report to connectivity service if necessary.
3319      *
3320      * @param keepConnectedForHandover indicate handover is in progress or not.
3321      */
3322     private void updateNetworkScore(boolean keepConnectedForHandover) {
3323         int connectedReason = keepConnectedForHandover
3324                 ? NetworkScore.KEEP_CONNECTED_FOR_HANDOVER : NetworkScore.KEEP_CONNECTED_NONE;
3325         if (mNetworkScore.getKeepConnectedReason() != connectedReason) {
3326             mNetworkScore = new NetworkScore.Builder()
3327                     .setKeepConnectedReason(connectedReason).build();
3328             mNetworkAgent.sendNetworkScore(mNetworkScore);
3329         }
3330     }
3331 
3332     /**
3333      * @return Network registration info on the current transport.
3334      */
3335     @Nullable
3336     private NetworkRegistrationInfo getNetworkRegistrationInfo() {
3337         NetworkRegistrationInfo nri = mPhone.getServiceStateTracker().getServiceState()
3338                 .getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS, mTransport);
3339         if (nri == null) {
3340             loge("Can't get network registration info for "
3341                     + AccessNetworkConstants.transportTypeToString(mTransport));
3342             return null;
3343         }
3344         return nri;
3345     }
3346 
3347     /**
3348      * Get the APN type network capability. If there are more than one capabilities that are
3349      * APN types, then return the highest priority one which also has associated network request.
3350      * For example, if the network supports both MMS and internet, but only internet request
3351      * attached at this time, then the capability would be internet. Later on if MMS network request
3352      * attached to this network, then the APN type capability would be MMS.
3353      *
3354      * @return The APN type network capability from this network.
3355      *
3356      * @see #getPriority()
3357      */
3358     @NetCapability
3359     public int getApnTypeNetworkCapability() {
3360         if (!mAttachedNetworkRequestList.isEmpty()) {
3361             // The highest priority network request is always at the top of list.
3362             return mAttachedNetworkRequestList.get(0).getApnTypeNetworkCapability();
3363         } else {
3364             return Arrays.stream(getNetworkCapabilities().getCapabilities()).boxed()
3365                     .filter(cap -> DataUtils.networkCapabilityToApnType(cap)
3366                             != ApnSetting.TYPE_NONE)
3367                     .max(Comparator.comparingInt(mDataConfigManager::getNetworkCapabilityPriority))
3368                     .orElse(-1);
3369         }
3370     }
3371 
3372     /**
3373      * Get the priority of the network. The priority is derived from the highest priority capability
3374      * which also has such associated network request. For example, if the network supports both
3375      * MMS and internet, but only has internet request attached, then this network has internet's
3376      * priority. Later on when the MMS request attached to this network, the network's priority will
3377      * be updated to MMS's priority.
3378      *
3379      * @return The priority of the network.
3380      *
3381      * @see #getApnTypeNetworkCapability()
3382      */
3383     public int getPriority() {
3384         if (!mAttachedNetworkRequestList.isEmpty()) {
3385             // The highest priority network request is always at the top of list.
3386             return mAttachedNetworkRequestList.get(0).getPriority();
3387         } else {
3388             // If all network requests are already detached, then just pick the highest priority
3389             // capability's priority.
3390             return Arrays.stream(getNetworkCapabilities().getCapabilities()).boxed()
3391                     .map(mDataConfigManager::getNetworkCapabilityPriority)
3392                     .max(Integer::compare)
3393                     .orElse(0);
3394         }
3395     }
3396 
3397     /**
3398      * @return The attached network request list.
3399      */
3400     @NonNull
3401     public NetworkRequestList getAttachedNetworkRequestList() {
3402         return mAttachedNetworkRequestList;
3403     }
3404 
3405     /**
3406      * @return {@code true} if in connecting state.
3407      */
3408     public boolean isConnecting() {
3409         return getCurrentState() == mConnectingState;
3410     }
3411 
3412     /**
3413      * @return {@code true} if in connected state.
3414      */
3415     public boolean isConnected() {
3416         return getCurrentState() == mConnectedState;
3417     }
3418 
3419     /**
3420      * @return {@code true} if in disconnecting state.
3421      */
3422     public boolean isDisconnecting() {
3423         return getCurrentState() == mDisconnectingState;
3424     }
3425 
3426     /**
3427      * @return {@code true} if in disconnected state.
3428      */
3429     public boolean isDisconnected() {
3430         return getCurrentState() == mDisconnectedState;
3431     }
3432 
3433     /**
3434      * @return {@code true} if in handover state.
3435      */
3436     public boolean isHandoverInProgress() {
3437         return getCurrentState() == mHandoverState;
3438     }
3439 
3440     /**
3441      * @return {@code true} if the data network is suspended.
3442      */
3443     public boolean isSuspended() {
3444         return getState() == TelephonyManager.DATA_SUSPENDED;
3445     }
3446 
3447     /**
3448      * @return The current transport of the data network.
3449      */
3450     @TransportType
3451     public int getTransport() {
3452         return mTransport;
3453     }
3454 
3455     @DataState
3456     private int getState() {
3457         IState state = getCurrentState();
3458         if (state == null || isDisconnected()) {
3459             return TelephonyManager.DATA_DISCONNECTED;
3460         } else if (isConnecting()) {
3461             return TelephonyManager.DATA_CONNECTING;
3462         } else if (isConnected()) {
3463             // The data connection can only be suspended when it's in active state.
3464             if (mSuspended) {
3465                 return TelephonyManager.DATA_SUSPENDED;
3466             }
3467             return TelephonyManager.DATA_CONNECTED;
3468         } else if (isDisconnecting()) {
3469             return TelephonyManager.DATA_DISCONNECTING;
3470         } else if (isHandoverInProgress()) {
3471             return TelephonyManager.DATA_HANDOVER_IN_PROGRESS;
3472         }
3473 
3474         return TelephonyManager.DATA_UNKNOWN;
3475     }
3476 
3477     /**
3478      * @return {@code true} if this data network supports internet.
3479      */
3480     public boolean isInternetSupported() {
3481         return mNetworkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
3482     }
3483 
3484     /**
3485      * @return {@code true} if this network was setup for SUPL during emergency call. {@code false}
3486      * otherwise.
3487      */
3488     public boolean isEmergencySupl() {
3489         return mDataAllowedReason == DataAllowedReason.EMERGENCY_SUPL;
3490     }
3491 
3492     /**
3493      * Get precise data connection state
3494      *
3495      * @return The {@link PreciseDataConnectionState}
3496      */
3497     private PreciseDataConnectionState getPreciseDataConnectionState() {
3498         return new PreciseDataConnectionState.Builder()
3499                 .setTransportType(mTransport)
3500                 .setId(mCid.get(mTransport))
3501                 .setNetworkAgentId(mNetworkAgent.getId())
3502                 .setState(getState())
3503                 .setApnSetting(mDataProfile.getApnSetting())
3504                 .setLinkProperties(mLinkProperties)
3505                 .setNetworkType(getDataNetworkType())
3506                 .setFailCause(mFailCause)
3507                 .setDefaultQos(mDefaultQos)
3508                 .setNetworkValidationStatus(mNetworkValidationStatus)
3509                 .build();
3510     }
3511 
3512     /**
3513      * Send the precise data connection state to the listener of
3514      * {@link android.telephony.TelephonyCallback.PreciseDataConnectionStateListener}.
3515      * <p>
3516      * Note that notify only when {@link DataState} or {@link
3517      * PreciseDataConnectionState.NetworkValidationStatus} or {@link TelephonyNetworkAgent#getId}
3518      * changes.
3519      */
3520     private void notifyPreciseDataConnectionState() {
3521         PreciseDataConnectionState pdcs = getPreciseDataConnectionState();
3522         if (mPreciseDataConnectionState == null
3523                 || mPreciseDataConnectionState.getState() != pdcs.getState()
3524                 || mPreciseDataConnectionState.getNetworkValidationStatus()
3525                         != pdcs.getNetworkValidationStatus()
3526                 || mPreciseDataConnectionState.getNetId() != pdcs.getNetId()) {
3527             mPreciseDataConnectionState = pdcs;
3528             logv("notifyPreciseDataConnectionState=" + pdcs);
3529             mPhone.notifyDataConnection(pdcs);
3530         }
3531     }
3532 
3533     /**
3534      * Request the data network to handover to the target transport.
3535      * <p>
3536      * This is the starting point of initiating IWLAN/cellular handover. It will first call
3537      * {@link DataServiceManager#startHandover(int, Message)} to notify source transport that
3538      * handover is about to start, and then call {@link DataServiceManager#setupDataCall(int,
3539      * DataProfile, boolean, boolean, int, LinkProperties, int, NetworkSliceInfo, TrafficDescriptor,
3540      * boolean, Message)} on target transport to initiate the handover process.
3541      *
3542      * @param targetTransport The target transport.
3543      * @param retryEntry Data handover retry entry. This would be {@code null} for first time
3544      * handover attempt.
3545      * @return {@code true} if the request has been accepted.
3546      */
3547     public boolean startHandover(@TransportType int targetTransport,
3548             @Nullable DataHandoverRetryEntry retryEntry) {
3549         if (getCurrentState() == null || isDisconnected() || isDisconnecting()) {
3550             // Fail the request if not in the appropriate state.
3551             if (retryEntry != null) retryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3552             return false;
3553         }
3554 
3555         // Before we really initiate the handover process on target transport, we need to notify
3556         // source transport that handover is about to start. Handover will be eventually initiated
3557         // in onStartHandover().
3558         sendMessage(obtainMessage(EVENT_NOTIFY_HANDOVER_STARTED, 0, targetTransport, retryEntry));
3559         return true;
3560     }
3561 
3562     /**
3563      * Called when starting IWLAN/cellular handover process on the target transport.
3564      *
3565      * @param targetTransport The target transport.
3566      * @param retryEntry Data handover retry entry. This would be {@code null} for first time
3567      * handover attempt.
3568      */
3569     private void onStartHandover(@TransportType int targetTransport,
3570             @Nullable DataHandoverRetryEntry retryEntry) {
3571         if (mTransport == targetTransport) {
3572             log("onStartHandover: The network is already on "
3573                     + AccessNetworkConstants.transportTypeToString(mTransport)
3574                     + ", handover is not needed.");
3575             if (retryEntry != null) retryEntry.setState(DataRetryEntry.RETRY_STATE_CANCELLED);
3576             return;
3577         }
3578 
3579         // We need to use the actual modem roaming state instead of the framework roaming state
3580         // here. This flag is only passed down to ril_service for picking the correct protocol (for
3581         // old modem backward compatibility).
3582         boolean isModemRoaming = mPhone.getServiceState().getDataRoamingFromRegistration();
3583 
3584         // Set this flag to true if the user turns on data roaming. Or if we override the roaming
3585         // state in framework, we should set this flag to true as well so the modem will not reject
3586         // the data call setup (because the modem actually thinks the device is roaming).
3587         boolean allowRoaming = mPhone.getDataRoamingEnabled()
3588                 || (isModemRoaming && (!mPhone.getServiceState().getDataRoaming()));
3589 
3590         mHandoverDataProfile = mDataProfile;
3591         int targetNetworkType = getDataNetworkType(targetTransport);
3592         if (targetNetworkType != TelephonyManager.NETWORK_TYPE_UNKNOWN
3593                 && !mAttachedNetworkRequestList.isEmpty()) {
3594             TelephonyNetworkRequest networkRequest = mAttachedNetworkRequestList.get(0);
3595             DataProfile dataProfile = mDataNetworkController.getDataProfileManager()
3596                     .getDataProfileForNetworkRequest(networkRequest, targetNetworkType,
3597                             mPhone.getServiceState().isUsingNonTerrestrialNetwork(),
3598                             mDataNetworkController.isEsimBootStrapProvisioningActivated(), false);
3599             // Some carriers have different profiles between cellular and IWLAN. We need to
3600             // dynamically switch profile, but only when those profiles have same APN name.
3601             if (dataProfile != null && dataProfile.getApnSetting() != null
3602                     && mDataProfile.getApnSetting() != null
3603                     && TextUtils.equals(dataProfile.getApnSetting().getApnName(),
3604                     mDataProfile.getApnSetting().getApnName())
3605                     && !dataProfile.equals(mDataProfile)) {
3606                 mHandoverDataProfile = dataProfile;
3607                 log("Used different data profile for handover. " + mDataProfile);
3608             }
3609         }
3610 
3611         logl("Start handover from " + AccessNetworkConstants.transportTypeToString(mTransport)
3612                 + " to " + AccessNetworkConstants.transportTypeToString(targetTransport));
3613         // Send the handover request to the target transport data service.
3614         mDataServiceManagers.get(targetTransport).setupDataCall(
3615                 DataUtils.networkTypeToAccessNetworkType(getDataNetworkType(targetTransport)),
3616                 mHandoverDataProfile, isModemRoaming, allowRoaming,
3617                 DataService.REQUEST_REASON_HANDOVER, mLinkProperties, mPduSessionId,
3618                 mNetworkSliceInfo, mHandoverDataProfile.getTrafficDescriptor(), true,
3619                 obtainMessage(EVENT_HANDOVER_RESPONSE, retryEntry));
3620 
3621         mDataNetworkValidationStats.onHandoverAttempted();
3622     }
3623 
3624     /**
3625      * Called when receiving handover response from the data service.
3626      *
3627      * @param resultCode The result code.
3628      * @param response The response.
3629      * @param retryEntry Data handover retry entry. This would be {@code null} for first time
3630      * handover attempt.
3631      */
3632     private void onHandoverResponse(@DataServiceCallback.ResultCode int resultCode,
3633             @Nullable DataCallResponse response, @Nullable DataHandoverRetryEntry retryEntry) {
3634         logl("onHandoverResponse: resultCode=" + DataServiceCallback.resultCodeToString(resultCode)
3635                 + ", response=" + response);
3636         mFailCause = getFailCauseFromDataCallResponse(resultCode, response);
3637         validateDataCallResponse(response, -1 /*setupRegState setup only*/);
3638         if (mFailCause == DataFailCause.NONE) {
3639             // Handover succeeded.
3640 
3641             // Clean up on the source transport.
3642             mDataServiceManagers.get(mTransport).deactivateDataCall(mCid.get(mTransport),
3643                     DataService.REQUEST_REASON_HANDOVER, null);
3644             // Switch the transport to the target.
3645             mTransport = DataUtils.getTargetTransport(mTransport);
3646             // Update the logging tag
3647             mLogTag = "DN-" + mInitialNetworkAgentId + "-"
3648                     + ((mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WWAN) ? "C" : "I");
3649             // Switch the data profile. This is no-op in most of the case since almost all carriers
3650             // use same data profile between IWLAN and cellular.
3651             mDataProfile = mHandoverDataProfile;
3652             updateDataNetwork(response);
3653             if (mTransport != AccessNetworkConstants.TRANSPORT_TYPE_WWAN) {
3654                 unregisterForWwanEvents();
3655             } else {
3656                 // Handover from WLAN to WWAN
3657                 registerForWwanEvents();
3658             }
3659             if (retryEntry != null) retryEntry.setState(DataRetryEntry.RETRY_STATE_SUCCEEDED);
3660             mDataNetworkCallback.invokeFromExecutor(
3661                     () -> mDataNetworkCallback.onHandoverSucceeded(DataNetwork.this));
3662         } else {
3663             // Handover failed.
3664 
3665             // Notify source transport that handover failed on target transport so that PDU session
3666             // id can be released if it is preserved for handover.
3667             mDataServiceManagers.get(mTransport).cancelHandover(mCid.get(mTransport),
3668                     obtainMessage(EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE));
3669             sendMessageDelayed(EVENT_CANCEL_HANDOVER_NO_RESPONSE,
3670                     mDataConfigManager.getNetworkHandoverTimeoutMs());
3671 
3672             long retry = response != null ? response.getRetryDurationMillis()
3673                     : DataCallResponse.RETRY_DURATION_UNDEFINED;
3674             // If the handover mode is unspecified, default to HANDOVER_FAILURE_MODE_UNKNOWN,
3675             // which will retry handover if retry rules are defined.
3676             int handoverFailureMode = response != null ? response.getHandoverFailureMode()
3677                     : DataCallResponse.HANDOVER_FAILURE_MODE_UNKNOWN;
3678             if (retryEntry != null) retryEntry.setState(DataRetryEntry.RETRY_STATE_FAILED);
3679             mDataNetworkCallback.invokeFromExecutor(
3680                     () -> mDataNetworkCallback.onHandoverFailed(DataNetwork.this,
3681                             mFailCause, retry, handoverFailureMode));
3682             trackHandoverFailure(response != null ? response.getCause() : mFailCause);
3683         }
3684 
3685         // No matter handover succeeded or not, transit back to connected state.
3686         transitionTo(mConnectedState);
3687     }
3688 
3689     /**
3690      * Called when handover failed. Record the source and target RAT{@link NetworkType} and the
3691      * failure cause {@link android.telephony.DataFailCause}.
3692      *
3693      * @param cause The fail cause.
3694      */
3695     private void trackHandoverFailure(int cause) {
3696         int sourceRat = getDataNetworkType();
3697         int targetTransport = DataUtils.getTargetTransport(mTransport);
3698         int targetRat = getDataNetworkType(targetTransport);
3699 
3700         mDataCallSessionStats.onHandoverFailure(cause, sourceRat, targetRat);
3701     }
3702 
3703     /**
3704      * Called when receiving PCO (Protocol Configuration Options) data from the cellular network.
3705      *
3706      * @param pcoData The PCO data.
3707      */
3708     private void onPcoDataChanged(@NonNull PcoData pcoData) {
3709         log("onPcoDataChanged: " + pcoData);
3710         mDataNetworkCallback.invokeFromExecutor(
3711                 () -> mDataNetworkCallback.onPcoDataChanged(DataNetwork.this));
3712         if (mDataProfile.getApnSetting() != null) {
3713             for (int apnType : mDataProfile.getApnSetting().getApnTypes()) {
3714                 Intent intent = new Intent(TelephonyManager.ACTION_CARRIER_SIGNAL_PCO_VALUE);
3715                 intent.putExtra(TelephonyManager.EXTRA_APN_TYPE, apnType);
3716                 intent.putExtra(TelephonyManager.EXTRA_APN_PROTOCOL,
3717                         ApnSetting.getProtocolIntFromString(pcoData.bearerProto));
3718                 intent.putExtra(TelephonyManager.EXTRA_PCO_ID, pcoData.pcoId);
3719                 intent.putExtra(TelephonyManager.EXTRA_PCO_VALUE, pcoData.contents);
3720                 mPhone.getCarrierSignalAgent().notifyCarrierSignalReceivers(intent);
3721             }
3722         }
3723     }
3724 
3725     /**
3726      * Called when receiving PCO (Protocol Configuration Options) data from the cellular network.
3727      *
3728      * @param pcoData PCO data.
3729      */
3730     private void onPcoDataReceived(@NonNull PcoData pcoData) {
3731         // Save all the PCO data received, even though it might be unrelated to this data network.
3732         // The network might be still in connecting state. Save all now and use it when entering
3733         // connected state.
3734         log("onPcoDataReceived: " + pcoData);
3735         PcoData oldData = mPcoData.computeIfAbsent(pcoData.cid, m -> new ArrayMap<>())
3736                 .put(pcoData.pcoId, pcoData);
3737         if (getId() == INVALID_CID || pcoData.cid != getId()) return;
3738         if (!Objects.equals(oldData, pcoData)) {
3739             onPcoDataChanged(pcoData);
3740         }
3741     }
3742 
3743     /**
3744      * @return The last known data network type of the data network.
3745      */
3746     @NetworkType
3747     public int getLastKnownDataNetworkType() {
3748         return mLastKnownDataNetworkType;
3749     }
3750 
3751     /**
3752      * @return The last known roaming state of this data network.
3753      */
3754     public boolean getLastKnownRoamingState() {
3755         return mLastKnownRoamingState;
3756     }
3757 
3758     /**
3759      * @return The PCO data received from the network.
3760      */
3761     @NonNull
3762     public Map<Integer, PcoData> getPcoData() {
3763         if (mTransport == AccessNetworkConstants.TRANSPORT_TYPE_WLAN
3764                 || mCid.get(mTransport) == INVALID_CID) {
3765             return Collections.emptyMap();
3766         }
3767         return mPcoData.getOrDefault(mCid.get(mTransport), Collections.emptyMap());
3768     }
3769 
3770     /**
3771      * Check if the this data network is VCN-managed.
3772      *
3773      * @param networkCapabilities The network capabilities of this data network.
3774      * @return The VCN's policy for this DataNetwork.
3775      */
3776     private VcnNetworkPolicyResult getVcnPolicy(NetworkCapabilities networkCapabilities) {
3777         if (mVcnManager == null) {
3778             return null;
3779         }
3780 
3781         return mVcnManager.applyVcnNetworkPolicy(networkCapabilities, getLinkProperties());
3782     }
3783 
3784     /**
3785      * Check if any of the attached request has the specified network capability.
3786      *
3787      * @param netCapability The network capability to check.
3788      * @return {@code true} if at least one network request has specified network capability.
3789      */
3790     public boolean hasNetworkCapabilityInNetworkRequests(@NetCapability int netCapability) {
3791         return mAttachedNetworkRequestList.stream().anyMatch(
3792                 request -> request.hasCapability(netCapability));
3793     }
3794 
3795     /**
3796      * The network validation requests moves to process on the state machine handler. A request is
3797      * processed according to state of the data network.
3798      */
3799     public void requestNetworkValidation(@NonNull Consumer<Integer> resultCodeCallback) {
3800         // request a network validation by DataNetwork state
3801         sendMessage(EVENT_DATA_NETWORK_VALIDATION_REQUESTED, resultCodeCallback);
3802     }
3803 
3804     /**
3805      * Request network validation to data service provider.
3806      */
3807     private void handleDataNetworkValidationRequest(@NonNull Consumer<Integer> resultCodeCallback) {
3808         if (mNetworkValidationResultCodeCallback != null) {
3809             loge("requestNetworkValidation: previous networkValidationRequest is in progress.");
3810             FunctionalUtils.ignoreRemoteException(resultCodeCallback::accept)
3811                     .accept(DataServiceCallback.RESULT_ERROR_BUSY);
3812             return;
3813         }
3814 
3815         mNetworkValidationResultCodeCallback = resultCodeCallback;
3816 
3817         // Request validation directly from the data service.
3818         mDataServiceManagers.get(mTransport).requestNetworkValidation(
3819                 mCid.get(mTransport), obtainMessage(EVENT_DATA_NETWORK_VALIDATION_RESPONSE));
3820 
3821         int apnTypeBitmask = mDataProfile.getApnSetting() != null
3822                 ? mDataProfile.getApnSetting().getApnTypeBitmask() : ApnSetting.TYPE_NONE;
3823         mDataNetworkValidationStats.onRequestNetworkValidation(apnTypeBitmask);
3824 
3825         log("handleDataNetworkValidationRequest, network validation requested");
3826     }
3827 
3828     private void handleErrorDataNetworkValidationRequest(
3829             @NonNull Consumer<Integer> resultCodeCallback) {
3830         loge("handleErrorDataNetworkValidationRequest: DataNetwork is not in Connected state");
3831         FunctionalUtils.ignoreRemoteException(resultCodeCallback::accept)
3832                 .accept(DataServiceCallback.RESULT_ERROR_ILLEGAL_STATE);
3833     }
3834 
3835     /**
3836      * handle the resultCode in response for the request.
3837      *
3838      * @param resultCode {@link DataServiceCallback.ResultCode}
3839      */
3840     private void handleDataNetworkValidationRequestResultCode(
3841             @DataServiceCallback.ResultCode int resultCode) {
3842         if (mNetworkValidationResultCodeCallback != null) {
3843             log("handleDataNetworkValidationRequestResultCode, resultCode:"
3844                     + DataServiceCallback.resultCodeToString(resultCode));
3845             FunctionalUtils.ignoreRemoteException(mNetworkValidationResultCodeCallback::accept)
3846                     .accept(resultCode);
3847             mNetworkValidationResultCodeCallback = null;
3848         }
3849     }
3850 
3851     /**
3852      * Update the validation status from {@link DataCallResponse}, convert to network validation
3853      * status {@link PreciseDataConnectionState.NetworkValidationStatus}.
3854      *
3855      * @param networkValidationStatus {@link PreciseDataConnectionState.NetworkValidationStatus}
3856      */
3857     private void updateValidationStatus(
3858             @PreciseDataConnectionState.NetworkValidationStatus int networkValidationStatus) {
3859         if (!mFlags.networkValidation()) {
3860             // Do nothing, if network validation feature is disabled
3861             return;
3862         }
3863 
3864         // if network validation status is changed, notify preciseDataConnectionState.
3865         if (mNetworkValidationStatus != networkValidationStatus) {
3866             log("updateValidationStatus:"
3867                     + PreciseDataConnectionState.networkValidationStatusToString(
3868                     networkValidationStatus));
3869             mNetworkValidationStatus = networkValidationStatus;
3870         }
3871 
3872         mDataNetworkValidationStats.onUpdateNetworkValidationState(
3873                 mNetworkValidationStatus, getDataNetworkType());
3874     }
3875 
3876     /**
3877      * Convert the data tear down reason to string.
3878      *
3879      * @param reason Data deactivation reason.
3880      * @return The deactivation reason in string format.
3881      */
3882     @NonNull
3883     public static String tearDownReasonToString(@TearDownReason int reason) {
3884         return switch (reason) {
3885             case TEAR_DOWN_REASON_NONE -> "NONE";
3886             case TEAR_DOWN_REASON_CONNECTIVITY_SERVICE_UNWANTED -> "CONNECTIVITY_SERVICE_UNWANTED";
3887             case TEAR_DOWN_REASON_SIM_REMOVAL -> "SIM_REMOVAL";
3888             case TEAR_DOWN_REASON_AIRPLANE_MODE_ON -> "AIRPLANE_MODE_ON";
3889             case TEAR_DOWN_REASON_DATA_DISABLED -> "DATA_DISABLED";
3890             case TEAR_DOWN_REASON_NO_LIVE_REQUEST -> "TEAR_DOWN_REASON_NO_LIVE_REQUEST";
3891             case TEAR_DOWN_REASON_RAT_NOT_ALLOWED -> "TEAR_DOWN_REASON_RAT_NOT_ALLOWED";
3892             case TEAR_DOWN_REASON_ROAMING_DISABLED -> "TEAR_DOWN_REASON_ROAMING_DISABLED";
3893             case TEAR_DOWN_REASON_CONCURRENT_VOICE_DATA_NOT_ALLOWED ->
3894                     "TEAR_DOWN_REASON_CONCURRENT_VOICE_DATA_NOT_ALLOWED";
3895             case TEAR_DOWN_REASON_SERVICE_OPTION_NOT_SUPPORTED ->
3896                     "TEAR_DOWN_REASON_SERVICE_OPTION_NOT_SUPPORTED";
3897             case TEAR_DOWN_REASON_DATA_SERVICE_NOT_READY ->
3898                     "TEAR_DOWN_REASON_DATA_SERVICE_NOT_READY";
3899             case TEAR_DOWN_REASON_POWER_OFF_BY_CARRIER -> "TEAR_DOWN_REASON_POWER_OFF_BY_CARRIER";
3900             case TEAR_DOWN_REASON_DATA_STALL -> "TEAR_DOWN_REASON_DATA_STALL";
3901             case TEAR_DOWN_REASON_HANDOVER_FAILED -> "TEAR_DOWN_REASON_HANDOVER_FAILED";
3902             case TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED -> "TEAR_DOWN_REASON_HANDOVER_NOT_ALLOWED";
3903             case TEAR_DOWN_REASON_VCN_REQUESTED -> "TEAR_DOWN_REASON_VCN_REQUESTED";
3904             case TEAR_DOWN_REASON_VOPS_NOT_SUPPORTED -> "TEAR_DOWN_REASON_VOPS_NOT_SUPPORTED";
3905             case TEAR_DOWN_REASON_DEFAULT_DATA_UNSELECTED ->
3906                     "TEAR_DOWN_REASON_DEFAULT_DATA_UNSELECTED";
3907             case TEAR_DOWN_REASON_NOT_IN_SERVICE -> "TEAR_DOWN_REASON_NOT_IN_SERVICE";
3908             case TEAR_DOWN_REASON_DATA_CONFIG_NOT_READY -> "TEAR_DOWN_REASON_DATA_CONFIG_NOT_READY";
3909             case TEAR_DOWN_REASON_PENDING_TEAR_DOWN_ALL -> "TEAR_DOWN_REASON_PENDING_TEAR_DOWN_ALL";
3910             case TEAR_DOWN_REASON_NO_SUITABLE_DATA_PROFILE ->
3911                     "TEAR_DOWN_REASON_NO_SUITABLE_DATA_PROFILE";
3912             case TEAR_DOWN_REASON_CDMA_EMERGENCY_CALLBACK_MODE ->
3913                     "TEAR_DOWN_REASON_CDMA_EMERGENCY_CALLBACK_MODE";
3914             case TEAR_DOWN_REASON_RETRY_SCHEDULED -> "TEAR_DOWN_REASON_RETRY_SCHEDULED";
3915             case TEAR_DOWN_REASON_DATA_THROTTLED -> "TEAR_DOWN_REASON_DATA_THROTTLED";
3916             case TEAR_DOWN_REASON_DATA_PROFILE_INVALID -> "TEAR_DOWN_REASON_DATA_PROFILE_INVALID";
3917             case TEAR_DOWN_REASON_DATA_PROFILE_NOT_PREFERRED ->
3918                     "TEAR_DOWN_REASON_DATA_PROFILE_NOT_PREFERRED";
3919             case TEAR_DOWN_REASON_NOT_ALLOWED_BY_POLICY -> "TEAR_DOWN_REASON_NOT_ALLOWED_BY_POLICY";
3920             case TEAR_DOWN_REASON_ILLEGAL_STATE -> "TEAR_DOWN_REASON_ILLEGAL_STATE";
3921             case TEAR_DOWN_REASON_ONLY_ALLOWED_SINGLE_NETWORK ->
3922                     "TEAR_DOWN_REASON_ONLY_ALLOWED_SINGLE_NETWORK";
3923             case TEAR_DOWN_REASON_PREFERRED_DATA_SWITCHED ->
3924                     "TEAR_DOWN_REASON_PREFERRED_DATA_SWITCHED";
3925             case TEAR_DOWN_REASON_DATA_LIMIT_REACHED -> "TEAR_DOWN_REASON_DATA_LIMIT_REACHED";
3926             case TEAR_DOWN_REASON_DATA_NETWORK_TRANSPORT_NOT_ALLOWED ->
3927                     "TEAR_DOWN_REASON_DATA_NETWORK_TRANSPORT_NOT_ALLOWED";
3928             default -> "UNKNOWN(" + reason + ")";
3929         };
3930     }
3931 
3932     /**
3933      * Convert event to string
3934      *
3935      * @param event The event
3936      * @return The event in string format.
3937      */
3938     @NonNull
3939     private static String eventToString(int event) {
3940         return switch (event) {
3941             case EVENT_DATA_CONFIG_UPDATED -> "EVENT_DATA_CONFIG_UPDATED";
3942             case EVENT_ATTACH_NETWORK_REQUEST -> "EVENT_ATTACH_NETWORK_REQUEST";
3943             case EVENT_DETACH_NETWORK_REQUEST -> "EVENT_DETACH_NETWORK_REQUEST";
3944             case EVENT_RADIO_NOT_AVAILABLE -> "EVENT_RADIO_NOT_AVAILABLE";
3945             case EVENT_ALLOCATE_PDU_SESSION_ID_RESPONSE -> "EVENT_ALLOCATE_PDU_SESSION_ID_RESPONSE";
3946             case EVENT_SETUP_DATA_NETWORK_RESPONSE -> "EVENT_SETUP_DATA_NETWORK_RESPONSE";
3947             case EVENT_TEAR_DOWN_NETWORK -> "EVENT_TEAR_DOWN_NETWORK";
3948             case EVENT_DATA_STATE_CHANGED -> "EVENT_DATA_STATE_CHANGED";
3949             case EVENT_SERVICE_STATE_CHANGED -> "EVENT_DATA_NETWORK_TYPE_REG_STATE_CHANGED";
3950             case EVENT_DETACH_ALL_NETWORK_REQUESTS -> "EVENT_DETACH_ALL_NETWORK_REQUESTS";
3951             case EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED ->
3952                     "EVENT_BANDWIDTH_ESTIMATE_FROM_MODEM_CHANGED";
3953             case EVENT_CANCEL_HANDOVER_NO_RESPONSE -> "EVENT_CANCEL_HANDOVER_NO_RESPONSE";
3954             case EVENT_DISPLAY_INFO_CHANGED -> "EVENT_DISPLAY_INFO_CHANGED";
3955             case EVENT_HANDOVER_RESPONSE -> "EVENT_HANDOVER_RESPONSE";
3956             case EVENT_SUBSCRIPTION_PLAN_OVERRIDE -> "EVENT_SUBSCRIPTION_PLAN_OVERRIDE";
3957             case EVENT_PCO_DATA_RECEIVED -> "EVENT_PCO_DATA_RECEIVED";
3958             case EVENT_CARRIER_PRIVILEGED_UIDS_CHANGED -> "EVENT_CARRIER_PRIVILEGED_UIDS_CHANGED";
3959             case EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE -> "EVENT_DEACTIVATE_DATA_NETWORK_RESPONSE";
3960             case EVENT_STUCK_IN_TRANSIENT_STATE -> "EVENT_STUCK_IN_TRANSIENT_STATE";
3961             case EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET ->
3962                     "EVENT_WAITING_FOR_TEARING_DOWN_CONDITION_MET";
3963             case EVENT_VOICE_CALL_STARTED -> "EVENT_VOICE_CALL_STARTED";
3964             case EVENT_VOICE_CALL_ENDED -> "EVENT_VOICE_CALL_ENDED";
3965             case EVENT_CSS_INDICATOR_CHANGED -> "EVENT_CSS_INDICATOR_CHANGED";
3966             case EVENT_NOTIFY_HANDOVER_STARTED -> "EVENT_NOTIFY_HANDOVER_STARTED";
3967             case EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE -> "EVENT_NOTIFY_HANDOVER_STARTED_RESPONSE";
3968             case EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE ->
3969                     "EVENT_NOTIFY_HANDOVER_CANCELLED_RESPONSE";
3970             case EVENT_DATA_NETWORK_VALIDATION_REQUESTED ->
3971                     "EVENT_DATA_NETWORK_VALIDATION_REQUESTED";
3972             case EVENT_DATA_NETWORK_VALIDATION_RESPONSE -> "EVENT_DATA_NETWORK_VALIDATION_RESPONSE";
3973             default -> "Unknown(" + event + ")";
3974         };
3975     }
3976 
3977     @Override
3978     public String toString() {
3979         return "[DataNetwork: " + mLogTag + ", " + (mDataProfile.getApnSetting() != null
3980                 ? mDataProfile.getApnSetting().getApnName() : null) + ", state="
3981                 + (getCurrentState() != null ? getCurrentState().getName() : null) + "]";
3982     }
3983 
3984     /**
3985      * @return The short name of the data network (e.g. DN-C-1)
3986      */
3987     @NonNull
3988     public String name() {
3989         return mLogTag;
3990     }
3991 
3992     /**
3993      * Trigger the anomaly report with the specified UUID.
3994      *
3995      * @param anomalyMsg Description of the event
3996      * @param uuid UUID associated with that event
3997      */
3998     private void reportAnomaly(@NonNull String anomalyMsg, @NonNull String uuid) {
3999         logl(anomalyMsg);
4000         AnomalyReporter.reportAnomaly(UUID.fromString(uuid), anomalyMsg, mPhone.getCarrierId());
4001     }
4002 
4003     /**
4004      * Log debug messages.
4005      * @param s debug messages
4006      */
4007     @Override
4008     protected void log(@NonNull String s) {
4009         Rlog.d(mLogTag, (getCurrentState() != null
4010                 ? (getCurrentState().getName() + ": ") : "") + s);
4011     }
4012 
4013     /**
4014      * Log error messages.
4015      * @param s error messages
4016      */
4017     @Override
4018     protected void loge(@NonNull String s) {
4019         Rlog.e(mLogTag, (getCurrentState() != null
4020                 ? (getCurrentState().getName() + ": ") : "") + s);
4021     }
4022 
4023     /**
4024      * Log verbose messages.
4025      * @param s error messages
4026      */
4027     @Override
4028     protected void logv(@NonNull String s) {
4029         if (VDBG) {
4030             Rlog.v(mLogTag, (getCurrentState() != null
4031                     ? (getCurrentState().getName() + ": ") : "") + s);
4032         }
4033     }
4034 
4035     /**
4036      * Log debug messages and also log into the local log.
4037      * @param s debug messages
4038      */
4039     private void logl(@NonNull String s) {
4040         log(s);
4041         mLocalLog.log((getCurrentState() != null ? (getCurrentState().getName() + ": ") : "") + s);
4042     }
4043 
4044     /**
4045      * Dump the state of DataNetwork
4046      *
4047      * @param fd File descriptor
4048      * @param printWriter Print writer
4049      * @param args Arguments
4050      */
4051     public void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
4052         IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ");
4053         super.dump(fd, pw, args);
4054         pw.println("Tag: " + name());
4055         pw.increaseIndent();
4056         pw.println("mSubId=" + mSubId);
4057         pw.println("mTransport=" + AccessNetworkConstants.transportTypeToString(mTransport));
4058         pw.println("mLastKnownDataNetworkType=" + TelephonyManager
4059                 .getNetworkTypeName(mLastKnownDataNetworkType));
4060         pw.println("WWAN cid=" + mCid.get(AccessNetworkConstants.TRANSPORT_TYPE_WWAN));
4061         pw.println("WLAN cid=" + mCid.get(AccessNetworkConstants.TRANSPORT_TYPE_WLAN));
4062         pw.println("mNetworkScore=" + mNetworkScore);
4063         pw.println("mDataAllowedReason=" + mDataAllowedReason);
4064         pw.println("mPduSessionId=" + mPduSessionId);
4065         pw.println("mDataProfile=" + mDataProfile);
4066         pw.println("mNetworkCapabilities=" + mNetworkCapabilities);
4067         pw.println("mLinkProperties=" + mLinkProperties);
4068         pw.println("mNetworkSliceInfo=" + mNetworkSliceInfo);
4069         pw.println("mNetworkBandwidth=" + mNetworkBandwidth);
4070         pw.println("mTcpBufferSizes=" + mTcpBufferSizes);
4071         pw.println("mTelephonyDisplayInfo=" + mTelephonyDisplayInfo);
4072         pw.println("mTempNotMeteredSupported=" + mTempNotMeteredSupported);
4073         pw.println("mTempNotMetered=" + mTempNotMetered);
4074         pw.println("mCongested=" + mCongested);
4075         pw.println("mSuspended=" + mSuspended);
4076         pw.println("mDataCallResponse=" + mDataCallResponse);
4077         pw.println("mFailCause=" + DataFailCause.toString(mFailCause));
4078         pw.println("mAdministratorUids=" + Arrays.toString(mAdministratorUids));
4079         pw.println("mCarrierServicePackageUid=" + mCarrierServicePackageUid);
4080         pw.println("mEverConnected=" + mEverConnected);
4081         pw.println("mInvokedDataDeactivation=" + mInvokedDataDeactivation);
4082 
4083         pw.println("Attached network requests:");
4084         pw.increaseIndent();
4085         for (TelephonyNetworkRequest request : mAttachedNetworkRequestList) {
4086             pw.println(request);
4087         }
4088         pw.decreaseIndent();
4089         pw.println("mQosBearerSessions=" + mQosBearerSessions);
4090 
4091         mNetworkAgent.dump(fd, pw, args);
4092         pw.println("Local logs:");
4093         pw.increaseIndent();
4094         mLocalLog.dump(fd, pw, args);
4095         pw.decreaseIndent();
4096         pw.decreaseIndent();
4097         pw.println("---------------");
4098     }
4099 }
4100