aboutsummaryrefslogtreecommitdiff
path: root/src/mm-port-qmi.c
blob: e5a1c21437769b354b433fc620b88df2d27c534d (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
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details:
 *
 * Copyright (C) 2012-2021 Google, Inc.
 * Copyright (C) 2021 Aleksander Morgado <aleksander@aleksander.es>
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>

#include <libqmi-glib.h>

#include <ModemManager.h>
#include <mm-errors-types.h>

#include "mm-port-qmi.h"
#include "mm-port-net.h"
#include "mm-port-enums-types.h"
#include "mm-modem-helpers-qmi.h"
#include "mm-log-object.h"

#define DEFAULT_LINK_PREALLOCATED_AMOUNT 4

G_DEFINE_TYPE (MMPortQmi, mm_port_qmi, MM_TYPE_PORT)

enum {
    PROP_0,
#if defined WITH_QRTR
    PROP_NODE,
#endif
    PROP_LAST
};

static GParamSpec *properties[PROP_LAST];

typedef struct {
    QmiService     service;
    QmiClient     *client;
    MMPortQmiFlag  flag;
} ServiceInfo;

struct _MMPortQmiPrivate {
    gboolean   in_progress;
    QmiDevice *qmi_device;
    GList     *services;
    gchar     *net_driver;
#if defined WITH_QRTR
    QrtrNode  *node;
#endif

    /* endpoint info */
    gulong              endpoint_info_signal_id;
    QmiDataEndpointType endpoint_type;
    gint                endpoint_interface_number;
    /* kernel data mode */
    MMPortQmiKernelDataMode kernel_data_modes;
    /* wda settings */
    gboolean                      wda_unsupported;
    QmiWdaLinkLayerProtocol       llp;
    QmiWdaDataAggregationProtocol dap;
    guint                         max_multiplexed_links;
    /* preallocated links */
    MMPort   *preallocated_links_master;
    GArray   *preallocated_links;
    GList    *preallocated_links_setup_pending;
};

/*****************************************************************************/

static QmiClient *
lookup_client (MMPortQmi     *self,
               QmiService     service,
               MMPortQmiFlag  flag,
               gboolean       steal)
{
    GList *l;

    for (l = self->priv->services; l; l = g_list_next (l)) {
        ServiceInfo *info = l->data;

        if (info->service == service && info->flag == flag) {
            QmiClient *found;

            found = info->client;
            if (steal) {
                self->priv->services = g_list_delete_link (self->priv->services, l);
                g_free (info);
            }
            return found;
        }
    }

    return NULL;
}

QmiClient *
mm_port_qmi_peek_client (MMPortQmi *self,
                         QmiService service,
                         MMPortQmiFlag flag)
{
    return lookup_client (self, service, flag, FALSE);
}

QmiClient *
mm_port_qmi_get_client (MMPortQmi *self,
                        QmiService service,
                        MMPortQmiFlag flag)
{
    QmiClient *client;

    client = mm_port_qmi_peek_client (self, service, flag);
    return (client ? g_object_ref (client) : NULL);
}

/*****************************************************************************/

QmiDevice *
mm_port_qmi_peek_device (MMPortQmi *self)
{
    g_return_val_if_fail (MM_IS_PORT_QMI (self), NULL);

    return self->priv->qmi_device;
}

/*****************************************************************************/

static void
initialize_endpoint_info (MMPortQmi *self)
{
    MMKernelDevice *kernel_device;

    kernel_device = mm_port_peek_kernel_device (MM_PORT (self));

    if (!kernel_device)
        self->priv->endpoint_type = QMI_DATA_ENDPOINT_TYPE_UNDEFINED;
    else
        self->priv->endpoint_type = mm_port_subsys_to_qmi_endpoint_type (mm_port_get_subsys (MM_PORT (self)));

    switch (self->priv->endpoint_type) {
        case QMI_DATA_ENDPOINT_TYPE_HSUSB:
            g_assert (kernel_device);
            self->priv->endpoint_interface_number = mm_kernel_device_get_interface_number (kernel_device);
            break;
        case QMI_DATA_ENDPOINT_TYPE_EMBEDDED:
            self->priv->endpoint_interface_number = 1;
            break;
        case QMI_DATA_ENDPOINT_TYPE_PCIE:
        case QMI_DATA_ENDPOINT_TYPE_UNDEFINED:
        case QMI_DATA_ENDPOINT_TYPE_HSIC:
        case QMI_DATA_ENDPOINT_TYPE_BAM_DMUX:
        case QMI_DATA_ENDPOINT_TYPE_UNKNOWN:
        default:
            self->priv->endpoint_interface_number = 0;
            break;
    }

    mm_obj_dbg (self, "endpoint info updated: type '%s', interface number '%u'",
                qmi_data_endpoint_type_get_string (self->priv->endpoint_type),
                self->priv->endpoint_interface_number);
}

QmiDataEndpointType
mm_port_qmi_get_endpoint_type (MMPortQmi *self)
{
    return self->priv->endpoint_type;
}

guint
mm_port_qmi_get_endpoint_interface_number (MMPortQmi *self)
{
    return self->priv->endpoint_interface_number;
}

/*****************************************************************************/

void
mm_port_qmi_release_client (MMPortQmi     *self,
                            QmiService     service,
                            MMPortQmiFlag  flag)
{
    QmiClient *client;

    if (!self->priv->qmi_device)
        return;

    client = lookup_client (self, service, flag, TRUE);
    if (!client)
        return;

    mm_obj_dbg (self, "explicitly releasing client for service '%s'...", qmi_service_get_string (service));
    qmi_device_release_client (self->priv->qmi_device,
                               client,
                               QMI_DEVICE_RELEASE_CLIENT_FLAGS_RELEASE_CID,
                               3, NULL, NULL, NULL);
    g_object_unref (client);
}

/*****************************************************************************/

typedef struct {
    ServiceInfo *info;
} AllocateClientContext;

static void
allocate_client_context_free (AllocateClientContext *ctx)
{
    if (ctx->info) {
        g_assert (ctx->info->client == NULL);
        g_free (ctx->info);
    }
    g_free (ctx);
}

gboolean
mm_port_qmi_allocate_client_finish (MMPortQmi *self,
                                    GAsyncResult *res,
                                    GError **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
allocate_client_ready (QmiDevice *qmi_device,
                       GAsyncResult *res,
                       GTask *task)
{
    MMPortQmi *self;
    AllocateClientContext *ctx;
    GError *error = NULL;

    self = g_task_get_source_object (task);
    ctx = g_task_get_task_data (task);
    ctx->info->client = qmi_device_allocate_client_finish (qmi_device, res, &error);
    if (!ctx->info->client) {
        g_prefix_error (&error,
                        "Couldn't create client for service '%s': ",
                        qmi_service_get_string (ctx->info->service));
        g_task_return_error (task, error);
    } else {
        /* Move the service info to our internal list */
        self->priv->services = g_list_prepend (self->priv->services, ctx->info);
        ctx->info = NULL;
        g_task_return_boolean (task, TRUE);
    }

    g_object_unref (task);
}

void
mm_port_qmi_allocate_client (MMPortQmi *self,
                             QmiService service,
                             MMPortQmiFlag flag,
                             GCancellable *cancellable,
                             GAsyncReadyCallback callback,
                             gpointer user_data)
{
    AllocateClientContext *ctx;
    GTask *task;

    task = g_task_new (self, cancellable, callback, user_data);

    if (!mm_port_qmi_is_open (self)) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE,
                                 "Port is closed");
        g_object_unref (task);
        return;
    }

    if (!!mm_port_qmi_peek_client (self, service, flag)) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_EXISTS,
                                 "Client for service '%s' already allocated",
                                 qmi_service_get_string (service));
        g_object_unref (task);
        return;
    }

    ctx = g_new0 (AllocateClientContext, 1);
    ctx->info = g_new0 (ServiceInfo, 1);
    ctx->info->service = service;
    ctx->info->flag = flag;
    g_task_set_task_data (task, ctx, (GDestroyNotify)allocate_client_context_free);

    qmi_device_allocate_client (self->priv->qmi_device,
                                service,
                                QMI_CID_NONE,
                                10,
                                cancellable,
                                (GAsyncReadyCallback)allocate_client_ready,
                                task);
}

/*****************************************************************************/

typedef struct {
    gchar    *link_name;
    guint     mux_id;
    gboolean  setup;
} PreallocatedLinkInfo;

static void
preallocated_link_info_clear (PreallocatedLinkInfo *info)
{
    g_free (info->link_name);
}

static void
delete_preallocated_links (QmiDevice *qmi_device,
                           GArray    *preallocated_links)
{
    guint i;

    /* This link deletion cleanup may fail if the master interface is up
     * (a limitation of qmi_wwan in some kernel versions). It's just a minor
     * inconvenience really, if MM restarts they'll be all removed during
     * initialization anyway */

    for (i = 0; i < preallocated_links->len; i++) {
        PreallocatedLinkInfo *info;

        info = &g_array_index (preallocated_links, PreallocatedLinkInfo, i);
        qmi_device_delete_link (qmi_device, info->link_name, info->mux_id,
                                NULL, NULL, NULL);
    }
}

static guint
count_preallocated_links_setup (MMPortQmi *self)
{
    guint i;
    guint count = 0;

    for (i = 0; self->priv->preallocated_links && (i < self->priv->preallocated_links->len); i++) {
        PreallocatedLinkInfo *info;

        info = &g_array_index (self->priv->preallocated_links, PreallocatedLinkInfo, i);
        if (info->setup)
            count++;
    }

    return count;
}

static gboolean
release_preallocated_link (MMPortQmi    *self,
                           const gchar  *link_name,
                           guint         mux_id,
                           GError     **error)
{
    guint i;

    for (i = 0; self->priv->preallocated_links && (i < self->priv->preallocated_links->len); i++) {
        PreallocatedLinkInfo *info;

        info = &g_array_index (self->priv->preallocated_links, PreallocatedLinkInfo, i);
        if (!info->setup || (g_strcmp0 (info->link_name, link_name) != 0) || (info->mux_id != mux_id))
            continue;

        info->setup = FALSE;
        return TRUE;
    }

    g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                 "No preallocated link found to release");
    return FALSE;
}

static gboolean
acquire_preallocated_link (MMPortQmi  *self,
                           MMPort     *master,
                           gchar     **link_name,
                           guint      *mux_id,
                           GError    **error)
{
    guint i;

    if (!self->priv->qmi_device) {
        g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_ABORTED,
                     "port is closed");
        return FALSE;
    }

    if (!self->priv->preallocated_links || !self->priv->preallocated_links_master) {
        g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                     "No preallocated links available");
        return FALSE;
    }

    if ((master != self->priv->preallocated_links_master) &&
        (g_strcmp0 (mm_port_get_device (master), mm_port_get_device (self->priv->preallocated_links_master)) != 0)) {
        g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                     "Preallocated links available in 'net/%s', not in 'net/%s'",
                     mm_port_get_device (self->priv->preallocated_links_master),
                     mm_port_get_device (master));
        return FALSE;
    }

    for (i = 0; i < self->priv->preallocated_links->len; i++) {
        PreallocatedLinkInfo *info;

        info = &g_array_index (self->priv->preallocated_links, PreallocatedLinkInfo, i);
        if (info->setup)
            continue;

        info->setup = TRUE;
        *link_name = g_strdup (info->link_name);
        *mux_id = info->mux_id;
        return TRUE;
    }

    g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                 "No more preallocated links available");
    return FALSE;
}

/*****************************************************************************/

typedef struct {
    QmiDevice *qmi_device;
    MMPort    *data;
    GArray    *preallocated_links;
} InitializePreallocatedLinksContext;

static void
initialize_preallocated_links_context_free (InitializePreallocatedLinksContext *ctx)
{
    if (ctx->preallocated_links) {
        delete_preallocated_links (ctx->qmi_device, ctx->preallocated_links);
        g_array_unref (ctx->preallocated_links);
    }
    g_object_unref (ctx->qmi_device);
    g_object_unref (ctx->data);
    g_slice_free (InitializePreallocatedLinksContext, ctx);
}

static GArray *
initialize_preallocated_links_finish (MMPortQmi     *self,
                                      GAsyncResult  *res,
                                      GError       **error)
{
    return g_task_propagate_pointer (G_TASK (res), error);
}

static void initialize_preallocated_links_next (GTask *task);

static void
device_add_link_preallocated_ready (QmiDevice     *device,
                                    GAsyncResult  *res,
                                    GTask         *task)
{
    InitializePreallocatedLinksContext *ctx;
    GError                             *error = NULL;
    PreallocatedLinkInfo                info = { NULL, 0, FALSE };

    ctx = g_task_get_task_data (task);

    info.link_name = qmi_device_add_link_finish (device, res, &info.mux_id, &error);
    if (!info.link_name) {
        g_prefix_error (&error, "failed to add preallocated link (%u/%u) for device: ",
                        ctx->preallocated_links->len + 1, DEFAULT_LINK_PREALLOCATED_AMOUNT);
        g_task_return_error (task, error);
        return;
    }

    g_array_append_val (ctx->preallocated_links, info);
    initialize_preallocated_links_next (task);
}

static void
initialize_preallocated_links_next (GTask *task)
{
    MMPortQmi                          *self;
    InitializePreallocatedLinksContext *ctx;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    /* if we were closed while allocating, bad thing, abort */
    if (!self->priv->qmi_device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_ABORTED, "port is closed");
        g_object_unref (task);
        return;
    }

    if (ctx->preallocated_links->len == DEFAULT_LINK_PREALLOCATED_AMOUNT) {
        g_task_return_pointer (task, g_steal_pointer (&ctx->preallocated_links), (GDestroyNotify)g_array_unref);
        g_object_unref (task);
        return;
    }

    qmi_device_add_link (self->priv->qmi_device,
                         ctx->preallocated_links->len + 1,
                         mm_kernel_device_get_name (mm_port_peek_kernel_device (ctx->data)),
                         "ignored", /* n/a in qmi_wwan add_mux */
                         NULL,
                         (GAsyncReadyCallback) device_add_link_preallocated_ready,
                         task);
}

static void
initialize_preallocated_links (MMPortQmi           *self,
                               GAsyncReadyCallback  callback,
                               gpointer             user_data)
{
    InitializePreallocatedLinksContext *ctx;
    GTask                              *task;

    task = g_task_new (self, NULL, callback, user_data);

    ctx = g_slice_new0 (InitializePreallocatedLinksContext);
    ctx->qmi_device = g_object_ref (self->priv->qmi_device);
    ctx->data = g_object_ref (self->priv->preallocated_links_master);
    ctx->preallocated_links = g_array_sized_new (FALSE, FALSE, sizeof (PreallocatedLinkInfo), DEFAULT_LINK_PREALLOCATED_AMOUNT);
    g_array_set_clear_func (ctx->preallocated_links, (GDestroyNotify)preallocated_link_info_clear);
    g_task_set_task_data (task, ctx, (GDestroyNotify)initialize_preallocated_links_context_free);

    initialize_preallocated_links_next (task);
}

/*****************************************************************************/

typedef struct {
    MMPort *master;
    gchar  *link_name;
    guint   mux_id;
} SetupLinkContext;

static void
setup_link_context_free (SetupLinkContext *ctx)
{
    g_free (ctx->link_name);
    g_clear_object (&ctx->master);
    g_slice_free (SetupLinkContext, ctx);
}

gchar *
mm_port_qmi_setup_link_finish (MMPortQmi     *self,
                               GAsyncResult  *res,
                               guint         *mux_id,
                               GError       **error)
{
    SetupLinkContext *ctx;

    if (!g_task_propagate_boolean (G_TASK (res), error))
        return NULL;

    ctx = g_task_get_task_data (G_TASK (res));
    if (mux_id)
        *mux_id = ctx->mux_id;
    return g_steal_pointer (&ctx->link_name);
}

static void
device_add_link_ready (QmiDevice    *device,
                       GAsyncResult *res,
                       GTask        *task)
{
    SetupLinkContext *ctx;
    GError           *error = NULL;

    ctx = g_task_get_task_data (task);

    ctx->link_name = qmi_device_add_link_with_flags_finish (device, res, &ctx->mux_id, &error);
    if (!ctx->link_name) {
        g_prefix_error (&error, "failed to add link for device: ");
        g_task_return_error (task, error);
    } else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

static void
setup_preallocated_link (GTask *task)
{
    MMPortQmi        *self;
    SetupLinkContext *ctx;
    GError           *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (!acquire_preallocated_link (self, ctx->master, &ctx->link_name, &ctx->mux_id, &error))
        g_task_return_error (task, error);
    else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

static void
initialize_preallocated_links_ready (MMPortQmi    *self,
                                     GAsyncResult *res,
                                     GTask        *task)
{
    g_autoptr(GError) error = NULL;

    g_assert (!self->priv->preallocated_links);
    self->priv->preallocated_links = initialize_preallocated_links_finish (self, res, &error);
    if (!self->priv->preallocated_links) {
        /* We need to fail this task and all the additional tasks also pending */
        g_task_return_error (task, g_error_copy (error));
        g_object_unref (task);
        while (self->priv->preallocated_links_setup_pending) {
            g_task_return_error (self->priv->preallocated_links_setup_pending->data, g_error_copy (error));
            g_object_unref (self->priv->preallocated_links_setup_pending->data);
            self->priv->preallocated_links_setup_pending = g_list_delete_link (self->priv->preallocated_links_setup_pending,
                                                                               self->priv->preallocated_links_setup_pending);
        }
        /* and reset back the master, because we're not really initialized */
        g_clear_object (&self->priv->preallocated_links_master);
        return;
    }

    /* Now we know preallocated links are available, complete our task and all the pending ones */
    setup_preallocated_link (task);
    while (self->priv->preallocated_links_setup_pending) {
        setup_preallocated_link (self->priv->preallocated_links_setup_pending->data);
        self->priv->preallocated_links_setup_pending = g_list_delete_link (self->priv->preallocated_links_setup_pending,
                                                                           self->priv->preallocated_links_setup_pending);
    }
}

void
mm_port_qmi_setup_link (MMPortQmi           *self,
                        MMPort              *data,
                        const gchar         *link_prefix_hint,
                        GAsyncReadyCallback  callback,
                        gpointer             user_data)
{
    SetupLinkContext *ctx;
    GTask            *task;

    task = g_task_new (self, NULL, callback, user_data);

    if (!self->priv->qmi_device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Port is not open");
        g_object_unref (task);
        return;
    }

    if (!(self->priv->kernel_data_modes & (MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN))) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Multiplex support not available in kernel");
        g_object_unref (task);
        return;
    }

    if (!MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (self->priv->dap)) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Aggregation not enabled");
        g_object_unref (task);
        return;
    }

    ctx = g_slice_new0 (SetupLinkContext);
    ctx->master = g_object_ref (data);
    ctx->mux_id = QMI_DEVICE_MUX_ID_UNBOUND;
    g_task_set_task_data (task, ctx, (GDestroyNotify) setup_link_context_free);

    /* When using rmnet, just try to add link in the QmiDevice */
    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET) {
        QmiDeviceAddLinkFlags flags = QMI_DEVICE_ADD_LINK_FLAGS_NONE;

        /* This may not be fully right, but it's the only way forward we know
         * right now for the Qualcomm SoCs based on QRTR+IPA, where QMAPV4 is
         * used and the device has checksum offload enabled by default, so we
         * should create the link with special flags. Ideally, we would have a
         * way to know in advance whether the checksum offload flags are needed
         * or not.
         */
        if (self->priv->dap == QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAPV4)
            flags = (QMI_DEVICE_ADD_LINK_FLAGS_INGRESS_MAP_CKSUMV4 | QMI_DEVICE_ADD_LINK_FLAGS_EGRESS_MAP_CKSUMV4);

        qmi_device_add_link_with_flags (self->priv->qmi_device,
                                        QMI_DEVICE_MUX_ID_AUTOMATIC,
                                        mm_kernel_device_get_name (mm_port_peek_kernel_device (data)),
                                        link_prefix_hint,
                                        flags,
                                        NULL,
                                        (GAsyncReadyCallback) device_add_link_ready,
                                        task);
        return;
    }

    /* For qmi_wwan, use preallocated links */
    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN) {
        if (self->priv->preallocated_links) {
            setup_preallocated_link (task);
            return;
        }

        /* We must make sure we don't run this procedure in parallel (e.g. if multiple
         * connection attempts reach at the same time), so if we're told the preallocated
         * links are already being initialized (master is set) but the array didn't exist,
         * queue our task for completion once we're fully initialized */
        if (self->priv->preallocated_links_master) {
            self->priv->preallocated_links_setup_pending = g_list_append (self->priv->preallocated_links_setup_pending, task);
            return;
        }

        /* Store master to flag that we're initializing preallocated links */
        self->priv->preallocated_links_master = g_object_ref (data);
        initialize_preallocated_links (self,
                                       (GAsyncReadyCallback) initialize_preallocated_links_ready,
                                       task);
        return;
    }

    g_assert_not_reached ();
}

/*****************************************************************************/

gboolean
mm_port_qmi_cleanup_link_finish (MMPortQmi     *self,
                                 GAsyncResult  *res,
                                 GError       **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
device_delete_link_ready (QmiDevice    *device,
                          GAsyncResult *res,
                          GTask        *task)
{
    GError *error = NULL;

    if (!qmi_device_delete_link_finish (device, res, &error))
        g_task_return_error (task, error);
    else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

void
mm_port_qmi_cleanup_link (MMPortQmi           *self,
                          const gchar         *link_name,
                          guint                mux_id,
                          GAsyncReadyCallback  callback,
                          gpointer             user_data)
{
    GTask  *task;
    GError *error = NULL;

    task = g_task_new (self, NULL, callback, user_data);

    if (!self->priv->qmi_device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Port is not open");
        g_object_unref (task);
        return;
    }

    if (!(self->priv->kernel_data_modes & (MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN))) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Multiplex support not available in kernel");
        g_object_unref (task);
        return;
    }

    if (!MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (self->priv->dap)) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Aggregation not enabled");
        g_object_unref (task);
        return;
    }

    /* When using rmnet, just try to add link in the QmiDevice */
    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET) {
        qmi_device_delete_link (self->priv->qmi_device,
                                link_name,
                                mux_id,
                                NULL,
                                (GAsyncReadyCallback) device_delete_link_ready,
                                task);
        return;
    }

    /* For qmi_wwan, use preallocated links */
    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN) {
        if (!release_preallocated_link (self, link_name, mux_id, &error))
            g_task_return_error (task, error);
        else
            g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return;
    }

    g_assert_not_reached ();
}

/*****************************************************************************/

typedef struct {
    QmiDevice *device;
    MMPort    *data;
} InternalResetContext;

static void
internal_reset_context_free (InternalResetContext *ctx)
{
    g_clear_object (&ctx->device);
    g_clear_object (&ctx->data);
    g_slice_free (InternalResetContext, ctx);
}

static gboolean
internal_reset_finish (MMPortQmi     *self,
                       GAsyncResult  *res,
                       GError       **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
delete_all_links_ready (QmiDevice    *device,
                        GAsyncResult *res,
                        GTask        *task)
{
    MMPortQmi            *self;
    InternalResetContext *ctx;
    GError               *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    /* link deletion not fatal, it may happen if in 802.3 already */
    if (!qmi_device_delete_all_links_finish (device, res, &error)) {
        mm_obj_dbg (self, "couldn't delete all links: %s", error->message);
        g_clear_error (&error);
    }

    /* expected data format only applicable to qmi_wwan */
    if (g_strcmp0 (self->priv->net_driver, "qmi_wwan") == 0) {
        mm_obj_dbg (self, "reseting expected kernel data format to 802.3 in data interface '%s'",
                    mm_port_get_device (MM_PORT (ctx->data)));
        if (!qmi_device_set_expected_data_format (ctx->device, QMI_DEVICE_EXPECTED_DATA_FORMAT_802_3, &error)) {
            g_task_return_error (task, error);
            g_object_unref (task);
            return;
        }
    }

    g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

static void
net_link_down_ready (MMPortNet    *data,
                     GAsyncResult *res,
                     GTask        *task)
{
    MMPortQmi            *self;
    InternalResetContext *ctx;
    GError               *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (!mm_port_net_link_setup_finish (data, res, &error)) {
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    /* first, delete all links found, if any */
    mm_obj_dbg (self, "deleting all links in data interface '%s'",
                mm_port_get_device (ctx->data));
    qmi_device_delete_all_links (ctx->device,
                                 mm_port_get_device (ctx->data),
                                 NULL,
                                 (GAsyncReadyCallback)delete_all_links_ready,
                                 task);
}

static void
internal_reset (MMPortQmi           *self,
                MMPort              *data,
                QmiDevice           *device,
                GAsyncReadyCallback  callback,
                gpointer             user_data)
{
    GTask                *task;
    InternalResetContext *ctx;

    task = g_task_new (self, NULL, callback, user_data);

    ctx = g_slice_new0 (InternalResetContext);
    ctx->data = g_object_ref (data);
    ctx->device = g_object_ref (device);
    g_task_set_task_data (task, ctx, (GDestroyNotify) internal_reset_context_free);

    /* first, bring down master interface */
    mm_obj_dbg (self, "bringing down data interface '%s'",
                mm_port_get_device (ctx->data));
    mm_port_net_link_setup (MM_PORT_NET (ctx->data),
                            FALSE,
                            MM_PORT_NET_MTU_DEFAULT,
                            NULL,
                            (GAsyncReadyCallback) net_link_down_ready,
                            task);
}

/*****************************************************************************/

typedef struct {
    QmiDevice *device;
    MMPort    *data;
} ResetContext;

static void
reset_context_free (ResetContext *ctx)
{
    g_clear_object (&ctx->device);
    g_clear_object (&ctx->data);
    g_slice_free (ResetContext, ctx);
}

gboolean
mm_port_qmi_reset_finish (MMPortQmi     *self,
                          GAsyncResult  *res,
                          GError       **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
internal_reset_ready (MMPortQmi    *self,
                      GAsyncResult *res,
                      GTask        *task)
{
    GError *error = NULL;

    if (!internal_reset_finish (self, res, &error))
        g_task_return_error (task, error);
    else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

static void
reset_device_new_ready (GObject      *source,
                        GAsyncResult *res,
                        GTask        *task)
{
    MMPortQmi    *self;
    ResetContext *ctx;
    GError       *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    ctx->device = qmi_device_new_finish (res, &error);
    if (!ctx->device) {
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    internal_reset (self,
                    ctx->data,
                    ctx->device,
                    (GAsyncReadyCallback) internal_reset_ready,
                    task);
}

void
mm_port_qmi_reset (MMPortQmi           *self,
                   MMPort              *data,
                   GAsyncReadyCallback  callback,
                   gpointer             user_data)
{
    GTask            *task;
    ResetContext     *ctx;
    g_autoptr(GFile)  file = NULL;
    g_autofree gchar *fullpath = NULL;

    task = g_task_new (self, NULL, callback, user_data);

    if (self->priv->qmi_device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Port is already open");
        g_object_unref (task);
        return;
    }

    ctx = g_slice_new0 (ResetContext);
    ctx->data = g_object_ref (data);
    g_task_set_task_data (task, ctx, (GDestroyNotify) reset_context_free);

    fullpath = g_strdup_printf ("/dev/%s", mm_port_get_device (MM_PORT (self)));
    file = g_file_new_for_path (fullpath);

    qmi_device_new (file, NULL,
                    (GAsyncReadyCallback) reset_device_new_ready,
                    task);
}

/*****************************************************************************/

MMPortQmiKernelDataMode
mm_port_qmi_get_kernel_data_modes (MMPortQmi *self)
{
    return self->priv->kernel_data_modes;
}

QmiWdaLinkLayerProtocol
mm_port_qmi_get_link_layer_protocol (MMPortQmi *self)
{
    return self->priv->llp;
}

QmiWdaDataAggregationProtocol
mm_port_qmi_get_data_aggregation_protocol (MMPortQmi *self)
{
    return self->priv->dap;
}

guint
mm_port_qmi_get_max_multiplexed_links (MMPortQmi *self)
{
    return self->priv->max_multiplexed_links;
}

/*****************************************************************************/

static MMPortQmiKernelDataMode
load_current_kernel_data_modes (MMPortQmi *self,
                                QmiDevice *device)
{
    /* For BAM-DMUX based setups, raw-ip only and no multiplexing */
    if (g_strcmp0 (self->priv->net_driver, "bam-dmux") == 0)
        return MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;

    /* For IPA based setups, always rmnet multiplexing */
    if (g_strcmp0 (self->priv->net_driver, "ipa") == 0)
        return MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET;

    /* For USB based setups, query kernel */
    if (g_strcmp0 (self->priv->net_driver, "qmi_wwan") == 0) {
        switch (qmi_device_get_expected_data_format (device, NULL)) {
        case QMI_DEVICE_EXPECTED_DATA_FORMAT_QMAP_PASS_THROUGH:
            return MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET;
        case QMI_DEVICE_EXPECTED_DATA_FORMAT_RAW_IP:
            if (qmi_device_check_link_supported (device, NULL))
                return (MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN);
            return MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;
        case QMI_DEVICE_EXPECTED_DATA_FORMAT_UNKNOWN:
            /* If the expected data format is unknown, it means the kernel in use
             * doesn't have support for querying it; therefore it's 802.3 */
        case QMI_DEVICE_EXPECTED_DATA_FORMAT_802_3:
            return MM_PORT_QMI_KERNEL_DATA_MODE_802_3;
        default:
            g_assert_not_reached ();
            return MM_PORT_QMI_KERNEL_DATA_MODE_NONE;
        }
    }

    /* For any driver, assume raw-ip only */
    return MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;
}

static MMPortQmiKernelDataMode
load_supported_kernel_data_modes (MMPortQmi *self,
                                  QmiDevice *device)
{
    /* For BAM-DMUX based setups, raw-ip only and no multiplexing */
    if (g_strcmp0 (self->priv->net_driver, "bam-dmux") == 0)
        return MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;

    /* For IPA based setups, always rmnet multiplexing */
    if (g_strcmp0 (self->priv->net_driver, "ipa") == 0)
        return MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET;

    /* For USB based setups, we may have all supported */
    if (g_strcmp0 (self->priv->net_driver, "qmi_wwan") == 0) {
        MMPortQmiKernelDataMode supported = MM_PORT_QMI_KERNEL_DATA_MODE_802_3;

        /* If raw-ip is not supported, muxing is also not supported */
        if (qmi_device_check_expected_data_format_supported (device, QMI_DEVICE_EXPECTED_DATA_FORMAT_RAW_IP, NULL)) {
            supported |= MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;

            /* We switch to raw-ip to see if we can do link management with qmi_wwan.
             * This switch would not truly be required, but the logic afterwards is robust
             * enough to support this, nothing to worry about */
            if (qmi_device_set_expected_data_format (device, QMI_DEVICE_EXPECTED_DATA_FORMAT_RAW_IP, NULL) &&
                qmi_device_check_link_supported (device, NULL))
                supported |= MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN;

            if (qmi_device_check_expected_data_format_supported (device, QMI_DEVICE_EXPECTED_DATA_FORMAT_QMAP_PASS_THROUGH, NULL))
                supported |= MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET;
        }

        return supported;
    }

    /* For any driver, assume raw-ip only */
    return MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP;
}

/*****************************************************************************/

#define DEFAULT_DOWNLINK_DATA_AGGREGATION_MAX_SIZE      32768
#define DEFAULT_DOWNLINK_DATA_AGGREGATION_MAX_DATAGRAMS 32

typedef struct {
    MMPortQmiKernelDataMode       kernel_data_mode;
    QmiWdaLinkLayerProtocol       wda_llp;
    QmiWdaDataAggregationProtocol wda_dap;
} DataFormatCombination;

static const DataFormatCombination data_format_combinations[] = {
    { MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET,   QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAPV5   },
    { MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET,   QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAPV4   },
    { MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET,   QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAP     },
    { MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN, QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAPV5   },
    { MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN, QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_QMAP     },
    { MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP,      QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP, QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED },
    { MM_PORT_QMI_KERNEL_DATA_MODE_802_3,       QMI_WDA_LINK_LAYER_PROTOCOL_802_3,  QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED },
};

typedef enum {
    INTERNAL_SETUP_DATA_FORMAT_STEP_FIRST,
    INTERNAL_SETUP_DATA_FORMAT_STEP_SUPPORTED_KERNEL_DATA_MODES,
    INTERNAL_SETUP_DATA_FORMAT_STEP_RETRY,
    INTERNAL_SETUP_DATA_FORMAT_STEP_CURRENT_KERNEL_DATA_MODES,
    INTERNAL_SETUP_DATA_FORMAT_STEP_ALLOCATE_WDA_CLIENT,
    INTERNAL_SETUP_DATA_FORMAT_STEP_GET_WDA_DATA_FORMAT,
    INTERNAL_SETUP_DATA_FORMAT_STEP_QUERY_DONE,
    INTERNAL_SETUP_DATA_FORMAT_STEP_CHECK_DATA_FORMAT_COMBINATION,
    INTERNAL_SETUP_DATA_FORMAT_STEP_SYNC_WDA_DATA_FORMAT,
    INTERNAL_SETUP_DATA_FORMAT_STEP_SETUP_MASTER_MTU,
    INTERNAL_SETUP_DATA_FORMAT_STEP_SYNC_KERNEL_DATA_MODE,
    INTERNAL_SETUP_DATA_FORMAT_STEP_LAST,
} InternalSetupDataFormatStep;

typedef struct {
    QmiDevice                      *device;
    MMPort                         *data;
    MMPortQmiSetupDataFormatAction  action;

    InternalSetupDataFormatStep step;
    gboolean                    use_endpoint;
    gint                        data_format_combination_i;

    /* kernel data modes */
    MMPortQmiKernelDataMode kernel_data_modes_current;
    MMPortQmiKernelDataMode kernel_data_modes_requested;
    MMPortQmiKernelDataMode kernel_data_modes_supported;

    /* configured device data format */
    QmiClient                     *wda;
    QmiWdaLinkLayerProtocol        wda_llp_current;
    QmiWdaLinkLayerProtocol        wda_llp_requested;
    QmiWdaDataAggregationProtocol  wda_ul_dap_current;
    QmiWdaDataAggregationProtocol  wda_ul_dap_requested;
    QmiWdaDataAggregationProtocol  wda_dl_dap_current;
    QmiWdaDataAggregationProtocol  wda_dl_dap_requested;
    guint32                        wda_dl_dap_max_datagrams_current;
    guint32                        wda_dl_dap_max_size_current;
    gboolean                       wda_dap_supported;
} InternalSetupDataFormatContext;

static void
internal_setup_data_format_context_free (InternalSetupDataFormatContext *ctx)
{
    if (ctx->wda && ctx->device)
        qmi_device_release_client (ctx->device,
                                   ctx->wda,
                                   QMI_DEVICE_RELEASE_CLIENT_FLAGS_RELEASE_CID,
                                   3, NULL, NULL, NULL);
    g_clear_object (&ctx->wda);
    g_clear_object (&ctx->data);
    g_clear_object (&ctx->device);
    g_slice_free (InternalSetupDataFormatContext, ctx);
}

static gboolean
internal_setup_data_format_finish (MMPortQmi                      *self,
                                   GAsyncResult                   *res,
                                   MMPortQmiKernelDataMode        *out_kernel_data_modes,
                                   QmiWdaLinkLayerProtocol        *out_llp,
                                   QmiWdaDataAggregationProtocol  *out_dap,
                                   guint                          *out_max_multiplexed_links,
                                   GError                        **error)
{
    InternalSetupDataFormatContext *ctx;

    if (!g_task_propagate_boolean (G_TASK (res), error))
        return FALSE;

    ctx = g_task_get_task_data (G_TASK (res));
    *out_kernel_data_modes = ctx->kernel_data_modes_current;
    *out_llp = ctx->wda_llp_current;
    g_assert (ctx->wda_dl_dap_current == ctx->wda_ul_dap_current);
    *out_dap = ctx->wda_dl_dap_current;

    if (out_max_multiplexed_links) {
        if (!ctx->wda_dap_supported) {
            *out_max_multiplexed_links = 0;
            mm_obj_dbg (self, "wda data aggregation protocol unsupported: no multiplexed bearers allowed");
        } else {
            /* if multiplex backend may be rmnet, MAX-MIN */
            if (ctx->kernel_data_modes_supported & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET) {
                *out_max_multiplexed_links = 1 + (QMI_DEVICE_MUX_ID_MAX - QMI_DEVICE_MUX_ID_MIN);
                mm_obj_dbg (self, "rmnet link management supported: %u multiplexed bearers allowed",
                            *out_max_multiplexed_links);
            }
            /* if multiplex backend may be qmi_wwan, the max preallocated amount :/  */
            else if (ctx->kernel_data_modes_supported & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN) {
                *out_max_multiplexed_links = DEFAULT_LINK_PREALLOCATED_AMOUNT;
                mm_obj_dbg (self, "qmi_wwan link management supported: %u multiplexed bearers allowed",
                            *out_max_multiplexed_links);
            } else {
                *out_max_multiplexed_links = 0;
                mm_obj_dbg (self, "link management unsupported: no multiplexed bearers allowed");
            }
        }
    }

    return TRUE;
}

static void internal_setup_data_format_context_step (GTask *task);

static void
sync_kernel_data_mode (GTask *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;
    GError                         *error = NULL;
    g_autofree gchar               *kernel_data_modes_current_str = NULL;
    g_autofree gchar               *kernel_data_modes_requested_str = NULL;
    QmiDeviceExpectedDataFormat     expected_data_format_requested = QMI_DEVICE_EXPECTED_DATA_FORMAT_UNKNOWN;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    kernel_data_modes_current_str = mm_port_qmi_kernel_data_mode_build_string_from_mask (ctx->kernel_data_modes_current);
    kernel_data_modes_requested_str = mm_port_qmi_kernel_data_mode_build_string_from_mask (ctx->kernel_data_modes_requested);

    mm_obj_dbg (self, "Updating kernel expected data format: %s -> %s",
                kernel_data_modes_current_str, kernel_data_modes_requested_str);

    if (ctx->kernel_data_modes_requested & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET)
        expected_data_format_requested = QMI_DEVICE_EXPECTED_DATA_FORMAT_QMAP_PASS_THROUGH;
    else if (ctx->kernel_data_modes_requested & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN)
        expected_data_format_requested = QMI_DEVICE_EXPECTED_DATA_FORMAT_RAW_IP;
    else if (ctx->kernel_data_modes_requested & MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP)
        expected_data_format_requested = QMI_DEVICE_EXPECTED_DATA_FORMAT_RAW_IP;
    else if (ctx->kernel_data_modes_requested & MM_PORT_QMI_KERNEL_DATA_MODE_802_3)
        expected_data_format_requested = QMI_DEVICE_EXPECTED_DATA_FORMAT_802_3;
    else
        g_assert_not_reached ();

    if (!qmi_device_set_expected_data_format (ctx->device, expected_data_format_requested, &error)) {
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    /* request reload */
    ctx->kernel_data_modes_current = MM_PORT_QMI_KERNEL_DATA_MODE_NONE;

    /* Go on to next step */
    ctx->step++;
    internal_setup_data_format_context_step (task);
}

static void
master_mtu_ready (MMPortNet    *data,
                  GAsyncResult *res,
                  GTask        *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;
    GError                         *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (!mm_port_net_link_setup_finish (data, res, &error)) {
        mm_obj_dbg (self, "failed to setup master MTU: %s", error->message);
        g_clear_error (&error);
    }

    /* Go on to next step */
    ctx->step++;
    internal_setup_data_format_context_step (task);
}

static void
setup_master_mtu (GTask *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;
    guint                           mtu = MM_PORT_NET_MTU_DEFAULT;
    GError                         *error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data     (task);

    /* qmi_wwan add_mux/del_mux based logic requires master mtu set to the maximum data
     * aggregation size */
    if (ctx->kernel_data_modes_requested & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN) {
        /* Load current max datagram size supported */
        if (MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (ctx->wda_dl_dap_requested))
            mtu = ctx->wda_dl_dap_max_size_current;

        /* If no max aggregation size was specified by the modem (e.g. if we requested QMAP
         * aggregation protocol but the modem doesn't support it), skip */
        if (!mtu) {
            mm_obj_dbg (self, "ignoring master mtu setup");
            ctx->step++;
            internal_setup_data_format_context_step (task);
            return;
        }
    }

    /* Master MTU change can only be changed while in 802-3 */
    if (!(ctx->kernel_data_modes_current & MM_PORT_QMI_KERNEL_DATA_MODE_802_3)) {
        mm_obj_dbg (self, "Updating kernel expected data format to 802-3 temporarily for master mtu setup");
        if (!qmi_device_set_expected_data_format (ctx->device, QMI_DEVICE_EXPECTED_DATA_FORMAT_802_3, &error)) {
            g_prefix_error (&error, "Failed setting up 802.3 kernel data format before master mtu change: ");
            g_task_return_error (task, error);
            g_object_unref (task);
            return;
        }
        /* the sync kernel data mode step will fix this appropriately */
        ctx->kernel_data_modes_current = MM_PORT_QMI_KERNEL_DATA_MODE_802_3;
    }

    mm_obj_dbg (self, "setting up master mtu: %u bytes", mtu);
    mm_port_net_link_setup (MM_PORT_NET (ctx->data),
                            FALSE,
                            mtu,
                            NULL,
                            (GAsyncReadyCallback) master_mtu_ready,
                            task);
}

static void
set_data_format_ready (QmiClientWda *client,
                       GAsyncResult *res,
                       GTask        *task)
{
    InternalSetupDataFormatContext              *ctx;
    g_autoptr(QmiMessageWdaSetDataFormatOutput)  output = NULL;
    g_autoptr(GError)                            error = NULL;

    ctx = g_task_get_task_data (task);

    output = qmi_client_wda_set_data_format_finish (client, res, &error);
    if (!output || !qmi_message_wda_set_data_format_output_get_result (output, &error)) {
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    /* store max aggregation size so that the master MTU logic works */
    qmi_message_wda_set_data_format_output_get_downlink_data_aggregation_max_size (output, &ctx->wda_dl_dap_max_size_current, NULL);

    /* request reload */
    ctx->wda_llp_current = QMI_WDA_LINK_LAYER_PROTOCOL_UNKNOWN;
    ctx->wda_ul_dap_current = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;
    ctx->wda_dl_dap_current = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;

    /* Go on to next step */
    ctx->step++;
    internal_setup_data_format_context_step (task);
}

static void
sync_wda_data_format (GTask *task)
{
    MMPortQmi                                  *self;
    InternalSetupDataFormatContext             *ctx;
    g_autoptr(QmiMessageWdaSetDataFormatInput)  input = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (ctx->wda_llp_current != ctx->wda_llp_requested)
        mm_obj_dbg (self, "Updating device link layer protocol: %s -> %s",
                    qmi_wda_link_layer_protocol_get_string (ctx->wda_llp_current),
                    qmi_wda_link_layer_protocol_get_string (ctx->wda_llp_requested));

    if (ctx->wda_ul_dap_current != ctx->wda_ul_dap_requested)
        mm_obj_dbg (self, "Updating device uplink data aggregation protocol: %s -> %s",
                    qmi_wda_data_aggregation_protocol_get_string (ctx->wda_ul_dap_current),
                    qmi_wda_data_aggregation_protocol_get_string (ctx->wda_ul_dap_requested));

    if (ctx->wda_dl_dap_current != ctx->wda_dl_dap_requested)
        mm_obj_dbg (self, "Updating device downlink data aggregation protocol: %s -> %s",
                    qmi_wda_data_aggregation_protocol_get_string (ctx->wda_dl_dap_current),
                    qmi_wda_data_aggregation_protocol_get_string (ctx->wda_dl_dap_requested));

    input = qmi_message_wda_set_data_format_input_new ();
    qmi_message_wda_set_data_format_input_set_link_layer_protocol (input, ctx->wda_llp_requested, NULL);
    qmi_message_wda_set_data_format_input_set_uplink_data_aggregation_protocol (input, ctx->wda_ul_dap_requested, NULL);
    qmi_message_wda_set_data_format_input_set_downlink_data_aggregation_protocol (input, ctx->wda_dl_dap_requested, NULL);
    if (ctx->wda_dl_dap_requested != QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED) {
        qmi_message_wda_set_data_format_input_set_downlink_data_aggregation_max_size (input, DEFAULT_DOWNLINK_DATA_AGGREGATION_MAX_SIZE, NULL);
        qmi_message_wda_set_data_format_input_set_downlink_data_aggregation_max_datagrams (input, DEFAULT_DOWNLINK_DATA_AGGREGATION_MAX_DATAGRAMS, NULL);
    }
    if (ctx->use_endpoint)
        qmi_message_wda_set_data_format_input_set_endpoint_info (input, self->priv->endpoint_type, self->priv->endpoint_interface_number, NULL);

    qmi_client_wda_set_data_format (QMI_CLIENT_WDA (ctx->wda),
                                    input,
                                    10,
                                    g_task_get_cancellable (task),
                                    (GAsyncReadyCallback) set_data_format_ready,
                                    task);
}

static gboolean
setup_data_format_completed (GTask *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;

    self = g_task_get_source_object (task);
    ctx = g_task_get_task_data (task);

    /* if aggregation enabled we require link management supported; this covers the
     * case of old qmi_wwan drivers where add_mux/del_mux wasn't available yet  */
    if ((MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (ctx->wda_dl_dap_requested)) &&
        (!(ctx->kernel_data_modes_current & (MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN)))) {
        mm_obj_dbg (self, "cannot enable data aggregation: link management unsupported");
        return FALSE;
    }

    /* check whether the current and requested ones are the same */
    if ((ctx->kernel_data_modes_current & ctx->kernel_data_modes_requested) &&
        (ctx->wda_llp_current    == ctx->wda_llp_requested) &&
        (ctx->wda_ul_dap_current == ctx->wda_ul_dap_requested) &&
        (ctx->wda_dl_dap_current == ctx->wda_dl_dap_requested)) {
        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return TRUE;
    }

    return FALSE;
}

static void
check_data_format_combination (GTask *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;
    gboolean                        first_iteration;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    first_iteration = (ctx->data_format_combination_i < 0);
    if (!first_iteration && setup_data_format_completed (task))
        return;

    /* go on to the next supported combination */
    for (++ctx->data_format_combination_i;
         ctx->data_format_combination_i <= (gint)G_N_ELEMENTS (data_format_combinations);
         ctx->data_format_combination_i++) {
        const DataFormatCombination *combination;
        g_autofree gchar            *kernel_data_mode_str = NULL;

        combination = &data_format_combinations[ctx->data_format_combination_i];

        if (!(ctx->kernel_data_modes_supported & combination->kernel_data_mode))
            continue;

        if ((MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (combination->wda_dap)) &&
            ((!ctx->wda_dap_supported) ||
             (ctx->action != MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_SET_MULTIPLEX)))
            continue;

        kernel_data_mode_str = mm_port_qmi_kernel_data_mode_build_string_from_mask (combination->kernel_data_mode);
        mm_obj_dbg (self, "selected data format setup:");
        mm_obj_dbg (self, "    kernel data mode: %s", kernel_data_mode_str);
        mm_obj_dbg (self, "    link layer protocol: %s", qmi_wda_link_layer_protocol_get_string (combination->wda_llp));
        mm_obj_dbg (self, "    aggregation protocol: %s", qmi_wda_data_aggregation_protocol_get_string (combination->wda_dap));

        ctx->kernel_data_modes_requested = combination->kernel_data_mode;
        ctx->wda_llp_requested           = combination->wda_llp;
        ctx->wda_ul_dap_requested        = combination->wda_dap;
        ctx->wda_dl_dap_requested        = combination->wda_dap;

        if (first_iteration && setup_data_format_completed (task))
            return;

        /* Go on to next step */
        ctx->step++;
        internal_setup_data_format_context_step (task);
        return;
    }

    g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "No more data format combinations supported");
    g_object_unref (task);
}

static gboolean
process_data_format_output (MMPortQmi                         *self,
                            QmiMessageWdaGetDataFormatOutput  *output,
                            InternalSetupDataFormatContext    *ctx,
                            GError                           **error)
{
    /* Let's consider the lack o the LLP TLV a hard error; it really would be strange
     * a module supporting WDA Get Data Format but not containing the LLP info */
    if (!qmi_message_wda_get_data_format_output_get_link_layer_protocol (output, &ctx->wda_llp_current, error))
        return FALSE;

    /* QMAP assumed supported if both uplink and downlink TLVs are given */
    ctx->wda_dap_supported = TRUE;
    if (!qmi_message_wda_get_data_format_output_get_uplink_data_aggregation_protocol (output, &ctx->wda_ul_dap_current, NULL))
        ctx->wda_dap_supported = FALSE;
    if (!qmi_message_wda_get_data_format_output_get_downlink_data_aggregation_protocol (output, &ctx->wda_dl_dap_current, NULL))
        ctx->wda_dap_supported = FALSE;

    ctx->wda_dl_dap_max_size_current = 0;
    ctx->wda_dl_dap_max_datagrams_current = 0;
    if (ctx->wda_dl_dap_current != QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED) {
        qmi_message_wda_get_data_format_output_get_downlink_data_aggregation_max_size (output, &ctx->wda_dl_dap_max_size_current, NULL);
        qmi_message_wda_get_data_format_output_get_downlink_data_aggregation_max_datagrams (output, &ctx->wda_dl_dap_max_datagrams_current, NULL);
    }
    return TRUE;
}

static void
get_data_format_ready (QmiClientWda *client,
                       GAsyncResult *res,
                       GTask        *task)
{
    MMPortQmi                                   *self;
    InternalSetupDataFormatContext              *ctx;
    g_autoptr(QmiMessageWdaGetDataFormatOutput)  output = NULL;
    g_autoptr(GError)                            error = NULL;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    output = qmi_client_wda_get_data_format_finish (client, res, &error);
    if (!output ||
        !qmi_message_wda_get_data_format_output_get_result (output, &error) ||
        !process_data_format_output (self, output, ctx, &error)) {
        /* A 'missing argument' error when querying data format is seen in new
         * devices like the Quectel RM500Q, requiring the 'endpoint info' TLV.
         * When this happens, retry the step with the missing TLV.
         *
         * Note that this is not an additional step, we're still in the
         * GET_WDA_DATA_FORMAT step.
         */
        if (g_error_matches (error, QMI_PROTOCOL_ERROR, QMI_PROTOCOL_ERROR_MISSING_ARGUMENT) &&
            (self->priv->endpoint_type != QMI_DATA_ENDPOINT_TYPE_UNDEFINED)) {
            /* retry same step with endpoint info */
            ctx->use_endpoint = TRUE;
            internal_setup_data_format_context_step (task);
            return;
        }

        /* otherwise, fatal */
        g_task_return_error (task, g_steal_pointer (&error));
        g_object_unref (task);
        return;
    }

    /* Go on to next step */
    ctx->step++;
    internal_setup_data_format_context_step (task);
}

static void
allocate_client_wda_ready (QmiDevice    *device,
                           GAsyncResult *res,
                           GTask        *task)
{
    InternalSetupDataFormatContext *ctx;
    GError                         *error = NULL;

    ctx = g_task_get_task_data (task);

    ctx->wda = qmi_device_allocate_client_finish (device, res, &error);
    if (!ctx->wda) {
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    /* Go on to next step */
    ctx->step++;
    internal_setup_data_format_context_step (task);
}

static void
internal_setup_data_format_context_step (GTask *task)
{
    MMPortQmi                      *self;
    InternalSetupDataFormatContext *ctx;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    switch (ctx->step) {
        case INTERNAL_SETUP_DATA_FORMAT_STEP_FIRST:
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_SUPPORTED_KERNEL_DATA_MODES:
            /* Load kernel data format capabilities, only on first loop iteration */
            ctx->kernel_data_modes_supported = load_supported_kernel_data_modes (self, ctx->device);
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_RETRY:
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_CURRENT_KERNEL_DATA_MODES:
            /* Only reload kernel data modes if it was updated or on first loop */
            if (ctx->kernel_data_modes_current == MM_PORT_QMI_KERNEL_DATA_MODE_NONE)
                ctx->kernel_data_modes_current = load_current_kernel_data_modes (self, ctx->device);
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_ALLOCATE_WDA_CLIENT:
            /* Only allocate new WDA client on first loop */
            if (ctx->data_format_combination_i < 0) {
                g_assert (!ctx->wda);
                qmi_device_allocate_client (ctx->device,
                                            QMI_SERVICE_WDA,
                                            QMI_CID_NONE,
                                            10,
                                            g_task_get_cancellable (task),
                                            (GAsyncReadyCallback) allocate_client_wda_ready,
                                            task);
                return;
            }
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_GET_WDA_DATA_FORMAT:
            /* Only reload WDA data format if it was updated or on first loop */
            if (ctx->wda_llp_current == QMI_WDA_LINK_LAYER_PROTOCOL_UNKNOWN) {
                g_autoptr(QmiMessageWdaGetDataFormatInput) input = NULL;

                if (ctx->use_endpoint) {
                    input = qmi_message_wda_get_data_format_input_new ();
                    qmi_message_wda_get_data_format_input_set_endpoint_info (input,
                                                                             self->priv->endpoint_type,
                                                                             self->priv->endpoint_interface_number,
                                                                             NULL);
                }
                qmi_client_wda_get_data_format (QMI_CLIENT_WDA (ctx->wda),
                                                input,
                                                10,
                                                g_task_get_cancellable (task),
                                                (GAsyncReadyCallback) get_data_format_ready,
                                                task);
                return;
            }
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_QUERY_DONE: {
            g_autofree gchar *kernel_data_modes_str = NULL;

            kernel_data_modes_str = mm_port_qmi_kernel_data_mode_build_string_from_mask (ctx->kernel_data_modes_current);
            mm_obj_dbg (self, "current data format setup:");
            mm_obj_dbg (self, "    kernel data modes: %s", kernel_data_modes_str);
            mm_obj_dbg (self, "    link layer protocol: %s", qmi_wda_link_layer_protocol_get_string (ctx->wda_llp_current));
            mm_obj_dbg (self, "    aggregation protocol ul: %s", qmi_wda_data_aggregation_protocol_get_string (ctx->wda_ul_dap_current));
            mm_obj_dbg (self, "    aggregation protocol dl: %s", qmi_wda_data_aggregation_protocol_get_string (ctx->wda_dl_dap_current));

            if (ctx->action == MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_QUERY) {
                g_task_return_boolean (task, TRUE);
                g_object_unref (task);
                return;
            }

            ctx->step++;
        } /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_CHECK_DATA_FORMAT_COMBINATION:
            /* This step is the one that may complete the async operation
             * successfully */
            check_data_format_combination (task);
            return;

        case INTERNAL_SETUP_DATA_FORMAT_STEP_SYNC_WDA_DATA_FORMAT:
            if ((ctx->wda_llp_current != ctx->wda_llp_requested) ||
                (ctx->wda_ul_dap_current != ctx->wda_ul_dap_requested) ||
                (ctx->wda_dl_dap_current != ctx->wda_dl_dap_requested)) {
                sync_wda_data_format (task);
                return;
            }
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_SETUP_MASTER_MTU:
            /* qmi_wwan add_mux/del_mux based logic requires master MTU set to the maximum
             * data aggregation size reported by the modem.  */
            if (g_strcmp0 (self->priv->net_driver, "qmi_wwan") == 0) {
                setup_master_mtu (task);
                return;
            }
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_SYNC_KERNEL_DATA_MODE:
            if (!(ctx->kernel_data_modes_current & ctx->kernel_data_modes_requested)) {
                sync_kernel_data_mode (task);
                return;
            }
            ctx->step++;
            /* Fall through */

        case INTERNAL_SETUP_DATA_FORMAT_STEP_LAST:
            /* jump back to first step to reload current state after
             * the updates have been done */
            ctx->step = INTERNAL_SETUP_DATA_FORMAT_STEP_RETRY;
            internal_setup_data_format_context_step (task);
            return;

        default:
            g_assert_not_reached ();
    }
}

static void
internal_setup_data_format (MMPortQmi                      *self,
                            QmiDevice                      *device,
                            MMPort                         *data, /* may be NULL in query */
                            MMPortQmiSetupDataFormatAction  action,
                            GAsyncReadyCallback             callback,
                            gpointer                        user_data)
{
    InternalSetupDataFormatContext *ctx;
    GTask                          *task;

    task = g_task_new (self, NULL, callback, user_data);

    if (!device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE,
                                 "Port must be open to setup data format");
        g_object_unref (task);
        return;
    }

    if (self->priv->wda_unsupported) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_UNSUPPORTED,
                                 "Setting up data format is not supported");
        g_object_unref (task);
        return;
    }

    ctx = g_slice_new0 (InternalSetupDataFormatContext);
    ctx->device = g_object_ref (device);
    ctx->data = data ? g_object_ref (data) : NULL;
    ctx->action = action;
    ctx->step = INTERNAL_SETUP_DATA_FORMAT_STEP_FIRST;
    ctx->data_format_combination_i = -1;
    ctx->kernel_data_modes_current = MM_PORT_QMI_KERNEL_DATA_MODE_NONE;
    ctx->kernel_data_modes_requested = MM_PORT_QMI_KERNEL_DATA_MODE_NONE;
    ctx->kernel_data_modes_supported = MM_PORT_QMI_KERNEL_DATA_MODE_NONE;
    ctx->wda_llp_current = QMI_WDA_LINK_LAYER_PROTOCOL_UNKNOWN;
    ctx->wda_llp_requested = QMI_WDA_LINK_LAYER_PROTOCOL_UNKNOWN;
    ctx->wda_ul_dap_current = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;
    ctx->wda_ul_dap_requested = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;
    ctx->wda_dl_dap_current = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;
    ctx->wda_dl_dap_requested = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;

    if (mm_port_get_subsys (MM_PORT (self)) == MM_PORT_SUBSYS_QRTR)
        ctx->use_endpoint = TRUE;

    g_task_set_task_data (task, ctx, (GDestroyNotify) internal_setup_data_format_context_free);

    internal_setup_data_format_context_step (task);
}

/*****************************************************************************/

typedef struct {
    MMPort                         *data;
    QmiDevice                      *device;
    MMPortQmiSetupDataFormatAction  action;
} SetupDataFormatContext;

static void
setup_data_format_context_free (SetupDataFormatContext *ctx)
{
    g_clear_object (&ctx->device);
    g_clear_object (&ctx->data);
    g_slice_free (SetupDataFormatContext, ctx);
}

gboolean
mm_port_qmi_setup_data_format_finish (MMPortQmi                *self,
                                      GAsyncResult             *res,
                                      GError                  **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
internal_setup_data_format_ready (MMPortQmi    *self,
                                  GAsyncResult *res,
                                  GTask        *task)
{
    GError *error = NULL;

    if (!internal_setup_data_format_finish (self,
                                            res,
                                            &self->priv->kernel_data_modes,
                                            &self->priv->llp,
                                            &self->priv->dap,
                                            NULL, /* not expected to update */
                                            &error))
        g_task_return_error (task, error);
    else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

static void
setup_data_format_internal_reset_ready (MMPortQmi    *self,
                                        GAsyncResult *res,
                                        GTask        *task)
{
    SetupDataFormatContext *ctx;
    GError                 *error = NULL;

    ctx = g_task_get_task_data (task);

    if (!internal_reset_finish (self, res, &error)) {
        g_prefix_error (&error, "Couldn't reset interface before setting up data format: ");
        g_task_return_error (task, error);
        g_object_unref (task);
        return;
    }

    /* call internal method with the already open QmiDevice */
    internal_setup_data_format (self,
                                ctx->device,
                                ctx->data,
                                ctx->action,
                                (GAsyncReadyCallback)internal_setup_data_format_ready,
                                task);
}

static guint
count_links_setup (MMPortQmi *self,
                   MMPort    *data)
{
    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET) {
        g_autoptr(GPtrArray) links = NULL;
        g_autoptr(GError)    error = NULL;

        if (!qmi_device_list_links (self->priv->qmi_device,
                                    mm_port_get_device (data),
                                    &links,
                                    &error)) {
            mm_obj_warn (self, "couldn't list links in %s: %s",
                         mm_port_get_device (data),
                         error->message);
            return 0;
        }

        return links->len;
    }

    if (self->priv->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN)
        return count_preallocated_links_setup (self);

    return 0;
}

void
mm_port_qmi_setup_data_format (MMPortQmi                      *self,
                               MMPort                         *data,
                               MMPortQmiSetupDataFormatAction  action,
                               GAsyncReadyCallback             callback,
                               gpointer                        user_data)
{
    SetupDataFormatContext *ctx;
    GTask                  *task;

    /* External calls are never query */
    g_assert (action != MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_QUERY);
    g_assert (MM_IS_PORT (data));

    task = g_task_new (self, NULL, callback, user_data);

    if (!self->priv->qmi_device) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE, "Port not open");
        g_object_unref (task);
        return;
    }

    if (self->priv->wda_unsupported) {
        g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_UNSUPPORTED, "Setting up data format is unsupported");
        g_object_unref (task);
        return;
    }

    if ((action == MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_SET_MULTIPLEX) &&
        (self->priv->kernel_data_modes & (MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN)) &&
        MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (self->priv->dap)) {
        mm_obj_dbg (self, "multiplex support already available when setting up data format");
        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return;
    }

    if ((action == MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_SET_DEFAULT) &&
        (!(self->priv->kernel_data_modes & (MM_PORT_QMI_KERNEL_DATA_MODE_MUX_RMNET | MM_PORT_QMI_KERNEL_DATA_MODE_MUX_QMIWWAN))) &&
        !MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (self->priv->dap)) {
        mm_obj_dbg (self, "multiplex support already disabled when setting up data format");
        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return;
    }

    /* support switching from multiplex to non-multiplex, but only if there are no active
     * links allocated */
    if ((action == MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_SET_DEFAULT) &&
        MM_PORT_QMI_DAP_IS_SUPPORTED_QMAP (self->priv->dap)) {
        guint n_links_setup;

        n_links_setup = count_links_setup (self, data);
        if (n_links_setup > 0) {
            g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_WRONG_STATE,
                                     "Cannot switch to non-multiplex setup: %u links already setup exist",
                                     n_links_setup);
            g_object_unref (task);
            return;
        }
    }

    ctx = g_slice_new0 (SetupDataFormatContext);
    ctx->data = g_object_ref (data);
    ctx->device = g_object_ref (self->priv->qmi_device);
    ctx->action = action;
    g_task_set_task_data (task, ctx, (GDestroyNotify)setup_data_format_context_free);

    internal_reset (self,
                    data,
                    ctx->device,
                    (GAsyncReadyCallback)setup_data_format_internal_reset_ready,
                    task);
}

/*****************************************************************************/

typedef enum {
    PORT_OPEN_STEP_FIRST,
    PORT_OPEN_STEP_CHECK_OPENING,
    PORT_OPEN_STEP_CHECK_ALREADY_OPEN,
    PORT_OPEN_STEP_DEVICE_NEW,
    PORT_OPEN_STEP_OPEN_WITHOUT_DATA_FORMAT,
    PORT_OPEN_STEP_SETUP_DATA_FORMAT,
    PORT_OPEN_STEP_CLOSE_BEFORE_OPEN_WITH_DATA_FORMAT,
    PORT_OPEN_STEP_OPEN_WITH_DATA_FORMAT,
    PORT_OPEN_STEP_LAST
} PortOpenStep;

typedef struct {
    QmiDevice               *device;
    GError                  *error;
    PortOpenStep             step;
    gboolean                 set_data_format;
    MMPortQmiKernelDataMode  kernel_data_modes;
} PortOpenContext;

static void
port_open_context_free (PortOpenContext *ctx)
{
    g_assert (!ctx->error);
    g_clear_object (&ctx->device);
    g_slice_free (PortOpenContext, ctx);
}

gboolean
mm_port_qmi_open_finish (MMPortQmi     *self,
                         GAsyncResult  *res,
                         GError       **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void port_open_step (GTask *task);

static void
port_open_complete_with_error (GTask *task)
{
    MMPortQmi       *self;
    PortOpenContext *ctx;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    g_assert (ctx->error);
    self->priv->in_progress = FALSE;
    g_task_return_error (task, g_steal_pointer (&ctx->error));
    g_object_unref (task);
}

static void
qmi_device_close_on_error_ready (QmiDevice    *qmi_device,
                                 GAsyncResult *res,
                                 GTask        *task)
{
    MMPortQmi         *self;
    g_autoptr(GError)  error = NULL;

    self = g_task_get_source_object (task);

    if (!qmi_device_close_finish (qmi_device, res, &error))
        mm_obj_warn (self, "Couldn't close QMI device after failed open sequence: %s", error->message);

    port_open_complete_with_error (task);
}

static void
qmi_device_open_second_ready (QmiDevice    *qmi_device,
                              GAsyncResult *res,
                              GTask        *task)
{
    MMPortQmi       *self;
    PortOpenContext *ctx;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (qmi_device_open_finish (qmi_device, res, &ctx->error)) {
        /* If the open with CTL data format is sucessful, update all settings
         * that we would have received with the internal setup data format
         * process */
        self->priv->kernel_data_modes = ctx->kernel_data_modes;
        if (ctx->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP)
            self->priv->llp = QMI_WDA_LINK_LAYER_PROTOCOL_RAW_IP;
        else if (ctx->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_802_3)
            self->priv->llp = QMI_WDA_LINK_LAYER_PROTOCOL_802_3;
        else
            g_assert_not_reached ();
        self->priv->dap = QMI_WDA_DATA_AGGREGATION_PROTOCOL_DISABLED;
        self->priv->max_multiplexed_links = 0;
    }

    /* In both error and success, we go to last step */
    ctx->step++;
    port_open_step (task);
}

static void
qmi_device_close_to_reopen_ready (QmiDevice    *qmi_device,
                                  GAsyncResult *res,
                                  GTask        *task)
{
    MMPortQmi       *self;
    PortOpenContext *ctx;

    self = g_task_get_source_object (task);
    ctx  = g_task_get_task_data (task);

    if (!qmi_device_close_finish (qmi_device, res, &ctx->error)) {
        mm_obj_warn (self, "Couldn't close QMI device to reopen it");
        ctx->step = PORT_OPEN_STEP_LAST;
    } else
        ctx->step++;
    port_open_step (task);
}

static void
open_internal_setup_data_format_ready (MMPortQmi    *self,
                                       GAsyncResult *res,
                                       GTask        *task)
{
    PortOpenContext   *ctx;
    g_autoptr(GError)  error = NULL;

    ctx = g_task_get_task_data (task);

    if (!internal_setup_data_format_finish (self,
                                            res,
                                            &self->priv->kernel_data_modes,
                                            &self->priv->llp,
                                            &self->priv->dap,
                                            &self->priv->max_multiplexed_links,
                                            &error)) {
        /* Continue with fallback to LLP requested via CTL */
        mm_obj_warn (self, "Couldn't setup data format: %s", error->message);
        self->priv->wda_unsupported = TRUE;
        ctx->step++;
    } else {
        /* on success, we're done */
        ctx->step = PORT_OPEN_STEP_LAST;
    }
    port_open_step (task);
}

static void
qmi_device_open_first_ready (QmiDevice    *qmi_device,
                             GAsyncResult *res,
                             GTask        *task)
{
    PortOpenContext *ctx;

    ctx = g_task_get_task_data (task);

    if (!qmi_device_open_finish (qmi_device, res, &ctx->error))
        /* Error opening the device */
        ctx->step = PORT_OPEN_STEP_LAST;
    else if (!ctx->set_data_format)
        /* If not setting data format, we're done */
        ctx->step = PORT_OPEN_STEP_LAST;
    else
        /* Go on to next step */
        ctx->step++;
    port_open_step (task);
}

static void
qmi_device_new_ready (GObject *unused,
                      GAsyncResult *res,
                      GTask *task)
{
    PortOpenContext *ctx;

    ctx = g_task_get_task_data (task);
    /* Store the device in the context until the operation is fully done,
     * so that we return IN_PROGRESS errors until we finish this async
     * operation. */
    ctx->device = qmi_device_new_finish (res, &ctx->error);
    if (!ctx->device)
        /* Error creating the device */
        ctx->step = PORT_OPEN_STEP_LAST;
    else
        /* Go on to next step */
        ctx->step++;
    port_open_step (task);
}

static void
port_open_step (GTask *task)
{
    MMPortQmi       *self;
    PortOpenContext *ctx;

    self = g_task_get_source_object (task);
    ctx = g_task_get_task_data (task);
    switch (ctx->step) {
    case PORT_OPEN_STEP_FIRST:
        mm_obj_dbg (self, "Opening QMI device...");
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_CHECK_OPENING:
        mm_obj_dbg (self, "Checking if QMI device already opening...");
        if (self->priv->in_progress) {
            g_task_return_new_error (task,
                                     MM_CORE_ERROR,
                                     MM_CORE_ERROR_IN_PROGRESS,
                                     "QMI device open/close operation in progress");
            g_object_unref (task);
            return;
        }
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_CHECK_ALREADY_OPEN:
        mm_obj_dbg (self, "Checking if QMI device already open...");
        if (self->priv->qmi_device) {
            g_task_return_boolean (task, TRUE);
            g_object_unref (task);
            return;
        }
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_DEVICE_NEW:
        /* We flag in this point that we're opening. From now on, if we stop
         * for whatever reason, we should clear this flag. We do this by ensuring
         * that all callbacks go through the LAST step for completing. */
        self->priv->in_progress = TRUE;

#if defined WITH_QRTR
        if (self->priv->node) {
            mm_obj_info (self, "Creating QMI device from QRTR node...");
            qmi_device_new_from_node (self->priv->node,
                                      g_task_get_cancellable (task),
                                      (GAsyncReadyCallback) qmi_device_new_ready,
                                      task);
            return;
        }
#endif
        {
            g_autoptr(GFile)  file = NULL;
            g_autofree gchar *fullpath = NULL;

            fullpath = g_strdup_printf ("/dev/%s", mm_port_get_device (MM_PORT (self)));
            file = g_file_new_for_path (fullpath);

            mm_obj_dbg (self, "Creating QMI device...");
            qmi_device_new (file,
                            g_task_get_cancellable (task),
                            (GAsyncReadyCallback) qmi_device_new_ready,
                            task);
            return;
        }

    case PORT_OPEN_STEP_OPEN_WITHOUT_DATA_FORMAT:
        if (!self->priv->wda_unsupported) {
            QmiDeviceOpenFlags  open_flags;
            g_autofree gchar   *open_flags_str = NULL;

            /* Now open the QMI device without any data format CTL flag */
            open_flags = (QMI_DEVICE_OPEN_FLAGS_VERSION_INFO | QMI_DEVICE_OPEN_FLAGS_PROXY);
            open_flags_str = qmi_device_open_flags_build_string_from_mask (open_flags);
            mm_obj_dbg (self, "Opening device with flags: %s...", open_flags_str);
            qmi_device_open (ctx->device,
                             open_flags,
                             45,
                             g_task_get_cancellable (task),
                             (GAsyncReadyCallback) qmi_device_open_first_ready,
                             task);
            return;
        }
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_SETUP_DATA_FORMAT:
        if (qmi_device_is_open (ctx->device)) {
            internal_setup_data_format (self,
                                        ctx->device,
                                        NULL,
                                        MM_PORT_QMI_SETUP_DATA_FORMAT_ACTION_QUERY,
                                        (GAsyncReadyCallback) open_internal_setup_data_format_ready,
                                        task);
            return;
        }
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_CLOSE_BEFORE_OPEN_WITH_DATA_FORMAT:
        /* This fallback only applies when WDA unsupported */
        if (qmi_device_is_open (ctx->device)) {
            mm_obj_dbg (self, "Closing device to reopen it right away...");
            qmi_device_close_async (ctx->device,
                                    5,
                                    g_task_get_cancellable (task),
                                    (GAsyncReadyCallback) qmi_device_close_to_reopen_ready,
                                    task);
            return;
        }
        ctx->step++;
        /* Fall through */

    case PORT_OPEN_STEP_OPEN_WITH_DATA_FORMAT: {
        QmiDeviceOpenFlags  open_flags;
        g_autofree gchar   *open_flags_str = NULL;

        /* Common open flags */
        open_flags = (QMI_DEVICE_OPEN_FLAGS_VERSION_INFO |
                      QMI_DEVICE_OPEN_FLAGS_PROXY        |
                      QMI_DEVICE_OPEN_FLAGS_NET_NO_QOS_HEADER);

        ctx->kernel_data_modes = load_current_kernel_data_modes (self, ctx->device);

        /* Need to reopen setting 802.3/raw-ip using CTL */
        if (ctx->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_RAW_IP)
            open_flags |= QMI_DEVICE_OPEN_FLAGS_NET_RAW_IP;
        else if (ctx->kernel_data_modes & MM_PORT_QMI_KERNEL_DATA_MODE_802_3)
            open_flags |= QMI_DEVICE_OPEN_FLAGS_NET_802_3;
        else {
            g_task_return_new_error (task, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                                     "Unexpected kernel data mode: cannot setup using CTL");
            g_object_unref (task);
            return;
        }

        open_flags_str = qmi_device_open_flags_build_string_from_mask (open_flags);
        mm_obj_dbg (self, "Reopening device with flags: %s...", open_flags_str);

        qmi_device_open (ctx->device,
                         open_flags,
                         10,
                         g_task_get_cancellable (task),
                         (GAsyncReadyCallback) qmi_device_open_second_ready,
                         task);
        return;
    }

    case PORT_OPEN_STEP_LAST:
        if (ctx->error) {
            mm_obj_dbg (self, "QMI port open operation failed: %s", ctx->error->message);

            if (ctx->device) {
                qmi_device_close_async (ctx->device,
                                        5,
                                        NULL,
                                        (GAsyncReadyCallback) qmi_device_close_on_error_ready,
                                        task);
                return;
            }

            port_open_complete_with_error (task);
            return;
        }

        mm_obj_dbg (self, "QMI port open operation finished successfully");

        /* Store device in private info */
        g_assert (ctx->device);
        g_assert (!self->priv->qmi_device);
        self->priv->qmi_device = g_object_ref (ctx->device);
        self->priv->in_progress = FALSE;
        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return;

    default:
        g_assert_not_reached ();
    }
}

void
mm_port_qmi_open (MMPortQmi           *self,
                  gboolean             set_data_format,
                  GCancellable        *cancellable,
                  GAsyncReadyCallback  callback,
                  gpointer             user_data)
{
    PortOpenContext *ctx;
    GTask           *task;

    ctx = g_slice_new0 (PortOpenContext);
    ctx->step = PORT_OPEN_STEP_FIRST;
    ctx->set_data_format = set_data_format;
    ctx->kernel_data_modes = MM_PORT_QMI_KERNEL_DATA_MODE_NONE;

    task = g_task_new (self, cancellable, callback, user_data);
    g_task_set_task_data (task, ctx, (GDestroyNotify)port_open_context_free);
    port_open_step (task);
}

/*****************************************************************************/

gboolean
mm_port_qmi_is_open (MMPortQmi *self)
{
    g_return_val_if_fail (MM_IS_PORT_QMI (self), FALSE);

    return !!self->priv->qmi_device;
}

/*****************************************************************************/

void
mm_port_qmi_set_net_driver (MMPortQmi   *self,
                            const gchar *net_driver)
{
    g_assert (MM_IS_PORT_QMI (self));
    g_assert (!self->priv->net_driver);
    self->priv->net_driver = g_strdup (net_driver);
}

/*****************************************************************************/

typedef struct {
    QmiDevice *qmi_device;
} PortQmiCloseContext;

static void
port_qmi_close_context_free (PortQmiCloseContext *ctx)
{
    g_clear_object (&ctx->qmi_device);
    g_slice_free (PortQmiCloseContext, ctx);
}

gboolean
mm_port_qmi_close_finish (MMPortQmi     *self,
                          GAsyncResult  *res,
                          GError       **error)
{
    return g_task_propagate_boolean (G_TASK (res), error);
}

static void
qmi_device_close_ready (QmiDevice    *qmi_device,
                        GAsyncResult *res,
                        GTask        *task)
{
    GError    *error = NULL;
    MMPortQmi *self;

    self = g_task_get_source_object (task);

    g_assert (!self->priv->qmi_device);
    self->priv->in_progress = FALSE;

    if (!qmi_device_close_finish (qmi_device, res, &error))
        g_task_return_error (task, error);
    else
        g_task_return_boolean (task, TRUE);
    g_object_unref (task);
}

void
mm_port_qmi_close (MMPortQmi           *self,
                   GAsyncReadyCallback  callback,
                   gpointer             user_data)
{
    PortQmiCloseContext *ctx;
    GTask               *task;
    GList               *l;

    g_return_if_fail (MM_IS_PORT_QMI (self));

    task = g_task_new (self, NULL, callback, user_data);

    if (self->priv->in_progress) {
        g_task_return_new_error (task,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_IN_PROGRESS,
                                 "QMI device open/close operation in progress");
        g_object_unref (task);
        return;
    }

    if (!self->priv->qmi_device) {
        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
        return;
    }

    self->priv->in_progress = TRUE;

    /* Store device to close in the context */
    ctx = g_slice_new0 (PortQmiCloseContext);
    ctx->qmi_device = g_steal_pointer (&self->priv->qmi_device);
    g_task_set_task_data (task, ctx, (GDestroyNotify)port_qmi_close_context_free);

    /* Release all allocated clients */
    for (l = self->priv->services; l; l = g_list_next (l)) {
        ServiceInfo *info = l->data;

        mm_obj_dbg (self, "Releasing client for service '%s'...", qmi_service_get_string (info->service));
        qmi_device_release_client (ctx->qmi_device,
                                   info->client,
                                   QMI_DEVICE_RELEASE_CLIENT_FLAGS_RELEASE_CID,
                                   3, NULL, NULL, NULL);
        g_clear_object (&info->client);
    }
    g_list_free_full (self->priv->services, g_free);
    self->priv->services = NULL;

    /* Cleanup preallocated links, if any */
    if (self->priv->preallocated_links) {
        delete_preallocated_links (ctx->qmi_device, self->priv->preallocated_links);
        g_clear_pointer (&self->priv->preallocated_links, g_array_unref);
    }
    g_clear_object (&self->priv->preallocated_links_master);

    qmi_device_close_async (ctx->qmi_device,
                            5,
                            NULL,
                            (GAsyncReadyCallback)qmi_device_close_ready,
                            task);
}

/*****************************************************************************/

MMPortQmi *
mm_port_qmi_new (const gchar  *name,
                 MMPortSubsys  subsys)
{
    return MM_PORT_QMI (g_object_new (MM_TYPE_PORT_QMI,
                                      MM_PORT_DEVICE, name,
                                      MM_PORT_SUBSYS, subsys,
                                      MM_PORT_TYPE, MM_PORT_TYPE_QMI,
                                      NULL));
}

#if defined WITH_QRTR
MMPortQmi *
mm_port_qmi_new_from_node (const gchar *name,
                           QrtrNode    *node)
{
    return MM_PORT_QMI (g_object_new (MM_TYPE_PORT_QMI,
                                      "node", node,
                                      MM_PORT_DEVICE, name,
                                      MM_PORT_SUBSYS, MM_PORT_SUBSYS_QRTR,
                                      MM_PORT_TYPE, MM_PORT_TYPE_QMI,
                                      NULL));
}
#endif

static void
mm_port_qmi_init (MMPortQmi *self)
{
    self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, MM_TYPE_PORT_QMI, MMPortQmiPrivate);

    /* load endpoint info as soon as kernel device is set */
    self->priv->endpoint_info_signal_id = g_signal_connect (self,
                                                            "notify::" MM_PORT_KERNEL_DEVICE,
                                                            G_CALLBACK (initialize_endpoint_info),
                                                            NULL);
}

static void
set_property (GObject      *object,
              guint         prop_id,
              const GValue *value,
              GParamSpec   *pspec)
{
    switch (prop_id) {
#if defined WITH_QRTR
    case PROP_NODE:
    {
        MMPortQmi *self = MM_PORT_QMI (object);

        /* construct only, no new reference! */
        self->priv->node = g_value_get_object (value);
        break;
    }
#endif
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}

static void
get_property (GObject    *object,
              guint       prop_id,
              GValue     *value,
              GParamSpec *pspec)
{
    switch (prop_id) {
#if defined WITH_QRTR
    case PROP_NODE:
    {
        MMPortQmi *self = MM_PORT_QMI (object);

        g_value_set_object (value, self->priv->node);
        break;
    }
#endif
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}

static void
dispose (GObject *object)
{
    MMPortQmi *self = MM_PORT_QMI (object);
    GList *l;

    if (self->priv->endpoint_info_signal_id) {
        g_signal_handler_disconnect (self, self->priv->endpoint_info_signal_id);
        self->priv->endpoint_info_signal_id = 0;
    }

    /* Deallocate all clients */
    for (l = self->priv->services; l; l = g_list_next (l)) {
        ServiceInfo *info = l->data;

        if (info->client)
            g_object_unref (info->client);
    }
    g_list_free_full (self->priv->services, g_free);
    self->priv->services = NULL;

    /* Cleanup preallocated links, if any */
    if (self->priv->preallocated_links && self->priv->qmi_device)
        delete_preallocated_links (self->priv->qmi_device, self->priv->preallocated_links);
    g_clear_pointer (&self->priv->preallocated_links, g_array_unref);
    g_clear_object (&self->priv->preallocated_links_master);

    /* Clear node object */
#if defined WITH_QRTR
    g_clear_object (&self->priv->node);
#endif
    /* Clear device object */
    g_clear_object (&self->priv->qmi_device);

    g_clear_pointer (&self->priv->net_driver, g_free);

    G_OBJECT_CLASS (mm_port_qmi_parent_class)->dispose (object);
}

static void
mm_port_qmi_class_init (MMPortQmiClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS (klass);

    g_type_class_add_private (object_class, sizeof (MMPortQmiPrivate));

    /* Virtual methods */
    object_class->get_property = get_property;
    object_class->set_property = set_property;
    object_class->dispose = dispose;

#if defined WITH_QRTR
    properties[PROP_NODE] =
        g_param_spec_object ("node",
                             "Qrtr Node",
                             "Qrtr node to be probed",
                             QRTR_TYPE_NODE,
                             G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);

#endif
    g_object_class_install_properties (object_class, PROP_LAST, properties);
}