aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/telephony/data/DataRetryManager.java
blob: b6ad10169339f0f8dfc91ead5b98c82ce3348b22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
/*
 * Copyright 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.telephony.data;

import android.annotation.CallbackExecutor;
import android.annotation.ElapsedRealtimeLong;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkCapabilities;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.telephony.AccessNetworkConstants;
import android.telephony.AccessNetworkConstants.TransportType;
import android.telephony.Annotation.DataFailureCause;
import android.telephony.Annotation.NetCapability;
import android.telephony.AnomalyReporter;
import android.telephony.DataFailCause;
import android.telephony.data.DataCallResponse;
import android.telephony.data.DataProfile;
import android.telephony.data.ThrottleStatus;
import android.telephony.data.ThrottleStatus.RetryType;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.IndentingPrintWriter;
import android.util.LocalLog;
import android.util.SparseArray;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.data.DataConfigManager.DataConfigManagerCallback;
import com.android.internal.telephony.data.DataNetworkController.DataNetworkControllerCallback;
import com.android.internal.telephony.data.DataNetworkController.NetworkRequestList;
import com.android.internal.telephony.data.DataProfileManager.DataProfileManagerCallback;
import com.android.telephony.Rlog;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * DataRetryManager manages data network setup retry and its configurations.
 */
public class DataRetryManager extends Handler {
    private static final boolean VDBG = false;

    /** Intent of Alarm Manager for long retry timer. */
    private static final String ACTION_RETRY = "com.android.internal.telephony.data.ACTION_RETRY";
    /** The extra key for the hashcode of the retry entry for Alarm Manager. */
    private static final String ACTION_RETRY_EXTRA_HASHCODE = "extra_retry_hashcode";

    /** Event for data setup retry. */
    private static final int EVENT_DATA_SETUP_RETRY = 3;

    /** Event for data handover retry. */
    private static final int EVENT_DATA_HANDOVER_RETRY = 4;

    /** Event for data profile/apn unthrottled. */
    private static final int EVENT_DATA_PROFILE_UNTHROTTLED = 6;

    /** Event for cancelling pending handover retry. */
    private static final int EVENT_CANCEL_PENDING_HANDOVER_RETRY = 7;

    /**
     * Event for radio on. This can happen when airplane mode is turned off, or RIL crashes and came
     * back online.
     */
    private static final int EVENT_RADIO_ON = 8;

    /** Event for modem reset. */
    private static final int EVENT_MODEM_RESET = 9;

    /** Event for tracking area code change. */
    private static final int EVENT_TAC_CHANGED = 10;

    /** The maximum entries to preserve. */
    private static final int MAXIMUM_HISTORICAL_ENTRIES = 100;
    /**
     * The threshold of retry timer, longer than or equal to which we use alarm manager to schedule
     * instead of handler.
     */
    private static final long RETRY_LONG_DELAY_TIMER_THRESHOLD_MILLIS = TimeUnit
            .MINUTES.toMillis(1);

    @IntDef(prefix = {"RESET_REASON_"},
            value = {
                    RESET_REASON_DATA_PROFILES_CHANGED,
                    RESET_REASON_RADIO_ON,
                    RESET_REASON_MODEM_RESTART,
                    RESET_REASON_DATA_SERVICE_BOUND,
                    RESET_REASON_DATA_CONFIG_CHANGED,
                    RESET_REASON_TAC_CHANGED,
            })
    public @interface RetryResetReason {}

    /** Reset due to data profiles changed. */
    private static final int RESET_REASON_DATA_PROFILES_CHANGED = 1;

    /** Reset due to radio on. This could happen after airplane mode off or RIL restarted. */
    private static final int RESET_REASON_RADIO_ON = 2;

    /** Reset due to modem restarted. */
    private static final int RESET_REASON_MODEM_RESTART = 3;

    /**
     * Reset due to data service bound. This could happen when reboot or when data service crashed
     * and rebound.
     */
    private static final int RESET_REASON_DATA_SERVICE_BOUND = 4;

    /** Reset due to data config changed. */
    private static final int RESET_REASON_DATA_CONFIG_CHANGED = 5;

    /** Reset due to tracking area code changed. */
    private static final int RESET_REASON_TAC_CHANGED = 6;

    /** The phone instance. */
    private final @NonNull Phone mPhone;

    /** The RIL instance. */
    private final @NonNull CommandsInterface mRil;

    /** Logging tag. */
    private final @NonNull String mLogTag;

    /** Local log. */
    private final @NonNull LocalLog mLocalLog = new LocalLog(128);

    /** Alarm Manager used to schedule long set up or handover retries. */
    private final @NonNull AlarmManager mAlarmManager;

    /**
     * The data retry callback. This is only used to notify {@link DataNetworkController} to retry
     * setup data network.
     */
    private @NonNull Set<DataRetryManagerCallback> mDataRetryManagerCallbacks = new ArraySet<>();

    /** Data service managers. */
    private @NonNull SparseArray<DataServiceManager> mDataServiceManagers;

    /** Data config manager instance. */
    private final @NonNull DataConfigManager mDataConfigManager;

    /** Data profile manager. */
    private final @NonNull DataProfileManager mDataProfileManager;

    /** Data setup retry rule list. */
    private @NonNull List<DataSetupRetryRule> mDataSetupRetryRuleList = new ArrayList<>();

    /** Data handover retry rule list. */
    private @NonNull List<DataHandoverRetryRule> mDataHandoverRetryRuleList = new ArrayList<>();

    /** Data retry entries. */
    private final @NonNull List<DataRetryEntry> mDataRetryEntries = new ArrayList<>();

    /**
     * Data throttling entries. Note this only stores throttling requested by networks. We intended
     * not to store frameworks-initiated throttling because they are not explicit/strong throttling
     * requests.
     */
    private final @NonNull List<DataThrottlingEntry> mDataThrottlingEntries = new ArrayList<>();

    /**
     * Represent a single data setup/handover throttling reported by networks.
     */
    public static class DataThrottlingEntry {
        /**
         * The data profile that is being throttled for setup/handover retry.
         */
        public final @NonNull DataProfile dataProfile;

        /**
         * The associated network request list when throttling happened. Should be {@code null} when
         * retry type is {@link ThrottleStatus#RETRY_TYPE_HANDOVER}.
         */
        public final @Nullable NetworkRequestList networkRequestList;

        /**
         * @param dataNetwork The data network that is being throttled for handover retry. Should be
         * {@code null} when retryType is {@link ThrottleStatus#RETRY_TYPE_NEW_CONNECTION}.
         */
        public final @Nullable DataNetwork dataNetwork;

        /** The transport that the data profile has been throttled on. */
        public final @TransportType int transport;

        /** The retry type when throttling expires. */
        public final @RetryType int retryType;

        /**
         * The expiration time of data throttling. This is the time retrieved from
         * {@link SystemClock#elapsedRealtime()}.
         */
        public final @ElapsedRealtimeLong long expirationTimeMillis;

        /**
         * Constructor.
         *
         * @param dataProfile The data profile that is being throttled for setup/handover retry.
         * @param networkRequestList The associated network request list when throttling happened.
         * Should be {@code null} when retry type is {@link ThrottleStatus#RETRY_TYPE_HANDOVER}.
         * @param dataNetwork The data network that is being throttled for handover retry.
         * Should be {@code null} when retryType is
         * {@link ThrottleStatus#RETRY_TYPE_NEW_CONNECTION}.
         * @param transport The transport that the data profile has been throttled on.
         * @param retryType The retry type when throttling expires.
         * @param expirationTimeMillis The expiration elapsed time of data throttling.
         */
        public DataThrottlingEntry(@NonNull DataProfile dataProfile,
                @Nullable NetworkRequestList networkRequestList,
                @Nullable DataNetwork dataNetwork, @TransportType int transport,
                @RetryType int retryType, @ElapsedRealtimeLong long expirationTimeMillis) {
            this.dataProfile = dataProfile;
            this.networkRequestList = networkRequestList;
            this.dataNetwork = dataNetwork;
            this.transport = transport;
            this.retryType = retryType;
            this.expirationTimeMillis = expirationTimeMillis;
        }

        @Override
        public @NonNull String toString() {
            return "[DataThrottlingEntry: dataProfile=" + dataProfile + ", request list="
                    + networkRequestList + ", dataNetwork=" + dataNetwork + ", transport="
                    + AccessNetworkConstants.transportTypeToString(transport) + ", expiration time="
                    + DataUtils.elapsedTimeToString(expirationTimeMillis) + "]";
        }
    }

    /**
     * Represent a data retry rule. A rule consists a retry type (e.g. either by capabilities,
     * fail cause, or both), and a retry interval.
     */
    public static class DataRetryRule {
        private static final String RULE_TAG_FAIL_CAUSES = "fail_causes";
        private static final String RULE_TAG_RETRY_INTERVAL = "retry_interval";
        private static final String RULE_TAG_MAXIMUM_RETRIES = "maximum_retries";

        /**
         * The data network setup retry interval. Note that if this is empty, then
         * {@link #getMaxRetries()} must return 0. Default retry interval is 5 seconds.
         */
        protected List<Long> mRetryIntervalsMillis = List.of(TimeUnit.SECONDS.toMillis(5));

        /**
         * The maximum retry times. After reaching the retry times, data retry will not be scheduled
         * with timer. Only environment changes (e.g. Airplane mode, SIM state, RAT, registration
         * state changes, etc..) can trigger the retry.
         */
        protected int mMaxRetries = 10;

        /**
         * The network capabilities. Each data setup must be
         * associated with at least one network request. If that network request contains network
         * capabilities specified here, then retry will happen. Empty set indicates the retry rule
         * is not using network capabilities.
         */
        protected @NonNull @NetCapability Set<Integer> mNetworkCapabilities = new ArraySet<>();

        /**
         * The fail causes. If data setup failed with certain fail causes, then retry will happen.
         * Empty set indicates the retry rule is not using the fail causes.
         */
        protected @NonNull @DataFailureCause Set<Integer> mFailCauses = new ArraySet<>();

        public DataRetryRule(@NonNull String ruleString) {
            if (TextUtils.isEmpty(ruleString)) {
                throw new IllegalArgumentException("illegal rule " + ruleString);
            }
            ruleString = ruleString.trim().toLowerCase(Locale.ROOT);
            String[] expressions = ruleString.split("\\s*,\\s*");
            for (String expression : expressions) {
                String[] tokens = expression.trim().split("\\s*=\\s*");
                if (tokens.length != 2) {
                    throw new IllegalArgumentException("illegal rule " + ruleString);
                }
                String key = tokens[0].trim();
                String value = tokens[1].trim();
                try {
                    switch (key) {
                        case RULE_TAG_FAIL_CAUSES:
                            mFailCauses = Arrays.stream(value.split("\\s*\\|\\s*"))
                                    .map(String::trim)
                                    .map(Integer::valueOf)
                                    .collect(Collectors.toSet());
                            break;
                        case RULE_TAG_RETRY_INTERVAL:
                            mRetryIntervalsMillis = Arrays.stream(value.split("\\s*\\|\\s*"))
                                    .map(String::trim)
                                    .map(Long::valueOf)
                                    .collect(Collectors.toList());
                            break;
                        case RULE_TAG_MAXIMUM_RETRIES:
                            mMaxRetries = Integer.parseInt(value);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("illegal rule " + ruleString + ", e=" + e);
                }
            }

            if (mMaxRetries < 0) {
                throw new IllegalArgumentException("Max retries should not be less than 0. "
                        + "mMaxRetries=" + mMaxRetries);
            }

            if (mRetryIntervalsMillis.stream().anyMatch(i -> i <= 0)) {
                throw new IllegalArgumentException("Retry interval should not be less than 0. "
                        + "mRetryIntervalsMillis=" + mRetryIntervalsMillis);
            }
        }

        /**
         * @return The data network setup retry intervals in milliseconds. If this is empty, then
         * {@link #getMaxRetries()} must return 0.
         */
        public @NonNull List<Long> getRetryIntervalsMillis() {
            return mRetryIntervalsMillis;
        }

        /**
         * @return The maximum retry times. After reaching the retry times, data retry will not be
         * scheduled with timer. Only environment changes (e.g. Airplane mode, SIM state, RAT,
         * registration state changes, etc..) can trigger the retry. Note that if max retries
         * is 0, then {@link #getRetryIntervalsMillis()} must be {@code null}.
         */
        public int getMaxRetries() {
            return mMaxRetries;
        }

        /**
         * @return The fail causes. If data setup failed with certain fail causes, then retry will
         * happen. Empty set indicates the retry rule is not using the fail causes.
         */
        @VisibleForTesting
        public @NonNull @DataFailureCause Set<Integer> getFailCauses() {
            return mFailCauses;
        }
    }

    /**
     * Represent a rule for data setup retry.
     *
     * The syntax of the retry rule:
     * 1. Retry based on {@link NetworkCapabilities}. Note that only APN-type network capabilities
     *    are supported. If the capabilities are not specified, then the retry rule only applies
     *    to the current failed APN used in setup data call request.
     * "capabilities=[netCaps1|netCaps2|...], [retry_interval=n1|n2|n3|n4...], [maximum_retries=n]"
     *
     * 2. Retry based on {@link DataFailCause}
     * "fail_causes=[cause1|cause2|cause3|..], [retry_interval=n1|n2|n3|n4...], [maximum_retries=n]"
     *
     * 3. Retry based on {@link NetworkCapabilities} and {@link DataFailCause}. Note that only
     *    APN-type network capabilities are supported.
     * "capabilities=[netCaps1|netCaps2|...], fail_causes=[cause1|cause2|cause3|...],
     *     [retry_interval=n1|n2|n3|n4...], [maximum_retries=n]"
     *
     * 4. Permanent fail causes (no timer-based retry) on the current failed APN. Retry interval
     *    is specified for retrying the next available APN.
     * "permanent_fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|-3|65543|65547|
     *     2252|2253|2254, retry_interval=2500"
     *
     * For example,
     * "capabilities=eims, retry_interval=1000, maximum_retries=20" means if the attached
     * network request is emergency, then retry data network setup every 1 second for up to 20
     * times.
     *
     * "capabilities=internet|enterprise|dun|ims|fota, retry_interval=2500|3000|"
     * "5000|10000|15000|20000|40000|60000|120000|240000|600000|1200000|1800000"
     * "1800000, maximum_retries=20" means for those capabilities, retry happens in 2.5s, 3s, 5s,
     * 10s, 15s, 20s, 40s, 1m, 2m, 4m, 10m, 20m, 30m, 30m, 30m, until reaching 20 retries.
     *
     */
    public static class DataSetupRetryRule extends DataRetryRule {
        private static final String RULE_TAG_PERMANENT_FAIL_CAUSES = "permanent_fail_causes";
        private static final String RULE_TAG_CAPABILITIES = "capabilities";

        /** {@code true} if this rule is for permanent fail causes. */
        private boolean mIsPermanentFailCauseRule;

        /**
         * Constructor
         *
         * @param ruleString The retry rule in string format.
         * @throws IllegalArgumentException if the string can't be parsed to a retry rule.
         */
        public DataSetupRetryRule(@NonNull String ruleString) {
            super(ruleString);

            ruleString = ruleString.trim().toLowerCase(Locale.ROOT);
            String[] expressions = ruleString.split("\\s*,\\s*");
            for (String expression : expressions) {
                String[] tokens = expression.trim().split("\\s*=\\s*");
                if (tokens.length != 2) {
                    throw new IllegalArgumentException("illegal rule " + ruleString);
                }
                String key = tokens[0].trim();
                String value = tokens[1].trim();
                try {
                    switch (key) {
                        case RULE_TAG_PERMANENT_FAIL_CAUSES:
                            mFailCauses = Arrays.stream(value.split("\\s*\\|\\s*"))
                                    .map(String::trim)
                                    .map(Integer::valueOf)
                                    .collect(Collectors.toSet());
                            mIsPermanentFailCauseRule = true;
                            break;
                        case RULE_TAG_CAPABILITIES:
                            mNetworkCapabilities = DataUtils
                                    .getNetworkCapabilitiesFromString(value);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("illegal rule " + ruleString + ", e=" + e);
                }
            }

            if (mFailCauses.isEmpty() && (mNetworkCapabilities.isEmpty()
                    || mNetworkCapabilities.contains(-1))) {
                throw new IllegalArgumentException("illegal rule " + ruleString
                            + ". Should have either valid network capabilities or fail causes.");
            }
        }

        /**
         * @return The network capabilities. Each data setup must be associated with at least one
         * network request. If that network request contains network capabilities specified here,
         * then retry will happen. Empty set indicates the retry rule is not using network
         * capabilities.
         */
        @VisibleForTesting
        public @NonNull @NetCapability Set<Integer> getNetworkCapabilities() {
            return mNetworkCapabilities;
        }

        /**
         * @return {@code true} if this rule is for permanent fail causes.
         */
        public boolean isPermanentFailCauseRule() {
            return mIsPermanentFailCauseRule;
        }

        /**
         * Check if this rule can be matched.
         *
         * @param networkCapability The network capability for matching.
         * @param cause Fail cause from previous setup data request.
         * @return {@code true} if the retry rule can be matched.
         */
        public boolean canBeMatched(@NonNull @NetCapability int networkCapability,
                @DataFailureCause int cause) {
            if (!mFailCauses.isEmpty() && !mFailCauses.contains(cause)) {
                return false;
            }

            return mNetworkCapabilities.isEmpty()
                    || mNetworkCapabilities.contains(networkCapability);
        }

        @Override
        public String toString() {
            return "[DataSetupRetryRule: Network capabilities:"
                    + DataUtils.networkCapabilitiesToString(mNetworkCapabilities.stream()
                    .mapToInt(Number::intValue).toArray())
                    + ", Fail causes=" + mFailCauses
                    + ", Retry intervals=" + mRetryIntervalsMillis + ", Maximum retries="
                    + mMaxRetries + "]";
        }
    }

    /**
     * Represent a handover data network retry rule.
     *
     * The syntax of the retry rule:
     * 1. Retry when handover fails.
     * "retry_interval=[n1|n2|n3|...], [maximum_retries=n]"
     *
     * For example,
     * "retry_interval=1000|3000|5000, maximum_retries=10" means handover retry will happen in 1s,
     * 3s, 5s, 5s, 5s....up to 10 times.
     *
     * 2. Retry when handover fails with certain fail causes.
     * "retry_interval=[n1|n2|n3|...], fail_causes=[cause1|cause2|cause3|...], [maximum_retries=n]
     *
     * For example,
     * "retry_interval=1000, maximum_retries=3, fail_causes=5" means handover retry every 1 second
     * for up to 3 times when handover fails with the cause 5.
     *
     * "maximum_retries=0, fail_causes=6|10|67" means handover retry should not happen for those
     * causes.
     */
    public static class DataHandoverRetryRule extends DataRetryRule {
        /**
         * Constructor
         *
         * @param ruleString The retry rule in string format.
         * @throws IllegalArgumentException if the string can't be parsed to a retry rule.
         */
        public DataHandoverRetryRule(@NonNull String ruleString) {
            super(ruleString);
        }

        @Override
        public String toString() {
            return "[DataHandoverRetryRule: Retry intervals=" + mRetryIntervalsMillis
                    + ", Fail causes=" + mFailCauses + ", Maximum retries=" + mMaxRetries + "]";
        }
    }

    /**
     * Represent a data retry entry.
     */
    public static class DataRetryEntry {
        /** Indicates the retry is not happened yet. */
        public static final int RETRY_STATE_NOT_RETRIED = 1;

        /** Indicates the retry happened, but still failed to setup/handover the data network. */
        public static final int RETRY_STATE_FAILED = 2;

        /** Indicates the retry happened and succeeded. */
        public static final int RETRY_STATE_SUCCEEDED = 3;

        /** Indicates the retry was cancelled. */
        public static final int RETRY_STATE_CANCELLED = 4;

        @IntDef(prefix = {"RETRY_STATE_"},
                value = {
                        RETRY_STATE_NOT_RETRIED,
                        RETRY_STATE_FAILED,
                        RETRY_STATE_SUCCEEDED,
                        RETRY_STATE_CANCELLED
                })
        public @interface DataRetryState {}

        /** The rule used for this data retry. {@code null} if the retry is requested by network. */
        public final @Nullable DataRetryRule appliedDataRetryRule;

        /** The retry delay in milliseconds. */
        public final long retryDelayMillis;

        /**
         * Retry elapsed time. This is the system elapsed time retrieved from
         * {@link SystemClock#elapsedRealtime()}.
         */
        public final @ElapsedRealtimeLong long retryElapsedTime;

        /** The retry state. */
        protected int mRetryState = RETRY_STATE_NOT_RETRIED;

        /** Timestamp when a state is set. For debugging purposes only. */
        protected @ElapsedRealtimeLong long mRetryStateTimestamp = 0;

        /**
         * Constructor
         *
         * @param appliedDataRetryRule The applied data retry rule.
         * @param retryDelayMillis The retry delay in milliseconds.
         */
        public DataRetryEntry(@Nullable DataRetryRule appliedDataRetryRule, long retryDelayMillis) {
            this.appliedDataRetryRule = appliedDataRetryRule;
            this.retryDelayMillis = retryDelayMillis;

            mRetryStateTimestamp = SystemClock.elapsedRealtime();
            retryElapsedTime =  mRetryStateTimestamp + retryDelayMillis;
        }

        /**
         * Set the state of a data retry.
         *
         * @param state The retry state.
         */
        public void setState(@DataRetryState int state) {
            mRetryState = state;
            mRetryStateTimestamp = SystemClock.elapsedRealtime();
        }

        /**
         * @return Get the retry state.
         */
        public @DataRetryState int getState() {
            return mRetryState;
        }

        /**
         * Convert retry state to string.
         *
         * @param retryState Retry state.
         * @return Retry state in string format.
         */
        public static String retryStateToString(@DataRetryState int retryState) {
            switch (retryState) {
                case RETRY_STATE_NOT_RETRIED: return "NOT_RETRIED";
                case RETRY_STATE_FAILED: return "FAILED";
                case RETRY_STATE_SUCCEEDED: return "SUCCEEDED";
                case RETRY_STATE_CANCELLED: return "CANCELLED";
                default: return "Unknown(" + retryState + ")";
            }
        }

        /**
         * The generic builder for retry entry.
         *
         * @param <T> The type of extended retry entry builder.
         */
        public static class Builder<T extends Builder<T>> {
            /**
             * The retry delay in milliseconds. Default is 5 seconds.
             */
            protected long mRetryDelayMillis = TimeUnit.SECONDS.toMillis(5);

            /** The applied data retry rule. */
            protected @Nullable DataRetryRule mAppliedDataRetryRule;

            /**
             * Set the data retry delay.
             *
             * @param retryDelayMillis The retry delay in milliseconds.
             * @return This builder.
             */
            public @NonNull T setRetryDelay(long retryDelayMillis) {
                mRetryDelayMillis = retryDelayMillis;
                return (T) this;
            }

            /**
             * Set the applied retry rule.
             *
             * @param dataRetryRule The rule that used for this data retry.
             * @return This builder.
             */
            public @NonNull T setAppliedRetryRule(@NonNull DataRetryRule dataRetryRule) {
                mAppliedDataRetryRule = dataRetryRule;
                return (T) this;
            }
        }
    }

    /**
     * Represent a setup data retry entry.
     */
    public static class DataSetupRetryEntry extends DataRetryEntry {
        /**
         * Retry type is unknown. This should be only used for initialized value.
         */
        public static final int RETRY_TYPE_UNKNOWN = 0;
        /**
         * To retry setup data with the same data profile.
         */
        public static final int RETRY_TYPE_DATA_PROFILE = 1;

        /**
         * To retry satisfying the network request(s). Could be using a
         * different data profile.
         */
        public static final int RETRY_TYPE_NETWORK_REQUESTS = 2;

        @IntDef(prefix = {"RETRY_TYPE_"},
                value = {
                        RETRY_TYPE_UNKNOWN,
                        RETRY_TYPE_DATA_PROFILE,
                        RETRY_TYPE_NETWORK_REQUESTS,
                })
        public @interface SetupRetryType {}

        /** Setup retry type. Could be retry by same data profile or same capability. */
        public final @SetupRetryType int setupRetryType;

        /** The network requests to satisfy when retry happens. */
        public final @NonNull NetworkRequestList networkRequestList;

        /** The data profile that will be used for retry. */
        public final @Nullable DataProfile dataProfile;

        /** The transport to retry data setup. */
        public final @TransportType int transport;

        /**
         * Constructor
         *
         * @param setupRetryType Data retry type. Could be retry by same data profile or same
         * capabilities.
         * @param networkRequestList The network requests to satisfy when retry happens.
         * @param dataProfile The data profile that will be used for retry.
         * @param transport The transport to retry data setup.
         * @param appliedDataSetupRetryRule The applied data setup retry rule.
         * @param retryDelayMillis The retry delay in milliseconds.
         */
        private DataSetupRetryEntry(@SetupRetryType int setupRetryType,
                @Nullable NetworkRequestList networkRequestList, @NonNull DataProfile dataProfile,
                @TransportType int transport,
                @Nullable DataSetupRetryRule appliedDataSetupRetryRule, long retryDelayMillis) {
            super(appliedDataSetupRetryRule, retryDelayMillis);
            this.setupRetryType = setupRetryType;
            this.networkRequestList = networkRequestList;
            this.dataProfile = dataProfile;
            this.transport = transport;
        }

        /**
         * Convert retry type to string.
         *
         * @param setupRetryType Data setup retry type.
         * @return Retry type in string format.
         */
        private static String retryTypeToString(@SetupRetryType int setupRetryType) {
            switch (setupRetryType) {
                case RETRY_TYPE_DATA_PROFILE: return "BY_PROFILE";
                case RETRY_TYPE_NETWORK_REQUESTS: return "BY_NETWORK_REQUESTS";
                default: return "Unknown(" + setupRetryType + ")";
            }
        }

        @Override
        public String toString() {
            return "[DataSetupRetryEntry: delay=" + retryDelayMillis + "ms, retry time:"
                    + DataUtils.elapsedTimeToString(retryElapsedTime) + ", " + dataProfile
                    + ", transport=" + AccessNetworkConstants.transportTypeToString(transport)
                    + ", retry type=" + retryTypeToString(setupRetryType) + ", retry requests="
                    + networkRequestList + ", applied rule=" + appliedDataRetryRule + ", state="
                    + retryStateToString(mRetryState) + ", timestamp="
                    + DataUtils.elapsedTimeToString(mRetryStateTimestamp) + "]";
        }

        /**
         * The builder of {@link DataSetupRetryEntry}.
         *
         * @param <T> Type of the builder.
         */
        public static class Builder<T extends Builder<T>> extends DataRetryEntry.Builder<T> {
            /** Data setup retry type. Could be retry by same data profile or same capabilities. */
            private @SetupRetryType int mSetupRetryType = RETRY_TYPE_UNKNOWN;

            /** The network requests to satisfy when retry happens. */
            private @NonNull NetworkRequestList mNetworkRequestList;

            /** The data profile that will be used for retry. */
            private @Nullable DataProfile mDataProfile;

            /** The transport to retry data setup. */
            private @TransportType int mTransport = AccessNetworkConstants.TRANSPORT_TYPE_INVALID;

            /**
             * Set the data retry type.
             *
             * @param setupRetryType Data retry type. Could be retry by same data profile or same
             * capabilities.
             * @return This builder.
             */
            public @NonNull Builder<T> setSetupRetryType(@SetupRetryType int setupRetryType) {
                mSetupRetryType = setupRetryType;
                return this;
            }

            /**
             * Set the network capability to satisfy when retry happens.
             *
             * @param networkRequestList The network requests to satisfy when retry happens.
             * @return This builder.
             */
            public @NonNull Builder<T> setNetworkRequestList(
                    @NonNull NetworkRequestList networkRequestList) {
                mNetworkRequestList = networkRequestList;
                return this;
            }

            /**
             * Set the data profile that will be used for retry.
             *
             * @param dataProfile The data profile that will be used for retry.
             * @return This builder.
             */
            public @NonNull Builder<T> setDataProfile(@NonNull DataProfile dataProfile) {
                mDataProfile = dataProfile;
                return this;
            }

            /**
             * Set the transport of the data setup retry.
             *
             * @param transport The transport to retry data setup.
             * @return This builder.
             */
            public @NonNull Builder<T> setTransport(@TransportType int transport) {
                mTransport = transport;
                return this;
            }

            /**
             * Build the instance of {@link DataSetupRetryEntry}.
             *
             * @return The instance of {@link DataSetupRetryEntry}.
             */
            public @NonNull DataSetupRetryEntry build() {
                if (mNetworkRequestList == null) {
                    throw new IllegalArgumentException("network request list is not specified.");
                }
                if (mTransport != AccessNetworkConstants.TRANSPORT_TYPE_WWAN
                        && mTransport != AccessNetworkConstants.TRANSPORT_TYPE_WLAN) {
                    throw new IllegalArgumentException("Invalid transport type " + mTransport);
                }
                if (mSetupRetryType != RETRY_TYPE_DATA_PROFILE
                        && mSetupRetryType != RETRY_TYPE_NETWORK_REQUESTS) {
                    throw new IllegalArgumentException("Invalid setup retry type "
                            + mSetupRetryType);
                }
                return new DataSetupRetryEntry(mSetupRetryType, mNetworkRequestList, mDataProfile,
                        mTransport, (DataSetupRetryRule) mAppliedDataRetryRule, mRetryDelayMillis);
            }
        }
    }

    /**
     * Represent a data handover retry entry.
     */
    public static class DataHandoverRetryEntry extends DataRetryEntry {
        /** The data network to be retried for handover. */
        public final @NonNull DataNetwork dataNetwork;

        /**
         * Constructor.
         *
         * @param dataNetwork The data network to be retried for handover.
         * @param appliedDataHandoverRetryRule The applied data retry rule.
         * @param retryDelayMillis The retry delay in milliseconds.
         */
        public DataHandoverRetryEntry(@NonNull DataNetwork dataNetwork,
                @Nullable DataHandoverRetryRule appliedDataHandoverRetryRule,
                long retryDelayMillis) {
            super(appliedDataHandoverRetryRule, retryDelayMillis);
            this.dataNetwork = dataNetwork;
        }

        @Override
        public String toString() {
            return "[DataHandoverRetryEntry: delay=" + retryDelayMillis + "ms, retry time:"
                    + DataUtils.elapsedTimeToString(retryElapsedTime) + ", " + dataNetwork
                     + ", applied rule=" + appliedDataRetryRule + ", state="
                    + retryStateToString(mRetryState) + ", timestamp="
                    + DataUtils.elapsedTimeToString(mRetryStateTimestamp) + "]";
        }

        /**
         * The builder of {@link DataHandoverRetryEntry}.
         *
         * @param <T> Type of the builder.
         */
        public static class Builder<T extends Builder<T>> extends DataRetryEntry.Builder<T> {
            /** The data network to be retried for handover. */
            public @NonNull DataNetwork mDataNetwork;

            /**
             * Set the data retry type.
             *
             * @param dataNetwork The data network to be retried for handover.
             *
             * @return This builder.
             */
            public @NonNull Builder<T> setDataNetwork(@NonNull DataNetwork dataNetwork) {
                mDataNetwork = dataNetwork;
                return this;
            }

            /**
             * Build the instance of {@link DataHandoverRetryEntry}.
             *
             * @return The instance of {@link DataHandoverRetryEntry}.
             */
            public @NonNull DataHandoverRetryEntry build() {
                return new DataHandoverRetryEntry(mDataNetwork,
                        (DataHandoverRetryRule) mAppliedDataRetryRule, mRetryDelayMillis);
            }
        }
    }

    /** Data retry callback. */
    public static class DataRetryManagerCallback extends DataCallback {
        /**
         * Constructor
         *
         * @param executor The executor of the callback.
         */
        public DataRetryManagerCallback(@NonNull @CallbackExecutor Executor executor) {
            super(executor);
        }

        /**
         * Called when data setup retry occurs.
         *
         * @param dataSetupRetryEntry The data setup retry entry.
         */
        public void onDataNetworkSetupRetry(@NonNull DataSetupRetryEntry dataSetupRetryEntry) {}

        /**
         * Called when data handover retry occurs.
         *
         * @param dataHandoverRetryEntry The data handover retry entry.
         */
        public void onDataNetworkHandoverRetry(
                @NonNull DataHandoverRetryEntry dataHandoverRetryEntry) {}

        /**
         * Called when retry manager determines that the retry will no longer be performed on
         * this data network.
         *
         * @param dataNetwork The data network that will never be retried handover.
         */
        public void onDataNetworkHandoverRetryStopped(@NonNull DataNetwork dataNetwork) {}

        /**
         * Called when throttle status changed reported from network.
         *
         * @param throttleStatusList List of throttle status.
         */
        public void onThrottleStatusChanged(@NonNull List<ThrottleStatus> throttleStatusList) {}
    }

    /**
     * Constructor
     *
     * @param phone The phone instance.
     * @param dataNetworkController Data network controller.
     * @param looper The looper to be used by the handler. Currently the handler thread is the
     * phone process's main thread.
     * @param dataRetryManagerCallback Data retry callback.
     */
    public DataRetryManager(@NonNull Phone phone,
            @NonNull DataNetworkController dataNetworkController,
            @NonNull SparseArray<DataServiceManager> dataServiceManagers,
            @NonNull Looper looper, @NonNull DataRetryManagerCallback dataRetryManagerCallback) {
        super(looper);
        mPhone = phone;
        mRil = phone.mCi;
        mLogTag = "DRM-" + mPhone.getPhoneId();
        mDataRetryManagerCallbacks.add(dataRetryManagerCallback);

        mDataServiceManagers = dataServiceManagers;
        mDataConfigManager = dataNetworkController.getDataConfigManager();
        mDataProfileManager = dataNetworkController.getDataProfileManager();
        mAlarmManager = mPhone.getContext().getSystemService(AlarmManager.class);

        mDataConfigManager.registerCallback(new DataConfigManagerCallback(this::post) {
            @Override
            public void onCarrierConfigChanged() {
                DataRetryManager.this.onCarrierConfigUpdated();
            }
        });

        for (int transport : mPhone.getAccessNetworksManager().getAvailableTransports()) {
            mDataServiceManagers.get(transport)
                    .registerForApnUnthrottled(this, EVENT_DATA_PROFILE_UNTHROTTLED);
        }
        mDataProfileManager.registerCallback(new DataProfileManagerCallback(this::post) {
            @Override
            public void onDataProfilesChanged() {
                onReset(RESET_REASON_DATA_PROFILES_CHANGED);
            }
        });
        dataNetworkController.registerDataNetworkControllerCallback(
                new DataNetworkControllerCallback(this::post) {
                    /**
                     * Called when data service is bound.
                     *
                     * @param transport The transport of the data service.
                     */
                    @Override
                    public void onDataServiceBound(@TransportType int transport) {
                        onReset(RESET_REASON_DATA_SERVICE_BOUND);
                    }

                    /**
                     * Called when data network is connected.
                     *
                     * @param transport Transport for the connected network.
                     * @param dataProfile The data profile of the connected data network.
                     */
                    @Override
                    public void onDataNetworkConnected(@TransportType int transport,
                            @NonNull DataProfile dataProfile) {
                        DataRetryManager.this.onDataNetworkConnected(transport, dataProfile);
                    }
                });
        mRil.registerForOn(this, EVENT_RADIO_ON, null);
        mRil.registerForModemReset(this, EVENT_MODEM_RESET, null);

        // Register intent of alarm manager for long retry timer
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_RETRY);
        mPhone.getContext().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (ACTION_RETRY.equals(intent.getAction())) {
                    DataRetryManager.this.onAlarmIntentRetry(
                            intent.getIntExtra(ACTION_RETRY_EXTRA_HASHCODE, -1 /*Bad hashcode*/));
                }
            }
        }, intentFilter);

        if (mDataConfigManager.shouldResetDataThrottlingWhenTacChanges()) {
            mPhone.getServiceStateTracker().registerForAreaCodeChanged(this, EVENT_TAC_CHANGED,
                    null);
        }
    }

    @Override
    public void handleMessage(Message msg) {
        AsyncResult ar;
        switch (msg.what) {
            case EVENT_DATA_SETUP_RETRY:
                DataSetupRetryEntry dataSetupRetryEntry = (DataSetupRetryEntry) msg.obj;
                if (!isRetryCancelled(dataSetupRetryEntry)) {
                    mDataRetryManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
                            () -> callback.onDataNetworkSetupRetry(dataSetupRetryEntry)));
                }
                break;
            case EVENT_DATA_HANDOVER_RETRY:
                DataHandoverRetryEntry dataHandoverRetryEntry = (DataHandoverRetryEntry) msg.obj;
                if (!isRetryCancelled(dataHandoverRetryEntry)) {
                    mDataRetryManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
                            () -> callback.onDataNetworkHandoverRetry(dataHandoverRetryEntry)));
                }
                break;
            case EVENT_RADIO_ON:
                onReset(RESET_REASON_RADIO_ON);
                break;
            case EVENT_MODEM_RESET:
                onReset(RESET_REASON_MODEM_RESTART);
                break;
            case EVENT_TAC_CHANGED:
                onReset(RESET_REASON_TAC_CHANGED);
                break;
            case EVENT_DATA_PROFILE_UNTHROTTLED:
                ar = (AsyncResult) msg.obj;
                int transport = (int) ar.userObj;
                String apn = null;
                DataProfile dataProfile = null;
                // 1.6 or older HAL
                if (ar.result instanceof String) {
                    apn = (String) ar.result;
                } else if (ar.result instanceof DataProfile) {
                    dataProfile = (DataProfile) ar.result;
                }
                onDataProfileUnthrottled(dataProfile, apn, transport, true, true);
                break;
            case EVENT_CANCEL_PENDING_HANDOVER_RETRY:
                onCancelPendingHandoverRetry((DataNetwork) msg.obj);
                break;
            default:
                loge("Unexpected message " + msg.what);
        }
    }

    /**
     * @param retryEntry The retry entry to check.
     * @return {@code true} if the retry is null or not in RETRY_STATE_NOT_RETRIED state.
     */
    private boolean isRetryCancelled(@Nullable DataRetryEntry retryEntry) {
        if (retryEntry != null && retryEntry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED) {
            return false;
        }
        log("Retry was removed earlier. " + retryEntry);
        return true;
    }

    /**
     * Called when carrier config is updated.
     */
    private void onCarrierConfigUpdated() {
        onReset(RESET_REASON_DATA_CONFIG_CHANGED);
        mDataSetupRetryRuleList = mDataConfigManager.getDataSetupRetryRules();
        mDataHandoverRetryRuleList = mDataConfigManager.getDataHandoverRetryRules();
        log("onDataConfigUpdated: mDataSetupRetryRuleList=" + mDataSetupRetryRuleList
                + ", mDataHandoverRetryRuleList=" + mDataHandoverRetryRuleList);
    }

    /**
     * Called when data network is connected.
     *
     * @param transport Transport for the connected network.
     * @param dataProfile The data profile of the connected data network.
     */
    public void onDataNetworkConnected(@TransportType int transport,
            @NonNull DataProfile dataProfile) {
        if (dataProfile.getApnSetting() != null) {
            dataProfile.getApnSetting().setPermanentFailed(false);
        }

        onDataProfileUnthrottled(dataProfile, null, transport, true, false);
    }

    /**
     * Evaluate if data setup retry is needed or not. If needed, retry will be scheduled
     * automatically after evaluation.
     *
     * @param dataProfile The data profile that has been used in the previous data network setup.
     * @param transport The transport to retry data setup.
     * @param requestList The network requests attached to the previous data network setup.
     * @param cause The fail cause of previous data network setup.
     * @param retryDelayMillis The retry delay in milliseconds suggested by the network/data
     * service. {@link android.telephony.data.DataCallResponse#RETRY_DURATION_UNDEFINED}
     * indicates network/data service did not suggest retry or not. Telephony frameworks would use
     * its logic to perform data retry.
     */
    public void evaluateDataSetupRetry(@NonNull DataProfile dataProfile,
            @TransportType int transport, @NonNull NetworkRequestList requestList,
            @DataFailureCause int cause, long retryDelayMillis) {
        post(() -> onEvaluateDataSetupRetry(dataProfile, transport, requestList, cause,
                retryDelayMillis));
    }

    private void onEvaluateDataSetupRetry(@NonNull DataProfile dataProfile,
            @TransportType int transport, @NonNull NetworkRequestList requestList,
            @DataFailureCause int cause, long retryDelayMillis) {
        logl("onEvaluateDataSetupRetry: " + dataProfile + ", transport="
                + AccessNetworkConstants.transportTypeToString(transport) + ", cause="
                + DataFailCause.toString(cause) + ", retryDelayMillis=" + retryDelayMillis + "ms"
                + ", " + requestList);
        // Check if network suggested never retry for this data profile. Note that for HAL 1.5
        // and older, Integer.MAX_VALUE indicates never retry. For 1.6 or above, Long.MAX_VALUE
        // indicates never retry.
        if (retryDelayMillis == Long.MAX_VALUE || retryDelayMillis == Integer.MAX_VALUE) {
            logl("Network suggested never retry for " + dataProfile);
            // Note that RETRY_TYPE_NEW_CONNECTION is intended here because
            // when unthrottling happens, we still want to retry and we'll need
            // a type there so we know what to retry. Using RETRY_TYPE_NONE
            // ThrottleStatus is just for API backwards compatibility reason.
            updateThrottleStatus(dataProfile, requestList, null,
                    ThrottleStatus.RETRY_TYPE_NEW_CONNECTION, transport, Long.MAX_VALUE);
            return;
        } else if (retryDelayMillis != DataCallResponse.RETRY_DURATION_UNDEFINED) {
            // Network specifically asks retry the previous data profile again.
            DataSetupRetryEntry dataSetupRetryEntry = new DataSetupRetryEntry.Builder<>()
                    .setRetryDelay(retryDelayMillis)
                    .setSetupRetryType(DataSetupRetryEntry.RETRY_TYPE_DATA_PROFILE)
                    .setNetworkRequestList(requestList)
                    .setDataProfile(dataProfile)
                    .setTransport(transport)
                    .build();
            updateThrottleStatus(dataProfile, requestList, null,
                    ThrottleStatus.RETRY_TYPE_NEW_CONNECTION, transport,
                    dataSetupRetryEntry.retryElapsedTime);
            schedule(dataSetupRetryEntry);
            return;
        }

        // Network did not suggest any retry. Use the configured rules to perform retry.
        logv("mDataSetupRetryRuleList=" + mDataSetupRetryRuleList);

        boolean retryScheduled = false;
        List<NetworkRequestList> groupedNetworkRequestLists =
                DataUtils.getGroupedNetworkRequestList(requestList);
        for (DataSetupRetryRule retryRule : mDataSetupRetryRuleList) {
            if (retryRule.isPermanentFailCauseRule() && retryRule.getFailCauses().contains(cause)) {
                if (dataProfile.getApnSetting() != null) {
                    dataProfile.getApnSetting().setPermanentFailed(true);

                    // It seems strange to have retry timer in permanent failure rule, but since
                    // in this case permanent failure is only applicable to the failed profile, so
                    // we need to see if other profile can be selected for next data setup.
                    log("Marked " + dataProfile.getApnSetting().getApnName() + " permanently "
                            + "failed, but still schedule retry to see if another data profile "
                            + "can be used for setup data.");
                    // Schedule a data retry to see if another data profile could be selected.
                    // If the same data profile is selected again, since it's marked as
                    // permanent failure, it won't be used for setup data call.
                    schedule(new DataSetupRetryEntry.Builder<>()
                            .setRetryDelay(retryRule.getRetryIntervalsMillis().get(0))
                            .setAppliedRetryRule(retryRule)
                            .setSetupRetryType(DataSetupRetryEntry.RETRY_TYPE_NETWORK_REQUESTS)
                            .setTransport(transport)
                            .setNetworkRequestList(requestList)
                            .build());
                } else {
                    // For TD-based data profile, do not do anything for now. Should expand this in
                    // the future if needed.
                    log("Stopped timer-based retry for TD-based data profile. Will retry only when "
                            + "environment changes.");
                }
                return;
            }
            for (NetworkRequestList networkRequestList : groupedNetworkRequestLists) {
                int capability = networkRequestList.get(0).getApnTypeNetworkCapability();
                if (retryRule.canBeMatched(capability, cause)) {
                    // Check if there is already a similar network request retry scheduled.
                    if (isSimilarNetworkRequestRetryScheduled(
                            networkRequestList.get(0), transport)) {
                        log(networkRequestList.get(0) + " already had similar retry "
                                + "scheduled.");
                        return;
                    }

                    int failedCount = getRetryFailedCount(capability, retryRule, transport);
                    log("For capability " + DataUtils.networkCapabilityToString(capability)
                            + ", found matching rule " + retryRule + ", failed count="
                            + failedCount);
                    if (failedCount == retryRule.getMaxRetries()) {
                        log("Data retry failed for " + failedCount + " times on "
                                + AccessNetworkConstants.transportTypeToString(transport)
                                + ". Stopped timer-based data retry for "
                                + DataUtils.networkCapabilityToString(capability)
                                + ". Condition-based retry will still happen when condition "
                                + "changes.");
                        return;
                    }

                    retryDelayMillis = retryRule.getRetryIntervalsMillis().get(
                            Math.min(failedCount, retryRule
                                    .getRetryIntervalsMillis().size() - 1));

                    // Schedule a data retry.
                    schedule(new DataSetupRetryEntry.Builder<>()
                            .setRetryDelay(retryDelayMillis)
                            .setAppliedRetryRule(retryRule)
                            .setSetupRetryType(DataSetupRetryEntry.RETRY_TYPE_NETWORK_REQUESTS)
                            .setTransport(transport)
                            .setNetworkRequestList(networkRequestList)
                            .build());
                    retryScheduled = true;
                    break;
                }
            }
        }

        if (!retryScheduled) {
            log("onEvaluateDataSetupRetry: Did not match any retry rule. Stop timer-based "
                    + "retry.");
        }
    }

    /**
     * Evaluate if data handover retry is needed or not. If needed, retry will be scheduled
     * automatically after evaluation.
     *
     * @param dataNetwork The data network to be retried for handover.
     * @param cause The fail cause of previous data network handover.
     * @param retryDelayMillis The retry delay in milliseconds suggested by the network/data
     * service. {@link android.telephony.data.DataCallResponse#RETRY_DURATION_UNDEFINED}
     * indicates network/data service did not suggest retry or not. Telephony frameworks would use
     * its logic to perform handover retry.
     */
    public void evaluateDataHandoverRetry(@NonNull DataNetwork dataNetwork,
            @DataFailureCause int cause, long retryDelayMillis) {
        post(() -> onEvaluateDataHandoverRetry(dataNetwork, cause, retryDelayMillis));
    }

    private void onEvaluateDataHandoverRetry(@NonNull DataNetwork dataNetwork,
            @DataFailureCause int cause, long retryDelayMillis) {
        logl("onEvaluateDataHandoverRetry: " + dataNetwork + ", cause="
                + DataFailCause.toString(cause) + ", retryDelayMillis=" + retryDelayMillis + "ms");
        int targetTransport = DataUtils.getTargetTransport(dataNetwork.getTransport());
        if (retryDelayMillis == Long.MAX_VALUE || retryDelayMillis == Integer.MAX_VALUE) {
            logl("Network suggested never retry handover for " + dataNetwork);
            // Note that RETRY_TYPE_HANDOVER is intended here because
            // when unthrottling happens, we still want to retry and we'll need
            // a type there so we know what to retry. Using RETRY_TYPE_NONE
            // ThrottleStatus is just for API backwards compatibility reason.
            updateThrottleStatus(dataNetwork.getDataProfile(),
                    dataNetwork.getAttachedNetworkRequestList(), dataNetwork,
                    ThrottleStatus.RETRY_TYPE_HANDOVER, targetTransport, Long.MAX_VALUE);
        } else if (retryDelayMillis != DataCallResponse.RETRY_DURATION_UNDEFINED) {
            // Network specifically asks retry the previous data profile again.
            DataHandoverRetryEntry dataHandoverRetryEntry = new DataHandoverRetryEntry.Builder<>()
                    .setRetryDelay(retryDelayMillis)
                    .setDataNetwork(dataNetwork)
                    .build();

            updateThrottleStatus(dataNetwork.getDataProfile(),
                    dataNetwork.getAttachedNetworkRequestList(), dataNetwork,
                    ThrottleStatus.RETRY_TYPE_HANDOVER, targetTransport,
                    dataHandoverRetryEntry.retryElapsedTime);
            schedule(dataHandoverRetryEntry);
        } else {
            // Network did not suggest any retry. Use the configured rules to perform retry.

            // Matching the rule in configured order.
            for (DataHandoverRetryRule retryRule : mDataHandoverRetryRuleList) {
                if (retryRule.getFailCauses().isEmpty()
                        || retryRule.getFailCauses().contains(cause)) {
                    int failedCount = getRetryFailedCount(dataNetwork, retryRule);
                    log("Found matching rule " + retryRule + ", failed count=" + failedCount);
                    if (failedCount == retryRule.getMaxRetries()) {
                        log("Data handover retry failed for " + failedCount + " times. Stopped "
                                + "handover retry.");
                        mDataRetryManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
                                () -> callback.onDataNetworkHandoverRetryStopped(dataNetwork)));
                        return;
                    }

                    retryDelayMillis = retryRule.getRetryIntervalsMillis().get(
                            Math.min(failedCount, retryRule
                                    .getRetryIntervalsMillis().size() - 1));
                    schedule(new DataHandoverRetryEntry.Builder<>()
                            .setRetryDelay(retryDelayMillis)
                            .setDataNetwork(dataNetwork)
                            .setAppliedRetryRule(retryRule)
                            .build());
                }
            }
        }
    }

    /**
     * @param dataNetwork The data network to check.
     * @return {@code true} if the data network had failed the maximum number of attempts for
     * handover according to any retry rules.
     */
    public boolean isDataNetworkHandoverRetryStopped(@NonNull DataNetwork dataNetwork) {
        // Matching the rule in configured order.
        for (DataHandoverRetryRule retryRule : mDataHandoverRetryRuleList) {
            int failedCount = getRetryFailedCount(dataNetwork, retryRule);
            if (failedCount == retryRule.getMaxRetries()) {
                log("Data handover retry failed for " + failedCount + " times. Stopped "
                        + "handover retry.");
                return true;
            }
        }
        return false;
    }

    /** Cancel all retries and throttling entries. */
    private void onReset(@RetryResetReason int reason) {
        logl("Remove all retry and throttling entries, reason=" + resetReasonToString(reason));
        removeMessages(EVENT_DATA_SETUP_RETRY);
        removeMessages(EVENT_DATA_HANDOVER_RETRY);

        mDataProfileManager.clearAllDataProfilePermanentFailures();

        mDataRetryEntries.stream()
                .filter(entry -> entry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED)
                .forEach(entry -> entry.setState(DataRetryEntry.RETRY_STATE_CANCELLED));

        for (DataThrottlingEntry dataThrottlingEntry : mDataThrottlingEntries) {
            DataProfile dataProfile = dataThrottlingEntry.dataProfile;
            String apn = dataProfile.getApnSetting() != null
                    ? dataProfile.getApnSetting().getApnName() : null;
            onDataProfileUnthrottled(dataProfile, apn, dataThrottlingEntry.transport, false, true);
        }

        mDataThrottlingEntries.clear();
    }

    /**
     * Count how many times the same setup retry rule has been used for this data network but
     * failed.
     *
     * @param dataNetwork The data network to check.
     * @param dataRetryRule The data retry rule.
     * @return The failed count since last successful data setup.
     */
    private int getRetryFailedCount(@NonNull DataNetwork dataNetwork,
            @NonNull DataHandoverRetryRule dataRetryRule) {
        int count = 0;
        for (int i = mDataRetryEntries.size() - 1; i >= 0; i--) {
            if (mDataRetryEntries.get(i) instanceof DataHandoverRetryEntry) {
                DataHandoverRetryEntry entry = (DataHandoverRetryEntry) mDataRetryEntries.get(i);
                if (entry.dataNetwork == dataNetwork
                        && dataRetryRule.equals(entry.appliedDataRetryRule)) {
                    if (entry.getState() == DataRetryEntry.RETRY_STATE_SUCCEEDED
                            || entry.getState() == DataRetryEntry.RETRY_STATE_CANCELLED) {
                        break;
                    }
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * Count how many times the same setup retry rule has been used for the capability since
     * last success data setup.
     *
     * @param networkCapability The network capability to check.
     * @param dataRetryRule The data retry rule.
     * @param transport The transport on which setup failure has occurred.
     * @return The failed count since last successful data setup.
     */
    private int getRetryFailedCount(@NetCapability int networkCapability,
            @NonNull DataSetupRetryRule dataRetryRule, @TransportType int transport) {
        int count = 0;
        for (int i = mDataRetryEntries.size() - 1; i >= 0; i--) {
            if (mDataRetryEntries.get(i) instanceof DataSetupRetryEntry) {
                DataSetupRetryEntry entry = (DataSetupRetryEntry) mDataRetryEntries.get(i);
                // count towards the last succeeded data setup.
                if (entry.setupRetryType == DataSetupRetryEntry.RETRY_TYPE_NETWORK_REQUESTS
                        && entry.transport == transport) {
                    if (entry.networkRequestList.isEmpty()) {
                        String msg = "Invalid data retry entry detected";
                        logl(msg);
                        loge("mDataRetryEntries=" + mDataRetryEntries);
                        AnomalyReporter.reportAnomaly(
                                UUID.fromString("afeab78c-c0b0-49fc-a51f-f766814d7aa6"),
                                msg,
                                mPhone.getCarrierId());
                        continue;
                    }
                    if (entry.networkRequestList.get(0).getApnTypeNetworkCapability()
                            == networkCapability
                            && entry.appliedDataRetryRule.equals(dataRetryRule)) {
                        if (entry.getState() == DataRetryEntry.RETRY_STATE_SUCCEEDED
                                || entry.getState() == DataRetryEntry.RETRY_STATE_CANCELLED) {
                            break;
                        }
                        count++;
                    }
                }
            }
        }
        return count;
    }

    /**
     * Schedule the data retry.
     *
     * @param dataRetryEntry The data retry entry.
     */
    private void schedule(@NonNull DataRetryEntry dataRetryEntry) {
        logl("Scheduled data retry " + dataRetryEntry
                + " hashcode=" + dataRetryEntry.hashCode());
        mDataRetryEntries.add(dataRetryEntry);
        if (mDataRetryEntries.size() >= MAXIMUM_HISTORICAL_ENTRIES) {
            // Discard the oldest retry entry.
            mDataRetryEntries.remove(0);
        }

        // When the device is in doze mode, the handler message might be extremely delayed because
        // handler uses relative system time(not counting sleep) which is inaccurate even when we
        // enter the maintenance window.
        // Therefore, we use alarm manager when we need to schedule long timers.
        if (dataRetryEntry.retryDelayMillis <= RETRY_LONG_DELAY_TIMER_THRESHOLD_MILLIS) {
            sendMessageDelayed(obtainMessage(dataRetryEntry instanceof DataSetupRetryEntry
                            ? EVENT_DATA_SETUP_RETRY : EVENT_DATA_HANDOVER_RETRY, dataRetryEntry),
                    dataRetryEntry.retryDelayMillis);
        } else {
            Intent intent = new Intent(ACTION_RETRY);
            intent.putExtra(ACTION_RETRY_EXTRA_HASHCODE, dataRetryEntry.hashCode());
            // No need to wake up the device at the exact time, the retry can wait util next time
            // the device wake up to save power.
            mAlarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME,
                    dataRetryEntry.retryElapsedTime,
                    PendingIntent.getBroadcast(mPhone.getContext(),
                            dataRetryEntry.hashCode() /*Unique identifier of this retry attempt*/,
                            intent,
                            PendingIntent.FLAG_IMMUTABLE));
        }
    }

    /**
     * Called when it's time to retry scheduled by Alarm Manager.
     * @param retryHashcode The hashcode is the unique identifier of which retry entry to retry.
     */
    private void onAlarmIntentRetry(int retryHashcode) {
        DataRetryEntry dataRetryEntry = mDataRetryEntries.stream()
                .filter(entry -> entry.hashCode() == retryHashcode)
                .findAny()
                .orElse(null);
        logl("onAlarmIntentRetry: found " + dataRetryEntry + " with hashcode " + retryHashcode);
        if (dataRetryEntry != null) {
            sendMessage(obtainMessage(dataRetryEntry instanceof DataSetupRetryEntry
                    ? EVENT_DATA_SETUP_RETRY : EVENT_DATA_HANDOVER_RETRY, dataRetryEntry));
        }
    }

    /**
     * Add the latest throttling request and report it to the clients.
     *
     * @param dataProfile The data profile that is being throttled for setup/handover retry.
     * @param networkRequestList The associated network request list when throttling happened.
     * Can be {@code null} when retry type is {@link ThrottleStatus#RETRY_TYPE_HANDOVER}.
     * @param dataNetwork The data network that is being throttled for handover retry.
     * Must be {@code null} when retryType is
     * {@link ThrottleStatus#RETRY_TYPE_NEW_CONNECTION}.
     * @param retryType The retry type when throttling expires.
     * @param transport The transport that the data profile has been throttled on.
     * @param expirationTime The expiration time of data throttling. This is the time retrieved from
     * {@link SystemClock#elapsedRealtime()}.
     */
    private void updateThrottleStatus(@NonNull DataProfile dataProfile,
            @Nullable NetworkRequestList networkRequestList,
            @Nullable DataNetwork dataNetwork, @RetryType int retryType,
            @TransportType int transport, @ElapsedRealtimeLong long expirationTime) {
        DataThrottlingEntry entry = new DataThrottlingEntry(dataProfile, networkRequestList,
                dataNetwork, transport, retryType, expirationTime);
        // Remove previous entry that contains the same data profile. Therefore it should always
        // contain at maximum all the distinct data profiles of the current subscription.
        mDataThrottlingEntries.removeIf(
                throttlingEntry -> dataProfile.equals(throttlingEntry.dataProfile));

        if (mDataThrottlingEntries.size() >= MAXIMUM_HISTORICAL_ENTRIES) {
            // If we don't see the anomaly report after U release, we should remove this check for
            // the commented reason above.
            AnomalyReporter.reportAnomaly(
                    UUID.fromString("24fd4d46-1d0f-4b13-b7d6-7bad70b8289b"),
                    "DataRetryManager throttling more than 100 data profiles",
                    mPhone.getCarrierId());
            mDataThrottlingEntries.remove(0);
        }
        logl("Add throttling entry " + entry);
        mDataThrottlingEntries.add(entry);

        // For backwards compatibility, we use RETRY_TYPE_NONE if network suggests never retry.
        final int dataRetryType = expirationTime == Long.MAX_VALUE
                ? ThrottleStatus.RETRY_TYPE_NONE : retryType;

        // Report to the clients.
        final List<ThrottleStatus> throttleStatusList = new ArrayList<>();
        if (dataProfile.getApnSetting() != null) {
            throttleStatusList.addAll(dataProfile.getApnSetting().getApnTypes().stream()
                    .map(apnType -> new ThrottleStatus.Builder()
                            .setApnType(apnType)
                            .setRetryType(dataRetryType)
                            .setSlotIndex(mPhone.getPhoneId())
                            .setThrottleExpiryTimeMillis(expirationTime)
                            .setTransportType(transport)
                            .build())
                    .collect(Collectors.toList()));
        }

        mDataRetryManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
                () -> callback.onThrottleStatusChanged(throttleStatusList)));
    }

    /**
     * Called when network/modem informed to cancelling the previous throttling request.
     *
     * @param dataProfile The data profile to be unthrottled. Note this is only supported on HAL
     * with AIDL interface. When this is set, {@code apn} must be {@code null}.
     * @param apn The apn to be unthrottled. Note this should be only used for HIDL 1.6 or below.
     * When this is set, {@code dataProfile} must be {@code null}.
     * @param transport The transport that this unthrottling request is on.
     * @param remove Whether to remove unthrottled entries from the list of entries.
     * @param retry Whether schedule retry after unthrottling.
     */
    private void onDataProfileUnthrottled(@Nullable DataProfile dataProfile, @Nullable String apn,
            @TransportType int transport, boolean remove, boolean retry) {
        log("onDataProfileUnthrottled: dataProfile=" + dataProfile + ", apn=" + apn
                + ", transport=" + AccessNetworkConstants.transportTypeToString(transport)
                + ", remove=" + remove);

        long now = SystemClock.elapsedRealtime();
        List<DataThrottlingEntry> dataUnthrottlingEntries = new ArrayList<>();
        if (dataProfile != null) {
            // For AIDL-based HAL. There should be only one entry containing this data profile.
            // Note that the data profile reconstructed from DataProfileInfo.aidl will not be
            // equal to the data profiles kept in data profile manager (due to some fields missing
            // in DataProfileInfo.aidl), so we need to get the equivalent data profile from data
            // profile manager.
            Stream<DataThrottlingEntry> stream = mDataThrottlingEntries.stream();
            stream = stream.filter(entry -> entry.expirationTimeMillis > now);
            if (dataProfile.getApnSetting() != null) {
                stream = stream
                        .filter(entry -> entry.dataProfile.getApnSetting() != null)
                        .filter(entry -> entry.dataProfile.getApnSetting().getApnName()
                                .equals(dataProfile.getApnSetting().getApnName()));
            }
            stream = stream.filter(entry -> Objects.equals(entry.dataProfile.getTrafficDescriptor(),
                    dataProfile.getTrafficDescriptor()));

            dataUnthrottlingEntries = stream.collect(Collectors.toList());
        } else if (apn != null) {
            // For HIDL 1.6 or below
            dataUnthrottlingEntries = mDataThrottlingEntries.stream()
                    .filter(entry -> entry.expirationTimeMillis > now
                            && entry.dataProfile.getApnSetting() != null
                            && apn.equals(entry.dataProfile.getApnSetting().getApnName())
                            && entry.transport == transport)
                    .collect(Collectors.toList());
        }

        if (dataUnthrottlingEntries.isEmpty()) {
            log("onDataProfileUnthrottled: Nothing to unthrottle.");
            return;
        }

        // Report to the clients.
        final List<ThrottleStatus> throttleStatusList = new ArrayList<>();
        DataProfile unthrottledProfile = null;
        int retryType = ThrottleStatus.RETRY_TYPE_NONE;
        if (dataUnthrottlingEntries.get(0).retryType == ThrottleStatus.RETRY_TYPE_NEW_CONNECTION) {
            unthrottledProfile = dataUnthrottlingEntries.get(0).dataProfile;
            retryType = ThrottleStatus.RETRY_TYPE_NEW_CONNECTION;
        } else if (dataUnthrottlingEntries.get(0).retryType == ThrottleStatus.RETRY_TYPE_HANDOVER) {
            unthrottledProfile = dataUnthrottlingEntries.get(0).dataNetwork.getDataProfile();
            retryType = ThrottleStatus.RETRY_TYPE_HANDOVER;
        }

        // Make it final so it can be used in the lambda function below.
        final int dataRetryType = retryType;

        if (unthrottledProfile != null && unthrottledProfile.getApnSetting() != null) {
            unthrottledProfile.getApnSetting().setPermanentFailed(false);
            throttleStatusList.addAll(unthrottledProfile.getApnSetting().getApnTypes().stream()
                    .map(apnType -> new ThrottleStatus.Builder()
                            .setApnType(apnType)
                            .setSlotIndex(mPhone.getPhoneId())
                            .setNoThrottle()
                            .setRetryType(dataRetryType)
                            .setTransportType(transport)
                            .build())
                    .collect(Collectors.toList()));
        }

        mDataRetryManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
                () -> callback.onThrottleStatusChanged(throttleStatusList)));

        if (unthrottledProfile != null) {
            // cancel pending retries since we will soon schedule an immediate retry
            cancelRetriesForDataProfile(unthrottledProfile, transport);
        }

        logl("onDataProfileUnthrottled: Removing the following throttling entries. "
                + dataUnthrottlingEntries);
        if (retry) {
            for (DataThrottlingEntry entry : dataUnthrottlingEntries) {
                // Immediately retry after unthrottling.
                if (entry.retryType == ThrottleStatus.RETRY_TYPE_NEW_CONNECTION) {
                    schedule(new DataSetupRetryEntry.Builder<>()
                            .setDataProfile(entry.dataProfile)
                            .setTransport(entry.transport)
                            .setSetupRetryType(DataSetupRetryEntry.RETRY_TYPE_DATA_PROFILE)
                            .setNetworkRequestList(entry.networkRequestList)
                            .setRetryDelay(0)
                            .build());
                } else if (entry.retryType == ThrottleStatus.RETRY_TYPE_HANDOVER) {
                    schedule(new DataHandoverRetryEntry.Builder<>()
                            .setDataNetwork(entry.dataNetwork)
                            .setRetryDelay(0)
                            .build());
                }
            }
        }
        if (remove) {
            mDataThrottlingEntries.removeAll(dataUnthrottlingEntries);
        }
    }

    /**
     * Cancel pending retries that uses the specified data profile, with specified target transport.
     *
     * @param dataProfile The data profile to cancel.
     * @param transport The target {@link TransportType} on which the retry to cancel.
     */
    private void cancelRetriesForDataProfile(@NonNull DataProfile dataProfile,
            @TransportType int transport) {
        logl("cancelRetriesForDataProfile: Canceling pending retries for " + dataProfile);
        mDataRetryEntries.stream()
                .filter(entry -> {
                    if (entry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED) {
                        if (entry instanceof DataSetupRetryEntry) {
                            DataSetupRetryEntry retryEntry = (DataSetupRetryEntry) entry;
                            return dataProfile.equals(retryEntry.dataProfile)
                                    && transport == retryEntry.transport;
                        } else if (entry instanceof DataHandoverRetryEntry) {
                            DataHandoverRetryEntry retryEntry = (DataHandoverRetryEntry) entry;
                            return dataProfile.equals(retryEntry.dataNetwork.getDataProfile());
                        }
                    }
                    return false;
                })
                .forEach(entry -> entry.setState(DataRetryEntry.RETRY_STATE_CANCELLED));
    }



    /**
     * Check if there is any similar network request scheduled to retry. The definition of similar
     * is that network requests have same APN capability and on the same transport.
     *
     * @param networkRequest The network request to check.
     * @param transport The transport that this request is on.
     * @return {@code true} if similar network request scheduled to retry.
     */
    public boolean isSimilarNetworkRequestRetryScheduled(
            @NonNull TelephonyNetworkRequest networkRequest, @TransportType int transport) {
        long now = SystemClock.elapsedRealtime();
        for (int i = mDataRetryEntries.size() - 1; i >= 0; i--) {
            if (mDataRetryEntries.get(i) instanceof DataSetupRetryEntry) {
                DataSetupRetryEntry entry = (DataSetupRetryEntry) mDataRetryEntries.get(i);
                if (entry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED
                        && entry.setupRetryType
                        == DataSetupRetryEntry.RETRY_TYPE_NETWORK_REQUESTS
                        && entry.retryElapsedTime > now) {
                    if (entry.networkRequestList.isEmpty()) {
                        String msg = "Invalid data retry entry detected";
                        logl(msg);
                        loge("mDataRetryEntries=" + mDataRetryEntries);
                        AnomalyReporter.reportAnomaly(
                                UUID.fromString("781af571-f55d-476d-b510-7a5381f633dc"),
                                msg,
                                mPhone.getCarrierId());
                        continue;
                    }
                    if (entry.networkRequestList.get(0).getApnTypeNetworkCapability()
                            == networkRequest.getApnTypeNetworkCapability()
                            && entry.transport == transport) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Check if a specific data profile is explicitly throttled by the network.
     *
     * @param dataProfile The data profile to check.
     * @param transport The transport that the request is on.
     * @return {@code true} if the data profile is currently throttled.
     */
    public boolean isDataProfileThrottled(@NonNull DataProfile dataProfile,
            @TransportType int transport) {
        long now = SystemClock.elapsedRealtime();
        return mDataThrottlingEntries.stream().anyMatch(
                entry -> entry.dataProfile.equals(dataProfile) && entry.expirationTimeMillis > now
                        && entry.transport == transport);
    }

    /**
     * Cancel pending scheduled handover retry entries.
     *
     * @param dataNetwork The data network that was originally scheduled for handover retry.
     */
    public void cancelPendingHandoverRetry(@NonNull DataNetwork dataNetwork) {
        sendMessage(obtainMessage(EVENT_CANCEL_PENDING_HANDOVER_RETRY, dataNetwork));
    }

    /**
     * Called when cancelling pending scheduled handover retry entries.
     *
     * @param dataNetwork The data network that was originally scheduled for handover retry.
     */
    private void onCancelPendingHandoverRetry(@NonNull DataNetwork dataNetwork) {
        mDataRetryEntries.stream()
                .filter(entry -> entry instanceof DataHandoverRetryEntry
                        && ((DataHandoverRetryEntry) entry).dataNetwork == dataNetwork
                        && entry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED)
                .forEach(entry -> entry.setState(DataRetryEntry.RETRY_STATE_CANCELLED));
    }

    /**
     * Check if there is any data handover retry scheduled.
     *
     * @param dataNetwork The network network to retry handover.
     * @return {@code true} if there is retry scheduled for this network capability.
     */
    public boolean isAnyHandoverRetryScheduled(@NonNull DataNetwork dataNetwork) {
        return mDataRetryEntries.stream()
                .filter(DataHandoverRetryEntry.class::isInstance)
                .map(DataHandoverRetryEntry.class::cast)
                .anyMatch(entry -> entry.getState() == DataRetryEntry.RETRY_STATE_NOT_RETRIED
                        && entry.dataNetwork == dataNetwork);
    }

    /**
     * Register the callback for receiving information from {@link DataRetryManager}.
     *
     * @param callback The callback.
     */
    public void registerCallback(@NonNull DataRetryManagerCallback callback) {
        mDataRetryManagerCallbacks.add(callback);
    }

    /**
     * Unregister the previously registered {@link DataRetryManagerCallback}.
     *
     * @param callback The callback to unregister.
     */
    public void unregisterCallback(@NonNull DataRetryManagerCallback callback) {
        mDataRetryManagerCallbacks.remove(callback);
    }

    /**
     * Convert reset reason to string
     *
     * @param reason The reason
     * @return The reason in string format.
     */
    private static @NonNull String resetReasonToString(int reason) {
        switch (reason) {
            case RESET_REASON_DATA_PROFILES_CHANGED:
                return "DATA_PROFILES_CHANGED";
            case RESET_REASON_RADIO_ON:
                return "RADIO_ON";
            case RESET_REASON_MODEM_RESTART:
                return "MODEM_RESTART";
            case RESET_REASON_DATA_SERVICE_BOUND:
                return "DATA_SERVICE_BOUND";
            case RESET_REASON_DATA_CONFIG_CHANGED:
                return "DATA_CONFIG_CHANGED";
            case RESET_REASON_TAC_CHANGED:
                return "TAC_CHANGED";
            default:
                return "UNKNOWN(" + reason + ")";
        }
    }

    /**
     * Log debug messages.
     * @param s debug messages
     */
    private void log(@NonNull String s) {
        Rlog.d(mLogTag, s);
    }

    /**
     * Log error messages.
     * @param s error messages
     */
    private void loge(@NonNull String s) {
        Rlog.e(mLogTag, s);
    }

    /**
     * Log verbose messages.
     * @param s debug messages.
     */
    private void logv(@NonNull String s) {
        if (VDBG) Rlog.v(mLogTag, s);
    }

    /**
     * Log debug messages and also log into the local log.
     * @param s debug messages
     */
    private void logl(@NonNull String s) {
        log(s);
        mLocalLog.log(s);
    }

    /**
     * Dump the state of DataRetryManager.
     *
     * @param fd File descriptor
     * @param printWriter Print writer
     * @param args Arguments
     */
    public void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
        IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ");
        pw.println(DataRetryManager.class.getSimpleName() + "-" + mPhone.getPhoneId() + ":");
        pw.increaseIndent();
        pw.println("Data Setup Retry rules:");
        pw.increaseIndent();
        mDataSetupRetryRuleList.forEach(pw::println);
        pw.decreaseIndent();
        pw.println("Data Handover Retry rules:");
        pw.increaseIndent();
        mDataHandoverRetryRuleList.forEach(pw::println);
        pw.decreaseIndent();

        pw.println("Retry entries:");
        pw.increaseIndent();
        for (DataRetryEntry entry : mDataRetryEntries) {
            pw.println(entry);
        }
        pw.decreaseIndent();

        pw.println("Throttling entries:");
        pw.increaseIndent();
        for (DataThrottlingEntry entry : mDataThrottlingEntries) {
            pw.println(entry);
        }
        pw.decreaseIndent();

        pw.println("Local logs:");
        pw.increaseIndent();
        mLocalLog.dump(fd, pw, args);
        pw.decreaseIndent();
        pw.decreaseIndent();
    }
}